##// END OF EJS Templates
black: blacken scripts...
Gregory Szorc -
r44089:47ef023d default
parent child Browse files
Show More
@@ -15,6 +15,7 b' import sys'
15
15
16 try:
16 try:
17 import msvcrt
17 import msvcrt
18
18 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
19 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
19 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
20 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
20 except ImportError:
21 except ImportError:
@@ -25,14 +26,18 b" stdout = getattr(sys.stdout, 'buffer', s"
25 leadingline = re.compile(br'(^\s*)(\S.*)$')
26 leadingline = re.compile(br'(^\s*)(\S.*)$')
26
27
27 checks = [
28 checks = [
28 (br""":hg:`[^`]*'[^`]*`""",
29 (
29 b"""warning: please avoid nesting ' in :hg:`...`"""),
30 br""":hg:`[^`]*'[^`]*`""",
30 (br'\w:hg:`',
31 b"""warning: please avoid nesting ' in :hg:`...`""",
31 b'warning: please have a space before :hg:'),
32 ),
32 (br"""(?:[^a-z][^'.])hg ([^,;"`]*'(?!hg)){2}""",
33 (br'\w:hg:`', b'warning: please have a space before :hg:'),
33 b'''warning: please use " instead of ' for hg ... "..."'''),
34 (
35 br"""(?:[^a-z][^'.])hg ([^,;"`]*'(?!hg)){2}""",
36 b'''warning: please use " instead of ' for hg ... "..."''',
37 ),
34 ]
38 ]
35
39
40
36 def check(line):
41 def check(line):
37 messages = []
42 messages = []
38 for match, msg in checks:
43 for match, msg in checks:
@@ -43,6 +48,7 b' def check(line):'
43 for msg in messages:
48 for msg in messages:
44 stdout.write(b'%s\n' % msg)
49 stdout.write(b'%s\n' % msg)
45
50
51
46 def work(file):
52 def work(file):
47 (llead, lline) = (b'', b'')
53 (llead, lline) = (b'', b'')
48
54
@@ -55,8 +61,8 b' def work(file):'
55 continue
61 continue
56
62
57 lead, line = match.group(1), match.group(2)
63 lead, line = match.group(1), match.group(2)
58 if (lead == llead):
64 if lead == llead:
59 if (lline != b''):
65 if lline != b'':
60 lline += b' ' + line
66 lline += b' ' + line
61 else:
67 else:
62 lline = line
68 lline = line
@@ -65,6 +71,7 b' def work(file):'
65 (llead, lline) = (lead, line)
71 (llead, lline) = (lead, line)
66 check(lline)
72 check(lline)
67
73
74
68 def main():
75 def main():
69 for f in sys.argv[1:]:
76 for f in sys.argv[1:]:
70 try:
77 try:
@@ -73,4 +80,5 b' def main():'
73 except BaseException as e:
80 except BaseException as e:
74 sys.stdout.write(r"failed to process %s: %s\n" % (f, e))
81 sys.stdout.write(r"failed to process %s: %s\n" % (f, e))
75
82
83
76 main()
84 main()
@@ -15,18 +15,24 b' where WRITER is the name of a Docutils w'
15 from __future__ import absolute_import
15 from __future__ import absolute_import
16
16
17 import sys
17 import sys
18
18 try:
19 try:
19 import docutils.core as core
20 import docutils.core as core
20 import docutils.nodes as nodes
21 import docutils.nodes as nodes
21 import docutils.utils as utils
22 import docutils.utils as utils
22 import docutils.parsers.rst.roles as roles
23 import docutils.parsers.rst.roles as roles
23 except ImportError:
24 except ImportError:
24 sys.stderr.write("abort: couldn't generate documentation: docutils "
25 sys.stderr.write(
25 "module is missing\n")
26 "abort: couldn't generate documentation: docutils "
26 sys.stderr.write("please install python-docutils or see "
27 "module is missing\n"
27 "http://docutils.sourceforge.net/\n")
28 )
29 sys.stderr.write(
30 "please install python-docutils or see "
31 "http://docutils.sourceforge.net/\n"
32 )
28 sys.exit(-1)
33 sys.exit(-1)
29
34
35
30 def role_hg(name, rawtext, text, lineno, inliner, options=None, content=None):
36 def role_hg(name, rawtext, text, lineno, inliner, options=None, content=None):
31 text = "hg " + utils.unescape(text)
37 text = "hg " + utils.unescape(text)
32 linktext = nodes.literal(rawtext, text)
38 linktext = nodes.literal(rawtext, text)
@@ -46,10 +52,10 b' def role_hg(name, rawtext, text, lineno,'
46 refuri = "hg.1.html#%s" % args[1]
52 refuri = "hg.1.html#%s" % args[1]
47 else:
53 else:
48 refuri = "hg.1.html#%s" % args[0]
54 refuri = "hg.1.html#%s" % args[0]
49 node = nodes.reference(rawtext, '', linktext,
55 node = nodes.reference(rawtext, '', linktext, refuri=refuri)
50 refuri=refuri)
51 return [node], []
56 return [node], []
52
57
58
53 roles.register_local_role("hg", role_hg)
59 roles.register_local_role("hg", role_hg)
54
60
55 if __name__ == "__main__":
61 if __name__ == "__main__":
@@ -8,12 +8,15 b' config = "/path/to/repo/or/config"'
8
8
9 # Uncomment and adjust if Mercurial is not installed system-wide
9 # Uncomment and adjust if Mercurial is not installed system-wide
10 # (consult "installed modules" path from 'hg debuginstall'):
10 # (consult "installed modules" path from 'hg debuginstall'):
11 #import sys; sys.path.insert(0, "/path/to/python/lib")
11 # import sys; sys.path.insert(0, "/path/to/python/lib")
12
12
13 # Uncomment to send python tracebacks to the browser if an error occurs:
13 # Uncomment to send python tracebacks to the browser if an error occurs:
14 #import cgitb; cgitb.enable()
14 # import cgitb; cgitb.enable()
15
16 from mercurial import demandimport
15
17
16 from mercurial import demandimport; demandimport.enable()
18 demandimport.enable()
17 from mercurial.hgweb import hgweb, wsgicgi
19 from mercurial.hgweb import hgweb, wsgicgi
20
18 application = hgweb(config)
21 application = hgweb(config)
19 wsgicgi.launch(application)
22 wsgicgi.launch(application)
@@ -57,18 +57,22 b' def normalize(s):'
57
57
58
58
59 def poentry(path, lineno, s):
59 def poentry(path, lineno, s):
60 return ('#: %s:%d\n' % (path, lineno) +
60 return (
61 'msgid %s\n' % normalize(s) +
61 '#: %s:%d\n' % (path, lineno)
62 'msgstr ""\n')
62 + 'msgid %s\n' % normalize(s)
63 + 'msgstr ""\n'
64 )
65
63
66
64 doctestre = re.compile(r'^ +>>> ', re.MULTILINE)
67 doctestre = re.compile(r'^ +>>> ', re.MULTILINE)
65
68
69
66 def offset(src, doc, name, lineno, default):
70 def offset(src, doc, name, lineno, default):
67 """Compute offset or issue a warning on stdout."""
71 """Compute offset or issue a warning on stdout."""
68 # remove doctest part, in order to avoid backslash mismatching
72 # remove doctest part, in order to avoid backslash mismatching
69 m = doctestre.search(doc)
73 m = doctestre.search(doc)
70 if m:
74 if m:
71 doc = doc[:m.start()]
75 doc = doc[: m.start()]
72
76
73 # Backslashes in doc appear doubled in src.
77 # Backslashes in doc appear doubled in src.
74 end = src.find(doc.replace('\\', '\\\\'))
78 end = src.find(doc.replace('\\', '\\\\'))
@@ -76,9 +80,11 b' def offset(src, doc, name, lineno, defau'
76 # This can happen if the docstring contains unnecessary escape
80 # This can happen if the docstring contains unnecessary escape
77 # sequences such as \" in a triple-quoted string. The problem
81 # sequences such as \" in a triple-quoted string. The problem
78 # is that \" is turned into " and so doc wont appear in src.
82 # is that \" is turned into " and so doc wont appear in src.
79 sys.stderr.write("%s:%d:warning:"
83 sys.stderr.write(
80 " unknown docstr offset, assuming %d lines\n"
84 "%s:%d:warning:"
81 % (name, lineno, default))
85 " unknown docstr offset, assuming %d lines\n"
86 % (name, lineno, default)
87 )
82 return default
88 return default
83 else:
89 else:
84 return src.count('\n', 0, end)
90 return src.count('\n', 0, end)
@@ -121,7 +127,7 b' def docstrings(path):'
121
127
122 for func, rstrip in functions:
128 for func, rstrip in functions:
123 if func.__doc__:
129 if func.__doc__:
124 docobj = func # this might be a proxy to provide formatted doc
130 docobj = func # this might be a proxy to provide formatted doc
125 func = getattr(func, '_origfunc', func)
131 func = getattr(func, '_origfunc', func)
126 funcmod = inspect.getmodule(func)
132 funcmod = inspect.getmodule(func)
127 extra = ''
133 extra = ''
@@ -155,7 +161,9 b' if __name__ == "__main__":'
155 # accidentally import and extract strings from a Mercurial
161 # accidentally import and extract strings from a Mercurial
156 # installation mentioned in PYTHONPATH.
162 # installation mentioned in PYTHONPATH.
157 sys.path.insert(0, os.getcwd())
163 sys.path.insert(0, os.getcwd())
158 from mercurial import demandimport; demandimport.enable()
164 from mercurial import demandimport
165
166 demandimport.enable()
159 for path in sys.argv[1:]:
167 for path in sys.argv[1:]:
160 if path.endswith('.txt'):
168 if path.endswith('.txt'):
161 rawtext(path)
169 rawtext(path)
@@ -11,6 +11,7 b' import polib'
11 import re
11 import re
12 import sys
12 import sys
13
13
14
14 def addentry(po, entry, cache):
15 def addentry(po, entry, cache):
15 e = cache.get(entry.msgid)
16 e = cache.get(entry.msgid)
16 if e:
17 if e:
@@ -27,6 +28,7 b' def addentry(po, entry, cache):'
27 po.append(entry)
28 po.append(entry)
28 cache[entry.msgid] = entry
29 cache[entry.msgid] = entry
29
30
31
30 def mkentry(orig, delta, msgid, msgstr):
32 def mkentry(orig, delta, msgid, msgstr):
31 entry = polib.POEntry()
33 entry = polib.POEntry()
32 entry.merge(orig)
34 entry.merge(orig)
@@ -35,13 +37,14 b' def mkentry(orig, delta, msgid, msgstr):'
35 entry.occurrences = [(p, int(l) + delta) for (p, l) in orig.occurrences]
37 entry.occurrences = [(p, int(l) + delta) for (p, l) in orig.occurrences]
36 return entry
38 return entry
37
39
40
38 if __name__ == "__main__":
41 if __name__ == "__main__":
39 po = polib.pofile(sys.argv[1])
42 po = polib.pofile(sys.argv[1])
40
43
41 cache = {}
44 cache = {}
42 entries = po[:]
45 entries = po[:]
43 po[:] = []
46 po[:] = []
44 findd = re.compile(r' *\.\. (\w+)::') # for finding directives
47 findd = re.compile(r' *\.\. (\w+)::') # for finding directives
45 for entry in entries:
48 for entry in entries:
46 msgids = entry.msgid.split(u'\n\n')
49 msgids = entry.msgid.split(u'\n\n')
47 if entry.msgstr:
50 if entry.msgstr:
@@ -65,7 +68,7 b' if __name__ == "__main__":'
65 newentry = mkentry(entry, delta, msgid, msgstr)
68 newentry = mkentry(entry, delta, msgid, msgstr)
66 mdirective = findd.match(msgid)
69 mdirective = findd.match(msgid)
67 if mdirective:
70 if mdirective:
68 if not msgid[mdirective.end():].rstrip():
71 if not msgid[mdirective.end() :].rstrip():
69 # only directive, nothing to translate here
72 # only directive, nothing to translate here
70 delta += 2
73 delta += 2
71 continue
74 continue
@@ -77,8 +80,10 b' if __name__ == "__main__":'
77 continue
80 continue
78 else:
81 else:
79 # lines following directly, unexpected
82 # lines following directly, unexpected
80 print('Warning: text follows line with directive'
83 print(
81 ' %s' % directive)
84 'Warning: text follows line with directive'
85 ' %s' % directive
86 )
82 comment = 'do not translate: .. %s::' % directive
87 comment = 'do not translate: .. %s::' % directive
83 if not newentry.comment:
88 if not newentry.comment:
84 newentry.comment = comment
89 newentry.comment = comment
@@ -34,14 +34,18 b' import re'
34 import sys
34 import sys
35
35
36 # Python 3 adapters
36 # Python 3 adapters
37 ispy3 = (sys.version_info[0] >= 3)
37 ispy3 = sys.version_info[0] >= 3
38 if ispy3:
38 if ispy3:
39
39 def iterbytes(s):
40 def iterbytes(s):
40 for i in range(len(s)):
41 for i in range(len(s)):
41 yield s[i:i + 1]
42 yield s[i : i + 1]
43
44
42 else:
45 else:
43 iterbytes = iter
46 iterbytes = iter
44
47
48
45 def visit(opts, filenames, outfile):
49 def visit(opts, filenames, outfile):
46 """Process filenames in the way specified in opts, writing output to
50 """Process filenames in the way specified in opts, writing output to
47 outfile."""
51 outfile."""
@@ -88,21 +92,26 b' def visit(opts, filenames, outfile):'
88 if opts.newer:
92 if opts.newer:
89 # mtime might be in whole seconds so newer file might be same
93 # mtime might be in whole seconds so newer file might be same
90 if stat.st_mtime >= os.stat(opts.newer).st_mtime:
94 if stat.st_mtime >= os.stat(opts.newer).st_mtime:
91 facts.append(b'newer than %s' % opts.newer.encode(
95 facts.append(
92 'utf8', 'replace'))
96 b'newer than %s' % opts.newer.encode('utf8', 'replace')
97 )
93 else:
98 else:
94 facts.append(b'older than %s' % opts.newer.encode(
99 facts.append(
95 'utf8', 'replace'))
100 b'older than %s' % opts.newer.encode('utf8', 'replace')
101 )
96 if opts.md5 and content is not None:
102 if opts.md5 and content is not None:
97 h = hashlib.md5(content)
103 h = hashlib.md5(content)
98 facts.append(b'md5=%s' % binascii.hexlify(h.digest())[:opts.bytes])
104 facts.append(b'md5=%s' % binascii.hexlify(h.digest())[: opts.bytes])
99 if opts.sha1 and content is not None:
105 if opts.sha1 and content is not None:
100 h = hashlib.sha1(content)
106 h = hashlib.sha1(content)
101 facts.append(b'sha1=%s' % binascii.hexlify(h.digest())[:opts.bytes])
107 facts.append(
108 b'sha1=%s' % binascii.hexlify(h.digest())[: opts.bytes]
109 )
102 if opts.sha256 and content is not None:
110 if opts.sha256 and content is not None:
103 h = hashlib.sha256(content)
111 h = hashlib.sha256(content)
104 facts.append(b'sha256=%s' %
112 facts.append(
105 binascii.hexlify(h.digest())[:opts.bytes])
113 b'sha256=%s' % binascii.hexlify(h.digest())[: opts.bytes]
114 )
106 if isstdin:
115 if isstdin:
107 outfile.write(b', '.join(facts) + b'\n')
116 outfile.write(b', '.join(facts) + b'\n')
108 elif facts:
117 elif facts:
@@ -114,21 +123,25 b' def visit(opts, filenames, outfile):'
114 if not islink:
123 if not islink:
115 if opts.lines:
124 if opts.lines:
116 if opts.lines >= 0:
125 if opts.lines >= 0:
117 chunk = b''.join(chunk.splitlines(True)[:opts.lines])
126 chunk = b''.join(chunk.splitlines(True)[: opts.lines])
118 else:
127 else:
119 chunk = b''.join(chunk.splitlines(True)[opts.lines:])
128 chunk = b''.join(chunk.splitlines(True)[opts.lines :])
120 if opts.bytes:
129 if opts.bytes:
121 if opts.bytes >= 0:
130 if opts.bytes >= 0:
122 chunk = chunk[:opts.bytes]
131 chunk = chunk[: opts.bytes]
123 else:
132 else:
124 chunk = chunk[opts.bytes:]
133 chunk = chunk[opts.bytes :]
125 if opts.hexdump:
134 if opts.hexdump:
126 for i in range(0, len(chunk), 16):
135 for i in range(0, len(chunk), 16):
127 s = chunk[i:i + 16]
136 s = chunk[i : i + 16]
128 outfile.write(b'%04x: %-47s |%s|\n' %
137 outfile.write(
129 (i, b' '.join(
138 b'%04x: %-47s |%s|\n'
130 b'%02x' % ord(c) for c in iterbytes(s)),
139 % (
131 re.sub(b'[^ -~]', b'.', s)))
140 i,
141 b' '.join(b'%02x' % ord(c) for c in iterbytes(s)),
142 re.sub(b'[^ -~]', b'.', s),
143 )
144 )
132 if opts.dump:
145 if opts.dump:
133 if not quiet:
146 if not quiet:
134 outfile.write(b'>>>\n')
147 outfile.write(b'>>>\n')
@@ -142,36 +155,60 b' def visit(opts, filenames, outfile):'
142 assert not isstdin
155 assert not isstdin
143 visit(opts, dirfiles, outfile)
156 visit(opts, dirfiles, outfile)
144
157
158
145 if __name__ == "__main__":
159 if __name__ == "__main__":
146 parser = optparse.OptionParser("%prog [options] [filenames]")
160 parser = optparse.OptionParser("%prog [options] [filenames]")
147 parser.add_option("-t", "--type", action="store_true",
161 parser.add_option(
148 help="show file type (file or directory)")
162 "-t",
149 parser.add_option("-m", "--mode", action="store_true",
163 "--type",
150 help="show file mode")
164 action="store_true",
151 parser.add_option("-l", "--links", action="store_true",
165 help="show file type (file or directory)",
152 help="show number of links")
166 )
153 parser.add_option("-s", "--size", action="store_true",
167 parser.add_option(
154 help="show size of file")
168 "-m", "--mode", action="store_true", help="show file mode"
155 parser.add_option("-n", "--newer", action="store",
169 )
156 help="check if file is newer (or same)")
170 parser.add_option(
157 parser.add_option("-r", "--recurse", action="store_true",
171 "-l", "--links", action="store_true", help="show number of links"
158 help="recurse into directories")
172 )
159 parser.add_option("-S", "--sha1", action="store_true",
173 parser.add_option(
160 help="show sha1 hash of the content")
174 "-s", "--size", action="store_true", help="show size of file"
161 parser.add_option("", "--sha256", action="store_true",
175 )
162 help="show sha256 hash of the content")
176 parser.add_option(
163 parser.add_option("-M", "--md5", action="store_true",
177 "-n", "--newer", action="store", help="check if file is newer (or same)"
164 help="show md5 hash of the content")
178 )
165 parser.add_option("-D", "--dump", action="store_true",
179 parser.add_option(
166 help="dump file content")
180 "-r", "--recurse", action="store_true", help="recurse into directories"
167 parser.add_option("-H", "--hexdump", action="store_true",
181 )
168 help="hexdump file content")
182 parser.add_option(
169 parser.add_option("-B", "--bytes", type="int",
183 "-S",
170 help="number of characters to dump")
184 "--sha1",
171 parser.add_option("-L", "--lines", type="int",
185 action="store_true",
172 help="number of lines to dump")
186 help="show sha1 hash of the content",
173 parser.add_option("-q", "--quiet", action="store_true",
187 )
174 help="no default output")
188 parser.add_option(
189 "",
190 "--sha256",
191 action="store_true",
192 help="show sha256 hash of the content",
193 )
194 parser.add_option(
195 "-M", "--md5", action="store_true", help="show md5 hash of the content"
196 )
197 parser.add_option(
198 "-D", "--dump", action="store_true", help="dump file content"
199 )
200 parser.add_option(
201 "-H", "--hexdump", action="store_true", help="hexdump file content"
202 )
203 parser.add_option(
204 "-B", "--bytes", type="int", help="number of characters to dump"
205 )
206 parser.add_option(
207 "-L", "--lines", type="int", help="number of lines to dump"
208 )
209 parser.add_option(
210 "-q", "--quiet", action="store_true", help="no default output"
211 )
175 (opts, filenames) = parser.parse_args(sys.argv[1:])
212 (opts, filenames) = parser.parse_args(sys.argv[1:])
176 if not filenames:
213 if not filenames:
177 filenames = ['-']
214 filenames = ['-']
@@ -13,11 +13,13 b' import sys'
13
13
14 checks = hghave.checks
14 checks = hghave.checks
15
15
16
16 def list_features():
17 def list_features():
17 for name, feature in sorted(checks.items()):
18 for name, feature in sorted(checks.items()):
18 desc = feature[1]
19 desc = feature[1]
19 print(name + ':', desc)
20 print(name + ':', desc)
20
21
22
21 def test_features():
23 def test_features():
22 failed = 0
24 failed = 0
23 for name, feature in checks.items():
25 for name, feature in checks.items():
@@ -29,11 +31,15 b' def test_features():'
29 failed += 1
31 failed += 1
30 return failed
32 return failed
31
33
34
32 parser = optparse.OptionParser("%prog [options] [features]")
35 parser = optparse.OptionParser("%prog [options] [features]")
33 parser.add_option("--test-features", action="store_true",
36 parser.add_option(
34 help="test available features")
37 "--test-features", action="store_true", help="test available features"
35 parser.add_option("--list-features", action="store_true",
38 )
36 help="list available features")
39 parser.add_option(
40 "--list-features", action="store_true", help="list available features"
41 )
42
37
43
38 def _loadaddon():
44 def _loadaddon():
39 if 'TESTDIR' in os.environ:
45 if 'TESTDIR' in os.environ:
@@ -49,13 +55,16 b' def _loadaddon():'
49 sys.path.insert(0, path)
55 sys.path.insert(0, path)
50 try:
56 try:
51 import hghaveaddon
57 import hghaveaddon
58
52 assert hghaveaddon # silence pyflakes
59 assert hghaveaddon # silence pyflakes
53 except BaseException as inst:
60 except BaseException as inst:
54 sys.stderr.write('failed to import hghaveaddon.py from %r: %s\n'
61 sys.stderr.write(
55 % (path, inst))
62 'failed to import hghaveaddon.py from %r: %s\n' % (path, inst)
63 )
56 sys.exit(2)
64 sys.exit(2)
57 sys.path.pop(0)
65 sys.path.pop(0)
58
66
67
59 if __name__ == '__main__':
68 if __name__ == '__main__':
60 options, args = parser.parse_args()
69 options, args = parser.parse_args()
61 _loadaddon()
70 _loadaddon()
General Comments 0
You need to be logged in to leave comments. Login now