Debian Codegraph @

doc/gendoc.py

raw
1 #!/usr/bin/env python3
2 """usage: %s DOC ...
3
4 where DOC is the name of a document
5 """
6
7
8 import os
9 import sys
10 import textwrap
11 import argparse
12
13 try:
14 import msvcrt
15
16 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
17 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
18 except ImportError:
19 pass
20
21 # This script is executed during installs and may not have C extensions
22 # available. Relax C module requirements.
23 os.environ['HGMODULEPOLICY'] = 'allow'
24 # import from the live mercurial repo
25 sys.path.insert(0, os.path.abspath(".."))
26 from mercurial import demandimport
27
28 demandimport.enable()
29
30 from mercurial import (
31 cmd_impls,
32 encoding,
33 extensions,
34 fancyopts,
35 help,
36 initialization,
37 minirst,
38 pycompat,
39 tables,
40 ui as uimod,
41 )
42 from mercurial.i18n import (
43 gettext,
44 _,
45 )
46 from mercurial.utils import stringutil
47
48 initialization.init()
49
50 table = tables.command_table
51 globalopts = cmd_impls.global_opts
52 helptable = help.helptable
53 loaddoc = help.loaddoc
54
55
56 def get_desc(docstr):
57 if not docstr:
58 return b"", b""
59 # sanitize
60 docstr = docstr.strip(b"\n")
61 docstr = docstr.rstrip()
62 shortdesc = docstr.splitlines()[0].strip()
63
64 i = docstr.find(b"\n")
65 if i != -1:
66 desc = docstr[i + 2 :]
67 else:
68 desc = shortdesc
69
70 desc = textwrap.dedent(desc.decode('latin1')).encode('latin1')
71
72 return (shortdesc, desc)
73
74
75 def get_opts(opts):
76 for opt in opts:
77 if len(opt) == 5:
78 shortopt, longopt, default, desc, optlabel = opt
79 else:
80 shortopt, longopt, default, desc = opt
81 optlabel = _(b"VALUE")
82 allopts = []
83 if shortopt:
84 allopts.append(b"-%s" % shortopt)
85 if longopt:
86 allopts.append(b"--%s" % longopt)
87 if isinstance(default, list):
88 allopts[-1] += b" <%s[+]>" % optlabel
89 elif (default is not None) and not isinstance(default, bool):
90 allopts[-1] += b" <%s>" % optlabel
91 if b'\n' in desc:
92 # only remove line breaks and indentation
93 desc = b' '.join(l.lstrip() for l in desc.split(b'\n'))
94 if isinstance(default, fancyopts.customopt):
95 default = default.getdefaultvalue()
96 if default:
97 default = stringutil.forcebytestr(default)
98 desc += _(b" (default: %s)") % default
99 yield (b", ".join(allopts), desc)
100
101
102 def get_cmd(cmd, cmdtable):
103 d = {}
104 attr = cmdtable[cmd]
105 cmds = cmd.lstrip(b"^").split(b"|")
106
107 d[b'cmd'] = cmds[0]
108 d[b'aliases'] = cmd.split(b"|")[1:]
109 d[b'desc'] = get_desc(gettext(pycompat.getdoc(attr[0])))
110 d[b'opts'] = list(get_opts(attr[1]))
111
112 s = b'hg ' + cmds[0]
113 if len(attr) > 2:
114 if not attr[2].startswith(b'hg'):
115 s += b' ' + attr[2]
116 else:
117 s = attr[2]
118 d[b'synopsis'] = s.strip()
119
120 return d
121
122
123 def showdoc(ui, debugcmds=False):
124 # print options
125 ui.write(minirst.section(_(b"Options")))
126 multioccur = False
127 for optstr, desc in get_opts(globalopts):
128 ui.write(b"%s\n %s\n\n" % (optstr, desc))
129 if optstr.endswith(b"[+]>"):
130 multioccur = True
131 if multioccur:
132 ui.write(_(b"\n[+] marked option can be specified multiple times\n"))
133 ui.write(b"\n")
134
135 # print cmds
136 ui.write(minirst.section(_(b"Commands")))
137 commandprinter(
138 ui,
139 table,
140 minirst.subsection,
141 minirst.subsubsection,
142 debugcmds=debugcmds,
143 )
144
145 # print help topics
146 # The config help topic is included in the hgrc.5 man page.
147 topics = findtopics(helptable, exclude=[b'config'])
148 helpprinter(ui, topics, minirst.section)
149
150 ui.write(minirst.section(_(b"Extensions")))
151 ui.write(
152 _(
153 b"This section contains help for extensions that are "
154 b"distributed together with Mercurial. Help for other "
155 b"extensions is available in the help system."
156 )
157 )
158 ui.writenoi18n(
159 b"\n\n"
160 b".. contents::\n"
161 b" :class: htmlonly\n"
162 b" :local:\n"
163 b" :depth: 1\n\n"
164 )
165
166 for extensionname in sorted(allextensionnames()):
167 mod = extensions.load(ui, extensionname, None)
168 ui.write(minirst.subsection(extensionname))
169 ext_doc = help.ext_help(ui, mod)
170 ui.write(b"%s\n\n" % ext_doc)
171 cmdtable = getattr(mod, 'cmdtable', None)
172 if cmdtable:
173 ui.write(minirst.subsubsection(_(b'Commands')))
174 commandprinter(
175 ui,
176 cmdtable,
177 minirst.subsubsubsection,
178 minirst.subsubsubsubsection,
179 debugcmds=debugcmds,
180 )
181
182
183 def showcommandlist(ui, debugcmds=False):
184 """Render a plain text list of all command names
185
186 Args:
187 ui: the UI object to output to
188 debugcmds: whether to include debug commands
189 """
190 cmdnames = allcommandnames(table, debugcmds=debugcmds)
191 for mainname in cmdnames.keys():
192 # Make does not like semicolons in filenames (or what it
193 # considers as filenames). We use command names as targets so
194 # it applies here. For now let's skip commands with semicolons
195 # in them (at this time it only includes the `admin::verify`
196 # advanced command).
197 if b'::' in mainname:
198 continue
199 ui.write(mainname)
200 ui.write(b" ")
201
202
203 def showtopiclist(ui):
204 """Render a plain text list of all help topic names
205
206 Args:
207 ui: the UI object to output to
208 """
209 for topic in helptable:
210 topicname = topic[0][0]
211 if help.filtertopic(ui, topicname):
212 continue
213 ui.write(topicname)
214 ui.write(b" ")
215
216
217 def showextensionlist(ui):
218 """Render a plain text list of all extension names
219
220 Args:
221 ui: the UI object to output to
222 """
223 for extensionname in allextensionnames():
224 ui.write(extensionname)
225 ui.write(b" ")
226
227
228 def showhelpindex(ui, debugcmds=False):
229 """Render restructured text for a complete mercurial help index
230
231 This index will show a list of commands, followed by a list of help topics,
232 and finally a list of extensions. These lists are split in categories and
233 ordered 'nicely' as defined by alphabetical and categeory order.
234
235 Each entry in this index is a reference to the specific help page of the
236 command, topic, or extension at hand.
237 """
238 ui.write(minirst.section(_(b"Mercurial Distributed SCM")))
239
240 missingdoc = _(b"(no help text available)")
241
242 cats, h, syns = help._getcategorizedhelpcmds(ui, table, None)
243 ui.write(minirst.subsection(_(b"Commands")))
244
245 for cat in help.CATEGORY_ORDER:
246 catfns = sorted(cats.get(cat, []))
247 if not catfns:
248 continue
249
250 catname = gettext(help.CATEGORY_NAMES[cat])
251 ui.write(minirst.subsubsection(catname))
252 for c in catfns:
253 url = b'hg-%s.html' % c
254 ui.write(b" :`%s <%s>`__: %s" % (c, url, h[c]))
255 syns[c].remove(c)
256 if syns[c]:
257 ui.write(_(b" (aliases: *%s*)") % (b', '.join(syns[c])))
258 ui.write(b"\n")
259 ui.write(b"\n\n")
260
261 ui.write(b"\n\n")
262
263 ui.write(minirst.subsection(_(b"Additional Help Topics")))
264 topiccats, topicsyns = help._getcategorizedhelptopics(ui, helptable)
265 for cat in help.TOPIC_CATEGORY_ORDER:
266 topics = topiccats.get(cat, [])
267 if not topics:
268 continue
269
270 catname = gettext(help.TOPIC_CATEGORY_NAMES[cat])
271 ui.write(minirst.subsubsection(catname))
272 for t, desc in topics:
273 url = b'topic-%s.html' % t
274 ui.write(b" :`%s <%s>`__: %s" % (t, url, desc))
275 topicsyns[t].remove(t)
276 if topicsyns[t]:
277 ui.write(_(b" (aliases: *%s*)") % (b', '.join(topicsyns[t])))
278 ui.write(b"\n")
279 ui.write(b"\n\n")
280
281 ui.write(b"\n\n")
282
283 # Add an alphabetical list of extensions, categorized by group.
284 sectionkeywords = [
285 (b"(ADVANCED)", _(b"(ADVANCED)")),
286 (b"(EXPERIMENTAL)", _(b"(EXPERIMENTAL)")),
287 (b"(DEPRECATED)", _(b"(DEPRECATED)")),
288 ]
289 extensionsections = [
290 (b"Extensions", []),
291 (b"Advanced Extensions", []),
292 (b"Experimental Extensions", []),
293 (b"Deprecated Extensions", []),
294 ]
295 for extensionname in allextensionnames():
296 mod = extensions.load(ui, extensionname, None)
297 shortdoc, longdoc = _splitdoc(mod)
298 for i, kwds in enumerate(sectionkeywords):
299 if any([kwd in shortdoc for kwd in kwds]):
300 extensionsections[i + 1][1].append(
301 (extensionname, mod, shortdoc)
302 )
303 break
304 else:
305 extensionsections[0][1].append((extensionname, mod, shortdoc))
306 for sectiontitle, extinfos in extensionsections:
307 ui.write(minirst.subsection(_(sectiontitle)))
308 for extinfo in sorted(extinfos, key=lambda ei: ei[0]):
309 extensionname, mod, shortdoc = extinfo
310 url = b'ext-%s.html' % extensionname
311 ui.write(
312 minirst.subsubsection(b'`%s <%s>`__' % (extensionname, url))
313 )
314 ui.write(shortdoc)
315 ui.write(b'\n\n')
316 cmdtable = getattr(mod, 'cmdtable', None)
317 if cmdtable:
318 cmdnames = allcommandnames(cmdtable, debugcmds=debugcmds)
319 for f in sorted(cmdnames.keys()):
320 d = get_cmd(cmdnames[f], cmdtable)
321 ui.write(b':%s: ' % d[b'cmd'])
322 ui.write(d[b'desc'][0] or (missingdoc + b"\n"))
323 ui.write(b'\n')
324 ui.write(b'\n')
325
326
327 def showcommand(ui, mainname):
328 # Always pass debugcmds=True so that we find whatever command we are told
329 # to display.
330 cmdnames = allcommandnames(table, debugcmds=True)
331 allnames = cmdnames[mainname]
332 d = get_cmd(allnames, table)
333
334 header = _rendertpl(
335 'cmdheader.txt',
336 {
337 'cmdname': mainname,
338 'cmdtitle': minirst.section(b'hg ' + mainname),
339 'cmdshortdesc': minirst.subsection(d[b'desc'][0]),
340 'cmdlongdesc': d[b'desc'][1],
341 'cmdsynopsis': d[b'synopsis'],
342 },
343 )
344 ui.write(header.encode())
345
346 _optionsprinter(ui, d, minirst.subsubsection)
347 if d[b'aliases']:
348 ui.write(minirst.subsubsection(_(b"Aliases")))
349 ui.write(b"::\n\n ")
350 ui.write(b", ".join(d[b'aliases']))
351 ui.write(b"\n")
352
353
354 def _splitdoc(obj):
355 objdoc = pycompat.getdoc(obj)
356 firstnl = objdoc.find(b'\n')
357 if firstnl > 0:
358 shortdoc = objdoc[:firstnl]
359 longdoc = objdoc[firstnl + 1 :]
360 else:
361 shortdoc = objdoc
362 longdoc = ''
363 return shortdoc.lstrip(), longdoc.lstrip()
364
365
366 def _rendertpl(tplname, data):
367 tplpath = os.path.join(os.path.dirname(__file__), 'templates', tplname)
368 with open(tplpath) as f:
369 tpl = f.read()
370
371 if isinstance(tpl, bytes):
372 tpl = tpl.decode()
373 for k in data:
374 data[k] = data[k].decode()
375
376 return tpl % data
377
378
379 def gettopicstable():
380 extrahelptable = [
381 ([b"common"], b'', loaddoc(b'common'), help.TOPIC_CATEGORY_MISC),
382 ([b"hg.1"], b'', loaddoc(b'hg.1'), help.TOPIC_CATEGORY_CONFIG),
383 ([b"hg-ssh.8"], b'', loaddoc(b'hg-ssh.8'), help.TOPIC_CATEGORY_CONFIG),
384 (
385 [b"hgignore.5"],
386 b'',
387 loaddoc(b'hgignore.5'),
388 help.TOPIC_CATEGORY_CONFIG,
389 ),
390 ([b"hgrc.5"], b'', loaddoc(b'hgrc.5'), help.TOPIC_CATEGORY_CONFIG),
391 ([b"hg-ssh.8.gendoc"], b'', b'', help.TOPIC_CATEGORY_CONFIG),
392 (
393 [b"hgignore.5.gendoc"],
394 b'',
395 loaddoc(b'hgignore'),
396 help.TOPIC_CATEGORY_CONFIG,
397 ),
398 (
399 [b"hgrc.5.gendoc"],
400 b'',
401 loaddoc(b'config'),
402 help.TOPIC_CATEGORY_CONFIG,
403 ),
404 ]
405 return helptable + extrahelptable
406
407
408 def findtopics(helptable, include=[], exclude=[]):
409 """Find topics whose names match the given include/exclude rules
410
411 Note that exclude rules take precedence over include rules.
412 """
413 found = []
414 for h in helptable:
415 names, sec, doc = h[0:3]
416 if exclude and names[0] in exclude:
417 continue
418 if include and names[0] not in include:
419 continue
420 found.append((names, sec, doc))
421 return found
422
423
424 def showtopic(ui, topic, wraptpl=False):
425 """Render a help topic
426
427 Args:
428 ui: the UI object to output to
429 topic: the topic name to output
430 wraptpl: whether to wrap the output in the individual help topic
431 pages' header/footer
432 """
433 found = findtopics(gettopicstable(), include=[topic])
434 if not found:
435 ui.write_err(_(b"ERROR: no such topic: %s\n") % topic)
436 sys.exit(1)
437
438 if wraptpl:
439 header = _rendertpl(
440 'topicheader.txt',
441 {'topicname': topic, 'topictitle': minirst.section(found[0][1])},
442 )
443 ui.write(header.encode())
444 helpprinter(ui, found, None)
445 return True
446
447
448 def helpprinter(ui, topics, sectionfunc):
449 """Print a help topic
450
451 Args:
452 ui: the UI object to output to
453 topics: a list of help topics to output
454 sectionfunc: a callback to write the section title
455 """
456 for h in topics:
457 names, sec, doc = h[0:3]
458 for name in names:
459 ui.write(b".. _%s:\n" % name)
460 ui.write(b"\n")
461 if sectionfunc:
462 ui.write(sectionfunc(sec))
463 if callable(doc):
464 doc = doc(ui)
465 ui.write(doc)
466 ui.write(b"\n")
467
468
469 def showextension(ui, extensionname, debugcmds=False):
470 """Render the help text for an extension
471
472 Args:
473 ui: the UI object to output to
474 extensionname: the name of the extension to output
475 debugcmds: whether to include the extension's debug commands, if any
476 """
477 mod = extensions.load(ui, extensionname, None)
478
479 header = _rendertpl(
480 'extheader.txt',
481 {'extname': extensionname, 'exttitle': minirst.section(extensionname)},
482 )
483 ui.write(header.encode())
484
485 shortdoc, longdoc = _splitdoc(mod)
486 if shortdoc:
487 ui.write(b"%s\n\n" % gettext(shortdoc))
488 if longdoc:
489 ui.write(minirst.subsection(_(b"Description")))
490 ui.write(b"%s\n\n" % gettext(longdoc))
491
492 cmdtable = getattr(mod, 'cmdtable', None)
493 if cmdtable:
494 ui.write(minirst.subsection(_(b'Commands')))
495 commandprinter(
496 ui,
497 cmdtable,
498 minirst.subsubsection,
499 minirst.subsubsubsection,
500 debugcmds=debugcmds,
501 )
502
503
504 def commandprinter(ui, cmdtable, sectionfunc, subsectionfunc, debugcmds=False):
505 """Render restructuredtext describing a list of commands and their
506 documentations, grouped by command category.
507
508 Args:
509 ui: UI object to write the output to
510 cmdtable: a dict that maps a string of the command name plus its aliases
511 (separated with pipes) to a 3-tuple of (the command's function, a list
512 of its option descriptions, and a string summarizing available
513 options). Example, with aliases added for demonstration purposes:
514
515 'phase|alias1|alias2': (
516 <function phase at 0x7f0816b05e60>,
517 [ ('p', 'public', False, 'set changeset phase to public'),
518 ...,
519 ('r', 'rev', [], 'target revision', 'REV')],
520 '[-p|-d|-s] [-f] [-r] [REV...]'
521 )
522 sectionfunc: minirst function to format command category headers
523 subsectionfunc: minirst function to format command headers
524 """
525 h = allcommandnames(cmdtable, debugcmds=debugcmds)
526 cmds = h.keys()
527
528 def helpcategory(cmd):
529 """Given a canonical command name from `cmds` (above), retrieve its
530 help category. If helpcategory is None, default to CATEGORY_NONE.
531 """
532 fullname = h[cmd]
533 details = cmdtable[fullname]
534 helpcategory = details[0].helpcategory
535 return helpcategory or help.registrar.command.CATEGORY_NONE
536
537 cmdsbycategory = {category: [] for category in help.CATEGORY_ORDER}
538 for cmd in cmds:
539 # If a command category wasn't registered, the command won't get
540 # rendered below, so we raise an AssertionError.
541 if helpcategory(cmd) not in cmdsbycategory:
542 raise AssertionError(
543 "The following command did not register its (category) in "
544 "help.CATEGORY_ORDER: %s (%s)" % (cmd, helpcategory(cmd))
545 )
546 cmdsbycategory[helpcategory(cmd)].append(cmd)
547
548 # Print the help for each command. We present the commands grouped by
549 # category, and we use help.CATEGORY_ORDER as a guide for a helpful order
550 # in which to present the categories.
551 for category in help.CATEGORY_ORDER:
552 categorycmds = cmdsbycategory[category]
553 if not categorycmds:
554 # Skip empty categories
555 continue
556 # Print a section header for the category.
557 # For now, the category header is at the same level as the headers for
558 # the commands in the category; this is fixed in the next commit.
559 ui.write(sectionfunc(help.CATEGORY_NAMES[category]))
560 # Print each command in the category
561 for f in sorted(categorycmds):
562 d = get_cmd(h[f], cmdtable)
563 ui.write(subsectionfunc(d[b'cmd']))
564 # short description
565 ui.write(d[b'desc'][0])
566 # synopsis
567 ui.write(b"::\n\n")
568 synopsislines = d[b'synopsis'].splitlines()
569 for line in synopsislines:
570 # some commands (such as rebase) have a multi-line
571 # synopsis
572 ui.write(b" %s\n" % line)
573 ui.write(b'\n')
574 # description
575 ui.write(b"%s\n\n" % d[b'desc'][1])
576
577 # options
578 def _optsection(s):
579 return b"%s:\n\n" % s
580
581 _optionsprinter(ui, d, _optsection)
582 # aliases
583 if d[b'aliases']:
584 # Note the empty comment, this is required to separate this
585 # (which should be a blockquote) from any preceding things (such
586 # as a definition list).
587 ui.write(
588 _(b"..\n\n aliases: %s\n\n") % b" ".join(d[b'aliases'])
589 )
590
591
592 def _optionsprinter(ui, cmd, sectionfunc):
593 """Outputs the list of options for a given command object"""
594 opt_output = list(cmd[b'opts'])
595 if opt_output:
596 opts_len = max([len(line[0]) for line in opt_output])
597 ui.write(sectionfunc(_(b"Options")))
598 multioccur = False
599 for optstr, desc in opt_output:
600 if desc:
601 s = b"%-*s %s" % (opts_len, optstr, desc)
602 else:
603 s = optstr
604 ui.write(b"%s\n" % s)
605 if optstr.endswith(b"[+]>"):
606 multioccur = True
607 if multioccur:
608 ui.write(
609 _(b"\n[+] marked option can be specified multiple times\n")
610 )
611 ui.write(b"\n")
612
613
614 def allcommandnames(cmdtable, debugcmds=False):
615 """Get a collection of all command names in the given command table
616
617 Args:
618 cmdtable: the command table to get the names from
619 debugcmds: whether to include debug commands
620
621 Returns a dictionary where the keys are the main command names, and the
622 values are the "raw" names (in the form of `name|alias1|alias2`).
623 """
624 allcmdnames = {}
625 for rawnames, attr in cmdtable.items():
626 mainname = rawnames.split(b"|")[0].lstrip(b"^")
627 if not debugcmds and mainname.startswith(b"debug"):
628 continue
629 allcmdnames[mainname] = rawnames
630 return allcmdnames
631
632
633 def allextensionnames():
634 """Get a set of all known extension names"""
635 return set(extensions.enabled().keys()) | set(extensions.disabled().keys())
636
637
638 if __name__ == "__main__":
639 parser = argparse.ArgumentParser(
640 prog='gendoc', description="Generate mercurial documentation files"
641 )
642 parser.add_argument('doc', default='hg.1.gendoc', nargs='?')
643 parser.add_argument(
644 '-d',
645 '--debug-cmds',
646 action='store_true',
647 help="Show debug commands in help pages",
648 )
649 args = parser.parse_args()
650
651 doc = encoding.strtolocal(args.doc)
652 debugcmds = args.debug_cmds
653
654 ui = uimod.ui.load()
655 # Trigger extensions to load. This is disabled by default because it uses
656 # the current user's configuration, which is often not what is wanted.
657 if encoding.environ.get(b'GENDOC_LOAD_CONFIGURED_EXTENSIONS', b'0') != b'0':
658 extensions.loadall(ui)
659
660 # ui.debugflag determines if the help module returns debug commands to us.
661 ui.debugflag = debugcmds
662
663 # Render the 'all-in-one' giant documentation file
664 if doc == b'hg.1.gendoc':
665 showdoc(ui)
666 # Render a command/help-topic/extension name list (for internal use)
667 elif doc == b'commandlist':
668 showcommandlist(ui, debugcmds=debugcmds)
669 elif doc == b'topiclist':
670 showtopiclist(ui)
671 elif doc == b'extensionlist':
672 showextensionlist(ui)
673 # Render the help index/main page
674 elif doc == b'index':
675 showhelpindex(ui, debugcmds=debugcmds)
676 # Render an individual command/help-topic/extension page
677 elif doc.startswith(b'cmd-'):
678 showcommand(ui, doc[4:])
679 elif doc.startswith(b'topic-'):
680 showtopic(ui, doc[6:], wraptpl=True)
681 elif doc.startswith(b'ext-'):
682 showextension(ui, doc[4:], debugcmds=debugcmds)
683 # Render a help-topic page without any title/footer, for later inclusion
684 # into a hand-written help text file
685 else:
686 showtopic(ui, doc)