D7420: black: blacken scripts
indygreg (Gregory Szorc)
phabricator at mercurial-scm.org
Fri Nov 15 05:01:26 UTC 2019
indygreg created this revision.
Herald added subscribers: mercurial-devel, mjpieters.
Herald added a reviewer: hg-reviewers.
REVISION SUMMARY
test-check-format.t doesn't appear to detect Python scripts with shebangs.
But my editor which is configured to auto run black on Python files does
and it appears some files are not blackened.
This commit blackens scripts that need it.
1. skip-blame reformatting
REPOSITORY
rHG Mercurial
BRANCH
default
REVISION DETAIL
https://phab.mercurial-scm.org/D7420
AFFECTED FILES
contrib/check-commit
contrib/dumprevlog
contrib/hg-ssh
contrib/hgperf
contrib/hgweb.fcgi
contrib/packaging/hg-docker
contrib/relnotes
contrib/simplemerge
contrib/undumprevlog
hg
CHANGE DETAILS
diff --git a/hg b/hg
--- a/hg
+++ b/hg
@@ -15,22 +15,29 @@
if libdir != '@' 'LIBDIR' '@':
if not os.path.isabs(libdir):
- libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
- libdir)
+ libdir = os.path.join(
+ os.path.dirname(os.path.realpath(__file__)), libdir
+ )
libdir = os.path.abspath(libdir)
sys.path.insert(0, libdir)
from hgdemandimport import tracing
+
with tracing.log('hg script'):
# enable importing on demand to reduce startup time
try:
if sys.version_info[0] < 3 or sys.version_info >= (3, 6):
- import hgdemandimport; hgdemandimport.enable()
+ import hgdemandimport
+
+ hgdemandimport.enable()
except ImportError:
- sys.stderr.write("abort: couldn't find mercurial libraries in [%s]\n" %
- ' '.join(sys.path))
+ sys.stderr.write(
+ "abort: couldn't find mercurial libraries in [%s]\n"
+ % ' '.join(sys.path)
+ )
sys.stderr.write("(check your install and PYTHONPATH)\n")
sys.exit(-1)
from mercurial import dispatch
+
dispatch.run()
diff --git a/contrib/undumprevlog b/contrib/undumprevlog
--- a/contrib/undumprevlog
+++ b/contrib/undumprevlog
@@ -14,16 +14,15 @@
transaction,
vfs as vfsmod,
)
-from mercurial.utils import (
- procutil,
-)
+from mercurial.utils import procutil
for fp in (sys.stdin, sys.stdout, sys.stderr):
procutil.setbinary(fp)
opener = vfsmod.vfs(b'.', False)
-tr = transaction.transaction(sys.stderr.write, opener, {b'store': opener},
- b"undump.journal")
+tr = transaction.transaction(
+ sys.stderr.write, opener, {b'store': opener}, b"undump.journal"
+)
while True:
l = sys.stdin.readline()
if not l:
@@ -42,9 +41,9 @@
p2 = node.bin(p[1])
elif l.startswith("length:"):
length = int(l[8:-1])
- sys.stdin.readline() # start marker
+ sys.stdin.readline() # start marker
d = encoding.strtolocal(sys.stdin.read(length))
- sys.stdin.readline() # end marker
+ sys.stdin.readline() # end marker
r.addrevision(d, tr, lr, p1, p2)
tr.close()
diff --git a/contrib/simplemerge b/contrib/simplemerge
--- a/contrib/simplemerge
+++ b/contrib/simplemerge
@@ -5,6 +5,7 @@
import sys
import hgdemandimport
+
hgdemandimport.enable()
from mercurial.i18n import _
@@ -16,44 +17,54 @@
simplemerge,
ui as uimod,
)
-from mercurial.utils import (
- procutil,
- stringutil
-)
+from mercurial.utils import procutil, stringutil
-options = [(b'L', b'label', [], _(b'labels to use on conflict markers')),
- (b'a', b'text', None, _(b'treat all files as text')),
- (b'p', b'print', None,
- _(b'print results instead of overwriting LOCAL')),
- (b'', b'no-minimal', None, _(b'no effect (DEPRECATED)')),
- (b'h', b'help', None, _(b'display help and exit')),
- (b'q', b'quiet', None, _(b'suppress output'))]
+options = [
+ (b'L', b'label', [], _(b'labels to use on conflict markers')),
+ (b'a', b'text', None, _(b'treat all files as text')),
+ (b'p', b'print', None, _(b'print results instead of overwriting LOCAL')),
+ (b'', b'no-minimal', None, _(b'no effect (DEPRECATED)')),
+ (b'h', b'help', None, _(b'display help and exit')),
+ (b'q', b'quiet', None, _(b'suppress output')),
+]
-usage = _(b'''simplemerge [OPTS] LOCAL BASE OTHER
+usage = _(
+ b'''simplemerge [OPTS] LOCAL BASE OTHER
Simple three-way file merge utility with a minimal feature set.
Apply to LOCAL the changes necessary to go from BASE to OTHER.
By default, LOCAL is overwritten with the results of this operation.
-''')
+'''
+)
+
class ParseError(Exception):
"""Exception raised on errors in parsing the command line."""
+
def showhelp():
pycompat.stdout.write(usage)
pycompat.stdout.write(b'\noptions:\n')
out_opts = []
for shortopt, longopt, default, desc in options:
- out_opts.append((b'%2s%s' % (shortopt and b'-%s' % shortopt,
- longopt and b' --%s' % longopt),
- b'%s' % desc))
+ out_opts.append(
+ (
+ b'%2s%s'
+ % (
+ shortopt and b'-%s' % shortopt,
+ longopt and b' --%s' % longopt,
+ ),
+ b'%s' % desc,
+ )
+ )
opts_len = max([len(opt[0]) for opt in out_opts])
for first, second in out_opts:
pycompat.stdout.write(b' %-*s %s\n' % (opts_len, first, second))
+
try:
for fp in (sys.stdin, pycompat.stdout, sys.stderr):
procutil.setbinary(fp)
@@ -68,13 +79,17 @@
showhelp()
sys.exit(0)
if len(args) != 3:
- raise ParseError(_(b'wrong number of arguments').decode('utf8'))
+ raise ParseError(_(b'wrong number of arguments').decode('utf8'))
local, base, other = args
- sys.exit(simplemerge.simplemerge(uimod.ui.load(),
- context.arbitraryfilectx(local),
- context.arbitraryfilectx(base),
- context.arbitraryfilectx(other),
- **pycompat.strkwargs(opts)))
+ sys.exit(
+ simplemerge.simplemerge(
+ uimod.ui.load(),
+ context.arbitraryfilectx(local),
+ context.arbitraryfilectx(base),
+ context.arbitraryfilectx(other),
+ **pycompat.strkwargs(opts)
+ )
+ )
except ParseError as e:
e = stringutil.forcebytestr(e)
pycompat.stdout.write(b"%s: %s\n" % (sys.argv[0].encode('utf8'), e))
diff --git a/contrib/relnotes b/contrib/relnotes
--- a/contrib/relnotes
+++ b/contrib/relnotes
@@ -98,6 +98,7 @@
(r"shelve|unshelve", "extensions"),
]
+
def wikify(desc):
desc = desc.replace("(issue", "(Bts:issue")
desc = re.sub(r"\b([0-9a-f]{12})\b", r"Cset:\1", desc)
@@ -107,6 +108,7 @@
desc = re.sub(r"\b(\S*__\S*)\b", r"`\1`", desc)
return desc
+
def main():
desc = "example: %(prog)s 4.7.2 --stoprev 4.8rc0"
ap = argparse.ArgumentParser(description=desc)
@@ -200,5 +202,6 @@
for d in sorted(apis):
print(" * %s" % d)
+
if __name__ == "__main__":
main()
diff --git a/contrib/packaging/hg-docker b/contrib/packaging/hg-docker
--- a/contrib/packaging/hg-docker
+++ b/contrib/packaging/hg-docker
@@ -11,6 +11,7 @@
import subprocess
import sys
+
def get_docker() -> str:
docker = shutil.which('docker.io') or shutil.which('docker')
if not docker:
@@ -21,15 +22,16 @@
out = subprocess.check_output([docker, '-h'], stderr=subprocess.STDOUT)
if b'Jansens' in out:
- print('%s is the Docking System Tray; try installing docker.io' %
- docker)
+ print(
+ '%s is the Docking System Tray; try installing docker.io'
+ % docker
+ )
sys.exit(1)
except subprocess.CalledProcessError as e:
print('error calling `%s -h`: %s' % (docker, e.output))
sys.exit(1)
- out = subprocess.check_output([docker, 'version'],
- stderr=subprocess.STDOUT)
+ out = subprocess.check_output([docker, 'version'], stderr=subprocess.STDOUT)
lines = out.splitlines()
if not any(l.startswith((b'Client:', b'Client version:')) for l in lines):
@@ -42,6 +44,7 @@
return docker
+
def get_dockerfile(path: pathlib.Path, args: list) -> bytes:
with path.open('rb') as fh:
df = fh.read()
@@ -51,6 +54,7 @@
return df
+
def build_docker_image(dockerfile: pathlib.Path, params: list, tag: str):
"""Build a Docker image from a templatized Dockerfile."""
docker = get_docker()
@@ -65,9 +69,12 @@
args = [
docker,
'build',
- '--build-arg', 'http_proxy',
- '--build-arg', 'https_proxy',
- '--tag', tag,
+ '--build-arg',
+ 'http_proxy',
+ '--build-arg',
+ 'https_proxy',
+ '--tag',
+ tag,
'-',
]
@@ -76,8 +83,10 @@
p.communicate(input=dockerfile)
if p.returncode:
raise subprocess.CalledProcessException(
- p.returncode, 'failed to build docker image: %s %s'
- % (p.stdout, p.stderr))
+ p.returncode,
+ 'failed to build docker image: %s %s' % (p.stdout, p.stderr),
+ )
+
def command_build(args):
build_args = []
@@ -85,13 +94,13 @@
k, v = arg.split('=', 1)
build_args.append((k.encode('utf-8'), v.encode('utf-8')))
- build_docker_image(pathlib.Path(args.dockerfile),
- build_args,
- args.tag)
+ build_docker_image(pathlib.Path(args.dockerfile), build_args, args.tag)
+
def command_docker(args):
print(get_docker())
+
def main() -> int:
parser = argparse.ArgumentParser()
@@ -99,9 +108,12 @@
build = subparsers.add_parser('build', help='Build a Docker image')
build.set_defaults(func=command_build)
- build.add_argument('--build-arg', action='append', default=[],
- help='Substitution to perform in Dockerfile; '
- 'format: key=value')
+ build.add_argument(
+ '--build-arg',
+ action='append',
+ default=[],
+ help='Substitution to perform in Dockerfile; ' 'format: key=value',
+ )
build.add_argument('dockerfile', help='path to Dockerfile to use')
build.add_argument('tag', help='Tag to apply to created image')
@@ -112,5 +124,6 @@
return args.func(args)
+
if __name__ == '__main__':
sys.exit(main())
diff --git a/contrib/hgweb.fcgi b/contrib/hgweb.fcgi
--- a/contrib/hgweb.fcgi
+++ b/contrib/hgweb.fcgi
@@ -7,13 +7,16 @@
# Uncomment and adjust if Mercurial is not installed system-wide
# (consult "installed modules" path from 'hg debuginstall'):
-#import sys; sys.path.insert(0, "/path/to/python/lib")
+# import sys; sys.path.insert(0, "/path/to/python/lib")
# Uncomment to send python tracebacks to the browser if an error occurs:
-#import cgitb; cgitb.enable()
+# import cgitb; cgitb.enable()
-from mercurial import demandimport; demandimport.enable()
+from mercurial import demandimport
+
+demandimport.enable()
from mercurial.hgweb import hgweb
from flup.server.fcgi import WSGIServer
+
application = hgweb(config)
WSGIServer(application).run()
diff --git a/contrib/hgperf b/contrib/hgperf
--- a/contrib/hgperf
+++ b/contrib/hgperf
@@ -37,18 +37,24 @@
if libdir != '@' 'LIBDIR' '@':
if not os.path.isabs(libdir):
- libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
- libdir)
+ libdir = os.path.join(
+ os.path.dirname(os.path.realpath(__file__)), libdir
+ )
libdir = os.path.abspath(libdir)
sys.path.insert(0, libdir)
# enable importing on demand to reduce startup time
try:
- from mercurial import demandimport; demandimport.enable()
+ from mercurial import demandimport
+
+ demandimport.enable()
except ImportError:
import sys
- sys.stderr.write("abort: couldn't find mercurial libraries in [%s]\n" %
- ' '.join(sys.path))
+
+ sys.stderr.write(
+ "abort: couldn't find mercurial libraries in [%s]\n"
+ % ' '.join(sys.path)
+ )
sys.stderr.write("(check your install and PYTHONPATH)\n")
sys.exit(-1)
@@ -57,6 +63,7 @@
util,
)
+
def timer(func, title=None):
results = []
begin = util.timer()
@@ -69,7 +76,7 @@
ostop = os.times()
count += 1
a, b = ostart, ostop
- results.append((cstop - cstart, b[0] - a[0], b[1]-a[1]))
+ results.append((cstop - cstart, b[0] - a[0], b[1] - a[1]))
if cstop - begin > 3 and count >= 100:
break
if cstop - begin > 10 and count >= 3:
@@ -79,19 +86,27 @@
if r:
sys.stderr.write("! result: %s\n" % r)
m = min(results)
- sys.stderr.write("! wall %f comb %f user %f sys %f (best of %d)\n"
- % (m[0], m[1] + m[2], m[1], m[2], count))
+ sys.stderr.write(
+ "! wall %f comb %f user %f sys %f (best of %d)\n"
+ % (m[0], m[1] + m[2], m[1], m[2], count)
+ )
+
orgruncommand = dispatch.runcommand
+
def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
ui.pushbuffer()
lui.pushbuffer()
- timer(lambda : orgruncommand(lui, repo, cmd, fullargs, ui,
- options, d, cmdpats, cmdoptions))
+ timer(
+ lambda: orgruncommand(
+ lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions
+ )
+ )
ui.popbuffer()
lui.popbuffer()
+
dispatch.runcommand = runcommand
dispatch.run()
diff --git a/contrib/hg-ssh b/contrib/hg-ssh
--- a/contrib/hg-ssh
+++ b/contrib/hg-ssh
@@ -35,7 +35,9 @@
import sys
# enable importing on demand to reduce startup time
-import hgdemandimport ; hgdemandimport.enable()
+import hgdemandimport
+
+hgdemandimport.enable()
from mercurial import (
dispatch,
@@ -43,6 +45,7 @@
ui as uimod,
)
+
def main():
# Prevent insertion/deletion of CRs
dispatch.initstdio()
@@ -56,9 +59,10 @@
args.pop(0)
else:
break
- allowed_paths = [os.path.normpath(os.path.join(cwd,
- os.path.expanduser(path)))
- for path in args]
+ allowed_paths = [
+ os.path.normpath(os.path.join(cwd, os.path.expanduser(path)))
+ for path in args
+ ]
orig_cmd = os.getenv('SSH_ORIGINAL_COMMAND', '?')
try:
cmdargv = shlex.split(orig_cmd)
@@ -75,10 +79,18 @@
if readonly:
if not req.ui:
req.ui = uimod.ui.load()
- req.ui.setconfig(b'hooks', b'pretxnopen.hg-ssh',
- b'python:__main__.rejectpush', b'hg-ssh')
- req.ui.setconfig(b'hooks', b'prepushkey.hg-ssh',
- b'python:__main__.rejectpush', b'hg-ssh')
+ req.ui.setconfig(
+ b'hooks',
+ b'pretxnopen.hg-ssh',
+ b'python:__main__.rejectpush',
+ b'hg-ssh',
+ )
+ req.ui.setconfig(
+ b'hooks',
+ b'prepushkey.hg-ssh',
+ b'python:__main__.rejectpush',
+ b'hg-ssh',
+ )
dispatch.dispatch(req)
else:
sys.stderr.write('Illegal repository "%s"\n' % repo)
@@ -87,11 +99,13 @@
sys.stderr.write('Illegal command "%s"\n' % orig_cmd)
sys.exit(255)
+
def rejectpush(ui, **kwargs):
ui.warn((b"Permission denied\n"))
# mercurial hooks use unix process conventions for hook return values
# so a truthy return means failure
return True
+
if __name__ == '__main__':
main()
diff --git a/contrib/dumprevlog b/contrib/dumprevlog
--- a/contrib/dumprevlog
+++ b/contrib/dumprevlog
@@ -11,23 +11,26 @@
pycompat,
revlog,
)
-from mercurial.utils import (
- procutil,
-)
+from mercurial.utils import procutil
for fp in (sys.stdin, sys.stdout, sys.stderr):
procutil.setbinary(fp)
+
def binopen(path, mode=b'rb'):
if b'b' not in mode:
mode = mode + b'b'
return open(path, pycompat.sysstr(mode))
+
+
binopen.options = {}
+
def printb(data, end=b'\n'):
sys.stdout.flush()
pycompat.stdout.write(data + end)
+
for f in sys.argv[1:]:
r = revlog.revlog(binopen, encoding.strtolocal(f))
print("file:", f)
diff --git a/contrib/check-commit b/contrib/check-commit
--- a/contrib/check-commit
+++ b/contrib/check-commit
@@ -27,32 +27,42 @@
errors = [
(beforepatch + r".*[(]bc[)]", "(BC) needs to be uppercase"),
- (beforepatch + r".*[(]issue \d\d\d",
- "no space allowed between issue and number"),
+ (
+ beforepatch + r".*[(]issue \d\d\d",
+ "no space allowed between issue and number",
+ ),
(beforepatch + r".*[(]bug(\d|\s)", "use (issueDDDD) instead of bug"),
(commitheader + r"# User [^@\n]+\n", "username is not an email address"),
- (commitheader + r"(?!merge with )[^#]\S+[^:] ",
- "summary line doesn't start with 'topic: '"),
+ (
+ commitheader + r"(?!merge with )[^#]\S+[^:] ",
+ "summary line doesn't start with 'topic: '",
+ ),
(afterheader + r"[A-Z][a-z]\S+", "don't capitalize summary lines"),
(afterheader + r"^\S+: *[A-Z][a-z]\S+", "don't capitalize summary lines"),
- (afterheader + r"\S*[^A-Za-z0-9-_]\S*: ",
- "summary keyword should be most user-relevant one-word command or topic"),
+ (
+ afterheader + r"\S*[^A-Za-z0-9-_]\S*: ",
+ "summary keyword should be most user-relevant one-word command or topic",
+ ),
(afterheader + r".*\.\s*\n", "don't add trailing period on summary line"),
(afterheader + r".{79,}", "summary line too long (limit is 78)"),
]
word = re.compile(r'\S')
+
+
def nonempty(first, second):
if word.search(first):
return first
return second
+
def checkcommit(commit, node=None):
exitcode = 0
printed = node is None
hits = []
- signtag = (afterheader +
- r'Added (tag [^ ]+|signature) for changeset [a-f0-9]{12}')
+ signtag = (
+ afterheader + r'Added (tag [^ ]+|signature) for changeset [a-f0-9]{12}'
+ )
if re.search(signtag, commit):
return 0
for exp, msg in errors:
@@ -84,9 +94,11 @@
return exitcode
+
def readcommit(node):
return os.popen("hg export %s" % node).read()
+
if __name__ == "__main__":
exitcode = 0
node = os.environ.get("HG_NODE")
To: indygreg, #hg-reviewers
Cc: mjpieters, mercurial-devel
More information about the Mercurial-devel
mailing list