##// END OF EJS Templates
py3: byteify sys.argv in gendoc.py
Matt Harbison -
r41059:c0865f3d default
parent child Browse files
Show More
@@ -1,239 +1,240 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """usage: %s DOC ...
2 """usage: %s DOC ...
3
3
4 where DOC is the name of a document
4 where DOC is the name of a document
5 """
5 """
6
6
7 from __future__ import absolute_import
7 from __future__ import absolute_import
8
8
9 import os
9 import os
10 import sys
10 import sys
11 import textwrap
11 import textwrap
12
12
13 try:
13 try:
14 import msvcrt
14 import msvcrt
15 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
15 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
16 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
16 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
17 except ImportError:
17 except ImportError:
18 pass
18 pass
19
19
20 # This script is executed during installs and may not have C extensions
20 # This script is executed during installs and may not have C extensions
21 # available. Relax C module requirements.
21 # available. Relax C module requirements.
22 os.environ[r'HGMODULEPOLICY'] = r'allow'
22 os.environ[r'HGMODULEPOLICY'] = r'allow'
23 # import from the live mercurial repo
23 # import from the live mercurial repo
24 sys.path.insert(0, r"..")
24 sys.path.insert(0, r"..")
25 from mercurial import demandimport; demandimport.enable()
25 from mercurial import demandimport; demandimport.enable()
26 # Load util so that the locale path is set by i18n.setdatapath() before
26 # Load util so that the locale path is set by i18n.setdatapath() before
27 # calling _().
27 # calling _().
28 from mercurial import util
28 from mercurial import util
29 util.datapath
29 util.datapath
30 from mercurial import (
30 from mercurial import (
31 commands,
31 commands,
32 encoding,
32 extensions,
33 extensions,
33 help,
34 help,
34 minirst,
35 minirst,
35 pycompat,
36 pycompat,
36 ui as uimod,
37 ui as uimod,
37 )
38 )
38 from mercurial.i18n import (
39 from mercurial.i18n import (
39 gettext,
40 gettext,
40 _,
41 _,
41 )
42 )
42
43
43 table = commands.table
44 table = commands.table
44 globalopts = commands.globalopts
45 globalopts = commands.globalopts
45 helptable = help.helptable
46 helptable = help.helptable
46 loaddoc = help.loaddoc
47 loaddoc = help.loaddoc
47
48
48 def get_desc(docstr):
49 def get_desc(docstr):
49 if not docstr:
50 if not docstr:
50 return b"", b""
51 return b"", b""
51 # sanitize
52 # sanitize
52 docstr = docstr.strip(b"\n")
53 docstr = docstr.strip(b"\n")
53 docstr = docstr.rstrip()
54 docstr = docstr.rstrip()
54 shortdesc = docstr.splitlines()[0].strip()
55 shortdesc = docstr.splitlines()[0].strip()
55
56
56 i = docstr.find(b"\n")
57 i = docstr.find(b"\n")
57 if i != -1:
58 if i != -1:
58 desc = docstr[i + 2:]
59 desc = docstr[i + 2:]
59 else:
60 else:
60 desc = shortdesc
61 desc = shortdesc
61
62
62 desc = textwrap.dedent(desc.decode('latin1')).encode('latin1')
63 desc = textwrap.dedent(desc.decode('latin1')).encode('latin1')
63
64
64 return (shortdesc, desc)
65 return (shortdesc, desc)
65
66
66 def get_opts(opts):
67 def get_opts(opts):
67 for opt in opts:
68 for opt in opts:
68 if len(opt) == 5:
69 if len(opt) == 5:
69 shortopt, longopt, default, desc, optlabel = opt
70 shortopt, longopt, default, desc, optlabel = opt
70 else:
71 else:
71 shortopt, longopt, default, desc = opt
72 shortopt, longopt, default, desc = opt
72 optlabel = _(b"VALUE")
73 optlabel = _(b"VALUE")
73 allopts = []
74 allopts = []
74 if shortopt:
75 if shortopt:
75 allopts.append(b"-%s" % shortopt)
76 allopts.append(b"-%s" % shortopt)
76 if longopt:
77 if longopt:
77 allopts.append(b"--%s" % longopt)
78 allopts.append(b"--%s" % longopt)
78 if isinstance(default, list):
79 if isinstance(default, list):
79 allopts[-1] += b" <%s[+]>" % optlabel
80 allopts[-1] += b" <%s[+]>" % optlabel
80 elif (default is not None) and not isinstance(default, bool):
81 elif (default is not None) and not isinstance(default, bool):
81 allopts[-1] += b" <%s>" % optlabel
82 allopts[-1] += b" <%s>" % optlabel
82 if b'\n' in desc:
83 if b'\n' in desc:
83 # only remove line breaks and indentation
84 # only remove line breaks and indentation
84 desc = b' '.join(l.lstrip() for l in desc.split(b'\n'))
85 desc = b' '.join(l.lstrip() for l in desc.split(b'\n'))
85 desc += default and _(b" (default: %s)") % bytes(default) or b""
86 desc += default and _(b" (default: %s)") % bytes(default) or b""
86 yield (b", ".join(allopts), desc)
87 yield (b", ".join(allopts), desc)
87
88
88 def get_cmd(cmd, cmdtable):
89 def get_cmd(cmd, cmdtable):
89 d = {}
90 d = {}
90 attr = cmdtable[cmd]
91 attr = cmdtable[cmd]
91 cmds = cmd.lstrip(b"^").split(b"|")
92 cmds = cmd.lstrip(b"^").split(b"|")
92
93
93 d[b'cmd'] = cmds[0]
94 d[b'cmd'] = cmds[0]
94 d[b'aliases'] = cmd.split(b"|")[1:]
95 d[b'aliases'] = cmd.split(b"|")[1:]
95 d[b'desc'] = get_desc(gettext(pycompat.getdoc(attr[0])))
96 d[b'desc'] = get_desc(gettext(pycompat.getdoc(attr[0])))
96 d[b'opts'] = list(get_opts(attr[1]))
97 d[b'opts'] = list(get_opts(attr[1]))
97
98
98 s = b'hg ' + cmds[0]
99 s = b'hg ' + cmds[0]
99 if len(attr) > 2:
100 if len(attr) > 2:
100 if not attr[2].startswith(b'hg'):
101 if not attr[2].startswith(b'hg'):
101 s += b' ' + attr[2]
102 s += b' ' + attr[2]
102 else:
103 else:
103 s = attr[2]
104 s = attr[2]
104 d[b'synopsis'] = s.strip()
105 d[b'synopsis'] = s.strip()
105
106
106 return d
107 return d
107
108
108 def showdoc(ui):
109 def showdoc(ui):
109 # print options
110 # print options
110 ui.write(minirst.section(_(b"Options")))
111 ui.write(minirst.section(_(b"Options")))
111 multioccur = False
112 multioccur = False
112 for optstr, desc in get_opts(globalopts):
113 for optstr, desc in get_opts(globalopts):
113 ui.write(b"%s\n %s\n\n" % (optstr, desc))
114 ui.write(b"%s\n %s\n\n" % (optstr, desc))
114 if optstr.endswith(b"[+]>"):
115 if optstr.endswith(b"[+]>"):
115 multioccur = True
116 multioccur = True
116 if multioccur:
117 if multioccur:
117 ui.write(_(b"\n[+] marked option can be specified multiple times\n"))
118 ui.write(_(b"\n[+] marked option can be specified multiple times\n"))
118 ui.write(b"\n")
119 ui.write(b"\n")
119
120
120 # print cmds
121 # print cmds
121 ui.write(minirst.section(_(b"Commands")))
122 ui.write(minirst.section(_(b"Commands")))
122 commandprinter(ui, table, minirst.subsection)
123 commandprinter(ui, table, minirst.subsection)
123
124
124 # print help topics
125 # print help topics
125 # The config help topic is included in the hgrc.5 man page.
126 # The config help topic is included in the hgrc.5 man page.
126 helpprinter(ui, helptable, minirst.section, exclude=[b'config'])
127 helpprinter(ui, helptable, minirst.section, exclude=[b'config'])
127
128
128 ui.write(minirst.section(_(b"Extensions")))
129 ui.write(minirst.section(_(b"Extensions")))
129 ui.write(_(b"This section contains help for extensions that are "
130 ui.write(_(b"This section contains help for extensions that are "
130 b"distributed together with Mercurial. Help for other "
131 b"distributed together with Mercurial. Help for other "
131 b"extensions is available in the help system."))
132 b"extensions is available in the help system."))
132 ui.write((b"\n\n"
133 ui.write((b"\n\n"
133 b".. contents::\n"
134 b".. contents::\n"
134 b" :class: htmlonly\n"
135 b" :class: htmlonly\n"
135 b" :local:\n"
136 b" :local:\n"
136 b" :depth: 1\n\n"))
137 b" :depth: 1\n\n"))
137
138
138 for extensionname in sorted(allextensionnames()):
139 for extensionname in sorted(allextensionnames()):
139 mod = extensions.load(ui, extensionname, None)
140 mod = extensions.load(ui, extensionname, None)
140 ui.write(minirst.subsection(extensionname))
141 ui.write(minirst.subsection(extensionname))
141 ui.write(b"%s\n\n" % gettext(pycompat.getdoc(mod)))
142 ui.write(b"%s\n\n" % gettext(pycompat.getdoc(mod)))
142 cmdtable = getattr(mod, 'cmdtable', None)
143 cmdtable = getattr(mod, 'cmdtable', None)
143 if cmdtable:
144 if cmdtable:
144 ui.write(minirst.subsubsection(_(b'Commands')))
145 ui.write(minirst.subsubsection(_(b'Commands')))
145 commandprinter(ui, cmdtable, minirst.subsubsubsection)
146 commandprinter(ui, cmdtable, minirst.subsubsubsection)
146
147
147 def showtopic(ui, topic):
148 def showtopic(ui, topic):
148 extrahelptable = [
149 extrahelptable = [
149 ([b"common"], b'', loaddoc(b'common'), help.TOPIC_CATEGORY_MISC),
150 ([b"common"], b'', loaddoc(b'common'), help.TOPIC_CATEGORY_MISC),
150 ([b"hg.1"], b'', loaddoc(b'hg.1'), help.TOPIC_CATEGORY_CONFIG),
151 ([b"hg.1"], b'', loaddoc(b'hg.1'), help.TOPIC_CATEGORY_CONFIG),
151 ([b"hg-ssh.8"], b'', loaddoc(b'hg-ssh.8'), help.TOPIC_CATEGORY_CONFIG),
152 ([b"hg-ssh.8"], b'', loaddoc(b'hg-ssh.8'), help.TOPIC_CATEGORY_CONFIG),
152 ([b"hgignore.5"], b'', loaddoc(b'hgignore.5'),
153 ([b"hgignore.5"], b'', loaddoc(b'hgignore.5'),
153 help.TOPIC_CATEGORY_CONFIG),
154 help.TOPIC_CATEGORY_CONFIG),
154 ([b"hgrc.5"], b'', loaddoc(b'hgrc.5'), help.TOPIC_CATEGORY_CONFIG),
155 ([b"hgrc.5"], b'', loaddoc(b'hgrc.5'), help.TOPIC_CATEGORY_CONFIG),
155 ([b"hgignore.5.gendoc"], b'', loaddoc(b'hgignore'),
156 ([b"hgignore.5.gendoc"], b'', loaddoc(b'hgignore'),
156 help.TOPIC_CATEGORY_CONFIG),
157 help.TOPIC_CATEGORY_CONFIG),
157 ([b"hgrc.5.gendoc"], b'', loaddoc(b'config'),
158 ([b"hgrc.5.gendoc"], b'', loaddoc(b'config'),
158 help.TOPIC_CATEGORY_CONFIG),
159 help.TOPIC_CATEGORY_CONFIG),
159 ]
160 ]
160 helpprinter(ui, helptable + extrahelptable, None, include=[topic])
161 helpprinter(ui, helptable + extrahelptable, None, include=[topic])
161
162
162 def helpprinter(ui, helptable, sectionfunc, include=[], exclude=[]):
163 def helpprinter(ui, helptable, sectionfunc, include=[], exclude=[]):
163 for h in helptable:
164 for h in helptable:
164 names, sec, doc = h[0:3]
165 names, sec, doc = h[0:3]
165 if exclude and names[0] in exclude:
166 if exclude and names[0] in exclude:
166 continue
167 continue
167 if include and names[0] not in include:
168 if include and names[0] not in include:
168 continue
169 continue
169 for name in names:
170 for name in names:
170 ui.write(b".. _%s:\n" % name)
171 ui.write(b".. _%s:\n" % name)
171 ui.write(b"\n")
172 ui.write(b"\n")
172 if sectionfunc:
173 if sectionfunc:
173 ui.write(sectionfunc(sec))
174 ui.write(sectionfunc(sec))
174 if callable(doc):
175 if callable(doc):
175 doc = doc(ui)
176 doc = doc(ui)
176 ui.write(doc)
177 ui.write(doc)
177 ui.write(b"\n")
178 ui.write(b"\n")
178
179
179 def commandprinter(ui, cmdtable, sectionfunc):
180 def commandprinter(ui, cmdtable, sectionfunc):
180 h = {}
181 h = {}
181 for c, attr in cmdtable.items():
182 for c, attr in cmdtable.items():
182 f = c.split(b"|")[0]
183 f = c.split(b"|")[0]
183 f = f.lstrip(b"^")
184 f = f.lstrip(b"^")
184 h[f] = c
185 h[f] = c
185 cmds = h.keys()
186 cmds = h.keys()
186
187
187 for f in sorted(cmds):
188 for f in sorted(cmds):
188 if f.startswith(b"debug"):
189 if f.startswith(b"debug"):
189 continue
190 continue
190 d = get_cmd(h[f], cmdtable)
191 d = get_cmd(h[f], cmdtable)
191 ui.write(sectionfunc(d[b'cmd']))
192 ui.write(sectionfunc(d[b'cmd']))
192 # short description
193 # short description
193 ui.write(d[b'desc'][0])
194 ui.write(d[b'desc'][0])
194 # synopsis
195 # synopsis
195 ui.write(b"::\n\n")
196 ui.write(b"::\n\n")
196 synopsislines = d[b'synopsis'].splitlines()
197 synopsislines = d[b'synopsis'].splitlines()
197 for line in synopsislines:
198 for line in synopsislines:
198 # some commands (such as rebase) have a multi-line
199 # some commands (such as rebase) have a multi-line
199 # synopsis
200 # synopsis
200 ui.write(b" %s\n" % line)
201 ui.write(b" %s\n" % line)
201 ui.write(b'\n')
202 ui.write(b'\n')
202 # description
203 # description
203 ui.write(b"%s\n\n" % d[b'desc'][1])
204 ui.write(b"%s\n\n" % d[b'desc'][1])
204 # options
205 # options
205 opt_output = list(d[b'opts'])
206 opt_output = list(d[b'opts'])
206 if opt_output:
207 if opt_output:
207 opts_len = max([len(line[0]) for line in opt_output])
208 opts_len = max([len(line[0]) for line in opt_output])
208 ui.write(_(b"Options:\n\n"))
209 ui.write(_(b"Options:\n\n"))
209 multioccur = False
210 multioccur = False
210 for optstr, desc in opt_output:
211 for optstr, desc in opt_output:
211 if desc:
212 if desc:
212 s = b"%-*s %s" % (opts_len, optstr, desc)
213 s = b"%-*s %s" % (opts_len, optstr, desc)
213 else:
214 else:
214 s = optstr
215 s = optstr
215 ui.write(b"%s\n" % s)
216 ui.write(b"%s\n" % s)
216 if optstr.endswith(b"[+]>"):
217 if optstr.endswith(b"[+]>"):
217 multioccur = True
218 multioccur = True
218 if multioccur:
219 if multioccur:
219 ui.write(_(b"\n[+] marked option can be specified"
220 ui.write(_(b"\n[+] marked option can be specified"
220 b" multiple times\n"))
221 b" multiple times\n"))
221 ui.write(b"\n")
222 ui.write(b"\n")
222 # aliases
223 # aliases
223 if d[b'aliases']:
224 if d[b'aliases']:
224 ui.write(_(b" aliases: %s\n\n") % b" ".join(d[b'aliases']))
225 ui.write(_(b" aliases: %s\n\n") % b" ".join(d[b'aliases']))
225
226
226
227
227 def allextensionnames():
228 def allextensionnames():
228 return set(extensions.enabled().keys()) | set(extensions.disabled().keys())
229 return set(extensions.enabled().keys()) | set(extensions.disabled().keys())
229
230
230 if __name__ == "__main__":
231 if __name__ == "__main__":
231 doc = b'hg.1.gendoc'
232 doc = b'hg.1.gendoc'
232 if len(sys.argv) > 1:
233 if len(sys.argv) > 1:
233 doc = sys.argv[1]
234 doc = encoding.strtolocal(sys.argv[1])
234
235
235 ui = uimod.ui.load()
236 ui = uimod.ui.load()
236 if doc == b'hg.1.gendoc':
237 if doc == b'hg.1.gendoc':
237 showdoc(ui)
238 showdoc(ui)
238 else:
239 else:
239 showtopic(ui, sys.argv[1])
240 showtopic(ui, sys.argv[1])
General Comments 0
You need to be logged in to leave comments. Login now