##// END OF EJS Templates
cleanup: remove pointless r-prefixes on single-quoted strings...
Augie Fackler -
r43906:9f70512a default
parent child Browse files
Show More
@@ -39,7 +39,7 b' def connectpipe(path=None, extraargs=())'
39 cmdline.extend(extraargs)
39 cmdline.extend(extraargs)
40
40
41 def tonative(cmdline):
41 def tonative(cmdline):
42 if os.name != r'nt':
42 if os.name != 'nt':
43 return cmdline
43 return cmdline
44 return [arg.decode("utf-8") for arg in cmdline]
44 return [arg.decode("utf-8") for arg in cmdline]
45
45
@@ -726,8 +726,8 b' def clearfilecache(obj, attrname):'
726
726
727 def clearchangelog(repo):
727 def clearchangelog(repo):
728 if repo is not repo.unfiltered():
728 if repo is not repo.unfiltered():
729 object.__setattr__(repo, r'_clcachekey', None)
729 object.__setattr__(repo, '_clcachekey', None)
730 object.__setattr__(repo, r'_clcache', None)
730 object.__setattr__(repo, '_clcache', None)
731 clearfilecache(repo.unfiltered(), 'changelog')
731 clearfilecache(repo.unfiltered(), 'changelog')
732
732
733
733
@@ -1652,12 +1652,12 b' def perfstartup(ui, repo, **opts):'
1652 timer, fm = gettimer(ui, opts)
1652 timer, fm = gettimer(ui, opts)
1653
1653
1654 def d():
1654 def d():
1655 if os.name != r'nt':
1655 if os.name != 'nt':
1656 os.system(
1656 os.system(
1657 b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0])
1657 b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0])
1658 )
1658 )
1659 else:
1659 else:
1660 os.environ[r'HGRCPATH'] = r' '
1660 os.environ['HGRCPATH'] = r' '
1661 os.system("%s version -q > NUL" % sys.argv[0])
1661 os.system("%s version -q > NUL" % sys.argv[0])
1662
1662
1663 timer(d)
1663 timer(d)
@@ -1844,7 +1844,7 b' def perftemplating(ui, repo, testedtempl'
1844 opts = _byteskwargs(opts)
1844 opts = _byteskwargs(opts)
1845
1845
1846 nullui = ui.copy()
1846 nullui = ui.copy()
1847 nullui.fout = open(os.devnull, r'wb')
1847 nullui.fout = open(os.devnull, 'wb')
1848 nullui.disablepager()
1848 nullui.disablepager()
1849 revs = opts.get(b'rev')
1849 revs = opts.get(b'rev')
1850 if not revs:
1850 if not revs:
@@ -60,7 +60,7 b' def main(argv=()):'
60 )
60 )
61 p.add_argument(
61 p.add_argument(
62 '-j',
62 '-j',
63 default=os.sysconf(r'SC_NPROCESSORS_ONLN'),
63 default=os.sysconf('SC_NPROCESSORS_ONLN'),
64 type=int,
64 type=int,
65 help='Number of parallel tests to run.',
65 help='Number of parallel tests to run.',
66 )
66 )
@@ -20,7 +20,7 b' except ImportError:'
20
20
21 # This script is executed during installs and may not have C extensions
21 # This script is executed during installs and may not have C extensions
22 # available. Relax C module requirements.
22 # available. Relax C module requirements.
23 os.environ[r'HGMODULEPOLICY'] = r'allow'
23 os.environ['HGMODULEPOLICY'] = 'allow'
24 # import from the live mercurial repo
24 # import from the live mercurial repo
25 sys.path.insert(0, "..")
25 sys.path.insert(0, "..")
26 from mercurial import demandimport
26 from mercurial import demandimport
@@ -135,8 +135,8 b' class _demandmod(object):'
135 if locals:
135 if locals:
136 if locals.get(head) is self:
136 if locals.get(head) is self:
137 locals[head] = mod
137 locals[head] = mod
138 elif locals.get(head + r'mod') is self:
138 elif locals.get(head + 'mod') is self:
139 locals[head + r'mod'] = mod
139 locals[head + 'mod'] = mod
140
140
141 for modname in modrefs:
141 for modname in modrefs:
142 modref = sys.modules.get(modname, None)
142 modref = sys.modules.get(modname, None)
@@ -369,8 +369,8 b' def hook(ui, repo, hooktype, node=None, '
369 return
369 return
370
370
371 user = None
371 user = None
372 if source == b'serve' and r'url' in kwargs:
372 if source == b'serve' and 'url' in kwargs:
373 url = kwargs[r'url'].split(b':')
373 url = kwargs['url'].split(b':')
374 if url[0] == b'remote' and url[1].startswith(b'http'):
374 if url[0] == b'remote' and url[1].startswith(b'http'):
375 user = urlreq.unquote(url[3])
375 user = urlreq.unquote(url[3])
376
376
@@ -386,9 +386,9 b' def hook(ui, repo, hooktype, node=None, '
386
386
387
387
388 def _pkhook(ui, repo, hooktype, node, source, user, **kwargs):
388 def _pkhook(ui, repo, hooktype, node, source, user, **kwargs):
389 if kwargs[r'namespace'] == b'bookmarks':
389 if kwargs['namespace'] == b'bookmarks':
390 bookmark = kwargs[r'key']
390 bookmark = kwargs['key']
391 ctx = kwargs[r'new']
391 ctx = kwargs['new']
392 allowbookmarks = buildmatch(ui, None, user, b'acl.allow.bookmarks')
392 allowbookmarks = buildmatch(ui, None, user, b'acl.allow.bookmarks')
393 denybookmarks = buildmatch(ui, None, user, b'acl.deny.bookmarks')
393 denybookmarks = buildmatch(ui, None, user, b'acl.deny.bookmarks')
394
394
@@ -94,7 +94,7 b' def extsetup(ui):'
94 ui.warn(_(b'beautifygraph: unsupported encoding, UTF-8 required\n'))
94 ui.warn(_(b'beautifygraph: unsupported encoding, UTF-8 required\n'))
95 return
95 return
96
96
97 if r'A' in encoding._wide:
97 if 'A' in encoding._wide:
98 ui.warn(
98 ui.warn(
99 _(
99 _(
100 b'beautifygraph: unsupported terminal settings, '
100 b'beautifygraph: unsupported terminal settings, '
@@ -201,7 +201,7 b' def blackbox(ui, repo, *revs, **opts):'
201 if not repo.vfs.exists(b'blackbox.log'):
201 if not repo.vfs.exists(b'blackbox.log'):
202 return
202 return
203
203
204 limit = opts.get(r'limit')
204 limit = opts.get('limit')
205 fp = repo.vfs(b'blackbox.log', b'r')
205 fp = repo.vfs(b'blackbox.log', b'r')
206 lines = fp.read().split(b'\n')
206 lines = fp.read().split(b'\n')
207
207
@@ -101,7 +101,7 b' def commands_pull(orig, ui, repo, *args,'
101
101
102
102
103 def commands_branch(orig, ui, repo, label=None, **opts):
103 def commands_branch(orig, ui, repo, label=None, **opts):
104 if label and not opts.get(r'clean') and not opts.get(r'rev'):
104 if label and not opts.get('clean') and not opts.get('rev'):
105 raise error.Abort(
105 raise error.Abort(
106 _(
106 _(
107 b"creating named branches is disabled and you should use bookmarks"
107 b"creating named branches is disabled and you should use bookmarks"
@@ -612,7 +612,7 b' class bzmysql(bzaccess):'
612 self.ui.warn(_(b"Bugzilla/MySQL cannot update bug state\n"))
612 self.ui.warn(_(b"Bugzilla/MySQL cannot update bug state\n"))
613
613
614 (user, userid) = self.get_bugzilla_user(committer)
614 (user, userid) = self.get_bugzilla_user(committer)
615 now = time.strftime(r'%Y-%m-%d %H:%M:%S')
615 now = time.strftime('%Y-%m-%d %H:%M:%S')
616 self.run(
616 self.run(
617 '''insert into longdescs
617 '''insert into longdescs
618 (bug_id, who, bug_when, thetext)
618 (bug_id, who, bug_when, thetext)
@@ -197,7 +197,7 b' def churn(ui, repo, *pats, **opts):'
197 return s + b" " * (l - encoding.colwidth(s))
197 return s + b" " * (l - encoding.colwidth(s))
198
198
199 amap = {}
199 amap = {}
200 aliases = opts.get(r'aliases')
200 aliases = opts.get('aliases')
201 if not aliases and os.path.exists(repo.wjoin(b'.hgchurn')):
201 if not aliases and os.path.exists(repo.wjoin(b'.hgchurn')):
202 aliases = repo.wjoin(b'.hgchurn')
202 aliases = repo.wjoin(b'.hgchurn')
203 if aliases:
203 if aliases:
@@ -215,7 +215,7 b' def churn(ui, repo, *pats, **opts):'
215 if not rate:
215 if not rate:
216 return
216 return
217
217
218 if opts.get(r'sort'):
218 if opts.get('sort'):
219 rate.sort()
219 rate.sort()
220 else:
220 else:
221 rate.sort(key=lambda x: (-sum(x[1]), x))
221 rate.sort(key=lambda x: (-sum(x[1]), x))
@@ -228,7 +228,7 b' def churn(ui, repo, *pats, **opts):'
228 ui.debug(b"assuming %i character terminal\n" % ttywidth)
228 ui.debug(b"assuming %i character terminal\n" % ttywidth)
229 width = ttywidth - maxname - 2 - 2 - 2
229 width = ttywidth - maxname - 2 - 2 - 2
230
230
231 if opts.get(r'diffstat'):
231 if opts.get('diffstat'):
232 width -= 15
232 width -= 15
233
233
234 def format(name, diffstat):
234 def format(name, diffstat):
@@ -58,7 +58,7 b' def _commit(orig, ui, repo, *pats, **opt'
58
58
59 class repoextra(repo.__class__):
59 class repoextra(repo.__class__):
60 def commit(self, *innerpats, **inneropts):
60 def commit(self, *innerpats, **inneropts):
61 extras = opts.get(r'extra')
61 extras = opts.get('extra')
62 for raw in extras:
62 for raw in extras:
63 if b'=' not in raw:
63 if b'=' not in raw:
64 msg = _(
64 msg = _(
@@ -82,7 +82,7 b' def _commit(orig, ui, repo, *pats, **opt'
82 b"manually"
82 b"manually"
83 )
83 )
84 raise error.Abort(msg % k)
84 raise error.Abort(msg % k)
85 inneropts[r'extra'][k] = v
85 inneropts['extra'][k] = v
86 return super(repoextra, self).commit(*innerpats, **inneropts)
86 return super(repoextra, self).commit(*innerpats, **inneropts)
87
87
88 repo.__class__ = repoextra
88 repo.__class__ = repoextra
@@ -57,7 +57,7 b' class _shlexpy3proxy(object):'
57 def shlexer(data=None, filepath=None, wordchars=None, whitespace=None):
57 def shlexer(data=None, filepath=None, wordchars=None, whitespace=None):
58 if data is None:
58 if data is None:
59 if pycompat.ispy3:
59 if pycompat.ispy3:
60 data = open(filepath, b'r', encoding=r'latin1')
60 data = open(filepath, b'r', encoding='latin1')
61 else:
61 else:
62 data = open(filepath, b'r')
62 data = open(filepath, b'r')
63 else:
63 else:
@@ -302,25 +302,25 b' class gnuarch_source(common.converter_so'
302
302
303 # Commit date
303 # Commit date
304 self.changes[rev].date = dateutil.datestr(
304 self.changes[rev].date = dateutil.datestr(
305 dateutil.strdate(catlog[r'Standard-date'], b'%Y-%m-%d %H:%M:%S')
305 dateutil.strdate(catlog['Standard-date'], b'%Y-%m-%d %H:%M:%S')
306 )
306 )
307
307
308 # Commit author
308 # Commit author
309 self.changes[rev].author = self.recode(catlog[r'Creator'])
309 self.changes[rev].author = self.recode(catlog['Creator'])
310
310
311 # Commit description
311 # Commit description
312 self.changes[rev].summary = b'\n\n'.join(
312 self.changes[rev].summary = b'\n\n'.join(
313 (
313 (
314 self.recode(catlog[r'Summary']),
314 self.recode(catlog['Summary']),
315 self.recode(catlog.get_payload()),
315 self.recode(catlog.get_payload()),
316 )
316 )
317 )
317 )
318 self.changes[rev].summary = self.recode(self.changes[rev].summary)
318 self.changes[rev].summary = self.recode(self.changes[rev].summary)
319
319
320 # Commit revision origin when dealing with a branch or tag
320 # Commit revision origin when dealing with a branch or tag
321 if r'Continuation-of' in catlog:
321 if 'Continuation-of' in catlog:
322 self.changes[rev].continuationof = self.recode(
322 self.changes[rev].continuationof = self.recode(
323 catlog[r'Continuation-of']
323 catlog['Continuation-of']
324 )
324 )
325 except Exception:
325 except Exception:
326 raise error.Abort(_(b'could not parse cat-log of %s') % rev)
326 raise error.Abort(_(b'could not parse cat-log of %s') % rev)
@@ -96,7 +96,7 b' class monotone_source(common.converter_s'
96 return self.mtnrunsingle(*args, **kwargs)
96 return self.mtnrunsingle(*args, **kwargs)
97
97
98 def mtnrunsingle(self, *args, **kwargs):
98 def mtnrunsingle(self, *args, **kwargs):
99 kwargs[r'd'] = self.path
99 kwargs['d'] = self.path
100 return self.run0(b'automate', *args, **kwargs)
100 return self.run0(b'automate', *args, **kwargs)
101
101
102 def mtnrunstdio(self, *args, **kwargs):
102 def mtnrunstdio(self, *args, **kwargs):
@@ -1359,11 +1359,11 b' class svn_sink(converter_sink, commandli'
1359 m = set()
1359 m = set()
1360 output = self.run0(b'ls', recursive=True, xml=True)
1360 output = self.run0(b'ls', recursive=True, xml=True)
1361 doc = xml.dom.minidom.parseString(output)
1361 doc = xml.dom.minidom.parseString(output)
1362 for e in doc.getElementsByTagName(r'entry'):
1362 for e in doc.getElementsByTagName('entry'):
1363 for n in e.childNodes:
1363 for n in e.childNodes:
1364 if n.nodeType != n.ELEMENT_NODE or n.tagName != r'name':
1364 if n.nodeType != n.ELEMENT_NODE or n.tagName != 'name':
1365 continue
1365 continue
1366 name = r''.join(
1366 name = ''.join(
1367 c.data for c in n.childNodes if c.nodeType == c.TEXT_NODE
1367 c.data for c in n.childNodes if c.nodeType == c.TEXT_NODE
1368 )
1368 )
1369 # Entries are compared with names coming from
1369 # Entries are compared with names coming from
@@ -1502,7 +1502,7 b' class svn_sink(converter_sink, commandli'
1502 self.setexec = []
1502 self.setexec = []
1503
1503
1504 fd, messagefile = pycompat.mkstemp(prefix=b'hg-convert-')
1504 fd, messagefile = pycompat.mkstemp(prefix=b'hg-convert-')
1505 fp = os.fdopen(fd, r'wb')
1505 fp = os.fdopen(fd, 'wb')
1506 fp.write(util.tonativeeol(commit.desc))
1506 fp.write(util.tonativeeol(commit.desc))
1507 fp.close()
1507 fp.close()
1508 try:
1508 try:
@@ -655,7 +655,7 b' class savedcmd(object):'
655 # in an unknown encoding anyway), but avoid double separators on
655 # in an unknown encoding anyway), but avoid double separators on
656 # Windows
656 # Windows
657 docpath = stringutil.escapestr(path).replace(b'\\\\', b'\\')
657 docpath = stringutil.escapestr(path).replace(b'\\\\', b'\\')
658 self.__doc__ %= {r'path': pycompat.sysstr(stringutil.uirepr(docpath))}
658 self.__doc__ %= {'path': pycompat.sysstr(stringutil.uirepr(docpath))}
659 self._cmdline = cmdline
659 self._cmdline = cmdline
660 self._isgui = isgui
660 self._isgui = isgui
661
661
@@ -82,7 +82,7 b' def _matchpaths(repo, rev, pats, opts, a'
82
82
83
83
84 fastannotatecommandargs = {
84 fastannotatecommandargs = {
85 r'options': [
85 'options': [
86 (b'r', b'rev', b'.', _(b'annotate the specified revision'), _(b'REV')),
86 (b'r', b'rev', b'.', _(b'annotate the specified revision'), _(b'REV')),
87 (b'u', b'user', None, _(b'list the author (long with -v)')),
87 (b'u', b'user', None, _(b'list the author (long with -v)')),
88 (b'f', b'file', None, _(b'list the filename')),
88 (b'f', b'file', None, _(b'list the filename')),
@@ -133,8 +133,8 b' fastannotatecommandargs = {'
133 + commands.diffwsopts
133 + commands.diffwsopts
134 + commands.walkopts
134 + commands.walkopts
135 + commands.formatteropts,
135 + commands.formatteropts,
136 r'synopsis': _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
136 'synopsis': _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
137 r'inferrepo': True,
137 'inferrepo': True,
138 }
138 }
139
139
140
140
@@ -257,7 +257,7 b' def fastannotate(ui, repo, *pats, **opts'
257 _newopts = set()
257 _newopts = set()
258 _knownopts = {
258 _knownopts = {
259 opt[1].replace(b'-', b'_')
259 opt[1].replace(b'-', b'_')
260 for opt in (fastannotatecommandargs[r'options'] + commands.globalopts)
260 for opt in (fastannotatecommandargs['options'] + commands.globalopts)
261 }
261 }
262
262
263
263
@@ -269,10 +269,10 b' def _annotatewrapper(orig, ui, repo, *pa'
269
269
270 # treat the file as text (skip the isbinary check)
270 # treat the file as text (skip the isbinary check)
271 if ui.configbool(b'fastannotate', b'forcetext'):
271 if ui.configbool(b'fastannotate', b'forcetext'):
272 opts[r'text'] = True
272 opts['text'] = True
273
273
274 # check if we need to do prefetch (client-side)
274 # check if we need to do prefetch (client-side)
275 rev = opts.get(r'rev')
275 rev = opts.get('rev')
276 if util.safehasattr(repo, 'prefetchfastannotate') and rev is not None:
276 if util.safehasattr(repo, 'prefetchfastannotate') and rev is not None:
277 paths = list(_matchpaths(repo, rev, pats, pycompat.byteskwargs(opts)))
277 paths = list(_matchpaths(repo, rev, pats, pycompat.byteskwargs(opts)))
278 repo.prefetchfastannotate(paths)
278 repo.prefetchfastannotate(paths)
@@ -92,9 +92,9 b' def parseoptions(ui, cmdoptions, args):'
92 except getopt.GetoptError as ex:
92 except getopt.GetoptError as ex:
93 if "requires argument" in ex.msg:
93 if "requires argument" in ex.msg:
94 raise
94 raise
95 if (r'--' + ex.opt) in ex.msg:
95 if ('--' + ex.opt) in ex.msg:
96 flag = b'--' + pycompat.bytestr(ex.opt)
96 flag = b'--' + pycompat.bytestr(ex.opt)
97 elif (r'-' + ex.opt) in ex.msg:
97 elif ('-' + ex.opt) in ex.msg:
98 flag = b'-' + pycompat.bytestr(ex.opt)
98 flag = b'-' + pycompat.bytestr(ex.opt)
99 else:
99 else:
100 raise error.Abort(
100 raise error.Abort(
@@ -69,11 +69,11 b' class gpg(object):'
69 try:
69 try:
70 # create temporary files
70 # create temporary files
71 fd, sigfile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".sig")
71 fd, sigfile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".sig")
72 fp = os.fdopen(fd, r'wb')
72 fp = os.fdopen(fd, 'wb')
73 fp.write(sig)
73 fp.write(sig)
74 fp.close()
74 fp.close()
75 fd, datafile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".txt")
75 fd, datafile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".txt")
76 fp = os.fdopen(fd, r'wb')
76 fp = os.fdopen(fd, 'wb')
77 fp.write(data)
77 fp.write(data)
78 fp.close()
78 fp.close()
79 gpgcmd = (
79 gpgcmd = (
@@ -121,7 +121,7 b' class gpg(object):'
121 def newgpg(ui, **opts):
121 def newgpg(ui, **opts):
122 """create a new gpg instance"""
122 """create a new gpg instance"""
123 gpgpath = ui.config(b"gpg", b"cmd")
123 gpgpath = ui.config(b"gpg", b"cmd")
124 gpgkey = opts.get(r'key')
124 gpgkey = opts.get('key')
125 if not gpgkey:
125 if not gpgkey:
126 gpgkey = ui.config(b"gpg", b"key")
126 gpgkey = ui.config(b"gpg", b"key")
127 return gpg(gpgpath, gpgkey)
127 return gpg(gpgpath, gpgkey)
@@ -121,5 +121,5 b' def glog(ui, repo, *pats, **opts):'
121
121
122 This is an alias to :hg:`log -G`.
122 This is an alias to :hg:`log -G`.
123 """
123 """
124 opts[r'graph'] = True
124 opts['graph'] = True
125 return commands.log(ui, repo, *pats, **opts)
125 return commands.log(ui, repo, *pats, **opts)
@@ -115,7 +115,7 b' def difftree(ui, repo, node1=None, node2'
115 ##
115 ##
116
116
117 while True:
117 while True:
118 if opts[r'stdin']:
118 if opts['stdin']:
119 line = ui.fin.readline()
119 line = ui.fin.readline()
120 if not line:
120 if not line:
121 break
121 break
@@ -131,8 +131,8 b' def difftree(ui, repo, node1=None, node2'
131 else:
131 else:
132 node2 = node1
132 node2 = node1
133 node1 = repo.changelog.parents(node1)[0]
133 node1 = repo.changelog.parents(node1)[0]
134 if opts[r'patch']:
134 if opts['patch']:
135 if opts[r'pretty']:
135 if opts['pretty']:
136 catcommit(ui, repo, node2, b"")
136 catcommit(ui, repo, node2, b"")
137 m = scmutil.match(repo[node1], files)
137 m = scmutil.match(repo[node1], files)
138 diffopts = patch.difffeatureopts(ui)
138 diffopts = patch.difffeatureopts(ui)
@@ -142,7 +142,7 b' def difftree(ui, repo, node1=None, node2'
142 ui.write(chunk)
142 ui.write(chunk)
143 else:
143 else:
144 __difftree(repo, node1, node2, files=files)
144 __difftree(repo, node1, node2, files=files)
145 if not opts[r'stdin']:
145 if not opts['stdin']:
146 break
146 break
147
147
148
148
@@ -201,7 +201,7 b' def catfile(ui, repo, type=None, r=None,'
201 # strings
201 # strings
202 #
202 #
203 prefix = b""
203 prefix = b""
204 if opts[r'stdin']:
204 if opts['stdin']:
205 line = ui.fin.readline()
205 line = ui.fin.readline()
206 if not line:
206 if not line:
207 return
207 return
@@ -218,7 +218,7 b' def catfile(ui, repo, type=None, r=None,'
218 return 1
218 return 1
219 n = repo.lookup(r)
219 n = repo.lookup(r)
220 catcommit(ui, repo, n, prefix)
220 catcommit(ui, repo, n, prefix)
221 if opts[r'stdin']:
221 if opts['stdin']:
222 line = ui.fin.readline()
222 line = ui.fin.readline()
223 if not line:
223 if not line:
224 break
224 break
@@ -363,7 +363,7 b' def revlist(ui, repo, *revs, **opts):'
363 else:
363 else:
364 full = None
364 full = None
365 copy = [x for x in revs]
365 copy = [x for x in revs]
366 revtree(ui, copy, repo, full, opts[r'max_count'], opts[r'parents'])
366 revtree(ui, copy, repo, full, opts['max_count'], opts[r'parents'])
367
367
368
368
369 @command(
369 @command(
@@ -624,9 +624,9 b' def commitfuncfor(repo, src):'
624 def commitfunc(**kwargs):
624 def commitfunc(**kwargs):
625 overrides = {(b'phases', b'new-commit'): phasemin}
625 overrides = {(b'phases', b'new-commit'): phasemin}
626 with repo.ui.configoverride(overrides, b'histedit'):
626 with repo.ui.configoverride(overrides, b'histedit'):
627 extra = kwargs.get(r'extra', {}).copy()
627 extra = kwargs.get('extra', {}).copy()
628 extra[b'histedit_source'] = src.hex()
628 extra[b'histedit_source'] = src.hex()
629 kwargs[r'extra'] = extra
629 kwargs['extra'] = extra
630 return repo.commit(**kwargs)
630 return repo.commit(**kwargs)
631
631
632 return commitfunc
632 return commitfunc
@@ -1674,7 +1674,7 b' def _chistedit(ui, repo, *freeargs, **op'
1674 # Curses requires setting the locale or it will default to the C
1674 # Curses requires setting the locale or it will default to the C
1675 # locale. This sets the locale to the user's default system
1675 # locale. This sets the locale to the user's default system
1676 # locale.
1676 # locale.
1677 locale.setlocale(locale.LC_ALL, r'')
1677 locale.setlocale(locale.LC_ALL, '')
1678 rc = curses.wrapper(functools.partial(_chisteditmain, repo, ctxs))
1678 rc = curses.wrapper(functools.partial(_chisteditmain, repo, ctxs))
1679 curses.echo()
1679 curses.echo()
1680 curses.endwin()
1680 curses.endwin()
@@ -195,7 +195,7 b' scratchbranchparttype = bundleparts.scra'
195 revsetpredicate = registrar.revsetpredicate()
195 revsetpredicate = registrar.revsetpredicate()
196 templatekeyword = registrar.templatekeyword()
196 templatekeyword = registrar.templatekeyword()
197 _scratchbranchmatcher = lambda x: False
197 _scratchbranchmatcher = lambda x: False
198 _maybehash = re.compile(r'^[a-f0-9]+$').search
198 _maybehash = re.compile('^[a-f0-9]+$').search
199
199
200
200
201 def _buildexternalbundlestore(ui):
201 def _buildexternalbundlestore(ui):
@@ -1031,7 +1031,7 b' def storetobundlestore(orig, repo, op, u'
1031 fd, bundlefile = pycompat.mkstemp()
1031 fd, bundlefile = pycompat.mkstemp()
1032 try:
1032 try:
1033 try:
1033 try:
1034 fp = os.fdopen(fd, r'wb')
1034 fp = os.fdopen(fd, 'wb')
1035 fp.write(buf.read())
1035 fp.write(buf.read())
1036 finally:
1036 finally:
1037 fp.close()
1037 fp.close()
@@ -1122,7 +1122,7 b' def processparts(orig, repo, op, unbundl'
1122 fd, bundlefile = pycompat.mkstemp()
1122 fd, bundlefile = pycompat.mkstemp()
1123 try:
1123 try:
1124 try:
1124 try:
1125 fp = os.fdopen(fd, r'wb')
1125 fp = os.fdopen(fd, 'wb')
1126 fp.write(buf.read())
1126 fp.write(buf.read())
1127 finally:
1127 finally:
1128 fp.close()
1128 fp.close()
@@ -1254,7 +1254,7 b' def bundle2scratchbranch(op, part):'
1254 fd, bundlefile = pycompat.mkstemp()
1254 fd, bundlefile = pycompat.mkstemp()
1255 try:
1255 try:
1256 try:
1256 try:
1257 fp = os.fdopen(fd, r'wb')
1257 fp = os.fdopen(fd, 'wb')
1258 fp.write(buf.read())
1258 fp.write(buf.read())
1259 finally:
1259 finally:
1260 fp.close()
1260 fp.close()
@@ -37,7 +37,7 b' def _makebundlefromraw(data):'
37 fd, bundlefile = pycompat.mkstemp()
37 fd, bundlefile = pycompat.mkstemp()
38 try: # guards bundlefile
38 try: # guards bundlefile
39 try: # guards fp
39 try: # guards fp
40 fp = os.fdopen(fd, r'wb')
40 fp = os.fdopen(fd, 'wb')
41 fp.write(data)
41 fp.write(data)
42 finally:
42 finally:
43 fp.close()
43 fp.close()
@@ -149,7 +149,7 b' def _mergeentriesiter(*iterables, **kwar'
149
149
150 Note that by default entries go from most recent to oldest.
150 Note that by default entries go from most recent to oldest.
151 """
151 """
152 order = kwargs.pop(r'order', max)
152 order = kwargs.pop('order', max)
153 iterables = [iter(it) for it in iterables]
153 iterables = [iter(it) for it in iterables]
154 # this tracks still active iterables; iterables are deleted as they are
154 # this tracks still active iterables; iterables are deleted as they are
155 # exhausted, which is why this is a dictionary and why each entry also
155 # exhausted, which is why this is a dictionary and why each entry also
@@ -214,8 +214,8 b' def unsharejournal(orig, ui, repo, repop'
214
214
215 class journalentry(
215 class journalentry(
216 collections.namedtuple(
216 collections.namedtuple(
217 r'journalentry',
217 'journalentry',
218 r'timestamp user command namespace name oldhashes newhashes',
218 'timestamp user command namespace name oldhashes newhashes',
219 )
219 )
220 ):
220 ):
221 """Individual journal entry
221 """Individual journal entry
@@ -482,16 +482,16 b' def demo(ui, repo, *args, **opts):'
482 ui.setconfig(b'keywordset', b'svn', svn, b'keyword')
482 ui.setconfig(b'keywordset', b'svn', svn, b'keyword')
483
483
484 uikwmaps = ui.configitems(b'keywordmaps')
484 uikwmaps = ui.configitems(b'keywordmaps')
485 if args or opts.get(r'rcfile'):
485 if args or opts.get('rcfile'):
486 ui.status(_(b'\n\tconfiguration using custom keyword template maps\n'))
486 ui.status(_(b'\n\tconfiguration using custom keyword template maps\n'))
487 if uikwmaps:
487 if uikwmaps:
488 ui.status(_(b'\textending current template maps\n'))
488 ui.status(_(b'\textending current template maps\n'))
489 if opts.get(r'default') or not uikwmaps:
489 if opts.get('default') or not uikwmaps:
490 if svn:
490 if svn:
491 ui.status(_(b'\toverriding default svn keywordset\n'))
491 ui.status(_(b'\toverriding default svn keywordset\n'))
492 else:
492 else:
493 ui.status(_(b'\toverriding default cvs keywordset\n'))
493 ui.status(_(b'\toverriding default cvs keywordset\n'))
494 if opts.get(r'rcfile'):
494 if opts.get('rcfile'):
495 ui.readconfig(opts.get(b'rcfile'))
495 ui.readconfig(opts.get(b'rcfile'))
496 if args:
496 if args:
497 # simulate hgrc parsing
497 # simulate hgrc parsing
@@ -499,7 +499,7 b' def demo(ui, repo, *args, **opts):'
499 repo.vfs.write(b'hgrc', rcmaps)
499 repo.vfs.write(b'hgrc', rcmaps)
500 ui.readconfig(repo.vfs.join(b'hgrc'))
500 ui.readconfig(repo.vfs.join(b'hgrc'))
501 kwmaps = dict(ui.configitems(b'keywordmaps'))
501 kwmaps = dict(ui.configitems(b'keywordmaps'))
502 elif opts.get(r'default'):
502 elif opts.get('default'):
503 if svn:
503 if svn:
504 ui.status(_(b'\n\tconfiguration using default svn keywordset\n'))
504 ui.status(_(b'\n\tconfiguration using default svn keywordset\n'))
505 else:
505 else:
@@ -648,7 +648,7 b' def lfpull(ui, repo, source=b"default", '
648 """
648 """
649 repo.lfpullsource = source
649 repo.lfpullsource = source
650
650
651 revs = opts.get(r'rev', [])
651 revs = opts.get('rev', [])
652 if not revs:
652 if not revs:
653 raise error.Abort(_(b'no revisions specified'))
653 raise error.Abort(_(b'no revisions specified'))
654 revs = scmutil.revrange(repo, revs)
654 revs = scmutil.revrange(repo, revs)
@@ -84,9 +84,9 b' def composenormalfilematcher(match, mani'
84
84
85
85
86 def addlargefiles(ui, repo, isaddremove, matcher, uipathfn, **opts):
86 def addlargefiles(ui, repo, isaddremove, matcher, uipathfn, **opts):
87 large = opts.get(r'large')
87 large = opts.get('large')
88 lfsize = lfutil.getminsize(
88 lfsize = lfutil.getminsize(
89 ui, lfutil.islfilesrepo(repo), opts.get(r'lfsize')
89 ui, lfutil.islfilesrepo(repo), opts.get('lfsize')
90 )
90 )
91
91
92 lfmatcher = None
92 lfmatcher = None
@@ -131,7 +131,7 b' def addlargefiles(ui, repo, isaddremove,'
131 # Need to lock, otherwise there could be a race condition between
131 # Need to lock, otherwise there could be a race condition between
132 # when standins are created and added to the repo.
132 # when standins are created and added to the repo.
133 with repo.wlock():
133 with repo.wlock():
134 if not opts.get(r'dry_run'):
134 if not opts.get('dry_run'):
135 standins = []
135 standins = []
136 lfdirstate = lfutil.openlfdirstate(ui, repo)
136 lfdirstate = lfutil.openlfdirstate(ui, repo)
137 for f in lfnames:
137 for f in lfnames:
@@ -169,7 +169,7 b' def lfstatus(repo):'
169
169
170
170
171 def removelargefiles(ui, repo, isaddremove, matcher, uipathfn, dryrun, **opts):
171 def removelargefiles(ui, repo, isaddremove, matcher, uipathfn, dryrun, **opts):
172 after = opts.get(r'after')
172 after = opts.get('after')
173 m = composelargefilematcher(matcher, repo[None].manifest())
173 m = composelargefilematcher(matcher, repo[None].manifest())
174 with lfstatus(repo):
174 with lfstatus(repo):
175 s = repo.status(match=m, clean=not isaddremove)
175 s = repo.status(match=m, clean=not isaddremove)
@@ -269,7 +269,7 b' def decodepath(orig, path):'
269 ],
269 ],
270 )
270 )
271 def overrideadd(orig, ui, repo, *pats, **opts):
271 def overrideadd(orig, ui, repo, *pats, **opts):
272 if opts.get(r'normal') and opts.get(r'large'):
272 if opts.get('normal') and opts.get('large'):
273 raise error.Abort(_(b'--normal cannot be used with --large'))
273 raise error.Abort(_(b'--normal cannot be used with --large'))
274 return orig(ui, repo, *pats, **opts)
274 return orig(ui, repo, *pats, **opts)
275
275
@@ -277,7 +277,7 b' def overrideadd(orig, ui, repo, *pats, *'
277 @eh.wrapfunction(cmdutil, b'add')
277 @eh.wrapfunction(cmdutil, b'add')
278 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
278 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
279 # The --normal flag short circuits this override
279 # The --normal flag short circuits this override
280 if opts.get(r'normal'):
280 if opts.get('normal'):
281 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
281 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
282
282
283 ladded, lbad = addlargefiles(ui, repo, False, matcher, uipathfn, **opts)
283 ladded, lbad = addlargefiles(ui, repo, False, matcher, uipathfn, **opts)
@@ -477,9 +477,9 b' def overridelog(orig, ui, repo, *pats, *'
477 ],
477 ],
478 )
478 )
479 def overrideverify(orig, ui, repo, *pats, **opts):
479 def overrideverify(orig, ui, repo, *pats, **opts):
480 large = opts.pop(r'large', False)
480 large = opts.pop('large', False)
481 all = opts.pop(r'lfa', False)
481 all = opts.pop('lfa', False)
482 contents = opts.pop(r'lfc', False)
482 contents = opts.pop('lfc', False)
483
483
484 result = orig(ui, repo, *pats, **opts)
484 result = orig(ui, repo, *pats, **opts)
485 if large or all or contents:
485 if large or all or contents:
@@ -492,7 +492,7 b' def overrideverify(orig, ui, repo, *pats'
492 opts=[(b'', b'large', None, _(b'display largefiles dirstate'))],
492 opts=[(b'', b'large', None, _(b'display largefiles dirstate'))],
493 )
493 )
494 def overridedebugstate(orig, ui, repo, *pats, **opts):
494 def overridedebugstate(orig, ui, repo, *pats, **opts):
495 large = opts.pop(r'large', False)
495 large = opts.pop('large', False)
496 if large:
496 if large:
497
497
498 class fakerepo(object):
498 class fakerepo(object):
@@ -975,8 +975,8 b' def overridepull(orig, ui, repo, source='
975 repo.lfpullsource = source
975 repo.lfpullsource = source
976 result = orig(ui, repo, source, **opts)
976 result = orig(ui, repo, source, **opts)
977 revspostpull = len(repo)
977 revspostpull = len(repo)
978 lfrevs = opts.get(r'lfrev', [])
978 lfrevs = opts.get('lfrev', [])
979 if opts.get(r'all_largefiles'):
979 if opts.get('all_largefiles'):
980 lfrevs.append(b'pulled()')
980 lfrevs.append(b'pulled()')
981 if lfrevs and revspostpull > revsprepull:
981 if lfrevs and revspostpull > revsprepull:
982 numcached = 0
982 numcached = 0
@@ -1006,9 +1006,9 b' def overridepull(orig, ui, repo, source='
1006 )
1006 )
1007 def overridepush(orig, ui, repo, *args, **kwargs):
1007 def overridepush(orig, ui, repo, *args, **kwargs):
1008 """Override push command and store --lfrev parameters in opargs"""
1008 """Override push command and store --lfrev parameters in opargs"""
1009 lfrevs = kwargs.pop(r'lfrev', None)
1009 lfrevs = kwargs.pop('lfrev', None)
1010 if lfrevs:
1010 if lfrevs:
1011 opargs = kwargs.setdefault(r'opargs', {})
1011 opargs = kwargs.setdefault('opargs', {})
1012 opargs[b'lfrevs'] = scmutil.revrange(repo, lfrevs)
1012 opargs[b'lfrevs'] = scmutil.revrange(repo, lfrevs)
1013 return orig(ui, repo, *args, **kwargs)
1013 return orig(ui, repo, *args, **kwargs)
1014
1014
@@ -1016,7 +1016,7 b' def overridepush(orig, ui, repo, *args, '
1016 @eh.wrapfunction(exchange, b'pushoperation')
1016 @eh.wrapfunction(exchange, b'pushoperation')
1017 def exchangepushoperation(orig, *args, **kwargs):
1017 def exchangepushoperation(orig, *args, **kwargs):
1018 """Override pushoperation constructor and store lfrevs parameter"""
1018 """Override pushoperation constructor and store lfrevs parameter"""
1019 lfrevs = kwargs.pop(r'lfrevs', None)
1019 lfrevs = kwargs.pop('lfrevs', None)
1020 pushop = orig(*args, **kwargs)
1020 pushop = orig(*args, **kwargs)
1021 pushop.lfrevs = lfrevs
1021 pushop.lfrevs = lfrevs
1022 return pushop
1022 return pushop
@@ -1064,7 +1064,7 b' def overrideclone(orig, ui, source, dest'
1064 d = dest
1064 d = dest
1065 if d is None:
1065 if d is None:
1066 d = hg.defaultdest(source)
1066 d = hg.defaultdest(source)
1067 if opts.get(r'all_largefiles') and not hg.islocal(d):
1067 if opts.get('all_largefiles') and not hg.islocal(d):
1068 raise error.Abort(
1068 raise error.Abort(
1069 _(b'--all-largefiles is incompatible with non-local destination %s')
1069 _(b'--all-largefiles is incompatible with non-local destination %s')
1070 % d
1070 % d
@@ -1104,7 +1104,7 b' def overriderebase(orig, ui, repo, **opt'
1104 if not util.safehasattr(repo, b'_largefilesenabled'):
1104 if not util.safehasattr(repo, b'_largefilesenabled'):
1105 return orig(ui, repo, **opts)
1105 return orig(ui, repo, **opts)
1106
1106
1107 resuming = opts.get(r'continue')
1107 resuming = opts.get('continue')
1108 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1108 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1109 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1109 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1110 try:
1110 try:
@@ -1596,7 +1596,7 b' def overriderollback(orig, ui, repo, **o'
1596
1596
1597 @eh.wrapcommand(b'transplant', extension=b'transplant')
1597 @eh.wrapcommand(b'transplant', extension=b'transplant')
1598 def overridetransplant(orig, ui, repo, *revs, **opts):
1598 def overridetransplant(orig, ui, repo, *revs, **opts):
1599 resuming = opts.get(r'continue')
1599 resuming = opts.get('continue')
1600 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1600 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1601 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1601 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1602 try:
1602 try:
@@ -1681,7 +1681,7 b' def overridecat(orig, ui, repo, file1, *'
1681
1681
1682 @eh.wrapfunction(merge, b'update')
1682 @eh.wrapfunction(merge, b'update')
1683 def mergeupdate(orig, repo, node, branchmerge, force, *args, **kwargs):
1683 def mergeupdate(orig, repo, node, branchmerge, force, *args, **kwargs):
1684 matcher = kwargs.get(r'matcher', None)
1684 matcher = kwargs.get('matcher', None)
1685 # note if this is a partial update
1685 # note if this is a partial update
1686 partial = matcher and not matcher.always()
1686 partial = matcher and not matcher.always()
1687 with repo.wlock():
1687 with repo.wlock():
@@ -1741,7 +1741,7 b' def mergeupdate(orig, repo, node, branch'
1741 # Make sure the merge runs on disk, not in-memory. largefiles is not a
1741 # Make sure the merge runs on disk, not in-memory. largefiles is not a
1742 # good candidate for in-memory merge (large files, custom dirstate,
1742 # good candidate for in-memory merge (large files, custom dirstate,
1743 # matcher usage).
1743 # matcher usage).
1744 kwargs[r'wc'] = repo[None]
1744 kwargs['wc'] = repo[None]
1745 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1745 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1746
1746
1747 newstandins = lfutil.getstandinsstate(repo)
1747 newstandins = lfutil.getstandinsstate(repo)
@@ -116,7 +116,7 b' def wirereposetup(ui, repo):'
116 b'putlfile',
116 b'putlfile',
117 data=fd,
117 data=fd,
118 sha=sha,
118 sha=sha,
119 headers={r'content-type': r'application/mercurial-0.1'},
119 headers={'content-type': 'application/mercurial-0.1'},
120 )
120 )
121 try:
121 try:
122 d, output = res.split(b'\n', 1)
122 d, output = res.split(b'\n', 1)
@@ -206,7 +206,7 b' def sshrepocallstream(self, cmd, **args)'
206 if cmd == b'heads' and self.capable(b'largefiles'):
206 if cmd == b'heads' and self.capable(b'largefiles'):
207 cmd = b'lheads'
207 cmd = b'lheads'
208 if cmd == b'batch' and self.capable(b'largefiles'):
208 if cmd == b'batch' and self.capable(b'largefiles'):
209 args[r'cmds'] = args[r'cmds'].replace(b'heads ', b'lheads ')
209 args['cmds'] = args[r'cmds'].replace(b'heads ', b'lheads ')
210 return ssholdcallstream(self, cmd, **args)
210 return ssholdcallstream(self, cmd, **args)
211
211
212
212
@@ -217,5 +217,5 b' def httprepocallstream(self, cmd, **args'
217 if cmd == b'heads' and self.capable(b'largefiles'):
217 if cmd == b'heads' and self.capable(b'largefiles'):
218 cmd = b'lheads'
218 cmd = b'lheads'
219 if cmd == b'batch' and self.capable(b'largefiles'):
219 if cmd == b'batch' and self.capable(b'largefiles'):
220 args[r'cmds'] = headsre.sub(b'lheads', args[r'cmds'])
220 args['cmds'] = headsre.sub(b'lheads', args['cmds'])
221 return httpoldcallstream(self, cmd, **args)
221 return httpoldcallstream(self, cmd, **args)
@@ -241,12 +241,12 b' def _reposetup(ui, repo):'
241 if b'lfs' in repo.requirements:
241 if b'lfs' in repo.requirements:
242 return 0
242 return 0
243
243
244 last = kwargs.get(r'node_last')
244 last = kwargs.get('node_last')
245 _bin = node.bin
245 _bin = node.bin
246 if last:
246 if last:
247 s = repo.set(b'%n:%n', _bin(kwargs[r'node']), _bin(last))
247 s = repo.set(b'%n:%n', _bin(kwargs['node']), _bin(last))
248 else:
248 else:
249 s = repo.set(b'%n', _bin(kwargs[r'node']))
249 s = repo.set(b'%n', _bin(kwargs['node']))
250 match = repo._storenarrowmatch
250 match = repo._storenarrowmatch
251 for ctx in s:
251 for ctx in s:
252 # TODO: is there a way to just walk the files in the commit?
252 # TODO: is there a way to just walk the files in the commit?
@@ -399,6 +399,6 b' def lfsfiles(context, mapping):'
399 )
399 )
400 def debuglfsupload(ui, repo, **opts):
400 def debuglfsupload(ui, repo, **opts):
401 """upload lfs blobs added by the working copy parent or given revisions"""
401 """upload lfs blobs added by the working copy parent or given revisions"""
402 revs = opts.get(r'rev', [])
402 revs = opts.get('rev', [])
403 pointers = wrapper.extractpointers(repo, scmutil.revrange(repo, revs))
403 pointers = wrapper.extractpointers(repo, scmutil.revrange(repo, revs))
404 wrapper.uploadblobs(repo, pointers)
404 wrapper.uploadblobs(repo, pointers)
@@ -280,11 +280,11 b' class lfsauthhandler(util.urlreq.basehan'
280 """Enforces that any authentication performed is HTTP Basic
280 """Enforces that any authentication performed is HTTP Basic
281 Authentication. No authentication is also acceptable.
281 Authentication. No authentication is also acceptable.
282 """
282 """
283 authreq = headers.get(r'www-authenticate', None)
283 authreq = headers.get('www-authenticate', None)
284 if authreq:
284 if authreq:
285 scheme = authreq.split()[0]
285 scheme = authreq.split()[0]
286
286
287 if scheme.lower() != r'basic':
287 if scheme.lower() != 'basic':
288 msg = _(b'the server must support Basic Authentication')
288 msg = _(b'the server must support Basic Authentication')
289 raise util.urlerr.httperror(
289 raise util.urlerr.httperror(
290 req.get_full_url(),
290 req.get_full_url(),
@@ -324,18 +324,18 b' class _gitlfsremote(object):'
324 See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
324 See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
325 """
325 """
326 objects = [
326 objects = [
327 {r'oid': pycompat.strurl(p.oid()), r'size': p.size()}
327 {'oid': pycompat.strurl(p.oid()), 'size': p.size()}
328 for p in pointers
328 for p in pointers
329 ]
329 ]
330 requestdata = pycompat.bytesurl(
330 requestdata = pycompat.bytesurl(
331 json.dumps(
331 json.dumps(
332 {r'objects': objects, r'operation': pycompat.strurl(action),}
332 {'objects': objects, 'operation': pycompat.strurl(action),}
333 )
333 )
334 )
334 )
335 url = b'%s/objects/batch' % self.baseurl
335 url = b'%s/objects/batch' % self.baseurl
336 batchreq = util.urlreq.request(pycompat.strurl(url), data=requestdata)
336 batchreq = util.urlreq.request(pycompat.strurl(url), data=requestdata)
337 batchreq.add_header(r'Accept', r'application/vnd.git-lfs+json')
337 batchreq.add_header('Accept', 'application/vnd.git-lfs+json')
338 batchreq.add_header(r'Content-Type', r'application/vnd.git-lfs+json')
338 batchreq.add_header('Content-Type', 'application/vnd.git-lfs+json')
339 try:
339 try:
340 with contextlib.closing(self.urlopener.open(batchreq)) as rsp:
340 with contextlib.closing(self.urlopener.open(batchreq)) as rsp:
341 rawjson = rsp.read()
341 rawjson = rsp.read()
@@ -376,9 +376,9 b' class _gitlfsremote(object):'
376 headers = pycompat.bytestr(rsp.info()).strip()
376 headers = pycompat.bytestr(rsp.info()).strip()
377 self.ui.debug(b'%s\n' % b'\n'.join(sorted(headers.splitlines())))
377 self.ui.debug(b'%s\n' % b'\n'.join(sorted(headers.splitlines())))
378
378
379 if r'objects' in response:
379 if 'objects' in response:
380 response[r'objects'] = sorted(
380 response['objects'] = sorted(
381 response[r'objects'], key=lambda p: p[r'oid']
381 response['objects'], key=lambda p: p['oid']
382 )
382 )
383 self.ui.debug(
383 self.ui.debug(
384 b'%s\n'
384 b'%s\n'
@@ -386,7 +386,7 b' class _gitlfsremote(object):'
386 json.dumps(
386 json.dumps(
387 response,
387 response,
388 indent=2,
388 indent=2,
389 separators=(r'', r': '),
389 separators=('', ': '),
390 sort_keys=True,
390 sort_keys=True,
391 )
391 )
392 )
392 )
@@ -483,8 +483,8 b' class _gitlfsremote(object):'
483 )
483 )
484 request.data = filewithprogress(localstore.open(oid), None)
484 request.data = filewithprogress(localstore.open(oid), None)
485 request.get_method = lambda: r'PUT'
485 request.get_method = lambda: r'PUT'
486 request.add_header(r'Content-Type', r'application/octet-stream')
486 request.add_header('Content-Type', 'application/octet-stream')
487 request.add_header(r'Content-Length', len(request.data))
487 request.add_header('Content-Length', len(request.data))
488
488
489 for k, v in headers:
489 for k, v in headers:
490 request.add_header(pycompat.strurl(k), pycompat.strurl(v))
490 request.add_header(pycompat.strurl(k), pycompat.strurl(v))
@@ -136,7 +136,7 b' def _processbatchrequest(repo, req, res)'
136 lfsreq = pycompat.json_loads(req.bodyfh.read())
136 lfsreq = pycompat.json_loads(req.bodyfh.read())
137
137
138 # If no transfer handlers are explicitly requested, 'basic' is assumed.
138 # If no transfer handlers are explicitly requested, 'basic' is assumed.
139 if r'basic' not in lfsreq.get(r'transfers', [r'basic']):
139 if 'basic' not in lfsreq.get('transfers', ['basic']):
140 _sethttperror(
140 _sethttperror(
141 res,
141 res,
142 HTTP_BAD_REQUEST,
142 HTTP_BAD_REQUEST,
@@ -144,7 +144,7 b' def _processbatchrequest(repo, req, res)'
144 )
144 )
145 return True
145 return True
146
146
147 operation = lfsreq.get(r'operation')
147 operation = lfsreq.get('operation')
148 operation = pycompat.bytestr(operation)
148 operation = pycompat.bytestr(operation)
149
149
150 if operation not in (b'upload', b'download'):
150 if operation not in (b'upload', b'download'):
@@ -160,13 +160,13 b' def _processbatchrequest(repo, req, res)'
160 objects = [
160 objects = [
161 p
161 p
162 for p in _batchresponseobjects(
162 for p in _batchresponseobjects(
163 req, lfsreq.get(r'objects', []), operation, localstore
163 req, lfsreq.get('objects', []), operation, localstore
164 )
164 )
165 ]
165 ]
166
166
167 rsp = {
167 rsp = {
168 r'transfer': r'basic',
168 'transfer': 'basic',
169 r'objects': objects,
169 'objects': objects,
170 }
170 }
171
171
172 res.status = hgwebcommon.statusmessage(HTTP_OK)
172 res.status = hgwebcommon.statusmessage(HTTP_OK)
@@ -206,12 +206,12 b' def _batchresponseobjects(req, objects, '
206
206
207 for obj in objects:
207 for obj in objects:
208 # Convert unicode to ASCII to create a filesystem path
208 # Convert unicode to ASCII to create a filesystem path
209 soid = obj.get(r'oid')
209 soid = obj.get('oid')
210 oid = soid.encode(r'ascii')
210 oid = soid.encode('ascii')
211 rsp = {
211 rsp = {
212 r'oid': soid,
212 'oid': soid,
213 r'size': obj.get(r'size'), # XXX: should this check the local size?
213 'size': obj.get('size'), # XXX: should this check the local size?
214 # r'authenticated': True,
214 # 'authenticated': True,
215 }
215 }
216
216
217 exists = True
217 exists = True
@@ -234,9 +234,9 b' def _batchresponseobjects(req, objects, '
234 if inst.errno != errno.ENOENT:
234 if inst.errno != errno.ENOENT:
235 _logexception(req)
235 _logexception(req)
236
236
237 rsp[r'error'] = {
237 rsp['error'] = {
238 r'code': 500,
238 'code': 500,
239 r'message': inst.strerror or r'Internal Server Server',
239 'message': inst.strerror or 'Internal Server Server',
240 }
240 }
241 yield rsp
241 yield rsp
242 continue
242 continue
@@ -247,17 +247,17 b' def _batchresponseobjects(req, objects, '
247 # IFF they already exist locally.
247 # IFF they already exist locally.
248 if action == b'download':
248 if action == b'download':
249 if not exists:
249 if not exists:
250 rsp[r'error'] = {
250 rsp['error'] = {
251 r'code': 404,
251 'code': 404,
252 r'message': "The object does not exist",
252 'message': "The object does not exist",
253 }
253 }
254 yield rsp
254 yield rsp
255 continue
255 continue
256
256
257 elif not verifies:
257 elif not verifies:
258 rsp[r'error'] = {
258 rsp['error'] = {
259 r'code': 422, # XXX: is this the right code?
259 'code': 422, # XXX: is this the right code?
260 r'message': "The object is corrupt",
260 'message': "The object is corrupt",
261 }
261 }
262 yield rsp
262 yield rsp
263 continue
263 continue
@@ -272,23 +272,23 b' def _batchresponseobjects(req, objects, '
272 # The spec doesn't mention the Accept header here, but avoid
272 # The spec doesn't mention the Accept header here, but avoid
273 # a gratuitous deviation from lfs-test-server in the test
273 # a gratuitous deviation from lfs-test-server in the test
274 # output.
274 # output.
275 hdr = {r'Accept': r'application/vnd.git-lfs'}
275 hdr = {'Accept': 'application/vnd.git-lfs'}
276
276
277 auth = req.headers.get(b'Authorization', b'')
277 auth = req.headers.get(b'Authorization', b'')
278 if auth.startswith(b'Basic '):
278 if auth.startswith(b'Basic '):
279 hdr[r'Authorization'] = pycompat.strurl(auth)
279 hdr['Authorization'] = pycompat.strurl(auth)
280
280
281 return hdr
281 return hdr
282
282
283 rsp[r'actions'] = {
283 rsp['actions'] = {
284 r'%s'
284 '%s'
285 % pycompat.strurl(action): {
285 % pycompat.strurl(action): {
286 r'href': pycompat.strurl(
286 'href': pycompat.strurl(
287 b'%s%s/.hg/lfs/objects/%s' % (req.baseurl, req.apppath, oid)
287 b'%s%s/.hg/lfs/objects/%s' % (req.baseurl, req.apppath, oid)
288 ),
288 ),
289 # datetime.isoformat() doesn't include the 'Z' suffix
289 # datetime.isoformat() doesn't include the 'Z' suffix
290 "expires_at": expiresat.strftime(r'%Y-%m-%dT%H:%M:%SZ'),
290 "expires_at": expiresat.strftime('%Y-%m-%dT%H:%M:%SZ'),
291 r'header': _buildheader(),
291 'header': _buildheader(),
292 }
292 }
293 }
293 }
294
294
@@ -490,7 +490,7 b' class queue(object):'
490 def __init__(self, ui, baseui, path, patchdir=None):
490 def __init__(self, ui, baseui, path, patchdir=None):
491 self.basepath = path
491 self.basepath = path
492 try:
492 try:
493 with open(os.path.join(path, b'patches.queue'), r'rb') as fh:
493 with open(os.path.join(path, b'patches.queue'), 'rb') as fh:
494 cur = fh.read().rstrip()
494 cur = fh.read().rstrip()
495
495
496 if not cur:
496 if not cur:
@@ -2777,7 +2777,7 b' def init(ui, repo, **opts):'
2777
2777
2778 This command is deprecated. Without -c, it's implied by other relevant
2778 This command is deprecated. Without -c, it's implied by other relevant
2779 commands. With -c, use :hg:`init --mq` instead."""
2779 commands. With -c, use :hg:`init --mq` instead."""
2780 return qinit(ui, repo, create=opts.get(r'create_repo'))
2780 return qinit(ui, repo, create=opts.get('create_repo'))
2781
2781
2782
2782
2783 @command(
2783 @command(
@@ -2933,7 +2933,7 b' def series(ui, repo, **opts):'
2933
2933
2934 Returns 0 on success."""
2934 Returns 0 on success."""
2935 repo.mq.qseries(
2935 repo.mq.qseries(
2936 repo, missing=opts.get(r'missing'), summary=opts.get(r'summary')
2936 repo, missing=opts.get('missing'), summary=opts.get('summary')
2937 )
2937 )
2938 return 0
2938 return 0
2939
2939
@@ -2960,7 +2960,7 b' def top(ui, repo, **opts):'
2960 start=t - 1,
2960 start=t - 1,
2961 length=1,
2961 length=1,
2962 status=b'A',
2962 status=b'A',
2963 summary=opts.get(r'summary'),
2963 summary=opts.get('summary'),
2964 )
2964 )
2965 else:
2965 else:
2966 ui.write(_(b"no patches applied\n"))
2966 ui.write(_(b"no patches applied\n"))
@@ -2982,7 +2982,7 b' def next(ui, repo, **opts):'
2982 if end == len(q.series):
2982 if end == len(q.series):
2983 ui.write(_(b"all patches applied\n"))
2983 ui.write(_(b"all patches applied\n"))
2984 return 1
2984 return 1
2985 q.qseries(repo, start=end, length=1, summary=opts.get(r'summary'))
2985 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2986
2986
2987
2987
2988 @command(
2988 @command(
@@ -3005,7 +3005,7 b' def prev(ui, repo, **opts):'
3005 return 1
3005 return 1
3006 idx = q.series.index(q.applied[-2].name)
3006 idx = q.series.index(q.applied[-2].name)
3007 q.qseries(
3007 q.qseries(
3008 repo, start=idx, length=1, status=b'A', summary=opts.get(r'summary')
3008 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3009 )
3009 )
3010
3010
3011
3011
@@ -3356,8 +3356,8 b' def guard(ui, repo, *args, **opts):'
3356 applied = set(p.name for p in q.applied)
3356 applied = set(p.name for p in q.applied)
3357 patch = None
3357 patch = None
3358 args = list(args)
3358 args = list(args)
3359 if opts.get(r'list'):
3359 if opts.get('list'):
3360 if args or opts.get(r'none'):
3360 if args or opts.get('none'):
3361 raise error.Abort(
3361 raise error.Abort(
3362 _(b'cannot mix -l/--list with options or arguments')
3362 _(b'cannot mix -l/--list with options or arguments')
3363 )
3363 )
@@ -3372,7 +3372,7 b' def guard(ui, repo, *args, **opts):'
3372 patch = args.pop(0)
3372 patch = args.pop(0)
3373 if patch is None:
3373 if patch is None:
3374 raise error.Abort(_(b'no patch to work with'))
3374 raise error.Abort(_(b'no patch to work with'))
3375 if args or opts.get(r'none'):
3375 if args or opts.get('none'):
3376 idx = q.findseries(patch)
3376 idx = q.findseries(patch)
3377 if idx is None:
3377 if idx is None:
3378 raise error.Abort(_(b'no patch named %s') % patch)
3378 raise error.Abort(_(b'no patch named %s') % patch)
@@ -3634,9 +3634,7 b' def restore(ui, repo, rev, **opts):'
3634 This command is deprecated, use :hg:`rebase` instead."""
3634 This command is deprecated, use :hg:`rebase` instead."""
3635 rev = repo.lookup(rev)
3635 rev = repo.lookup(rev)
3636 q = repo.mq
3636 q = repo.mq
3637 q.restore(
3637 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3638 repo, rev, delete=opts.get(r'delete'), qupdate=opts.get(r'update')
3639 )
3640 q.savedirty()
3638 q.savedirty()
3641 return 0
3639 return 0
3642
3640
@@ -3841,9 +3839,9 b' def finish(ui, repo, *revrange, **opts):'
3841
3839
3842 Returns 0 on success.
3840 Returns 0 on success.
3843 """
3841 """
3844 if not opts.get(r'applied') and not revrange:
3842 if not opts.get('applied') and not revrange:
3845 raise error.Abort(_(b'no revisions specified'))
3843 raise error.Abort(_(b'no revisions specified'))
3846 elif opts.get(r'applied'):
3844 elif opts.get('applied'):
3847 revrange = (b'qbase::qtip',) + revrange
3845 revrange = (b'qbase::qtip',) + revrange
3848
3846
3849 q = repo.mq
3847 q = repo.mq
@@ -4072,9 +4070,9 b' def reposetup(ui, repo):'
4072
4070
4073 def invalidateall(self):
4071 def invalidateall(self):
4074 super(mqrepo, self).invalidateall()
4072 super(mqrepo, self).invalidateall()
4075 if localrepo.hasunfilteredcache(self, r'mq'):
4073 if localrepo.hasunfilteredcache(self, 'mq'):
4076 # recreate mq in case queue path was changed
4074 # recreate mq in case queue path was changed
4077 delattr(self.unfiltered(), r'mq')
4075 delattr(self.unfiltered(), 'mq')
4078
4076
4079 def abortifwdirpatched(self, errmsg, force=False):
4077 def abortifwdirpatched(self, errmsg, force=False):
4080 if self.mq.applied and self.mq.checkapplied and not force:
4078 if self.mq.applied and self.mq.checkapplied and not force:
@@ -4172,16 +4170,16 b' def reposetup(ui, repo):'
4172
4170
4173 def mqimport(orig, ui, repo, *args, **kwargs):
4171 def mqimport(orig, ui, repo, *args, **kwargs):
4174 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4172 if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get(
4175 r'no_commit', False
4173 'no_commit', False
4176 ):
4174 ):
4177 repo.abortifwdirpatched(
4175 repo.abortifwdirpatched(
4178 _(b'cannot import over an applied patch'), kwargs.get(r'force')
4176 _(b'cannot import over an applied patch'), kwargs.get('force')
4179 )
4177 )
4180 return orig(ui, repo, *args, **kwargs)
4178 return orig(ui, repo, *args, **kwargs)
4181
4179
4182
4180
4183 def mqinit(orig, ui, *args, **kwargs):
4181 def mqinit(orig, ui, *args, **kwargs):
4184 mq = kwargs.pop(r'mq', None)
4182 mq = kwargs.pop('mq', None)
4185
4183
4186 if not mq:
4184 if not mq:
4187 return orig(ui, *args, **kwargs)
4185 return orig(ui, *args, **kwargs)
@@ -4206,7 +4204,7 b' def mqcommand(orig, ui, repo, *args, **k'
4206 """Add --mq option to operate on patch repository instead of main"""
4204 """Add --mq option to operate on patch repository instead of main"""
4207
4205
4208 # some commands do not like getting unknown options
4206 # some commands do not like getting unknown options
4209 mq = kwargs.pop(r'mq', None)
4207 mq = kwargs.pop('mq', None)
4210
4208
4211 if not mq:
4209 if not mq:
4212 return orig(ui, repo, *args, **kwargs)
4210 return orig(ui, repo, *args, **kwargs)
@@ -62,8 +62,8 b' def getbundlechangegrouppart_narrow('
62 raise ValueError(_(b'no common changegroup version'))
62 raise ValueError(_(b'no common changegroup version'))
63 version = max(cgversions)
63 version = max(cgversions)
64
64
65 include = sorted(filter(bool, kwargs.get(r'includepats', [])))
65 include = sorted(filter(bool, kwargs.get('includepats', [])))
66 exclude = sorted(filter(bool, kwargs.get(r'excludepats', [])))
66 exclude = sorted(filter(bool, kwargs.get('excludepats', [])))
67 generateellipsesbundle2(
67 generateellipsesbundle2(
68 bundler,
68 bundler,
69 repo,
69 repo,
@@ -72,7 +72,7 b' def getbundlechangegrouppart_narrow('
72 version,
72 version,
73 common,
73 common,
74 heads,
74 heads,
75 kwargs.get(r'depth', None),
75 kwargs.get('depth', None),
76 )
76 )
77
77
78
78
@@ -316,7 +316,7 b' def setup():'
316 if repo.ui.has_section(_NARROWACL_SECTION):
316 if repo.ui.has_section(_NARROWACL_SECTION):
317 kwargs = exchange.applynarrowacl(repo, kwargs)
317 kwargs = exchange.applynarrowacl(repo, kwargs)
318
318
319 if kwargs.get(r'narrow', False) and repo.ui.configbool(
319 if kwargs.get('narrow', False) and repo.ui.configbool(
320 b'experimental', b'narrowservebrokenellipses'
320 b'experimental', b'narrowservebrokenellipses'
321 ):
321 ):
322 getbundlechangegrouppart_narrow(*args, **kwargs)
322 getbundlechangegrouppart_narrow(*args, **kwargs)
@@ -136,8 +136,8 b' def pullnarrowcmd(orig, ui, repo, *args,'
136
136
137 def pullbundle2extraprepare_widen(orig, pullop, kwargs):
137 def pullbundle2extraprepare_widen(orig, pullop, kwargs):
138 orig(pullop, kwargs)
138 orig(pullop, kwargs)
139 if opts.get(r'depth'):
139 if opts.get('depth'):
140 kwargs[b'depth'] = opts[r'depth']
140 kwargs[b'depth'] = opts['depth']
141
141
142 wrappedextraprepare = extensions.wrappedfunction(
142 wrappedextraprepare = extensions.wrappedfunction(
143 exchange, b'_pullbundle2extraprepare', pullbundle2extraprepare_widen
143 exchange, b'_pullbundle2extraprepare', pullbundle2extraprepare_widen
@@ -151,15 +151,15 b' def archivenarrowcmd(orig, ui, repo, *ar'
151 """Wraps archive command to narrow the default includes."""
151 """Wraps archive command to narrow the default includes."""
152 if repository.NARROW_REQUIREMENT in repo.requirements:
152 if repository.NARROW_REQUIREMENT in repo.requirements:
153 repo_includes, repo_excludes = repo.narrowpats
153 repo_includes, repo_excludes = repo.narrowpats
154 includes = set(opts.get(r'include', []))
154 includes = set(opts.get('include', []))
155 excludes = set(opts.get(r'exclude', []))
155 excludes = set(opts.get('exclude', []))
156 includes, excludes, unused_invalid = narrowspec.restrictpatterns(
156 includes, excludes, unused_invalid = narrowspec.restrictpatterns(
157 includes, excludes, repo_includes, repo_excludes
157 includes, excludes, repo_includes, repo_excludes
158 )
158 )
159 if includes:
159 if includes:
160 opts[r'include'] = includes
160 opts['include'] = includes
161 if excludes:
161 if excludes:
162 opts[r'exclude'] = excludes
162 opts['exclude'] = excludes
163 return orig(ui, repo, *args, **opts)
163 return orig(ui, repo, *args, **opts)
164
164
165
165
@@ -139,12 +139,12 b' def narrow_widen('
139
139
140
140
141 def peernarrowwiden(remote, **kwargs):
141 def peernarrowwiden(remote, **kwargs):
142 for ch in (r'commonheads', r'known'):
142 for ch in ('commonheads', 'known'):
143 kwargs[ch] = wireprototypes.encodelist(kwargs[ch])
143 kwargs[ch] = wireprototypes.encodelist(kwargs[ch])
144
144
145 for ch in (r'oldincludes', r'newincludes', r'oldexcludes', r'newexcludes'):
145 for ch in ('oldincludes', 'newincludes', 'oldexcludes', 'newexcludes'):
146 kwargs[ch] = b','.join(kwargs[ch])
146 kwargs[ch] = b','.join(kwargs[ch])
147
147
148 kwargs[r'ellipses'] = b'%i' % bool(kwargs[r'ellipses'])
148 kwargs['ellipses'] = b'%i' % bool(kwargs['ellipses'])
149 f = remote._callcompressable(b'narrow_widen', **kwargs)
149 f = remote._callcompressable(b'narrow_widen', **kwargs)
150 return bundle2.getunbundler(remote.ui, f)
150 return bundle2.getunbundler(remote.ui, f)
@@ -388,13 +388,13 b' class notifier(object):'
388 raise error.Abort(inst)
388 raise error.Abort(inst)
389
389
390 # store sender and subject
390 # store sender and subject
391 sender = msg[r'From']
391 sender = msg['From']
392 subject = msg[r'Subject']
392 subject = msg['Subject']
393 if sender is not None:
393 if sender is not None:
394 sender = mail.headdecode(sender)
394 sender = mail.headdecode(sender)
395 if subject is not None:
395 if subject is not None:
396 subject = mail.headdecode(subject)
396 subject = mail.headdecode(subject)
397 del msg[r'From'], msg[r'Subject']
397 del msg['From'], msg['Subject']
398
398
399 if not msg.is_multipart():
399 if not msg.is_multipart():
400 # create fresh mime message from scratch
400 # create fresh mime message from scratch
@@ -407,7 +407,7 b' class notifier(object):'
407 for k, v in headers:
407 for k, v in headers:
408 msg[k] = v
408 msg[k] = v
409
409
410 msg[r'Date'] = encoding.strfromlocal(
410 msg['Date'] = encoding.strfromlocal(
411 dateutil.datestr(format=b"%a, %d %b %Y %H:%M:%S %1%2")
411 dateutil.datestr(format=b"%a, %d %b %Y %H:%M:%S %1%2")
412 )
412 )
413
413
@@ -421,7 +421,7 b' class notifier(object):'
421 maxsubject = int(self.ui.config(b'notify', b'maxsubject'))
421 maxsubject = int(self.ui.config(b'notify', b'maxsubject'))
422 if maxsubject:
422 if maxsubject:
423 subject = stringutil.ellipsis(subject, maxsubject)
423 subject = stringutil.ellipsis(subject, maxsubject)
424 msg[r'Subject'] = encoding.strfromlocal(
424 msg['Subject'] = encoding.strfromlocal(
425 mail.headencode(self.ui, subject, self.charsets, self.test)
425 mail.headencode(self.ui, subject, self.charsets, self.test)
426 )
426 )
427
427
@@ -430,14 +430,14 b' class notifier(object):'
430 sender = self.ui.config(b'email', b'from') or self.ui.username()
430 sender = self.ui.config(b'email', b'from') or self.ui.username()
431 if b'@' not in sender or b'@localhost' in sender:
431 if b'@' not in sender or b'@localhost' in sender:
432 sender = self.fixmail(sender)
432 sender = self.fixmail(sender)
433 msg[r'From'] = encoding.strfromlocal(
433 msg['From'] = encoding.strfromlocal(
434 mail.addressencode(self.ui, sender, self.charsets, self.test)
434 mail.addressencode(self.ui, sender, self.charsets, self.test)
435 )
435 )
436
436
437 msg[r'X-Hg-Notification'] = r'changeset %s' % ctx
437 msg['X-Hg-Notification'] = 'changeset %s' % ctx
438 if not msg[r'Message-Id']:
438 if not msg['Message-Id']:
439 msg[r'Message-Id'] = messageid(ctx, self.domain, self.messageidseed)
439 msg['Message-Id'] = messageid(ctx, self.domain, self.messageidseed)
440 msg[r'To'] = encoding.strfromlocal(b', '.join(sorted(subs)))
440 msg['To'] = encoding.strfromlocal(b', '.join(sorted(subs)))
441
441
442 msgtext = msg.as_bytes() if pycompat.ispy3 else msg.as_string()
442 msgtext = msg.as_bytes() if pycompat.ispy3 else msg.as_string()
443 if self.test:
443 if self.test:
@@ -451,7 +451,7 b' class notifier(object):'
451 )
451 )
452 mail.sendmail(
452 mail.sendmail(
453 self.ui,
453 self.ui,
454 emailutils.parseaddr(msg[r'From'])[1],
454 emailutils.parseaddr(msg['From'])[1],
455 subs,
455 subs,
456 msgtext,
456 msgtext,
457 mbox=self.mbox,
457 mbox=self.mbox,
@@ -306,8 +306,8 b' def makepatch('
306 disposition = r'inline'
306 disposition = r'inline'
307 if opts.get(b'attach'):
307 if opts.get(b'attach'):
308 disposition = r'attachment'
308 disposition = r'attachment'
309 p[r'Content-Disposition'] = (
309 p['Content-Disposition'] = (
310 disposition + r'; filename=' + encoding.strfromlocal(patchname)
310 disposition + '; filename=' + encoding.strfromlocal(patchname)
311 )
311 )
312 msg.attach(p)
312 msg.attach(p)
313 else:
313 else:
@@ -358,7 +358,7 b' def _getbundle(repo, dest, **opts):'
358 tmpfn = os.path.join(tmpdir, b'bundle')
358 tmpfn = os.path.join(tmpdir, b'bundle')
359 btype = ui.config(b'patchbomb', b'bundletype')
359 btype = ui.config(b'patchbomb', b'bundletype')
360 if btype:
360 if btype:
361 opts[r'type'] = btype
361 opts['type'] = btype
362 try:
362 try:
363 commands.bundle(ui, repo, tmpfn, dest, **opts)
363 commands.bundle(ui, repo, tmpfn, dest, **opts)
364 return util.readfile(tmpfn)
364 return util.readfile(tmpfn)
@@ -379,8 +379,8 b' def _getdescription(repo, defaultbody, s'
379 the user through the editor.
379 the user through the editor.
380 """
380 """
381 ui = repo.ui
381 ui = repo.ui
382 if opts.get(r'desc'):
382 if opts.get('desc'):
383 body = open(opts.get(r'desc')).read()
383 body = open(opts.get('desc')).read()
384 else:
384 else:
385 ui.write(
385 ui.write(
386 _(b'\nWrite the introductory message for the patch series.\n\n')
386 _(b'\nWrite the introductory message for the patch series.\n\n')
@@ -403,25 +403,25 b' def _getbundlemsgs(repo, sender, bundle,'
403 """
403 """
404 ui = repo.ui
404 ui = repo.ui
405 _charsets = mail._charsets(ui)
405 _charsets = mail._charsets(ui)
406 subj = opts.get(r'subject') or prompt(
406 subj = opts.get('subject') or prompt(
407 ui, b'Subject:', b'A bundle for your repository'
407 ui, b'Subject:', b'A bundle for your repository'
408 )
408 )
409
409
410 body = _getdescription(repo, b'', sender, **opts)
410 body = _getdescription(repo, b'', sender, **opts)
411 msg = emimemultipart.MIMEMultipart()
411 msg = emimemultipart.MIMEMultipart()
412 if body:
412 if body:
413 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get(r'test')))
413 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
414 datapart = emimebase.MIMEBase(r'application', r'x-mercurial-bundle')
414 datapart = emimebase.MIMEBase('application', 'x-mercurial-bundle')
415 datapart.set_payload(bundle)
415 datapart.set_payload(bundle)
416 bundlename = b'%s.hg' % opts.get(r'bundlename', b'bundle')
416 bundlename = b'%s.hg' % opts.get('bundlename', b'bundle')
417 datapart.add_header(
417 datapart.add_header(
418 r'Content-Disposition',
418 'Content-Disposition',
419 r'attachment',
419 'attachment',
420 filename=encoding.strfromlocal(bundlename),
420 filename=encoding.strfromlocal(bundlename),
421 )
421 )
422 emailencoders.encode_base64(datapart)
422 emailencoders.encode_base64(datapart)
423 msg.attach(datapart)
423 msg.attach(datapart)
424 msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get(r'test'))
424 msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
425 return [(msg, subj, None)]
425 return [(msg, subj, None)]
426
426
427
427
@@ -434,9 +434,9 b' def _makeintro(repo, sender, revs, patch'
434
434
435 # use the last revision which is likely to be a bookmarked head
435 # use the last revision which is likely to be a bookmarked head
436 prefix = _formatprefix(
436 prefix = _formatprefix(
437 ui, repo, revs.last(), opts.get(r'flag'), 0, len(patches), numbered=True
437 ui, repo, revs.last(), opts.get('flag'), 0, len(patches), numbered=True
438 )
438 )
439 subj = opts.get(r'subject') or prompt(
439 subj = opts.get('subject') or prompt(
440 ui, b'(optional) Subject: ', rest=prefix, default=b''
440 ui, b'(optional) Subject: ', rest=prefix, default=b''
441 )
441 )
442 if not subj:
442 if not subj:
@@ -445,7 +445,7 b' def _makeintro(repo, sender, revs, patch'
445 subj = prefix + b' ' + subj
445 subj = prefix + b' ' + subj
446
446
447 body = b''
447 body = b''
448 if opts.get(r'diffstat'):
448 if opts.get('diffstat'):
449 # generate a cumulative diffstat of the whole patch series
449 # generate a cumulative diffstat of the whole patch series
450 diffstat = patch.diffstat(sum(patches, []))
450 diffstat = patch.diffstat(sum(patches, []))
451 body = b'\n' + diffstat
451 body = b'\n' + diffstat
@@ -453,8 +453,8 b' def _makeintro(repo, sender, revs, patch'
453 diffstat = None
453 diffstat = None
454
454
455 body = _getdescription(repo, body, sender, **opts)
455 body = _getdescription(repo, body, sender, **opts)
456 msg = mail.mimeencode(ui, body, _charsets, opts.get(r'test'))
456 msg = mail.mimeencode(ui, body, _charsets, opts.get('test'))
457 msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get(r'test'))
457 msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
458 return (msg, subj, diffstat)
458 return (msg, subj, diffstat)
459
459
460
460
@@ -847,7 +847,7 b' def email(ui, repo, *revs, **opts):'
847 stropts = pycompat.strkwargs(opts)
847 stropts = pycompat.strkwargs(opts)
848 bundledata = _getbundle(repo, dest, **stropts)
848 bundledata = _getbundle(repo, dest, **stropts)
849 bundleopts = stropts.copy()
849 bundleopts = stropts.copy()
850 bundleopts.pop(r'bundle', None) # already processed
850 bundleopts.pop('bundle', None) # already processed
851 msgs = _getbundlemsgs(repo, sender, bundledata, **bundleopts)
851 msgs = _getbundlemsgs(repo, sender, bundledata, **bundleopts)
852 else:
852 else:
853 msgs = _getpatchmsgs(repo, sender, revs, **pycompat.strkwargs(opts))
853 msgs = _getpatchmsgs(repo, sender, revs, **pycompat.strkwargs(opts))
@@ -167,13 +167,13 b' def vcrcommand(name, flags, spec, helpca'
167 return request
167 return request
168
168
169 def sanitiseresponse(response):
169 def sanitiseresponse(response):
170 if r'set-cookie' in response[r'headers']:
170 if 'set-cookie' in response['headers']:
171 del response[r'headers'][r'set-cookie']
171 del response['headers']['set-cookie']
172 return response
172 return response
173
173
174 def decorate(fn):
174 def decorate(fn):
175 def inner(*args, **kwargs):
175 def inner(*args, **kwargs):
176 cassette = pycompat.fsdecode(kwargs.pop(r'test_vcr', None))
176 cassette = pycompat.fsdecode(kwargs.pop('test_vcr', None))
177 if cassette:
177 if cassette:
178 import hgdemandimport
178 import hgdemandimport
179
179
@@ -182,24 +182,24 b' def vcrcommand(name, flags, spec, helpca'
182 import vcr.stubs as stubs
182 import vcr.stubs as stubs
183
183
184 vcr = vcrmod.VCR(
184 vcr = vcrmod.VCR(
185 serializer=r'json',
185 serializer='json',
186 before_record_request=sanitiserequest,
186 before_record_request=sanitiserequest,
187 before_record_response=sanitiseresponse,
187 before_record_response=sanitiseresponse,
188 custom_patches=[
188 custom_patches=[
189 (
189 (
190 urlmod,
190 urlmod,
191 r'httpconnection',
191 'httpconnection',
192 stubs.VCRHTTPConnection,
192 stubs.VCRHTTPConnection,
193 ),
193 ),
194 (
194 (
195 urlmod,
195 urlmod,
196 r'httpsconnection',
196 'httpsconnection',
197 stubs.VCRHTTPSConnection,
197 stubs.VCRHTTPSConnection,
198 ),
198 ),
199 ],
199 ],
200 )
200 )
201 vcr.register_matcher(r'hgmatcher', hgmatcher)
201 vcr.register_matcher('hgmatcher', hgmatcher)
202 with vcr.use_cassette(cassette, match_on=[r'hgmatcher']):
202 with vcr.use_cassette(cassette, match_on=['hgmatcher']):
203 return fn(*args, **kwargs)
203 return fn(*args, **kwargs)
204 return fn(*args, **kwargs)
204 return fn(*args, **kwargs)
205
205
@@ -408,7 +408,7 b' def getoldnodedrevmap(repo, nodelist):'
408 # Check commit message
408 # Check commit message
409 m = _differentialrevisiondescre.search(ctx.description())
409 m = _differentialrevisiondescre.search(ctx.description())
410 if m:
410 if m:
411 toconfirm[node] = (1, set(precnodes), int(m.group(r'id')))
411 toconfirm[node] = (1, set(precnodes), int(m.group('id')))
412
412
413 # Double check if tags are genuine by collecting all old nodes from
413 # Double check if tags are genuine by collecting all old nodes from
414 # Phabricator, and expect precursors overlap with it.
414 # Phabricator, and expect precursors overlap with it.
@@ -1088,7 +1088,7 b' def phabsend(ui, repo, *revs, **opts):'
1088 # Create a local tag to note the association, if commit message
1088 # Create a local tag to note the association, if commit message
1089 # does not have it already
1089 # does not have it already
1090 m = _differentialrevisiondescre.search(ctx.description())
1090 m = _differentialrevisiondescre.search(ctx.description())
1091 if not m or int(m.group(r'id')) != newrevid:
1091 if not m or int(m.group('id')) != newrevid:
1092 tagname = b'D%d' % newrevid
1092 tagname = b'D%d' % newrevid
1093 tags.tag(
1093 tags.tag(
1094 repo,
1094 repo,
@@ -1635,7 +1635,7 b' def template_review(context, mapping):'
1635 m = _differentialrevisiondescre.search(ctx.description())
1635 m = _differentialrevisiondescre.search(ctx.description())
1636 if m:
1636 if m:
1637 return templateutil.hybriddict(
1637 return templateutil.hybriddict(
1638 {b'url': m.group(r'url'), b'id': b"D%s" % m.group(r'id'),}
1638 {b'url': m.group('url'), b'id': b"D%s" % m.group('id'),}
1639 )
1639 )
1640 else:
1640 else:
1641 tags = ctx.repo().nodetags(ctx.node())
1641 tags = ctx.repo().nodetags(ctx.node())
@@ -2127,15 +2127,15 b' def clearrebased('
2127
2127
2128 def pullrebase(orig, ui, repo, *args, **opts):
2128 def pullrebase(orig, ui, repo, *args, **opts):
2129 b'Call rebase after pull if the latter has been invoked with --rebase'
2129 b'Call rebase after pull if the latter has been invoked with --rebase'
2130 if opts.get(r'rebase'):
2130 if opts.get('rebase'):
2131 if ui.configbool(b'commands', b'rebase.requiredest'):
2131 if ui.configbool(b'commands', b'rebase.requiredest'):
2132 msg = _(b'rebase destination required by configuration')
2132 msg = _(b'rebase destination required by configuration')
2133 hint = _(b'use hg pull followed by hg rebase -d DEST')
2133 hint = _(b'use hg pull followed by hg rebase -d DEST')
2134 raise error.Abort(msg, hint=hint)
2134 raise error.Abort(msg, hint=hint)
2135
2135
2136 with repo.wlock(), repo.lock():
2136 with repo.wlock(), repo.lock():
2137 if opts.get(r'update'):
2137 if opts.get('update'):
2138 del opts[r'update']
2138 del opts['update']
2139 ui.debug(
2139 ui.debug(
2140 b'--update and --rebase are not compatible, ignoring '
2140 b'--update and --rebase are not compatible, ignoring '
2141 b'the update flag\n'
2141 b'the update flag\n'
@@ -2165,15 +2165,15 b' def pullrebase(orig, ui, repo, *args, **'
2165 if revspostpull > revsprepull:
2165 if revspostpull > revsprepull:
2166 # --rev option from pull conflict with rebase own --rev
2166 # --rev option from pull conflict with rebase own --rev
2167 # dropping it
2167 # dropping it
2168 if r'rev' in opts:
2168 if 'rev' in opts:
2169 del opts[r'rev']
2169 del opts['rev']
2170 # positional argument from pull conflicts with rebase's own
2170 # positional argument from pull conflicts with rebase's own
2171 # --source.
2171 # --source.
2172 if r'source' in opts:
2172 if 'source' in opts:
2173 del opts[r'source']
2173 del opts['source']
2174 # revsprepull is the len of the repo, not revnum of tip.
2174 # revsprepull is the len of the repo, not revnum of tip.
2175 destspace = list(repo.changelog.revs(start=revsprepull))
2175 destspace = list(repo.changelog.revs(start=revsprepull))
2176 opts[r'_destspace'] = destspace
2176 opts['_destspace'] = destspace
2177 try:
2177 try:
2178 rebase(ui, repo, **opts)
2178 rebase(ui, repo, **opts)
2179 except error.NoMergeDestAbort:
2179 except error.NoMergeDestAbort:
@@ -2187,7 +2187,7 b' def pullrebase(orig, ui, repo, *args, **'
2187 # with warning and trumpets
2187 # with warning and trumpets
2188 commands.update(ui, repo)
2188 commands.update(ui, repo)
2189 else:
2189 else:
2190 if opts.get(r'tool'):
2190 if opts.get('tool'):
2191 raise error.Abort(_(b'--tool can only be used with --rebase'))
2191 raise error.Abort(_(b'--tool can only be used with --rebase'))
2192 ret = orig(ui, repo, *args, **opts)
2192 ret = orig(ui, repo, *args, **opts)
2193
2193
@@ -79,7 +79,7 b' def record(ui, repo, *pats, **opts):'
79
79
80
80
81 def qrefresh(origfn, ui, repo, *pats, **opts):
81 def qrefresh(origfn, ui, repo, *pats, **opts):
82 if not opts[r'interactive']:
82 if not opts['interactive']:
83 return origfn(ui, repo, *pats, **opts)
83 return origfn(ui, repo, *pats, **opts)
84
84
85 mq = extensions.find(b'mq')
85 mq = extensions.find(b'mq')
@@ -123,7 +123,7 b' def _qrecord(cmdsuggest, ui, repo, patch'
123 repo.mq.checkpatchname(patch)
123 repo.mq.checkpatchname(patch)
124
124
125 def committomq(ui, repo, *pats, **opts):
125 def committomq(ui, repo, *pats, **opts):
126 opts[r'checkname'] = False
126 opts['checkname'] = False
127 mq.new(ui, repo, patch, *pats, **opts)
127 mq.new(ui, repo, patch, *pats, **opts)
128
128
129 overrides = {(b'experimental', b'crecord'): False}
129 overrides = {(b'experimental', b'crecord'): False}
@@ -142,7 +142,7 b' def _qrecord(cmdsuggest, ui, repo, patch'
142
142
143
143
144 def qnew(origfn, ui, repo, patch, *args, **opts):
144 def qnew(origfn, ui, repo, patch, *args, **opts):
145 if opts[r'interactive']:
145 if opts['interactive']:
146 return _qrecord(None, ui, repo, patch, *args, **opts)
146 return _qrecord(None, ui, repo, patch, *args, **opts)
147 return origfn(ui, repo, patch, *args, **opts)
147 return origfn(ui, repo, patch, *args, **opts)
148
148
@@ -288,7 +288,7 b' def uisetup(ui):'
288
288
289 # Prevent 'hg manifest --all'
289 # Prevent 'hg manifest --all'
290 def _manifest(orig, ui, repo, *args, **opts):
290 def _manifest(orig, ui, repo, *args, **opts):
291 if isenabled(repo) and opts.get(r'all'):
291 if isenabled(repo) and opts.get('all'):
292 raise error.Abort(_(b"--all is not supported in a shallow repo"))
292 raise error.Abort(_(b"--all is not supported in a shallow repo"))
293
293
294 return orig(ui, repo, *args, **opts)
294 return orig(ui, repo, *args, **opts)
@@ -344,7 +344,7 b' def uisetup(ui):'
344
344
345
345
346 def cloneshallow(orig, ui, repo, *args, **opts):
346 def cloneshallow(orig, ui, repo, *args, **opts):
347 if opts.get(r'shallow'):
347 if opts.get('shallow'):
348 repos = []
348 repos = []
349
349
350 def pull_shallow(orig, self, *args, **kwargs):
350 def pull_shallow(orig, self, *args, **kwargs):
@@ -381,13 +381,9 b' def cloneshallow(orig, ui, repo, *args, '
381 if constants.NETWORK_CAP_LEGACY_SSH_GETFILES in caps:
381 if constants.NETWORK_CAP_LEGACY_SSH_GETFILES in caps:
382 opts = {}
382 opts = {}
383 if repo.includepattern:
383 if repo.includepattern:
384 opts[r'includepattern'] = b'\0'.join(
384 opts['includepattern'] = b'\0'.join(repo.includepattern)
385 repo.includepattern
386 )
387 if repo.excludepattern:
385 if repo.excludepattern:
388 opts[r'excludepattern'] = b'\0'.join(
386 opts['excludepattern'] = b'\0'.join(repo.excludepattern)
389 repo.excludepattern
390 )
391 return remote._callstream(b'stream_out_shallow', **opts)
387 return remote._callstream(b'stream_out_shallow', **opts)
392 else:
388 else:
393 return orig()
389 return orig()
@@ -424,7 +420,7 b' def cloneshallow(orig, ui, repo, *args, '
424 try:
420 try:
425 orig(ui, repo, *args, **opts)
421 orig(ui, repo, *args, **opts)
426 finally:
422 finally:
427 if opts.get(r'shallow'):
423 if opts.get('shallow'):
428 for r in repos:
424 for r in repos:
429 if util.safehasattr(r, b'fileservice'):
425 if util.safehasattr(r, b'fileservice'):
430 r.fileservice.close()
426 r.fileservice.close()
@@ -991,14 +987,14 b' def log(orig, ui, repo, *pats, **opts):'
991 if not isenabled(repo):
987 if not isenabled(repo):
992 return orig(ui, repo, *pats, **opts)
988 return orig(ui, repo, *pats, **opts)
993
989
994 follow = opts.get(r'follow')
990 follow = opts.get('follow')
995 revs = opts.get(r'rev')
991 revs = opts.get('rev')
996 if pats:
992 if pats:
997 # Force slowpath for non-follow patterns and follows that start from
993 # Force slowpath for non-follow patterns and follows that start from
998 # non-working-copy-parent revs.
994 # non-working-copy-parent revs.
999 if not follow or revs:
995 if not follow or revs:
1000 # This forces the slowpath
996 # This forces the slowpath
1001 opts[r'removed'] = True
997 opts['removed'] = True
1002
998
1003 # If this is a non-follow log without any revs specified, recommend that
999 # If this is a non-follow log without any revs specified, recommend that
1004 # the user add -f to speed it up.
1000 # the user add -f to speed it up.
@@ -1279,20 +1275,20 b' def prefetch(ui, repo, *pats, **opts):'
1279 _(b'hg repack [OPTIONS]'),
1275 _(b'hg repack [OPTIONS]'),
1280 )
1276 )
1281 def repack_(ui, repo, *pats, **opts):
1277 def repack_(ui, repo, *pats, **opts):
1282 if opts.get(r'background'):
1278 if opts.get('background'):
1283 ensurestart = repo.ui.configbool(b'devel', b'remotefilelog.ensurestart')
1279 ensurestart = repo.ui.configbool(b'devel', b'remotefilelog.ensurestart')
1284 repackmod.backgroundrepack(
1280 repackmod.backgroundrepack(
1285 repo,
1281 repo,
1286 incremental=opts.get(r'incremental'),
1282 incremental=opts.get('incremental'),
1287 packsonly=opts.get(r'packsonly', False),
1283 packsonly=opts.get('packsonly', False),
1288 ensurestart=ensurestart,
1284 ensurestart=ensurestart,
1289 )
1285 )
1290 return
1286 return
1291
1287
1292 options = {b'packsonly': opts.get(r'packsonly')}
1288 options = {b'packsonly': opts.get('packsonly')}
1293
1289
1294 try:
1290 try:
1295 if opts.get(r'incremental'):
1291 if opts.get('incremental'):
1296 repackmod.incrementalrepack(repo, options=options)
1292 repackmod.incrementalrepack(repo, options=options)
1297 else:
1293 else:
1298 repackmod.fullrepack(repo, options=options)
1294 repackmod.fullrepack(repo, options=options)
@@ -22,7 +22,7 b' from mercurial import ('
22 )
22 )
23 from . import shallowutil
23 from . import shallowutil
24
24
25 osutil = policy.importmod(r'osutil')
25 osutil = policy.importmod('osutil')
26
26
27 # The pack version supported by this implementation. This will need to be
27 # The pack version supported by this implementation. This will need to be
28 # rev'd whenever the byte format changes. Ex: changing the fanout prefix,
28 # rev'd whenever the byte format changes. Ex: changing the fanout prefix,
@@ -390,8 +390,8 b' class mutablebasepack(versionmixin):'
390 self.idxfp, self.idxpath = opener.mkstemp(
390 self.idxfp, self.idxpath = opener.mkstemp(
391 suffix=self.INDEXSUFFIX + b'-tmp'
391 suffix=self.INDEXSUFFIX + b'-tmp'
392 )
392 )
393 self.packfp = os.fdopen(self.packfp, r'wb+')
393 self.packfp = os.fdopen(self.packfp, 'wb+')
394 self.idxfp = os.fdopen(self.idxfp, r'wb+')
394 self.idxfp = os.fdopen(self.idxfp, 'wb+')
395 self.sha = hashlib.sha1()
395 self.sha = hashlib.sha1()
396 self._closed = False
396 self._closed = False
397
397
@@ -530,11 +530,11 b' class mutablebasepack(versionmixin):'
530
530
531 class indexparams(object):
531 class indexparams(object):
532 __slots__ = (
532 __slots__ = (
533 r'fanoutprefix',
533 'fanoutprefix',
534 r'fanoutstruct',
534 'fanoutstruct',
535 r'fanoutcount',
535 'fanoutcount',
536 r'fanoutsize',
536 'fanoutsize',
537 r'indexstart',
537 'indexstart',
538 )
538 )
539
539
540 def __init__(self, prefixsize, version):
540 def __init__(self, prefixsize, version):
@@ -420,10 +420,10 b' class baseunionstore(object):'
420 # throw a KeyError, try this many times with a full refresh between
420 # throw a KeyError, try this many times with a full refresh between
421 # attempts. A repack operation may have moved data from one store to
421 # attempts. A repack operation may have moved data from one store to
422 # another while we were running.
422 # another while we were running.
423 self.numattempts = kwargs.get(r'numretries', 0) + 1
423 self.numattempts = kwargs.get('numretries', 0) + 1
424 # If not-None, call this function on every retry and if the attempts are
424 # If not-None, call this function on every retry and if the attempts are
425 # exhausted.
425 # exhausted.
426 self.retrylog = kwargs.get(r'retrylog', None)
426 self.retrylog = kwargs.get('retrylog', None)
427
427
428 def markforrefresh(self):
428 def markforrefresh(self):
429 for store in self.stores:
429 for store in self.stores:
@@ -40,12 +40,12 b' class unioncontentstore(basestore.baseun'
40 super(unioncontentstore, self).__init__(*args, **kwargs)
40 super(unioncontentstore, self).__init__(*args, **kwargs)
41
41
42 self.stores = args
42 self.stores = args
43 self.writestore = kwargs.get(r'writestore')
43 self.writestore = kwargs.get('writestore')
44
44
45 # If allowincomplete==True then the union store can return partial
45 # If allowincomplete==True then the union store can return partial
46 # delta chains, otherwise it will throw a KeyError if a full
46 # delta chains, otherwise it will throw a KeyError if a full
47 # deltachain can't be found.
47 # deltachain can't be found.
48 self.allowincomplete = kwargs.get(r'allowincomplete', False)
48 self.allowincomplete = kwargs.get('allowincomplete', False)
49
49
50 def get(self, name, node):
50 def get(self, name, node):
51 """Fetches the full text revision contents of the given name+node pair.
51 """Fetches the full text revision contents of the given name+node pair.
@@ -32,7 +32,7 b' from . import ('
32
32
33
33
34 def debugremotefilelog(ui, path, **opts):
34 def debugremotefilelog(ui, path, **opts):
35 decompress = opts.get(r'decompress')
35 decompress = opts.get('decompress')
36
36
37 size, firstnode, mapping = parsefileblob(path, decompress)
37 size, firstnode, mapping = parsefileblob(path, decompress)
38
38
@@ -101,9 +101,9 b' def buildtemprevlog(repo, file):'
101 def debugindex(orig, ui, repo, file_=None, **opts):
101 def debugindex(orig, ui, repo, file_=None, **opts):
102 """dump the contents of an index file"""
102 """dump the contents of an index file"""
103 if (
103 if (
104 opts.get(r'changelog')
104 opts.get('changelog')
105 or opts.get(r'manifest')
105 or opts.get('manifest')
106 or opts.get(r'dir')
106 or opts.get('dir')
107 or not shallowutil.isenabled(repo)
107 or not shallowutil.isenabled(repo)
108 or not repo.shallowmatch(file_)
108 or not repo.shallowmatch(file_)
109 ):
109 ):
@@ -199,7 +199,7 b' def debugindexdot(orig, ui, repo, file_)'
199
199
200
200
201 def verifyremotefilelog(ui, path, **opts):
201 def verifyremotefilelog(ui, path, **opts):
202 decompress = opts.get(r'decompress')
202 decompress = opts.get('decompress')
203
203
204 for root, dirs, files in os.walk(path):
204 for root, dirs, files in os.walk(path):
205 for file in files:
205 for file in files:
@@ -262,13 +262,13 b' def debugdatapack(ui, *paths, **opts):'
262 path = path[: path.index(b'.data')]
262 path = path[: path.index(b'.data')]
263 ui.write(b"%s:\n" % path)
263 ui.write(b"%s:\n" % path)
264 dpack = datapack.datapack(path)
264 dpack = datapack.datapack(path)
265 node = opts.get(r'node')
265 node = opts.get('node')
266 if node:
266 if node:
267 deltachain = dpack.getdeltachain(b'', bin(node))
267 deltachain = dpack.getdeltachain(b'', bin(node))
268 dumpdeltachain(ui, deltachain, **opts)
268 dumpdeltachain(ui, deltachain, **opts)
269 return
269 return
270
270
271 if opts.get(r'long'):
271 if opts.get('long'):
272 hashformatter = hex
272 hashformatter = hex
273 hashlen = 42
273 hashlen = 42
274 else:
274 else:
@@ -12,12 +12,12 b' class unionmetadatastore(basestore.baseu'
12 super(unionmetadatastore, self).__init__(*args, **kwargs)
12 super(unionmetadatastore, self).__init__(*args, **kwargs)
13
13
14 self.stores = args
14 self.stores = args
15 self.writestore = kwargs.get(r'writestore')
15 self.writestore = kwargs.get('writestore')
16
16
17 # If allowincomplete==True then the union store can return partial
17 # If allowincomplete==True then the union store can return partial
18 # ancestor lists, otherwise it will throw a KeyError if a full
18 # ancestor lists, otherwise it will throw a KeyError if a full
19 # history can't be found.
19 # history can't be found.
20 self.allowincomplete = kwargs.get(r'allowincomplete', False)
20 self.allowincomplete = kwargs.get('allowincomplete', False)
21
21
22 def getancestors(self, name, node, known=None):
22 def getancestors(self, name, node, known=None):
23 """Returns as many ancestors as we're aware of.
23 """Returns as many ancestors as we're aware of.
@@ -48,11 +48,11 b' class remotefilectx(context.filectx):'
48
48
49 @propertycache
49 @propertycache
50 def _changeid(self):
50 def _changeid(self):
51 if r'_changeid' in self.__dict__:
51 if '_changeid' in self.__dict__:
52 return self._changeid
52 return self._changeid
53 elif r'_changectx' in self.__dict__:
53 elif '_changectx' in self.__dict__:
54 return self._changectx.rev()
54 return self._changectx.rev()
55 elif r'_descendantrev' in self.__dict__:
55 elif '_descendantrev' in self.__dict__:
56 # this file context was created from a revision with a known
56 # this file context was created from a revision with a known
57 # descendant, we can (lazily) correct for linkrev aliases
57 # descendant, we can (lazily) correct for linkrev aliases
58 linknode = self._adjustlinknode(
58 linknode = self._adjustlinknode(
@@ -119,7 +119,7 b' class remotefilectx(context.filectx):'
119 """
119 """
120 lkr = self.linkrev()
120 lkr = self.linkrev()
121 attrs = vars(self)
121 attrs = vars(self)
122 noctx = not (r'_changeid' in attrs or r'_changectx' in attrs)
122 noctx = not ('_changeid' in attrs or r'_changectx' in attrs)
123 if noctx or self.rev() == lkr:
123 if noctx or self.rev() == lkr:
124 return lkr
124 return lkr
125 linknode = self._adjustlinknode(
125 linknode = self._adjustlinknode(
@@ -246,11 +246,11 b' class remotefilectx(context.filectx):'
246 return linknode
246 return linknode
247
247
248 commonlogkwargs = {
248 commonlogkwargs = {
249 r'revs': b' '.join([hex(cl.node(rev)) for rev in revs]),
249 'revs': b' '.join([hex(cl.node(rev)) for rev in revs]),
250 r'fnode': hex(fnode),
250 'fnode': hex(fnode),
251 r'filepath': path,
251 'filepath': path,
252 r'user': shallowutil.getusername(repo.ui),
252 'user': shallowutil.getusername(repo.ui),
253 r'reponame': shallowutil.getreponame(repo.ui),
253 'reponame': shallowutil.getreponame(repo.ui),
254 }
254 }
255
255
256 repo.ui.log(b'linkrevfixup', b'adjusting linknode\n', **commonlogkwargs)
256 repo.ui.log(b'linkrevfixup', b'adjusting linknode\n', **commonlogkwargs)
@@ -439,7 +439,7 b' class remotefilectx(context.filectx):'
439
439
440 def annotate(self, *args, **kwargs):
440 def annotate(self, *args, **kwargs):
441 introctx = self
441 introctx = self
442 prefetchskip = kwargs.pop(r'prefetchskip', None)
442 prefetchskip = kwargs.pop('prefetchskip', None)
443 if prefetchskip:
443 if prefetchskip:
444 # use introrev so prefetchskip can be accurately tested
444 # use introrev so prefetchskip can be accurately tested
445 introrev = self.introrev()
445 introrev = self.introrev()
@@ -29,7 +29,7 b' from . import ('
29 shallowutil,
29 shallowutil,
30 )
30 )
31
31
32 osutil = policy.importmod(r'osutil')
32 osutil = policy.importmod('osutil')
33
33
34
34
35 class RepackAlreadyRunning(error.Abort):
35 class RepackAlreadyRunning(error.Abort):
@@ -876,13 +876,13 b' class repackentry(object):'
876 """
876 """
877
877
878 __slots__ = (
878 __slots__ = (
879 r'filename',
879 'filename',
880 r'node',
880 'node',
881 r'datasource',
881 'datasource',
882 r'historysource',
882 'historysource',
883 r'datarepacked',
883 'datarepacked',
884 r'historyrepacked',
884 'historyrepacked',
885 r'gced',
885 'gced',
886 )
886 )
887
887
888 def __init__(self, filename, node):
888 def __init__(self, filename, node):
@@ -153,7 +153,7 b' def makechangegroup(orig, repo, outgoing'
153 try:
153 try:
154 # if serving, only send files the clients has patterns for
154 # if serving, only send files the clients has patterns for
155 if source == b'serve':
155 if source == b'serve':
156 bundlecaps = kwargs.get(r'bundlecaps')
156 bundlecaps = kwargs.get('bundlecaps')
157 includepattern = None
157 includepattern = None
158 excludepattern = None
158 excludepattern = None
159 for cap in bundlecaps or []:
159 for cap in bundlecaps or []:
@@ -122,7 +122,7 b' def clone(orig, ui, source, *args, **opt'
122 if pool:
122 if pool:
123 pool = util.expandpath(pool)
123 pool = util.expandpath(pool)
124
124
125 opts[r'shareopts'] = {
125 opts['shareopts'] = {
126 b'pool': pool,
126 b'pool': pool,
127 b'mode': ui.config(b'share', b'poolnaming'),
127 b'mode': ui.config(b'share', b'poolnaming'),
128 }
128 }
@@ -153,10 +153,10 b' def _setuplog(ui):'
153
153
154
154
155 def _clonesparsecmd(orig, ui, repo, *args, **opts):
155 def _clonesparsecmd(orig, ui, repo, *args, **opts):
156 include_pat = opts.get(r'include')
156 include_pat = opts.get('include')
157 exclude_pat = opts.get(r'exclude')
157 exclude_pat = opts.get('exclude')
158 enableprofile_pat = opts.get(r'enable_profile')
158 enableprofile_pat = opts.get('enable_profile')
159 narrow_pat = opts.get(r'narrow')
159 narrow_pat = opts.get('narrow')
160 include = exclude = enableprofile = False
160 include = exclude = enableprofile = False
161 if include_pat:
161 if include_pat:
162 pat = include_pat
162 pat = include_pat
@@ -209,7 +209,7 b' def _setupadd(ui):'
209 )
209 )
210
210
211 def _add(orig, ui, repo, *pats, **opts):
211 def _add(orig, ui, repo, *pats, **opts):
212 if opts.get(r'sparse'):
212 if opts.get('sparse'):
213 dirs = set()
213 dirs = set()
214 for pat in pats:
214 for pat in pats:
215 dirname, basename = util.split(pat)
215 dirname, basename = util.split(pat)
@@ -235,7 +235,7 b' class transplanter(object):'
235 patchfile = None
235 patchfile = None
236 else:
236 else:
237 fd, patchfile = pycompat.mkstemp(prefix=b'hg-transplant-')
237 fd, patchfile = pycompat.mkstemp(prefix=b'hg-transplant-')
238 fp = os.fdopen(fd, r'wb')
238 fp = os.fdopen(fd, 'wb')
239 gen = patch.diff(source, parent, node, opts=diffopts)
239 gen = patch.diff(source, parent, node, opts=diffopts)
240 for chunk in gen:
240 for chunk in gen:
241 fp.write(chunk)
241 fp.write(chunk)
@@ -290,7 +290,7 b' class transplanter(object):'
290 self.ui.status(_(b'filtering %s\n') % patchfile)
290 self.ui.status(_(b'filtering %s\n') % patchfile)
291 user, date, msg = (changelog[1], changelog[2], changelog[4])
291 user, date, msg = (changelog[1], changelog[2], changelog[4])
292 fd, headerfile = pycompat.mkstemp(prefix=b'hg-transplant-')
292 fd, headerfile = pycompat.mkstemp(prefix=b'hg-transplant-')
293 fp = os.fdopen(fd, r'wb')
293 fp = os.fdopen(fd, 'wb')
294 fp.write(b"# HG changeset patch\n")
294 fp.write(b"# HG changeset patch\n")
295 fp.write(b"# User %s\n" % user)
295 fp.write(b"# User %s\n" % user)
296 fp.write(b"# Date %d %d\n" % date)
296 fp.write(b"# Date %d %d\n" % date)
@@ -684,7 +684,7 b' class DNSIncoming(object):'
684 break
684 break
685 t = len & 0xC0
685 t = len & 0xC0
686 if t == 0x00:
686 if t == 0x00:
687 result = r''.join((result, self.readUTF(off, len) + r'.'))
687 result = ''.join((result, self.readUTF(off, len) + '.'))
688 off += len
688 off += len
689 elif t == 0xC0:
689 elif t == 0xC0:
690 if next < 0:
690 if next < 0:
@@ -1425,7 +1425,7 b' class Zeroconf(object):'
1425 self.socket.setsockopt(
1425 self.socket.setsockopt(
1426 socket.SOL_IP,
1426 socket.SOL_IP,
1427 socket.IP_ADD_MEMBERSHIP,
1427 socket.IP_ADD_MEMBERSHIP,
1428 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0'),
1428 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'),
1429 )
1429 )
1430
1430
1431 self.listeners = []
1431 self.listeners = []
@@ -1841,7 +1841,7 b' class Zeroconf(object):'
1841 self.socket.setsockopt(
1841 self.socket.setsockopt(
1842 socket.SOL_IP,
1842 socket.SOL_IP,
1843 socket.IP_DROP_MEMBERSHIP,
1843 socket.IP_DROP_MEMBERSHIP,
1844 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0'),
1844 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'),
1845 )
1845 )
1846 self.socket.close()
1846 self.socket.close()
1847
1847
@@ -55,7 +55,7 b' def getip():'
55 # finds external-facing interface without sending any packets (Linux)
55 # finds external-facing interface without sending any packets (Linux)
56 try:
56 try:
57 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
57 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
58 s.connect((r'1.0.0.1', 0))
58 s.connect(('1.0.0.1', 0))
59 ip = s.getsockname()[0]
59 ip = s.getsockname()[0]
60 return ip
60 return ip
61 except socket.error:
61 except socket.error:
@@ -64,17 +64,17 b' def getip():'
64 # Generic method, sometimes gives useless results
64 # Generic method, sometimes gives useless results
65 try:
65 try:
66 dumbip = socket.gethostbyaddr(socket.gethostname())[2][0]
66 dumbip = socket.gethostbyaddr(socket.gethostname())[2][0]
67 if r':' in dumbip:
67 if ':' in dumbip:
68 dumbip = r'127.0.0.1'
68 dumbip = '127.0.0.1'
69 if not dumbip.startswith(r'127.'):
69 if not dumbip.startswith('127.'):
70 return dumbip
70 return dumbip
71 except (socket.gaierror, socket.herror):
71 except (socket.gaierror, socket.herror):
72 dumbip = r'127.0.0.1'
72 dumbip = '127.0.0.1'
73
73
74 # works elsewhere, but actually sends a packet
74 # works elsewhere, but actually sends a packet
75 try:
75 try:
76 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
76 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
77 s.connect((r'1.0.0.1', 1))
77 s.connect(('1.0.0.1', 1))
78 ip = s.getsockname()[0]
78 ip = s.getsockname()[0]
79 return ip
79 return ip
80 except socket.error:
80 except socket.error:
@@ -87,20 +87,20 b' def publish(name, desc, path, port):'
87 global server, localip
87 global server, localip
88 if not server:
88 if not server:
89 ip = getip()
89 ip = getip()
90 if ip.startswith(r'127.'):
90 if ip.startswith('127.'):
91 # if we have no internet connection, this can happen.
91 # if we have no internet connection, this can happen.
92 return
92 return
93 localip = socket.inet_aton(ip)
93 localip = socket.inet_aton(ip)
94 server = Zeroconf.Zeroconf(ip)
94 server = Zeroconf.Zeroconf(ip)
95
95
96 hostname = socket.gethostname().split(r'.')[0]
96 hostname = socket.gethostname().split('.')[0]
97 host = hostname + r".local"
97 host = hostname + ".local"
98 name = "%s-%s" % (hostname, name)
98 name = "%s-%s" % (hostname, name)
99
99
100 # advertise to browsers
100 # advertise to browsers
101 svc = Zeroconf.ServiceInfo(
101 svc = Zeroconf.ServiceInfo(
102 b'_http._tcp.local.',
102 b'_http._tcp.local.',
103 pycompat.bytestr(name + r'._http._tcp.local.'),
103 pycompat.bytestr(name + '._http._tcp.local.'),
104 server=host,
104 server=host,
105 port=port,
105 port=port,
106 properties={b'description': desc, b'path': b"/" + path},
106 properties={b'description': desc, b'path': b"/" + path},
@@ -113,7 +113,7 b' def publish(name, desc, path, port):'
113 # advertise to Mercurial clients
113 # advertise to Mercurial clients
114 svc = Zeroconf.ServiceInfo(
114 svc = Zeroconf.ServiceInfo(
115 b'_hg._tcp.local.',
115 b'_hg._tcp.local.',
116 pycompat.bytestr(name + r'._hg._tcp.local.'),
116 pycompat.bytestr(name + '._hg._tcp.local.'),
117 server=host,
117 server=host,
118 port=port,
118 port=port,
119 properties={b'description': desc, b'path': b"/" + path},
119 properties={b'description': desc, b'path': b"/" + path},
@@ -171,7 +171,7 b' class listener(object):'
171
171
172 def getzcpaths():
172 def getzcpaths():
173 ip = getip()
173 ip = getip()
174 if ip.startswith(r'127.'):
174 if ip.startswith('127.'):
175 return
175 return
176 server = Zeroconf.Zeroconf(ip)
176 server = Zeroconf.Zeroconf(ip)
177 l = listener()
177 l = listener()
@@ -16,7 +16,7 b' from . import ('
16 pycompat,
16 pycompat,
17 )
17 )
18
18
19 parsers = policy.importmod(r'parsers')
19 parsers = policy.importmod('parsers')
20
20
21
21
22 def commonancestorsheads(pfunc, *nodes):
22 def commonancestorsheads(pfunc, *nodes):
@@ -138,8 +138,8 b' class tarit(object):'
138 class GzipFileWithTime(gzip.GzipFile):
138 class GzipFileWithTime(gzip.GzipFile):
139 def __init__(self, *args, **kw):
139 def __init__(self, *args, **kw):
140 timestamp = None
140 timestamp = None
141 if r'timestamp' in kw:
141 if 'timestamp' in kw:
142 timestamp = kw.pop(r'timestamp')
142 timestamp = kw.pop('timestamp')
143 if timestamp is None:
143 if timestamp is None:
144 self.timestamp = time.time()
144 self.timestamp = time.time()
145 else:
145 else:
@@ -222,7 +222,7 b' class zipit(object):'
222 if isinstance(dest, bytes):
222 if isinstance(dest, bytes):
223 dest = pycompat.fsdecode(dest)
223 dest = pycompat.fsdecode(dest)
224 self.z = zipfile.ZipFile(
224 self.z = zipfile.ZipFile(
225 dest, r'w', compress and zipfile.ZIP_DEFLATED or zipfile.ZIP_STORED
225 dest, 'w', compress and zipfile.ZIP_DEFLATED or zipfile.ZIP_STORED
226 )
226 )
227
227
228 # Python's zipfile module emits deprecation warnings if we try
228 # Python's zipfile module emits deprecation warnings if we try
@@ -124,7 +124,7 b' class BranchMapCache(object):'
124 def _unknownnode(node):
124 def _unknownnode(node):
125 """ raises ValueError when branchcache found a node which does not exists
125 """ raises ValueError when branchcache found a node which does not exists
126 """
126 """
127 raise ValueError(r'node %s does not exist' % pycompat.sysstr(hex(node)))
127 raise ValueError('node %s does not exist' % pycompat.sysstr(hex(node)))
128
128
129
129
130 def _branchcachedesc(repo):
130 def _branchcachedesc(repo):
@@ -260,7 +260,7 b' class branchcache(object):'
260 )
260 )
261 if not bcache.validfor(repo):
261 if not bcache.validfor(repo):
262 # invalidate the cache
262 # invalidate the cache
263 raise ValueError(r'tip differs')
263 raise ValueError('tip differs')
264 bcache.load(repo, lineiter)
264 bcache.load(repo, lineiter)
265 except (IOError, OSError):
265 except (IOError, OSError):
266 return None
266 return None
@@ -294,7 +294,7 b' class branchcache(object):'
294 continue
294 continue
295 node, state, label = line.split(b" ", 2)
295 node, state, label = line.split(b" ", 2)
296 if state not in b'oc':
296 if state not in b'oc':
297 raise ValueError(r'invalid branch state')
297 raise ValueError('invalid branch state')
298 label = encoding.tolocal(label.strip())
298 label = encoding.tolocal(label.strip())
299 node = bin(node)
299 node = bin(node)
300 self._entries.setdefault(label, []).append(node)
300 self._entries.setdefault(label, []).append(node)
@@ -646,7 +646,7 b' class revbranchcache(object):'
646 # self.branchinfo = self._branchinfo
646 # self.branchinfo = self._branchinfo
647 #
647 #
648 # Since we now have data in the cache, we need to drop this bypassing.
648 # Since we now have data in the cache, we need to drop this bypassing.
649 if r'branchinfo' in vars(self):
649 if 'branchinfo' in vars(self):
650 del self.branchinfo
650 del self.branchinfo
651
651
652 def _setcachedata(self, rev, node, branchidx):
652 def _setcachedata(self, rev, node, branchidx):
@@ -837,11 +837,11 b' class unbundle20(unpackermixin):'
837 ignored or failing.
837 ignored or failing.
838 """
838 """
839 if not name:
839 if not name:
840 raise ValueError(r'empty parameter name')
840 raise ValueError('empty parameter name')
841 if name[0:1] not in pycompat.bytestr(
841 if name[0:1] not in pycompat.bytestr(
842 string.ascii_letters # pytype: disable=wrong-arg-types
842 string.ascii_letters # pytype: disable=wrong-arg-types
843 ):
843 ):
844 raise ValueError(r'non letter first character: %s' % name)
844 raise ValueError('non letter first character: %s' % name)
845 try:
845 try:
846 handler = b2streamparamsmap[name.lower()]
846 handler = b2streamparamsmap[name.lower()]
847 except KeyError:
847 except KeyError:
@@ -1145,8 +1145,8 b' class bundlepart(object):'
1145 headerchunk = b''.join(header)
1145 headerchunk = b''.join(header)
1146 except TypeError:
1146 except TypeError:
1147 raise TypeError(
1147 raise TypeError(
1148 r'Found a non-bytes trying to '
1148 'Found a non-bytes trying to '
1149 r'build bundle part header: %r' % header
1149 'build bundle part header: %r' % header
1150 )
1150 )
1151 outdebug(ui, b'header chunk size: %i' % len(headerchunk))
1151 outdebug(ui, b'header chunk size: %i' % len(headerchunk))
1152 yield _pack(_fpartheadersize, len(headerchunk))
1152 yield _pack(_fpartheadersize, len(headerchunk))
@@ -1797,7 +1797,7 b' def _formatrequirementsparams(requiremen'
1797
1797
1798
1798
1799 def addpartbundlestream2(bundler, repo, **kwargs):
1799 def addpartbundlestream2(bundler, repo, **kwargs):
1800 if not kwargs.get(r'stream', False):
1800 if not kwargs.get('stream', False):
1801 return
1801 return
1802
1802
1803 if not streamclone.allowservergeneration(repo):
1803 if not streamclone.allowservergeneration(repo):
@@ -1819,8 +1819,8 b' def addpartbundlestream2(bundler, repo, '
1819 bundler.prefercompressed = False
1819 bundler.prefercompressed = False
1820
1820
1821 # get the includes and excludes
1821 # get the includes and excludes
1822 includepats = kwargs.get(r'includepats')
1822 includepats = kwargs.get('includepats')
1823 excludepats = kwargs.get(r'excludepats')
1823 excludepats = kwargs.get('excludepats')
1824
1824
1825 narrowstream = repo.ui.configbool(
1825 narrowstream = repo.ui.configbool(
1826 b'experimental', b'server.stream-narrow-clones'
1826 b'experimental', b'server.stream-narrow-clones'
@@ -1989,7 +1989,7 b' def handlechangegroup(op, inpart):'
1989 extrakwargs = {}
1989 extrakwargs = {}
1990 targetphase = inpart.params.get(b'targetphase')
1990 targetphase = inpart.params.get(b'targetphase')
1991 if targetphase is not None:
1991 if targetphase is not None:
1992 extrakwargs[r'targetphase'] = int(targetphase)
1992 extrakwargs['targetphase'] = int(targetphase)
1993 ret = _processchangegroup(
1993 ret = _processchangegroup(
1994 op,
1994 op,
1995 cg,
1995 cg,
@@ -331,7 +331,7 b' class bundlerepository(object):'
331 fdtemp, temp = self.vfs.mkstemp(prefix=b"hg-bundle-", suffix=suffix)
331 fdtemp, temp = self.vfs.mkstemp(prefix=b"hg-bundle-", suffix=suffix)
332 self.tempfile = temp
332 self.tempfile = temp
333
333
334 with os.fdopen(fdtemp, r'wb') as fptemp:
334 with os.fdopen(fdtemp, 'wb') as fptemp:
335 fptemp.write(header)
335 fptemp.write(header)
336 while True:
336 while True:
337 chunk = readfn(2 ** 18)
337 chunk = readfn(2 ** 18)
@@ -393,7 +393,7 b' class bundlerepository(object):'
393 # manifestlog implementation did not consume the manifests from the
393 # manifestlog implementation did not consume the manifests from the
394 # changegroup (ex: it might be consuming trees from a separate bundle2
394 # changegroup (ex: it might be consuming trees from a separate bundle2
395 # part instead). So we need to manually consume it.
395 # part instead). So we need to manually consume it.
396 if r'filestart' not in self.__dict__:
396 if 'filestart' not in self.__dict__:
397 self._consumemanifest()
397 self._consumemanifest()
398
398
399 return self.filestart
399 return self.filestart
@@ -211,10 +211,10 b' class changelogrevision(object):'
211 """
211 """
212
212
213 __slots__ = (
213 __slots__ = (
214 r'_offsets',
214 '_offsets',
215 r'_text',
215 '_text',
216 r'_sidedata',
216 '_sidedata',
217 r'_cpsd',
217 '_cpsd',
218 )
218 )
219
219
220 def __new__(cls, text, sidedata, cpsd):
220 def __new__(cls, text, sidedata, cpsd):
@@ -345,9 +345,9 b' class channeledsystem(object):'
345
345
346 _iochannels = [
346 _iochannels = [
347 # server.ch, ui.fp, mode
347 # server.ch, ui.fp, mode
348 (b'cin', b'fin', r'rb'),
348 (b'cin', b'fin', 'rb'),
349 (b'cout', b'fout', r'wb'),
349 (b'cout', b'fout', 'wb'),
350 (b'cerr', b'ferr', r'wb'),
350 (b'cerr', b'ferr', 'wb'),
351 ]
351 ]
352
352
353
353
@@ -320,7 +320,7 b' def parsealiases(cmd):'
320 def setupwrapcolorwrite(ui):
320 def setupwrapcolorwrite(ui):
321 # wrap ui.write so diff output can be labeled/colorized
321 # wrap ui.write so diff output can be labeled/colorized
322 def wrapwrite(orig, *args, **kw):
322 def wrapwrite(orig, *args, **kw):
323 label = kw.pop(r'label', b'')
323 label = kw.pop('label', b'')
324 for chunk, l in patch.difflabel(lambda: args):
324 for chunk, l in patch.difflabel(lambda: args):
325 orig(chunk, label=label + l)
325 orig(chunk, label=label + l)
326
326
@@ -2397,7 +2397,7 b' def add(ui, repo, match, prefix, uipathf'
2397 submatch = matchmod.subdirmatcher(subpath, match)
2397 submatch = matchmod.subdirmatcher(subpath, match)
2398 subprefix = repo.wvfs.reljoin(prefix, subpath)
2398 subprefix = repo.wvfs.reljoin(prefix, subpath)
2399 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2399 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2400 if opts.get(r'subrepos'):
2400 if opts.get('subrepos'):
2401 bad.extend(
2401 bad.extend(
2402 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2402 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2403 )
2403 )
@@ -2410,7 +2410,7 b' def add(ui, repo, match, prefix, uipathf'
2410 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2410 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2411 )
2411 )
2412
2412
2413 if not opts.get(r'dry_run'):
2413 if not opts.get('dry_run'):
2414 rejected = wctx.add(names, prefix)
2414 rejected = wctx.add(names, prefix)
2415 bad.extend(f for f in rejected if f in match.files())
2415 bad.extend(f for f in rejected if f in match.files())
2416 return bad
2416 return bad
@@ -184,7 +184,7 b' def _terminfosetup(ui, mode, formatted):'
184 # noisy and use ui.debug().
184 # noisy and use ui.debug().
185 ui.debug(b"no terminfo entry for %s\n" % e)
185 ui.debug(b"no terminfo entry for %s\n" % e)
186 del ui._terminfoparams[key]
186 del ui._terminfoparams[key]
187 if not curses.tigetstr(r'setaf') or not curses.tigetstr(r'setab'):
187 if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
188 # Only warn about missing terminfo entries if we explicitly asked for
188 # Only warn about missing terminfo entries if we explicitly asked for
189 # terminfo mode and we're in a formatted terminal.
189 # terminfo mode and we're in a formatted terminal.
190 if mode == b"terminfo" and formatted:
190 if mode == b"terminfo" and formatted:
@@ -353,9 +353,9 b' def _effect_str(ui, effect):'
353 else:
353 else:
354 return curses.tigetstr(pycompat.sysstr(val))
354 return curses.tigetstr(pycompat.sysstr(val))
355 elif bg:
355 elif bg:
356 return curses.tparm(curses.tigetstr(r'setab'), val)
356 return curses.tparm(curses.tigetstr('setab'), val)
357 else:
357 else:
358 return curses.tparm(curses.tigetstr(r'setaf'), val)
358 return curses.tparm(curses.tigetstr('setaf'), val)
359
359
360
360
361 def _mergeeffects(text, start, stop):
361 def _mergeeffects(text, start, stop):
@@ -442,23 +442,23 b' if pycompat.iswindows:'
442 _INVALID_HANDLE_VALUE = -1
442 _INVALID_HANDLE_VALUE = -1
443
443
444 class _COORD(ctypes.Structure):
444 class _COORD(ctypes.Structure):
445 _fields_ = [(r'X', ctypes.c_short), (r'Y', ctypes.c_short)]
445 _fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)]
446
446
447 class _SMALL_RECT(ctypes.Structure):
447 class _SMALL_RECT(ctypes.Structure):
448 _fields_ = [
448 _fields_ = [
449 (r'Left', ctypes.c_short),
449 ('Left', ctypes.c_short),
450 (r'Top', ctypes.c_short),
450 ('Top', ctypes.c_short),
451 (r'Right', ctypes.c_short),
451 ('Right', ctypes.c_short),
452 (r'Bottom', ctypes.c_short),
452 ('Bottom', ctypes.c_short),
453 ]
453 ]
454
454
455 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
455 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
456 _fields_ = [
456 _fields_ = [
457 (r'dwSize', _COORD),
457 ('dwSize', _COORD),
458 (r'dwCursorPosition', _COORD),
458 ('dwCursorPosition', _COORD),
459 (r'wAttributes', _WORD),
459 ('wAttributes', _WORD),
460 (r'srWindow', _SMALL_RECT),
460 ('srWindow', _SMALL_RECT),
461 (r'dwMaximumWindowSize', _COORD),
461 ('dwMaximumWindowSize', _COORD),
462 ]
462 ]
463
463
464 _STD_OUTPUT_HANDLE = 0xFFFFFFF5 # (DWORD)-11
464 _STD_OUTPUT_HANDLE = 0xFFFFFFF5 # (DWORD)-11
@@ -529,7 +529,7 b' if pycompat.iswindows:'
529 )
529 )
530
530
531 def win32print(ui, writefunc, text, **opts):
531 def win32print(ui, writefunc, text, **opts):
532 label = opts.get(r'label', b'')
532 label = opts.get('label', b'')
533 attr = origattr
533 attr = origattr
534
534
535 def mapcolor(val, attr):
535 def mapcolor(val, attr):
@@ -180,7 +180,7 b' def abort(ui, repo, **opts):'
180
180
181 use --dry-run/-n to dry run the command.
181 use --dry-run/-n to dry run the command.
182 """
182 """
183 dryrun = opts.get(r'dry_run')
183 dryrun = opts.get('dry_run')
184 abortstate = cmdutil.getunfinishedstate(repo)
184 abortstate = cmdutil.getunfinishedstate(repo)
185 if not abortstate:
185 if not abortstate:
186 raise error.Abort(_(b'no operation in progress'))
186 raise error.Abort(_(b'no operation in progress'))
@@ -2019,8 +2019,8 b' def commit(ui, repo, *pats, **opts):'
2019
2019
2020
2020
2021 def _docommit(ui, repo, *pats, **opts):
2021 def _docommit(ui, repo, *pats, **opts):
2022 if opts.get(r'interactive'):
2022 if opts.get('interactive'):
2023 opts.pop(r'interactive')
2023 opts.pop('interactive')
2024 ret = cmdutil.dorecord(
2024 ret = cmdutil.dorecord(
2025 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2025 ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts
2026 )
2026 )
@@ -2295,7 +2295,7 b' def continuecmd(ui, repo, **opts):'
2295
2295
2296 use --dry-run/-n to dry run the command.
2296 use --dry-run/-n to dry run the command.
2297 """
2297 """
2298 dryrun = opts.get(r'dry_run')
2298 dryrun = opts.get('dry_run')
2299 contstate = cmdutil.getunfinishedstate(repo)
2299 contstate = cmdutil.getunfinishedstate(repo)
2300 if not contstate:
2300 if not contstate:
2301 raise error.Abort(_(b'no operation in progress'))
2301 raise error.Abort(_(b'no operation in progress'))
@@ -2375,7 +2375,7 b" def debugcommands(ui, cmd=b'', *args):"
2375 def debugcomplete(ui, cmd=b'', **opts):
2375 def debugcomplete(ui, cmd=b'', **opts):
2376 """returns the completion list associated with the given command"""
2376 """returns the completion list associated with the given command"""
2377
2377
2378 if opts.get(r'options'):
2378 if opts.get('options'):
2379 options = []
2379 options = []
2380 otables = [globalopts]
2380 otables = [globalopts]
2381 if cmd:
2381 if cmd:
@@ -3456,13 +3456,13 b' def grep(ui, repo, pattern, *pats, **opt'
3456 def difflinestates(a, b):
3456 def difflinestates(a, b):
3457 sm = difflib.SequenceMatcher(None, a, b)
3457 sm = difflib.SequenceMatcher(None, a, b)
3458 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3458 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3459 if tag == r'insert':
3459 if tag == 'insert':
3460 for i in pycompat.xrange(blo, bhi):
3460 for i in pycompat.xrange(blo, bhi):
3461 yield (b'+', b[i])
3461 yield (b'+', b[i])
3462 elif tag == r'delete':
3462 elif tag == 'delete':
3463 for i in pycompat.xrange(alo, ahi):
3463 for i in pycompat.xrange(alo, ahi):
3464 yield (b'-', a[i])
3464 yield (b'-', a[i])
3465 elif tag == r'replace':
3465 elif tag == 'replace':
3466 for i in pycompat.xrange(alo, ahi):
3466 for i in pycompat.xrange(alo, ahi):
3467 yield (b'-', a[i])
3467 yield (b'-', a[i])
3468 for i in pycompat.xrange(blo, bhi):
3468 for i in pycompat.xrange(blo, bhi):
@@ -3789,7 +3789,7 b' def help_(ui, name=None, **opts):'
3789 Returns 0 if successful.
3789 Returns 0 if successful.
3790 """
3790 """
3791
3791
3792 keep = opts.get(r'system') or []
3792 keep = opts.get('system') or []
3793 if len(keep) == 0:
3793 if len(keep) == 0:
3794 if pycompat.sysplatform.startswith(b'win'):
3794 if pycompat.sysplatform.startswith(b'win'):
3795 keep.append(b'windows')
3795 keep.append(b'windows')
@@ -5699,7 +5699,7 b' def recover(ui, repo, **opts):'
5699 """
5699 """
5700 ret = repo.recover()
5700 ret = repo.recover()
5701 if ret:
5701 if ret:
5702 if opts[r'verify']:
5702 if opts['verify']:
5703 return hg.verify(repo)
5703 return hg.verify(repo)
5704 else:
5704 else:
5705 msg = _(
5705 msg = _(
@@ -6344,7 +6344,7 b' def rollback(ui, repo, **opts):'
6344 _(b'rollback is disabled because it is unsafe'),
6344 _(b'rollback is disabled because it is unsafe'),
6345 hint=b'see `hg help -v rollback` for information',
6345 hint=b'see `hg help -v rollback` for information',
6346 )
6346 )
6347 return repo.rollback(dryrun=opts.get(r'dry_run'), force=opts.get(r'force'))
6347 return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force'))
6348
6348
6349
6349
6350 @command(
6350 @command(
@@ -7494,7 +7494,7 b' def unbundle(ui, repo, fname1, *fnames, '
7494 )
7494 )
7495 modheads = bundle2.combinechangegroupresults(op)
7495 modheads = bundle2.combinechangegroupresults(op)
7496
7496
7497 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
7497 return postincoming(ui, repo, modheads, opts.get('update'), None, None)
7498
7498
7499
7499
7500 @command(
7500 @command(
@@ -7655,11 +7655,11 b' def update(ui, repo, node=None, **opts):'
7655
7655
7656 Returns 0 on success, 1 if there are unresolved files.
7656 Returns 0 on success, 1 if there are unresolved files.
7657 """
7657 """
7658 rev = opts.get(r'rev')
7658 rev = opts.get('rev')
7659 date = opts.get(r'date')
7659 date = opts.get('date')
7660 clean = opts.get(r'clean')
7660 clean = opts.get('clean')
7661 check = opts.get(r'check')
7661 check = opts.get('check')
7662 merge = opts.get(r'merge')
7662 merge = opts.get('merge')
7663 if rev and node:
7663 if rev and node:
7664 raise error.Abort(_(b"please specify just one revision"))
7664 raise error.Abort(_(b"please specify just one revision"))
7665
7665
@@ -7702,7 +7702,7 b' def update(ui, repo, node=None, **opts):'
7702 ctx = scmutil.revsingle(repo, rev, default=None)
7702 ctx = scmutil.revsingle(repo, rev, default=None)
7703 rev = ctx.rev()
7703 rev = ctx.rev()
7704 hidden = ctx.hidden()
7704 hidden = ctx.hidden()
7705 overrides = {(b'ui', b'forcemerge'): opts.get(r'tool', b'')}
7705 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
7706 with ui.configoverride(overrides, b'update'):
7706 with ui.configoverride(overrides, b'update'):
7707 ret = hg.updatetotally(
7707 ret = hg.updatetotally(
7708 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
7708 ui, repo, rev, brev, clean=clean, updatecheck=updatecheck
@@ -64,7 +64,7 b' class channeledoutput(object):'
64 self.out.flush()
64 self.out.flush()
65
65
66 def __getattr__(self, attr):
66 def __getattr__(self, attr):
67 if attr in (r'isatty', r'fileno', r'tell', r'seek'):
67 if attr in ('isatty', 'fileno', 'tell', 'seek'):
68 raise AttributeError(attr)
68 raise AttributeError(attr)
69 return getattr(self.out, attr)
69 return getattr(self.out, attr)
70
70
@@ -180,7 +180,7 b' class channeledinput(object):'
180 __next__ = next
180 __next__ = next
181
181
182 def __getattr__(self, attr):
182 def __getattr__(self, attr):
183 if attr in (r'isatty', r'fileno', r'tell', r'seek'):
183 if attr in ('isatty', 'fileno', 'tell', 'seek'):
184 raise AttributeError(attr)
184 raise AttributeError(attr)
185 return getattr(self.in_, attr)
185 return getattr(self.in_, attr)
186
186
@@ -450,8 +450,8 b' def _initworkerprocess():'
450
450
451
451
452 def _serverequest(ui, repo, conn, createcmdserver, prereposetups):
452 def _serverequest(ui, repo, conn, createcmdserver, prereposetups):
453 fin = conn.makefile(r'rb')
453 fin = conn.makefile('rb')
454 fout = conn.makefile(r'wb')
454 fout = conn.makefile('wb')
455 sv = None
455 sv = None
456 try:
456 try:
457 sv = createcmdserver(repo, conn, fin, fout, prereposetups)
457 sv = createcmdserver(repo, conn, fin, fout, prereposetups)
@@ -212,7 +212,7 b' class config(object):'
212 def read(self, path, fp=None, sections=None, remap=None):
212 def read(self, path, fp=None, sections=None, remap=None):
213 if not fp:
213 if not fp:
214 fp = util.posixfile(path, b'rb')
214 fp = util.posixfile(path, b'rb')
215 assert getattr(fp, 'mode', r'rb') == r'rb', (
215 assert getattr(fp, 'mode', 'rb') == 'rb', (
216 b'config files must be opened in binary mode, got fp=%r mode=%r'
216 b'config files must be opened in binary mode, got fp=%r mode=%r'
217 % (fp, fp.mode,)
217 % (fp, fp.mode,)
218 )
218 )
@@ -265,14 +265,14 b' class basectx(object):'
265 return self._repo[nullrev]
265 return self._repo[nullrev]
266
266
267 def _fileinfo(self, path):
267 def _fileinfo(self, path):
268 if r'_manifest' in self.__dict__:
268 if '_manifest' in self.__dict__:
269 try:
269 try:
270 return self._manifest[path], self._manifest.flags(path)
270 return self._manifest[path], self._manifest.flags(path)
271 except KeyError:
271 except KeyError:
272 raise error.ManifestLookupError(
272 raise error.ManifestLookupError(
273 self._node, path, _(b'not found in manifest')
273 self._node, path, _(b'not found in manifest')
274 )
274 )
275 if r'_manifestdelta' in self.__dict__ or path in self.files():
275 if '_manifestdelta' in self.__dict__ or path in self.files():
276 if path in self._manifestdelta:
276 if path in self._manifestdelta:
277 return (
277 return (
278 self._manifestdelta[path],
278 self._manifestdelta[path],
@@ -746,9 +746,9 b' class basefilectx(object):'
746
746
747 @propertycache
747 @propertycache
748 def _changeid(self):
748 def _changeid(self):
749 if r'_changectx' in self.__dict__:
749 if '_changectx' in self.__dict__:
750 return self._changectx.rev()
750 return self._changectx.rev()
751 elif r'_descendantrev' in self.__dict__:
751 elif '_descendantrev' in self.__dict__:
752 # this file context was created from a revision with a known
752 # this file context was created from a revision with a known
753 # descendant, we can (lazily) correct for linkrev aliases
753 # descendant, we can (lazily) correct for linkrev aliases
754 return self._adjustlinkrev(self._descendantrev)
754 return self._adjustlinkrev(self._descendantrev)
@@ -757,7 +757,7 b' class basefilectx(object):'
757
757
758 @propertycache
758 @propertycache
759 def _filenode(self):
759 def _filenode(self):
760 if r'_fileid' in self.__dict__:
760 if '_fileid' in self.__dict__:
761 return self._filelog.lookup(self._fileid)
761 return self._filelog.lookup(self._fileid)
762 else:
762 else:
763 return self._changectx.filenode(self._path)
763 return self._changectx.filenode(self._path)
@@ -1024,16 +1024,16 b' class basefilectx(object):'
1024 """
1024 """
1025 toprev = None
1025 toprev = None
1026 attrs = vars(self)
1026 attrs = vars(self)
1027 if r'_changeid' in attrs:
1027 if '_changeid' in attrs:
1028 # We have a cached value already
1028 # We have a cached value already
1029 toprev = self._changeid
1029 toprev = self._changeid
1030 elif r'_changectx' in attrs:
1030 elif '_changectx' in attrs:
1031 # We know which changelog entry we are coming from
1031 # We know which changelog entry we are coming from
1032 toprev = self._changectx.rev()
1032 toprev = self._changectx.rev()
1033
1033
1034 if toprev is not None:
1034 if toprev is not None:
1035 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1035 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1036 elif r'_descendantrev' in attrs:
1036 elif '_descendantrev' in attrs:
1037 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1037 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1038 # be nice and cache the result of the computation
1038 # be nice and cache the result of the computation
1039 if introrev is not None:
1039 if introrev is not None:
@@ -1053,14 +1053,14 b' class basefilectx(object):'
1053 def _parentfilectx(self, path, fileid, filelog):
1053 def _parentfilectx(self, path, fileid, filelog):
1054 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1054 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1055 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1055 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1056 if r'_changeid' in vars(self) or r'_changectx' in vars(self):
1056 if '_changeid' in vars(self) or '_changectx' in vars(self):
1057 # If self is associated with a changeset (probably explicitly
1057 # If self is associated with a changeset (probably explicitly
1058 # fed), ensure the created filectx is associated with a
1058 # fed), ensure the created filectx is associated with a
1059 # changeset that is an ancestor of self.changectx.
1059 # changeset that is an ancestor of self.changectx.
1060 # This lets us later use _adjustlinkrev to get a correct link.
1060 # This lets us later use _adjustlinkrev to get a correct link.
1061 fctx._descendantrev = self.rev()
1061 fctx._descendantrev = self.rev()
1062 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1062 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1063 elif r'_descendantrev' in vars(self):
1063 elif '_descendantrev' in vars(self):
1064 # Otherwise propagate _descendantrev if we have one associated.
1064 # Otherwise propagate _descendantrev if we have one associated.
1065 fctx._descendantrev = self._descendantrev
1065 fctx._descendantrev = self._descendantrev
1066 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1066 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
@@ -1120,7 +1120,7 b' class basefilectx(object):'
1120 # renamed filectx won't have a filelog yet, so set it
1120 # renamed filectx won't have a filelog yet, so set it
1121 # from the cache to save time
1121 # from the cache to save time
1122 for p in pl:
1122 for p in pl:
1123 if not r'_filelog' in p.__dict__:
1123 if not '_filelog' in p.__dict__:
1124 p._filelog = getlog(p.path())
1124 p._filelog = getlog(p.path())
1125
1125
1126 return pl
1126 return pl
@@ -1534,7 +1534,7 b' class workingctx(committablectx):'
1534 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1534 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1535
1535
1536 def flags(self, path):
1536 def flags(self, path):
1537 if r'_manifest' in self.__dict__:
1537 if '_manifest' in self.__dict__:
1538 try:
1538 try:
1539 return self._manifest.flags(path)
1539 return self._manifest.flags(path)
1540 except KeyError:
1540 except KeyError:
@@ -522,7 +522,7 b' class uihunk(patchnode):'
522 return getattr(self._hunk, name)
522 return getattr(self._hunk, name)
523
523
524 def __repr__(self):
524 def __repr__(self):
525 return r'<hunk %r@%d>' % (self.filename(), self.fromline)
525 return '<hunk %r@%d>' % (self.filename(), self.fromline)
526
526
527
527
528 def filterpatch(ui, chunks, chunkselector, operation=None):
528 def filterpatch(ui, chunks, chunkselector, operation=None):
@@ -569,7 +569,7 b' def chunkselector(ui, headerlist, operat'
569 chunkselector = curseschunkselector(headerlist, ui, operation)
569 chunkselector = curseschunkselector(headerlist, ui, operation)
570 # This is required for ncurses to display non-ASCII characters in
570 # This is required for ncurses to display non-ASCII characters in
571 # default user locale encoding correctly. --immerrr
571 # default user locale encoding correctly. --immerrr
572 locale.setlocale(locale.LC_ALL, r'')
572 locale.setlocale(locale.LC_ALL, '')
573 origsigtstp = sentinel = object()
573 origsigtstp = sentinel = object()
574 if util.safehasattr(signal, b'SIGTSTP'):
574 if util.safehasattr(signal, b'SIGTSTP'):
575 origsigtstp = signal.getsignal(signal.SIGTSTP)
575 origsigtstp = signal.getsignal(signal.SIGTSTP)
@@ -393,7 +393,7 b' def _debugbundle2(ui, gen, all=None, **o'
393 if not isinstance(gen, bundle2.unbundle20):
393 if not isinstance(gen, bundle2.unbundle20):
394 raise error.Abort(_(b'not a bundle2 file'))
394 raise error.Abort(_(b'not a bundle2 file'))
395 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
395 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
396 parttypes = opts.get(r'part_type', [])
396 parttypes = opts.get('part_type', [])
397 for part in gen.iterparts():
397 for part in gen.iterparts():
398 if parttypes and part.type not in parttypes:
398 if parttypes and part.type not in parttypes:
399 continue
399 continue
@@ -492,7 +492,7 b' def debugcheckstate(ui, repo):'
492 def debugcolor(ui, repo, **opts):
492 def debugcolor(ui, repo, **opts):
493 """show available color, effects or style"""
493 """show available color, effects or style"""
494 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
494 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
495 if opts.get(r'style'):
495 if opts.get('style'):
496 return _debugdisplaystyle(ui)
496 return _debugdisplaystyle(ui)
497 else:
497 else:
498 return _debugdisplaycolor(ui)
498 return _debugdisplaycolor(ui)
@@ -573,8 +573,8 b' def debugdag(ui, repo, file_=None, *revs'
573
573
574 Otherwise, the changelog DAG of the current repo is emitted.
574 Otherwise, the changelog DAG of the current repo is emitted.
575 """
575 """
576 spaces = opts.get(r'spaces')
576 spaces = opts.get('spaces')
577 dots = opts.get(r'dots')
577 dots = opts.get('dots')
578 if file_:
578 if file_:
579 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
579 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
580 revs = set((int(r) for r in revs))
580 revs = set((int(r) for r in revs))
@@ -587,8 +587,8 b' def debugdag(ui, repo, file_=None, *revs'
587
587
588 elif repo:
588 elif repo:
589 cl = repo.changelog
589 cl = repo.changelog
590 tags = opts.get(r'tags')
590 tags = opts.get('tags')
591 branches = opts.get(r'branches')
591 branches = opts.get('branches')
592 if tags:
592 if tags:
593 labels = {}
593 labels = {}
594 for l, n in repo.tags().items():
594 for l, n in repo.tags().items():
@@ -861,10 +861,10 b' def debugdeltachain(ui, repo, file_=None'
861 def debugstate(ui, repo, **opts):
861 def debugstate(ui, repo, **opts):
862 """show the contents of the current dirstate"""
862 """show the contents of the current dirstate"""
863
863
864 nodates = not opts[r'dates']
864 nodates = not opts['dates']
865 if opts.get(r'nodates') is not None:
865 if opts.get('nodates') is not None:
866 nodates = True
866 nodates = True
867 datesort = opts.get(r'datesort')
867 datesort = opts.get('datesort')
868
868
869 if datesort:
869 if datesort:
870 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
870 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
@@ -1298,11 +1298,11 b' def debuggetbundle(ui, repopath, bundlep'
1298 raise error.Abort(b"getbundle() not supported by target repository")
1298 raise error.Abort(b"getbundle() not supported by target repository")
1299 args = {}
1299 args = {}
1300 if common:
1300 if common:
1301 args[r'common'] = [bin(s) for s in common]
1301 args['common'] = [bin(s) for s in common]
1302 if head:
1302 if head:
1303 args[r'heads'] = [bin(s) for s in head]
1303 args['heads'] = [bin(s) for s in head]
1304 # TODO: get desired bundlecaps from command line.
1304 # TODO: get desired bundlecaps from command line.
1305 args[r'bundlecaps'] = None
1305 args['bundlecaps'] = None
1306 bundle = repo.getbundle(b'debug', **args)
1306 bundle = repo.getbundle(b'debug', **args)
1307
1307
1308 bundletype = opts.get(b'type', b'bzip2').lower()
1308 bundletype = opts.get(b'type', b'bzip2').lower()
@@ -1775,21 +1775,21 b' def debuglocks(ui, repo, **opts):'
1775
1775
1776 """
1776 """
1777
1777
1778 if opts.get(r'force_lock'):
1778 if opts.get('force_lock'):
1779 repo.svfs.unlink(b'lock')
1779 repo.svfs.unlink(b'lock')
1780 if opts.get(r'force_wlock'):
1780 if opts.get('force_wlock'):
1781 repo.vfs.unlink(b'wlock')
1781 repo.vfs.unlink(b'wlock')
1782 if opts.get(r'force_lock') or opts.get(r'force_wlock'):
1782 if opts.get('force_lock') or opts.get('force_wlock'):
1783 return 0
1783 return 0
1784
1784
1785 locks = []
1785 locks = []
1786 try:
1786 try:
1787 if opts.get(r'set_wlock'):
1787 if opts.get('set_wlock'):
1788 try:
1788 try:
1789 locks.append(repo.wlock(False))
1789 locks.append(repo.wlock(False))
1790 except error.LockHeld:
1790 except error.LockHeld:
1791 raise error.Abort(_(b'wlock is already held'))
1791 raise error.Abort(_(b'wlock is already held'))
1792 if opts.get(r'set_lock'):
1792 if opts.get('set_lock'):
1793 try:
1793 try:
1794 locks.append(repo.lock(False))
1794 locks.append(repo.lock(False))
1795 except error.LockHeld:
1795 except error.LockHeld:
@@ -1871,7 +1871,7 b' def debugmanifestfulltextcache(ui, repo,'
1871 )
1871 )
1872 raise error.Abort(msg)
1872 raise error.Abort(msg)
1873
1873
1874 if opts.get(r'clear'):
1874 if opts.get('clear'):
1875 with repo.wlock():
1875 with repo.wlock():
1876 cache = getcache()
1876 cache = getcache()
1877 cache.clear(clear_persisted_data=True)
1877 cache.clear(clear_persisted_data=True)
@@ -2265,7 +2265,7 b' def debugpathcomplete(ui, repo, *specs, '
2265 if fixpaths:
2265 if fixpaths:
2266 spec = spec.replace(pycompat.ossep, b'/')
2266 spec = spec.replace(pycompat.ossep, b'/')
2267 speclen = len(spec)
2267 speclen = len(spec)
2268 fullpaths = opts[r'full']
2268 fullpaths = opts['full']
2269 files, dirs = set(), set()
2269 files, dirs = set(), set()
2270 adddir, addfile = dirs.add, files.add
2270 adddir, addfile = dirs.add, files.add
2271 for f, st in pycompat.iteritems(dirstate):
2271 for f, st in pycompat.iteritems(dirstate):
@@ -2283,11 +2283,11 b' def debugpathcomplete(ui, repo, *specs, '
2283 return files, dirs
2283 return files, dirs
2284
2284
2285 acceptable = b''
2285 acceptable = b''
2286 if opts[r'normal']:
2286 if opts['normal']:
2287 acceptable += b'nm'
2287 acceptable += b'nm'
2288 if opts[r'added']:
2288 if opts['added']:
2289 acceptable += b'a'
2289 acceptable += b'a'
2290 if opts[r'removed']:
2290 if opts['removed']:
2291 acceptable += b'r'
2291 acceptable += b'r'
2292 cwd = repo.getcwd()
2292 cwd = repo.getcwd()
2293 if not specs:
2293 if not specs:
@@ -2526,7 +2526,7 b' def debugrebuilddirstate(ui, repo, rev, '
2526 dirstate = repo.dirstate
2526 dirstate = repo.dirstate
2527 changedfiles = None
2527 changedfiles = None
2528 # See command doc for what minimal does.
2528 # See command doc for what minimal does.
2529 if opts.get(r'minimal'):
2529 if opts.get('minimal'):
2530 manifestfiles = set(ctx.manifest().keys())
2530 manifestfiles = set(ctx.manifest().keys())
2531 dirstatefiles = set(dirstate)
2531 dirstatefiles = set(dirstate)
2532 manifestonly = manifestfiles - dirstatefiles
2532 manifestonly = manifestfiles - dirstatefiles
@@ -3147,13 +3147,13 b' def debugrevspec(ui, repo, expr, **opts)'
3147 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3147 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3148 sm = difflib.SequenceMatcher(None, arevs, brevs)
3148 sm = difflib.SequenceMatcher(None, arevs, brevs)
3149 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3149 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3150 if tag in (r'delete', r'replace'):
3150 if tag in ('delete', 'replace'):
3151 for c in arevs[alo:ahi]:
3151 for c in arevs[alo:ahi]:
3152 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3152 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3153 if tag in (r'insert', r'replace'):
3153 if tag in ('insert', 'replace'):
3154 for c in brevs[blo:bhi]:
3154 for c in brevs[blo:bhi]:
3155 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3155 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3156 if tag == r'equal':
3156 if tag == 'equal':
3157 for c in arevs[alo:ahi]:
3157 for c in arevs[alo:ahi]:
3158 ui.write(b' %d\n' % c)
3158 ui.write(b' %d\n' % c)
3159 return 1
3159 return 1
@@ -3202,12 +3202,12 b' def debugserve(ui, repo, **opts):'
3202 if opts[b'logiofd']:
3202 if opts[b'logiofd']:
3203 # Line buffered because output is line based.
3203 # Line buffered because output is line based.
3204 try:
3204 try:
3205 logfh = os.fdopen(int(opts[b'logiofd']), r'ab', 1)
3205 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 1)
3206 except OSError as e:
3206 except OSError as e:
3207 if e.errno != errno.ESPIPE:
3207 if e.errno != errno.ESPIPE:
3208 raise
3208 raise
3209 # can't seek a pipe, so `ab` mode fails on py3
3209 # can't seek a pipe, so `ab` mode fails on py3
3210 logfh = os.fdopen(int(opts[b'logiofd']), r'wb', 1)
3210 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 1)
3211 elif opts[b'logiofile']:
3211 elif opts[b'logiofile']:
3212 logfh = open(opts[b'logiofile'], b'ab', 1)
3212 logfh = open(opts[b'logiofile'], b'ab', 1)
3213
3213
@@ -3391,7 +3391,7 b' def debugsuccessorssets(ui, repo, *revs,'
3391 ctx = repo[rev]
3391 ctx = repo[rev]
3392 ui.write(b'%s\n' % ctx2str(ctx))
3392 ui.write(b'%s\n' % ctx2str(ctx))
3393 for succsset in obsutil.successorssets(
3393 for succsset in obsutil.successorssets(
3394 repo, ctx.node(), closest=opts[r'closest'], cache=cache
3394 repo, ctx.node(), closest=opts['closest'], cache=cache
3395 ):
3395 ):
3396 if succsset:
3396 if succsset:
3397 ui.write(b' ')
3397 ui.write(b' ')
@@ -3421,15 +3421,15 b' def debugtemplate(ui, repo, tmpl, **opts'
3421 Use --verbose to print the parsed tree.
3421 Use --verbose to print the parsed tree.
3422 """
3422 """
3423 revs = None
3423 revs = None
3424 if opts[r'rev']:
3424 if opts['rev']:
3425 if repo is None:
3425 if repo is None:
3426 raise error.RepoError(
3426 raise error.RepoError(
3427 _(b'there is no Mercurial repository here (.hg not found)')
3427 _(b'there is no Mercurial repository here (.hg not found)')
3428 )
3428 )
3429 revs = scmutil.revrange(repo, opts[r'rev'])
3429 revs = scmutil.revrange(repo, opts['rev'])
3430
3430
3431 props = {}
3431 props = {}
3432 for d in opts[r'define']:
3432 for d in opts['define']:
3433 try:
3433 try:
3434 k, v = (e.strip() for e in d.split(b'=', 1))
3434 k, v = (e.strip() for e in d.split(b'=', 1))
3435 if not k or k == b'ui':
3435 if not k or k == b'ui':
@@ -3985,27 +3985,27 b' def debugwireproto(ui, repo, path=None, '
3985
3985
3986 url, authinfo = u.authinfo()
3986 url, authinfo = u.authinfo()
3987 openerargs = {
3987 openerargs = {
3988 r'useragent': b'Mercurial debugwireproto',
3988 'useragent': b'Mercurial debugwireproto',
3989 }
3989 }
3990
3990
3991 # Turn pipes/sockets into observers so we can log I/O.
3991 # Turn pipes/sockets into observers so we can log I/O.
3992 if ui.verbose:
3992 if ui.verbose:
3993 openerargs.update(
3993 openerargs.update(
3994 {
3994 {
3995 r'loggingfh': ui,
3995 'loggingfh': ui,
3996 r'loggingname': b's',
3996 'loggingname': b's',
3997 r'loggingopts': {r'logdata': True, r'logdataapis': False,},
3997 'loggingopts': {'logdata': True, 'logdataapis': False,},
3998 }
3998 }
3999 )
3999 )
4000
4000
4001 if ui.debugflag:
4001 if ui.debugflag:
4002 openerargs[r'loggingopts'][r'logdataapis'] = True
4002 openerargs['loggingopts']['logdataapis'] = True
4003
4003
4004 # Don't send default headers when in raw mode. This allows us to
4004 # Don't send default headers when in raw mode. This allows us to
4005 # bypass most of the behavior of our URL handling code so we can
4005 # bypass most of the behavior of our URL handling code so we can
4006 # have near complete control over what's sent on the wire.
4006 # have near complete control over what's sent on the wire.
4007 if opts[b'peer'] == b'raw':
4007 if opts[b'peer'] == b'raw':
4008 openerargs[r'sendaccept'] = False
4008 openerargs['sendaccept'] = False
4009
4009
4010 opener = urlmod.opener(ui, authinfo, **openerargs)
4010 opener = urlmod.opener(ui, authinfo, **openerargs)
4011
4011
@@ -4105,7 +4105,7 b' def debugwireproto(ui, repo, path=None, '
4105 ui.status(_(b'sending %s command\n') % command)
4105 ui.status(_(b'sending %s command\n') % command)
4106
4106
4107 if b'PUSHFILE' in args:
4107 if b'PUSHFILE' in args:
4108 with open(args[b'PUSHFILE'], r'rb') as fh:
4108 with open(args[b'PUSHFILE'], 'rb') as fh:
4109 del args[b'PUSHFILE']
4109 del args[b'PUSHFILE']
4110 res, output = peer._callpush(
4110 res, output = peer._callpush(
4111 command, fh, **pycompat.strkwargs(args)
4111 command, fh, **pycompat.strkwargs(args)
@@ -4213,8 +4213,8 b' def debugwireproto(ui, repo, path=None, '
4213 getattr(e, 'read', lambda: None)()
4213 getattr(e, 'read', lambda: None)()
4214 continue
4214 continue
4215
4215
4216 ct = res.headers.get(r'Content-Type')
4216 ct = res.headers.get('Content-Type')
4217 if ct == r'application/mercurial-cbor':
4217 if ct == 'application/mercurial-cbor':
4218 ui.write(
4218 ui.write(
4219 _(b'cbor> %s\n')
4219 _(b'cbor> %s\n')
4220 % stringutil.pprint(
4220 % stringutil.pprint(
@@ -36,8 +36,8 b' from .interfaces import ('
36 util as interfaceutil,
36 util as interfaceutil,
37 )
37 )
38
38
39 parsers = policy.importmod(r'parsers')
39 parsers = policy.importmod('parsers')
40 rustmod = policy.importrust(r'dirstate')
40 rustmod = policy.importrust('dirstate')
41
41
42 propertycache = util.propertycache
42 propertycache = util.propertycache
43 filecache = scmutil.filecache
43 filecache = scmutil.filecache
@@ -658,10 +658,10 b' class cmdalias(object):'
658
658
659 def __getattr__(self, name):
659 def __getattr__(self, name):
660 adefaults = {
660 adefaults = {
661 r'norepo': True,
661 'norepo': True,
662 r'intents': set(),
662 'intents': set(),
663 r'optionalrepo': False,
663 'optionalrepo': False,
664 r'inferrepo': False,
664 'inferrepo': False,
665 }
665 }
666 if name not in adefaults:
666 if name not in adefaults:
667 raise AttributeError(name)
667 raise AttributeError(name)
@@ -37,7 +37,7 b' if not globals(): # hide this from non-'
37
37
38 _Tlocalstr = TypeVar('_Tlocalstr', bound=localstr)
38 _Tlocalstr = TypeVar('_Tlocalstr', bound=localstr)
39
39
40 charencode = policy.importmod(r'charencode')
40 charencode = policy.importmod('charencode')
41
41
42 isasciistr = charencode.isasciistr
42 isasciistr = charencode.isasciistr
43 asciilower = charencode.asciilower
43 asciilower = charencode.asciilower
@@ -87,7 +87,7 b' else:'
87 # preferred encoding isn't known yet; use utf-8 to avoid unicode error
87 # preferred encoding isn't known yet; use utf-8 to avoid unicode error
88 # and recreate it once encoding is settled
88 # and recreate it once encoding is settled
89 environ = dict(
89 environ = dict(
90 (k.encode(r'utf-8'), v.encode(r'utf-8'))
90 (k.encode('utf-8'), v.encode('utf-8'))
91 for k, v in os.environ.items() # re-exports
91 for k, v in os.environ.items() # re-exports
92 )
92 )
93
93
@@ -280,7 +280,7 b' if not _nativeenviron:'
280 # now encoding and helper functions are available, recreate the environ
280 # now encoding and helper functions are available, recreate the environ
281 # dict to be exported to other modules
281 # dict to be exported to other modules
282 environ = dict(
282 environ = dict(
283 (tolocal(k.encode(r'utf-8')), tolocal(v.encode(r'utf-8')))
283 (tolocal(k.encode('utf-8')), tolocal(v.encode('utf-8')))
284 for k, v in os.environ.items() # re-exports
284 for k, v in os.environ.items() # re-exports
285 )
285 )
286
286
@@ -307,7 +307,7 b' else:'
307 def colwidth(s):
307 def colwidth(s):
308 # type: (bytes) -> int
308 # type: (bytes) -> int
309 b"Find the column width of a string for display in the local encoding"
309 b"Find the column width of a string for display in the local encoding"
310 return ucolwidth(s.decode(_sysstr(encoding), r'replace'))
310 return ucolwidth(s.decode(_sysstr(encoding), 'replace'))
311
311
312
312
313 def ucolwidth(d):
313 def ucolwidth(d):
@@ -34,7 +34,7 b' class Hint(object):'
34 """
34 """
35
35
36 def __init__(self, *args, **kw):
36 def __init__(self, *args, **kw):
37 self.hint = kw.pop(r'hint', None)
37 self.hint = kw.pop('hint', None)
38 super(Hint, self).__init__(*args, **kw)
38 super(Hint, self).__init__(*args, **kw)
39
39
40
40
@@ -2197,8 +2197,8 b' def applynarrowacl(repo, kwargs):'
2197 b'path:.' if p == b'*' else b'path:' + p for p in user_excludes
2197 b'path:.' if p == b'*' else b'path:' + p for p in user_excludes
2198 ]
2198 ]
2199
2199
2200 req_includes = set(kwargs.get(r'includepats', []))
2200 req_includes = set(kwargs.get('includepats', []))
2201 req_excludes = set(kwargs.get(r'excludepats', []))
2201 req_excludes = set(kwargs.get('excludepats', []))
2202
2202
2203 req_includes, req_excludes, invalid_includes = narrowspec.restrictpatterns(
2203 req_includes, req_excludes, invalid_includes = narrowspec.restrictpatterns(
2204 req_includes, req_excludes, user_includes, user_excludes
2204 req_includes, req_excludes, user_includes, user_excludes
@@ -2213,11 +2213,11 b' def applynarrowacl(repo, kwargs):'
2213
2213
2214 new_args = {}
2214 new_args = {}
2215 new_args.update(kwargs)
2215 new_args.update(kwargs)
2216 new_args[r'narrow'] = True
2216 new_args['narrow'] = True
2217 new_args[r'narrow_acl'] = True
2217 new_args['narrow_acl'] = True
2218 new_args[r'includepats'] = req_includes
2218 new_args['includepats'] = req_includes
2219 if req_excludes:
2219 if req_excludes:
2220 new_args[r'excludepats'] = req_excludes
2220 new_args['excludepats'] = req_excludes
2221
2221
2222 return new_args
2222 return new_args
2223
2223
@@ -2480,7 +2480,7 b' def _getbundlechangegrouppart('
2480 **kwargs
2480 **kwargs
2481 ):
2481 ):
2482 """add a changegroup part to the requested bundle"""
2482 """add a changegroup part to the requested bundle"""
2483 if not kwargs.get(r'cg', True):
2483 if not kwargs.get('cg', True):
2484 return
2484 return
2485
2485
2486 version = b'01'
2486 version = b'01'
@@ -2499,9 +2499,9 b' def _getbundlechangegrouppart('
2499 if not outgoing.missing:
2499 if not outgoing.missing:
2500 return
2500 return
2501
2501
2502 if kwargs.get(r'narrow', False):
2502 if kwargs.get('narrow', False):
2503 include = sorted(filter(bool, kwargs.get(r'includepats', [])))
2503 include = sorted(filter(bool, kwargs.get('includepats', [])))
2504 exclude = sorted(filter(bool, kwargs.get(r'excludepats', [])))
2504 exclude = sorted(filter(bool, kwargs.get('excludepats', [])))
2505 matcher = narrowspec.match(repo.root, include=include, exclude=exclude)
2505 matcher = narrowspec.match(repo.root, include=include, exclude=exclude)
2506 else:
2506 else:
2507 matcher = None
2507 matcher = None
@@ -2523,8 +2523,8 b' def _getbundlechangegrouppart('
2523 part.addparam(b'exp-sidedata', b'1')
2523 part.addparam(b'exp-sidedata', b'1')
2524
2524
2525 if (
2525 if (
2526 kwargs.get(r'narrow', False)
2526 kwargs.get('narrow', False)
2527 and kwargs.get(r'narrow_acl', False)
2527 and kwargs.get('narrow_acl', False)
2528 and (include or exclude)
2528 and (include or exclude)
2529 ):
2529 ):
2530 # this is mandatory because otherwise ACL clients won't work
2530 # this is mandatory because otherwise ACL clients won't work
@@ -2540,7 +2540,7 b' def _getbundlebookmarkpart('
2540 bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs
2540 bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs
2541 ):
2541 ):
2542 """add a bookmark part to the requested bundle"""
2542 """add a bookmark part to the requested bundle"""
2543 if not kwargs.get(r'bookmarks', False):
2543 if not kwargs.get('bookmarks', False):
2544 return
2544 return
2545 if b'bookmarks' not in b2caps:
2545 if b'bookmarks' not in b2caps:
2546 raise error.Abort(_(b'no common bookmarks exchange method'))
2546 raise error.Abort(_(b'no common bookmarks exchange method'))
@@ -2555,7 +2555,7 b' def _getbundlelistkeysparts('
2555 bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs
2555 bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs
2556 ):
2556 ):
2557 """add parts containing listkeys namespaces to the requested bundle"""
2557 """add parts containing listkeys namespaces to the requested bundle"""
2558 listkeys = kwargs.get(r'listkeys', ())
2558 listkeys = kwargs.get('listkeys', ())
2559 for namespace in listkeys:
2559 for namespace in listkeys:
2560 part = bundler.newpart(b'listkeys')
2560 part = bundler.newpart(b'listkeys')
2561 part.addparam(b'namespace', namespace)
2561 part.addparam(b'namespace', namespace)
@@ -2568,7 +2568,7 b' def _getbundleobsmarkerpart('
2568 bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs
2568 bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs
2569 ):
2569 ):
2570 """add an obsolescence markers part to the requested bundle"""
2570 """add an obsolescence markers part to the requested bundle"""
2571 if kwargs.get(r'obsmarkers', False):
2571 if kwargs.get('obsmarkers', False):
2572 if heads is None:
2572 if heads is None:
2573 heads = repo.heads()
2573 heads = repo.heads()
2574 subset = [c.node() for c in repo.set(b'::%ln', heads)]
2574 subset = [c.node() for c in repo.set(b'::%ln', heads)]
@@ -2582,7 +2582,7 b' def _getbundlephasespart('
2582 bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs
2582 bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs
2583 ):
2583 ):
2584 """add phase heads part to the requested bundle"""
2584 """add phase heads part to the requested bundle"""
2585 if kwargs.get(r'phases', False):
2585 if kwargs.get('phases', False):
2586 if not b'heads' in b2caps.get(b'phases'):
2586 if not b'heads' in b2caps.get(b'phases'):
2587 raise error.Abort(_(b'no common phases exchange method'))
2587 raise error.Abort(_(b'no common phases exchange method'))
2588 if heads is None:
2588 if heads is None:
@@ -2647,7 +2647,7 b' def _getbundletagsfnodes('
2647 # Don't send unless:
2647 # Don't send unless:
2648 # - changeset are being exchanged,
2648 # - changeset are being exchanged,
2649 # - the client supports it.
2649 # - the client supports it.
2650 if not (kwargs.get(r'cg', True) and b'hgtagsfnodes' in b2caps):
2650 if not (kwargs.get('cg', True) and b'hgtagsfnodes' in b2caps):
2651 return
2651 return
2652
2652
2653 outgoing = _computeoutgoing(repo, heads, common)
2653 outgoing = _computeoutgoing(repo, heads, common)
@@ -2680,9 +2680,9 b' def _getbundlerevbranchcache('
2680 # - the client supports it.
2680 # - the client supports it.
2681 # - narrow bundle isn't in play (not currently compatible).
2681 # - narrow bundle isn't in play (not currently compatible).
2682 if (
2682 if (
2683 not kwargs.get(r'cg', True)
2683 not kwargs.get('cg', True)
2684 or b'rev-branch-cache' not in b2caps
2684 or b'rev-branch-cache' not in b2caps
2685 or kwargs.get(r'narrow', False)
2685 or kwargs.get('narrow', False)
2686 or repo.ui.has_section(_NARROWACL_SECTION)
2686 or repo.ui.has_section(_NARROWACL_SECTION)
2687 ):
2687 ):
2688 return
2688 return
@@ -834,7 +834,7 b' def _walkcommand(node):'
834 continue
834 continue
835 if not isinstance(d.func, ast.Name):
835 if not isinstance(d.func, ast.Name):
836 continue
836 continue
837 if d.func.id != r'command':
837 if d.func.id != 'command':
838 continue
838 continue
839 yield d
839 yield d
840
840
@@ -805,7 +805,7 b' def help_('
805 appendcmds(catfns)
805 appendcmds(catfns)
806
806
807 ex = opts.get
807 ex = opts.get
808 anyopts = ex(r'keyword') or not (ex(r'command') or ex(r'extension'))
808 anyopts = ex('keyword') or not (ex('command') or ex('extension'))
809 if not name and anyopts:
809 if not name and anyopts:
810 exts = listexts(
810 exts = listexts(
811 _(b'enabled extensions:'),
811 _(b'enabled extensions:'),
@@ -77,19 +77,19 b' class httpservice(object):'
77 else:
77 else:
78 prefix = b''
78 prefix = b''
79
79
80 port = r':%d' % self.httpd.port
80 port = ':%d' % self.httpd.port
81 if port == r':80':
81 if port == ':80':
82 port = r''
82 port = ''
83
83
84 bindaddr = self.httpd.addr
84 bindaddr = self.httpd.addr
85 if bindaddr == r'0.0.0.0':
85 if bindaddr == '0.0.0.0':
86 bindaddr = r'*'
86 bindaddr = '*'
87 elif r':' in bindaddr: # IPv6
87 elif ':' in bindaddr: # IPv6
88 bindaddr = r'[%s]' % bindaddr
88 bindaddr = '[%s]' % bindaddr
89
89
90 fqaddr = self.httpd.fqaddr
90 fqaddr = self.httpd.fqaddr
91 if r':' in fqaddr:
91 if ':' in fqaddr:
92 fqaddr = r'[%s]' % fqaddr
92 fqaddr = '[%s]' % fqaddr
93
93
94 url = b'http://%s%s/%s' % (
94 url = b'http://%s%s/%s' % (
95 pycompat.sysbytes(fqaddr),
95 pycompat.sysbytes(fqaddr),
@@ -143,9 +143,7 b' class continuereader(object):'
143
143
144 def _statusmessage(code):
144 def _statusmessage(code):
145 responses = httpserver.basehttprequesthandler.responses
145 responses = httpserver.basehttprequesthandler.responses
146 return pycompat.bytesurl(
146 return pycompat.bytesurl(responses.get(code, ('Error', 'Unknown error'))[0])
147 responses.get(code, (r'Error', r'Unknown error'))[0]
148 )
149
147
150
148
151 def statusmessage(code, message=None):
149 def statusmessage(code, message=None):
@@ -43,8 +43,8 b' def _splitURI(uri):'
43 Just like CGI environment, the path is unquoted, the query is
43 Just like CGI environment, the path is unquoted, the query is
44 not.
44 not.
45 """
45 """
46 if r'?' in uri:
46 if '?' in uri:
47 path, query = uri.split(r'?', 1)
47 path, query = uri.split('?', 1)
48 else:
48 else:
49 path, query = uri, r''
49 path, query = uri, r''
50 return urlreq.unquote(path), query
50 return urlreq.unquote(path), query
@@ -97,18 +97,18 b' class _httprequesthandler(httpservermod.'
97 def log_message(self, format, *args):
97 def log_message(self, format, *args):
98 self._log_any(self.server.accesslog, format, *args)
98 self._log_any(self.server.accesslog, format, *args)
99
99
100 def log_request(self, code=r'-', size=r'-'):
100 def log_request(self, code='-', size='-'):
101 xheaders = []
101 xheaders = []
102 if util.safehasattr(self, b'headers'):
102 if util.safehasattr(self, b'headers'):
103 xheaders = [
103 xheaders = [
104 h for h in self.headers.items() if h[0].startswith(r'x-')
104 h for h in self.headers.items() if h[0].startswith('x-')
105 ]
105 ]
106 self.log_message(
106 self.log_message(
107 r'"%s" %s %s%s',
107 '"%s" %s %s%s',
108 self.requestline,
108 self.requestline,
109 str(code),
109 str(code),
110 str(size),
110 str(size),
111 r''.join([r' %s:%s' % h for h in sorted(xheaders)]),
111 ''.join([' %s:%s' % h for h in sorted(xheaders)]),
112 )
112 )
113
113
114 def do_write(self):
114 def do_write(self):
@@ -160,72 +160,72 b' class _httprequesthandler(httpservermod.'
160 self.server.prefix + b'/'
160 self.server.prefix + b'/'
161 ):
161 ):
162 self._start_response(pycompat.strurl(common.statusmessage(404)), [])
162 self._start_response(pycompat.strurl(common.statusmessage(404)), [])
163 if self.command == r'POST':
163 if self.command == 'POST':
164 # Paranoia: tell the client we're going to close the
164 # Paranoia: tell the client we're going to close the
165 # socket so they don't try and reuse a socket that
165 # socket so they don't try and reuse a socket that
166 # might have a POST body waiting to confuse us. We do
166 # might have a POST body waiting to confuse us. We do
167 # this by directly munging self.saved_headers because
167 # this by directly munging self.saved_headers because
168 # self._start_response ignores Connection headers.
168 # self._start_response ignores Connection headers.
169 self.saved_headers = [(r'Connection', r'Close')]
169 self.saved_headers = [('Connection', 'Close')]
170 self._write(b"Not Found")
170 self._write(b"Not Found")
171 self._done()
171 self._done()
172 return
172 return
173
173
174 env = {}
174 env = {}
175 env[r'GATEWAY_INTERFACE'] = r'CGI/1.1'
175 env['GATEWAY_INTERFACE'] = 'CGI/1.1'
176 env[r'REQUEST_METHOD'] = self.command
176 env['REQUEST_METHOD'] = self.command
177 env[r'SERVER_NAME'] = self.server.server_name
177 env['SERVER_NAME'] = self.server.server_name
178 env[r'SERVER_PORT'] = str(self.server.server_port)
178 env['SERVER_PORT'] = str(self.server.server_port)
179 env[r'REQUEST_URI'] = self.path
179 env['REQUEST_URI'] = self.path
180 env[r'SCRIPT_NAME'] = pycompat.sysstr(self.server.prefix)
180 env['SCRIPT_NAME'] = pycompat.sysstr(self.server.prefix)
181 env[r'PATH_INFO'] = pycompat.sysstr(path[len(self.server.prefix) :])
181 env['PATH_INFO'] = pycompat.sysstr(path[len(self.server.prefix) :])
182 env[r'REMOTE_HOST'] = self.client_address[0]
182 env['REMOTE_HOST'] = self.client_address[0]
183 env[r'REMOTE_ADDR'] = self.client_address[0]
183 env['REMOTE_ADDR'] = self.client_address[0]
184 env[r'QUERY_STRING'] = query or r''
184 env['QUERY_STRING'] = query or ''
185
185
186 if pycompat.ispy3:
186 if pycompat.ispy3:
187 if self.headers.get_content_type() is None:
187 if self.headers.get_content_type() is None:
188 env[r'CONTENT_TYPE'] = self.headers.get_default_type()
188 env['CONTENT_TYPE'] = self.headers.get_default_type()
189 else:
189 else:
190 env[r'CONTENT_TYPE'] = self.headers.get_content_type()
190 env['CONTENT_TYPE'] = self.headers.get_content_type()
191 length = self.headers.get(r'content-length')
191 length = self.headers.get('content-length')
192 else:
192 else:
193 if self.headers.typeheader is None:
193 if self.headers.typeheader is None:
194 env[r'CONTENT_TYPE'] = self.headers.type
194 env['CONTENT_TYPE'] = self.headers.type
195 else:
195 else:
196 env[r'CONTENT_TYPE'] = self.headers.typeheader
196 env['CONTENT_TYPE'] = self.headers.typeheader
197 length = self.headers.getheader(r'content-length')
197 length = self.headers.getheader('content-length')
198 if length:
198 if length:
199 env[r'CONTENT_LENGTH'] = length
199 env['CONTENT_LENGTH'] = length
200 for header in [
200 for header in [
201 h
201 h
202 for h in self.headers.keys()
202 for h in self.headers.keys()
203 if h.lower() not in (r'content-type', r'content-length')
203 if h.lower() not in ('content-type', 'content-length')
204 ]:
204 ]:
205 hkey = r'HTTP_' + header.replace(r'-', r'_').upper()
205 hkey = 'HTTP_' + header.replace('-', '_').upper()
206 hval = self.headers.get(header)
206 hval = self.headers.get(header)
207 hval = hval.replace(r'\n', r'').strip()
207 hval = hval.replace('\n', '').strip()
208 if hval:
208 if hval:
209 env[hkey] = hval
209 env[hkey] = hval
210 env[r'SERVER_PROTOCOL'] = self.request_version
210 env['SERVER_PROTOCOL'] = self.request_version
211 env[r'wsgi.version'] = (1, 0)
211 env['wsgi.version'] = (1, 0)
212 env[r'wsgi.url_scheme'] = pycompat.sysstr(self.url_scheme)
212 env['wsgi.url_scheme'] = pycompat.sysstr(self.url_scheme)
213 if env.get(r'HTTP_EXPECT', b'').lower() == b'100-continue':
213 if env.get('HTTP_EXPECT', b'').lower() == b'100-continue':
214 self.rfile = common.continuereader(self.rfile, self.wfile.write)
214 self.rfile = common.continuereader(self.rfile, self.wfile.write)
215
215
216 env[r'wsgi.input'] = self.rfile
216 env['wsgi.input'] = self.rfile
217 env[r'wsgi.errors'] = _error_logger(self)
217 env['wsgi.errors'] = _error_logger(self)
218 env[r'wsgi.multithread'] = isinstance(
218 env['wsgi.multithread'] = isinstance(
219 self.server, socketserver.ThreadingMixIn
219 self.server, socketserver.ThreadingMixIn
220 )
220 )
221 if util.safehasattr(socketserver, b'ForkingMixIn'):
221 if util.safehasattr(socketserver, b'ForkingMixIn'):
222 env[r'wsgi.multiprocess'] = isinstance(
222 env['wsgi.multiprocess'] = isinstance(
223 self.server, socketserver.ForkingMixIn
223 self.server, socketserver.ForkingMixIn
224 )
224 )
225 else:
225 else:
226 env[r'wsgi.multiprocess'] = False
226 env['wsgi.multiprocess'] = False
227
227
228 env[r'wsgi.run_once'] = 0
228 env['wsgi.run_once'] = 0
229
229
230 wsgiref.validate.check_environ(env)
230 wsgiref.validate.check_environ(env)
231
231
@@ -251,17 +251,16 b' class _httprequesthandler(httpservermod.'
251 self._chunked = False
251 self._chunked = False
252 for h in self.saved_headers:
252 for h in self.saved_headers:
253 self.send_header(*h)
253 self.send_header(*h)
254 if h[0].lower() == r'content-length':
254 if h[0].lower() == 'content-length':
255 self.length = int(h[1])
255 self.length = int(h[1])
256 if self.length is None and saved_status[0] != common.HTTP_NOT_MODIFIED:
256 if self.length is None and saved_status[0] != common.HTTP_NOT_MODIFIED:
257 self._chunked = (
257 self._chunked = (
258 not self.close_connection
258 not self.close_connection and self.request_version == 'HTTP/1.1'
259 and self.request_version == r'HTTP/1.1'
260 )
259 )
261 if self._chunked:
260 if self._chunked:
262 self.send_header(r'Transfer-Encoding', r'chunked')
261 self.send_header('Transfer-Encoding', 'chunked')
263 else:
262 else:
264 self.send_header(r'Connection', r'close')
263 self.send_header('Connection', 'close')
265 self.end_headers()
264 self.end_headers()
266 self.sent_headers = True
265 self.sent_headers = True
267
266
@@ -270,7 +269,7 b' class _httprequesthandler(httpservermod.'
270 code, msg = http_status.split(None, 1)
269 code, msg = http_status.split(None, 1)
271 code = int(code)
270 code = int(code)
272 self.saved_status = http_status
271 self.saved_status = http_status
273 bad_headers = (r'connection', r'transfer-encoding')
272 bad_headers = ('connection', 'transfer-encoding')
274 self.saved_headers = [
273 self.saved_headers = [
275 h for h in headers if h[0].lower() not in bad_headers
274 h for h in headers if h[0].lower() not in bad_headers
276 ]
275 ]
@@ -25,28 +25,28 b' def launch(application):'
25 procutil.setbinary(procutil.stdout)
25 procutil.setbinary(procutil.stdout)
26
26
27 environ = dict(pycompat.iteritems(os.environ)) # re-exports
27 environ = dict(pycompat.iteritems(os.environ)) # re-exports
28 environ.setdefault(r'PATH_INFO', b'')
28 environ.setdefault('PATH_INFO', b'')
29 if environ.get(r'SERVER_SOFTWARE', r'').startswith(r'Microsoft-IIS'):
29 if environ.get('SERVER_SOFTWARE', '').startswith('Microsoft-IIS'):
30 # IIS includes script_name in PATH_INFO
30 # IIS includes script_name in PATH_INFO
31 scriptname = environ[r'SCRIPT_NAME']
31 scriptname = environ['SCRIPT_NAME']
32 if environ[r'PATH_INFO'].startswith(scriptname):
32 if environ['PATH_INFO'].startswith(scriptname):
33 environ[r'PATH_INFO'] = environ[r'PATH_INFO'][len(scriptname) :]
33 environ['PATH_INFO'] = environ['PATH_INFO'][len(scriptname) :]
34
34
35 stdin = procutil.stdin
35 stdin = procutil.stdin
36 if environ.get(r'HTTP_EXPECT', r'').lower() == r'100-continue':
36 if environ.get('HTTP_EXPECT', '').lower() == '100-continue':
37 stdin = common.continuereader(stdin, procutil.stdout.write)
37 stdin = common.continuereader(stdin, procutil.stdout.write)
38
38
39 environ[r'wsgi.input'] = stdin
39 environ['wsgi.input'] = stdin
40 environ[r'wsgi.errors'] = procutil.stderr
40 environ['wsgi.errors'] = procutil.stderr
41 environ[r'wsgi.version'] = (1, 0)
41 environ['wsgi.version'] = (1, 0)
42 environ[r'wsgi.multithread'] = False
42 environ['wsgi.multithread'] = False
43 environ[r'wsgi.multiprocess'] = True
43 environ['wsgi.multiprocess'] = True
44 environ[r'wsgi.run_once'] = True
44 environ['wsgi.run_once'] = True
45
45
46 if environ.get(r'HTTPS', r'off').lower() in (r'on', r'1', r'yes'):
46 if environ.get('HTTPS', 'off').lower() in ('on', '1', 'yes'):
47 environ[r'wsgi.url_scheme'] = r'https'
47 environ['wsgi.url_scheme'] = 'https'
48 else:
48 else:
49 environ[r'wsgi.url_scheme'] = r'http'
49 environ['wsgi.url_scheme'] = 'http'
50
50
51 headers_set = []
51 headers_set = []
52 headers_sent = []
52 headers_sent = []
@@ -63,7 +63,7 b' def encodevalueinheaders(value, header, '
63 # and using an r-string to make it portable between Python 2 and 3
63 # and using an r-string to make it portable between Python 2 and 3
64 # doesn't work because then the \r is a literal backslash-r
64 # doesn't work because then the \r is a literal backslash-r
65 # instead of a carriage return.
65 # instead of a carriage return.
66 valuelen = limit - len(fmt % r'000') - len(b': \r\n')
66 valuelen = limit - len(fmt % '000') - len(b': \r\n')
67 result = []
67 result = []
68
68
69 n = 0
69 n = 0
@@ -158,7 +158,7 b' def makev1commandrequest('
158 argsio = io.BytesIO(strargs)
158 argsio = io.BytesIO(strargs)
159 argsio.length = len(strargs)
159 argsio.length = len(strargs)
160 data = _multifile(argsio, data)
160 data = _multifile(argsio, data)
161 headers[r'X-HgArgs-Post'] = len(strargs)
161 headers['X-HgArgs-Post'] = len(strargs)
162 elif args:
162 elif args:
163 # Calling self.capable() can infinite loop if we are calling
163 # Calling self.capable() can infinite loop if we are calling
164 # "capabilities". But that command should never accept wire
164 # "capabilities". But that command should never accept wire
@@ -187,8 +187,8 b' def makev1commandrequest('
187 size = data.length
187 size = data.length
188 elif data is not None:
188 elif data is not None:
189 size = len(data)
189 size = len(data)
190 if data is not None and r'Content-Type' not in headers:
190 if data is not None and 'Content-Type' not in headers:
191 headers[r'Content-Type'] = r'application/mercurial-0.1'
191 headers['Content-Type'] = 'application/mercurial-0.1'
192
192
193 # Tell the server we accept application/mercurial-0.2 and multiple
193 # Tell the server we accept application/mercurial-0.2 and multiple
194 # compression formats if the server is capable of emitting those
194 # compression formats if the server is capable of emitting those
@@ -228,17 +228,17 b' def makev1commandrequest('
228
228
229 varyheaders = []
229 varyheaders = []
230 for header in headers:
230 for header in headers:
231 if header.lower().startswith(r'x-hg'):
231 if header.lower().startswith('x-hg'):
232 varyheaders.append(header)
232 varyheaders.append(header)
233
233
234 if varyheaders:
234 if varyheaders:
235 headers[r'Vary'] = r','.join(sorted(varyheaders))
235 headers['Vary'] = ','.join(sorted(varyheaders))
236
236
237 req = requestbuilder(pycompat.strurl(cu), data, headers)
237 req = requestbuilder(pycompat.strurl(cu), data, headers)
238
238
239 if data is not None:
239 if data is not None:
240 ui.debug(b"sending %d bytes\n" % size)
240 ui.debug(b"sending %d bytes\n" % size)
241 req.add_unredirected_header(r'Content-Length', r'%d' % size)
241 req.add_unredirected_header('Content-Length', '%d' % size)
242
242
243 return req, cu, qs
243 return req, cu, qs
244
244
@@ -348,9 +348,9 b' def parsev1commandresponse('
348 ui.warn(_(b'real URL is %s\n') % respurl)
348 ui.warn(_(b'real URL is %s\n') % respurl)
349
349
350 try:
350 try:
351 proto = pycompat.bytesurl(resp.getheader(r'content-type', r''))
351 proto = pycompat.bytesurl(resp.getheader('content-type', ''))
352 except AttributeError:
352 except AttributeError:
353 proto = pycompat.bytesurl(resp.headers.get(r'content-type', r''))
353 proto = pycompat.bytesurl(resp.headers.get('content-type', ''))
354
354
355 safeurl = util.hidepassword(baseurl)
355 safeurl = util.hidepassword(baseurl)
356 if proto.startswith(b'application/hg-error'):
356 if proto.startswith(b'application/hg-error'):
@@ -517,7 +517,7 b' class httppeer(wireprotov1peer.wirepeer)'
517
517
518 tempname = bundle2.writebundle(self.ui, cg, None, type)
518 tempname = bundle2.writebundle(self.ui, cg, None, type)
519 fp = httpconnection.httpsendfile(self.ui, tempname, b"rb")
519 fp = httpconnection.httpsendfile(self.ui, tempname, b"rb")
520 headers = {r'Content-Type': r'application/mercurial-0.1'}
520 headers = {'Content-Type': 'application/mercurial-0.1'}
521
521
522 try:
522 try:
523 r = self._call(cmd, data=fp, headers=headers, **args)
523 r = self._call(cmd, data=fp, headers=headers, **args)
@@ -550,7 +550,7 b' class httppeer(wireprotov1peer.wirepeer)'
550 d = fp.read(4096)
550 d = fp.read(4096)
551 # start http push
551 # start http push
552 with httpconnection.httpsendfile(self.ui, filename, b"rb") as fp_:
552 with httpconnection.httpsendfile(self.ui, filename, b"rb") as fp_:
553 headers = {r'Content-Type': r'application/mercurial-0.1'}
553 headers = {'Content-Type': 'application/mercurial-0.1'}
554 return self._callstream(cmd, data=fp_, headers=headers, **args)
554 return self._callstream(cmd, data=fp_, headers=headers, **args)
555 finally:
555 finally:
556 if filename is not None:
556 if filename is not None:
@@ -621,12 +621,12 b' def sendv2request('
621
621
622 # TODO modify user-agent to reflect v2
622 # TODO modify user-agent to reflect v2
623 headers = {
623 headers = {
624 r'Accept': wireprotov2server.FRAMINGTYPE,
624 'Accept': wireprotov2server.FRAMINGTYPE,
625 r'Content-Type': wireprotov2server.FRAMINGTYPE,
625 'Content-Type': wireprotov2server.FRAMINGTYPE,
626 }
626 }
627
627
628 req = requestbuilder(pycompat.strurl(url), body, headers)
628 req = requestbuilder(pycompat.strurl(url), body, headers)
629 req.add_unredirected_header(r'Content-Length', r'%d' % len(body))
629 req.add_unredirected_header('Content-Length', '%d' % len(body))
630
630
631 try:
631 try:
632 res = opener.open(req)
632 res = opener.open(req)
@@ -965,7 +965,7 b' def performhandshake(ui, url, opener, re'
965
965
966 if advertisev2:
966 if advertisev2:
967 args[b'headers'] = {
967 args[b'headers'] = {
968 r'X-HgProto-1': r'cbor',
968 'X-HgProto-1': 'cbor',
969 }
969 }
970
970
971 args[b'headers'].update(
971 args[b'headers'].update(
@@ -50,8 +50,8 b' if ('
50
50
51 def setdatapath(datapath):
51 def setdatapath(datapath):
52 datapath = pycompat.fsdecode(datapath)
52 datapath = pycompat.fsdecode(datapath)
53 localedir = os.path.join(datapath, r'locale')
53 localedir = os.path.join(datapath, 'locale')
54 t = gettextmod.translation(r'hg', localedir, _languages, fallback=True)
54 t = gettextmod.translation('hg', localedir, _languages, fallback=True)
55 global _ugettext
55 global _ugettext
56 try:
56 try:
57 _ugettext = t.ugettext
57 _ugettext = t.ugettext
@@ -331,9 +331,9 b' class KeepAliveHandler(object):'
331 headers.update(sorted(req.unredirected_hdrs.items()))
331 headers.update(sorted(req.unredirected_hdrs.items()))
332 headers = util.sortdict((n.lower(), v) for n, v in headers.items())
332 headers = util.sortdict((n.lower(), v) for n, v in headers.items())
333 skipheaders = {}
333 skipheaders = {}
334 for n in (r'host', r'accept-encoding'):
334 for n in ('host', 'accept-encoding'):
335 if n in headers:
335 if n in headers:
336 skipheaders[r'skip_' + n.replace(r'-', r'_')] = 1
336 skipheaders['skip_' + n.replace('-', '_')] = 1
337 try:
337 try:
338 if urllibcompat.hasdata(req):
338 if urllibcompat.hasdata(req):
339 data = urllibcompat.getdata(req)
339 data = urllibcompat.getdata(req)
@@ -342,12 +342,12 b' class KeepAliveHandler(object):'
342 urllibcompat.getselector(req),
342 urllibcompat.getselector(req),
343 **skipheaders
343 **skipheaders
344 )
344 )
345 if r'content-type' not in headers:
345 if 'content-type' not in headers:
346 h.putheader(
346 h.putheader(
347 r'Content-type', r'application/x-www-form-urlencoded'
347 'Content-type', 'application/x-www-form-urlencoded'
348 )
348 )
349 if r'content-length' not in headers:
349 if 'content-length' not in headers:
350 h.putheader(r'Content-length', r'%d' % len(data))
350 h.putheader('Content-length', '%d' % len(data))
351 else:
351 else:
352 h.putrequest(
352 h.putrequest(
353 req.get_method(),
353 req.get_method(),
@@ -401,8 +401,8 b' class HTTPResponse(httplib.HTTPResponse)'
401 def __init__(self, sock, debuglevel=0, strict=0, method=None):
401 def __init__(self, sock, debuglevel=0, strict=0, method=None):
402 extrakw = {}
402 extrakw = {}
403 if not pycompat.ispy3:
403 if not pycompat.ispy3:
404 extrakw[r'strict'] = True
404 extrakw['strict'] = True
405 extrakw[r'buffering'] = True
405 extrakw['buffering'] = True
406 httplib.HTTPResponse.__init__(
406 httplib.HTTPResponse.__init__(
407 self, sock, debuglevel=debuglevel, method=method, **extrakw
407 self, sock, debuglevel=debuglevel, method=method, **extrakw
408 )
408 )
@@ -99,7 +99,7 b' class _jge(_llinstruction):'
99 self._target = op2
99 self._target = op2
100
100
101 def __str__(self):
101 def __str__(self):
102 return r'JGE %d %d' % (self._cmprev, self._target)
102 return 'JGE %d %d' % (self._cmprev, self._target)
103
103
104 def __eq__(self, other):
104 def __eq__(self, other):
105 return (
105 return (
@@ -126,7 +126,7 b' class _jump(_llinstruction):'
126 self._target = op2
126 self._target = op2
127
127
128 def __str__(self):
128 def __str__(self):
129 return r'JUMP %d' % (self._target)
129 return 'JUMP %d' % (self._target)
130
130
131 def __eq__(self, other):
131 def __eq__(self, other):
132 return type(self) == type(other) and self._target == other._target
132 return type(self) == type(other) and self._target == other._target
@@ -168,7 +168,7 b' class _jl(_llinstruction):'
168 self._target = op2
168 self._target = op2
169
169
170 def __str__(self):
170 def __str__(self):
171 return r'JL %d %d' % (self._cmprev, self._target)
171 return 'JL %d %d' % (self._cmprev, self._target)
172
172
173 def __eq__(self, other):
173 def __eq__(self, other):
174 return (
174 return (
@@ -196,7 +196,7 b' class _line(_llinstruction):'
196 self._origlineno = op2
196 self._origlineno = op2
197
197
198 def __str__(self):
198 def __str__(self):
199 return r'LINE %d %d' % (self._rev, self._origlineno)
199 return 'LINE %d %d' % (self._rev, self._origlineno)
200
200
201 def __eq__(self, other):
201 def __eq__(self, other):
202 return (
202 return (
@@ -262,7 +262,7 b' class linelog(object):'
262 )
262 )
263
263
264 def debugstr(self):
264 def debugstr(self):
265 fmt = r'%%%dd %%s' % len(str(len(self._program)))
265 fmt = '%%%dd %%s' % len(str(len(self._program)))
266 return pycompat.sysstr(b'\n').join(
266 return pycompat.sysstr(b'\n').join(
267 fmt % (idx, i) for idx, i in enumerate(self._program[1:], 1)
267 fmt % (idx, i) for idx, i in enumerate(self._program[1:], 1)
268 )
268 )
@@ -2459,9 +2459,9 b' class localrepository(object):'
2459
2459
2460 def invalidatecaches(self):
2460 def invalidatecaches(self):
2461
2461
2462 if r'_tagscache' in vars(self):
2462 if '_tagscache' in vars(self):
2463 # can't use delattr on proxy
2463 # can't use delattr on proxy
2464 del self.__dict__[r'_tagscache']
2464 del self.__dict__['_tagscache']
2465
2465
2466 self._branchcaches.clear()
2466 self._branchcaches.clear()
2467 self.invalidatevolatilesets()
2467 self.invalidatevolatilesets()
@@ -2480,13 +2480,13 b' class localrepository(object):'
2480 rereads the dirstate. Use dirstate.invalidate() if you want to
2480 rereads the dirstate. Use dirstate.invalidate() if you want to
2481 explicitly read the dirstate again (i.e. restoring it to a previous
2481 explicitly read the dirstate again (i.e. restoring it to a previous
2482 known good state).'''
2482 known good state).'''
2483 if hasunfilteredcache(self, r'dirstate'):
2483 if hasunfilteredcache(self, 'dirstate'):
2484 for k in self.dirstate._filecache:
2484 for k in self.dirstate._filecache:
2485 try:
2485 try:
2486 delattr(self.dirstate, k)
2486 delattr(self.dirstate, k)
2487 except AttributeError:
2487 except AttributeError:
2488 pass
2488 pass
2489 delattr(self.unfiltered(), r'dirstate')
2489 delattr(self.unfiltered(), 'dirstate')
2490
2490
2491 def invalidate(self, clearfilecache=False):
2491 def invalidate(self, clearfilecache=False):
2492 '''Invalidates both store and non-store parts other than dirstate
2492 '''Invalidates both store and non-store parts other than dirstate
@@ -2536,7 +2536,7 b' class localrepository(object):'
2536 """Reload stats of cached files so that they are flagged as valid"""
2536 """Reload stats of cached files so that they are flagged as valid"""
2537 for k, ce in self._filecache.items():
2537 for k, ce in self._filecache.items():
2538 k = pycompat.sysstr(k)
2538 k = pycompat.sysstr(k)
2539 if k == r'dirstate' or k not in self.__dict__:
2539 if k == 'dirstate' or k not in self.__dict__:
2540 continue
2540 continue
2541 ce.refresh()
2541 ce.refresh()
2542
2542
@@ -3363,10 +3363,10 b' class localrepository(object):'
3363 if tr is not None:
3363 if tr is not None:
3364 hookargs.update(tr.hookargs)
3364 hookargs.update(tr.hookargs)
3365 hookargs = pycompat.strkwargs(hookargs)
3365 hookargs = pycompat.strkwargs(hookargs)
3366 hookargs[r'namespace'] = namespace
3366 hookargs['namespace'] = namespace
3367 hookargs[r'key'] = key
3367 hookargs['key'] = key
3368 hookargs[r'old'] = old
3368 hookargs['old'] = old
3369 hookargs[r'new'] = new
3369 hookargs['new'] = new
3370 self.hook(b'prepushkey', throw=True, **hookargs)
3370 self.hook(b'prepushkey', throw=True, **hookargs)
3371 except error.HookAbort as exc:
3371 except error.HookAbort as exc:
3372 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3372 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
@@ -3706,7 +3706,7 b' def poisonrepository(repo):'
3706 # of repos call close() on repo references.
3706 # of repos call close() on repo references.
3707 class poisonedrepository(object):
3707 class poisonedrepository(object):
3708 def __getattribute__(self, item):
3708 def __getattribute__(self, item):
3709 if item == r'close':
3709 if item == 'close':
3710 return object.__getattribute__(self, item)
3710 return object.__getattribute__(self, item)
3711
3711
3712 raise error.ProgrammingError(
3712 raise error.ProgrammingError(
@@ -3718,4 +3718,4 b' def poisonrepository(repo):'
3718
3718
3719 # We may have a repoview, which intercepts __setattr__. So be sure
3719 # We may have a repoview, which intercepts __setattr__. So be sure
3720 # we operate at the lowest level possible.
3720 # we operate at the lowest level possible.
3721 object.__setattr__(repo, r'__class__', poisonedrepository)
3721 object.__setattr__(repo, '__class__', poisonedrepository)
@@ -135,9 +135,9 b' def label(code):'
135 mname = _fn2mod[code.co_filename] = k
135 mname = _fn2mod[code.co_filename] = k
136 break
136 break
137 else:
137 else:
138 mname = _fn2mod[code.co_filename] = r'<%s>' % code.co_filename
138 mname = _fn2mod[code.co_filename] = '<%s>' % code.co_filename
139
139
140 res = r'%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
140 res = '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
141
141
142 if sys.version_info.major >= 3:
142 if sys.version_info.major >= 3:
143 res = res.encode('latin-1')
143 res = res.encode('latin-1')
@@ -94,7 +94,7 b' class SMTPS(smtplib.SMTP):'
94 ui=self._ui,
94 ui=self._ui,
95 serverhostname=self._host,
95 serverhostname=self._host,
96 )
96 )
97 self.file = new_socket.makefile(r'rb')
97 self.file = new_socket.makefile('rb')
98 return new_socket
98 return new_socket
99
99
100
100
@@ -201,7 +201,7 b' def _mbox(mbox, sender, recipients, msg)'
201 fp = open(mbox, b'ab+')
201 fp = open(mbox, b'ab+')
202 # Should be time.asctime(), but Windows prints 2-characters day
202 # Should be time.asctime(), but Windows prints 2-characters day
203 # of month instead of one. Make them print the same thing.
203 # of month instead of one. Make them print the same thing.
204 date = time.strftime(r'%a %b %d %H:%M:%S %Y', time.localtime())
204 date = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime())
205 fp.write(
205 fp.write(
206 b'From %s %s\n'
206 b'From %s %s\n'
207 % (encoding.strtolocal(sender), encoding.strtolocal(date))
207 % (encoding.strtolocal(sender), encoding.strtolocal(date))
@@ -403,7 +403,7 b' def addrlistencode(ui, addrs, charsets=N'
403 A single element of input list may contain multiple addresses, but output
403 A single element of input list may contain multiple addresses, but output
404 always has one address per item'''
404 always has one address per item'''
405 for a in addrs:
405 for a in addrs:
406 assert isinstance(a, bytes), r'%r unexpectedly not a bytestr' % a
406 assert isinstance(a, bytes), '%r unexpectedly not a bytestr' % a
407 if display:
407 if display:
408 return [a.strip() for a in addrs if a.strip()]
408 return [a.strip() for a in addrs if a.strip()]
409
409
@@ -436,7 +436,7 b' if pycompat.ispy3:'
436 # I have no idea if ascii/surrogateescape is correct, but that's
436 # I have no idea if ascii/surrogateescape is correct, but that's
437 # what the standard Python email parser does.
437 # what the standard Python email parser does.
438 fp = io.TextIOWrapper(
438 fp = io.TextIOWrapper(
439 fp, encoding=r'ascii', errors=r'surrogateescape', newline=chr(10)
439 fp, encoding='ascii', errors='surrogateescape', newline=chr(10)
440 )
440 )
441 try:
441 try:
442 return ep.parse(fp)
442 return ep.parse(fp)
@@ -33,7 +33,7 b' from .interfaces import ('
33 util as interfaceutil,
33 util as interfaceutil,
34 )
34 )
35
35
36 parsers = policy.importmod(r'parsers')
36 parsers = policy.importmod('parsers')
37 propertycache = util.propertycache
37 propertycache = util.propertycache
38
38
39 # Allow tests to more easily test the alternate path in manifestdict.fastdelta()
39 # Allow tests to more easily test the alternate path in manifestdict.fastdelta()
@@ -24,7 +24,7 b' from . import ('
24 )
24 )
25 from .utils import stringutil
25 from .utils import stringutil
26
26
27 rustmod = policy.importrust(r'filepatterns')
27 rustmod = policy.importrust('filepatterns')
28
28
29 allpatternkinds = (
29 allpatternkinds = (
30 b're',
30 b're',
@@ -27,8 +27,8 b' from .utils import dateutil'
27
27
28 _missing_newline_marker = b"\\ No newline at end of file\n"
28 _missing_newline_marker = b"\\ No newline at end of file\n"
29
29
30 bdiff = policy.importmod(r'bdiff')
30 bdiff = policy.importmod('bdiff')
31 mpatch = policy.importmod(r'mpatch')
31 mpatch = policy.importmod('mpatch')
32
32
33 blocks = bdiff.blocks
33 blocks = bdiff.blocks
34 fixws = bdiff.fixws
34 fixws = bdiff.fixws
@@ -87,7 +87,7 b' from . import ('
87 )
87 )
88 from .utils import dateutil
88 from .utils import dateutil
89
89
90 parsers = policy.importmod(r'parsers')
90 parsers = policy.importmod('parsers')
91
91
92 _pack = struct.pack
92 _pack = struct.pack
93 _unpack = struct.unpack
93 _unpack = struct.unpack
@@ -580,7 +580,7 b' class obsstore(object):'
580 return len(self._all)
580 return len(self._all)
581
581
582 def __nonzero__(self):
582 def __nonzero__(self):
583 if not self._cached(r'_all'):
583 if not self._cached('_all'):
584 try:
584 try:
585 return self.svfs.stat(b'obsstore').st_size > 1
585 return self.svfs.stat(b'obsstore').st_size > 1
586 except OSError as inst:
586 except OSError as inst:
@@ -641,7 +641,7 b' class obsstore(object):'
641 raise ValueError(succ)
641 raise ValueError(succ)
642 if prec in succs:
642 if prec in succs:
643 raise ValueError(
643 raise ValueError(
644 r'in-marker cycle with %s' % pycompat.sysstr(node.hex(prec))
644 'in-marker cycle with %s' % pycompat.sysstr(node.hex(prec))
645 )
645 )
646
646
647 metadata = tuple(sorted(pycompat.iteritems(metadata)))
647 metadata = tuple(sorted(pycompat.iteritems(metadata)))
@@ -752,11 +752,11 b' class obsstore(object):'
752 markers = list(markers) # to allow repeated iteration
752 markers = list(markers) # to allow repeated iteration
753 self._data = self._data + rawdata
753 self._data = self._data + rawdata
754 self._all.extend(markers)
754 self._all.extend(markers)
755 if self._cached(r'successors'):
755 if self._cached('successors'):
756 _addsuccessors(self.successors, markers)
756 _addsuccessors(self.successors, markers)
757 if self._cached(r'predecessors'):
757 if self._cached('predecessors'):
758 _addpredecessors(self.predecessors, markers)
758 _addpredecessors(self.predecessors, markers)
759 if self._cached(r'children'):
759 if self._cached('children'):
760 _addchildren(self.children, markers)
760 _addchildren(self.children, markers)
761 _checkinvalidmarkers(markers)
761 _checkinvalidmarkers(markers)
762
762
@@ -802,7 +802,7 b' def makestore(ui, repo):'
802 # rely on obsstore class default when possible.
802 # rely on obsstore class default when possible.
803 kwargs = {}
803 kwargs = {}
804 if defaultformat is not None:
804 if defaultformat is not None:
805 kwargs[r'defaultformat'] = defaultformat
805 kwargs['defaultformat'] = defaultformat
806 readonly = not isenabled(repo, createmarkersopt)
806 readonly = not isenabled(repo, createmarkersopt)
807 store = obsstore(repo.svfs, readonly=readonly, **kwargs)
807 store = obsstore(repo.svfs, readonly=readonly, **kwargs)
808 if store and readonly:
808 if store and readonly:
@@ -217,7 +217,7 b' def extract(ui, fileobj):'
217 fileobj did not contain a patch. Caller must unlink filename when done.'''
217 fileobj did not contain a patch. Caller must unlink filename when done.'''
218
218
219 fd, tmpname = pycompat.mkstemp(prefix=b'hg-patch-')
219 fd, tmpname = pycompat.mkstemp(prefix=b'hg-patch-')
220 tmpfp = os.fdopen(fd, r'wb')
220 tmpfp = os.fdopen(fd, 'wb')
221 try:
221 try:
222 yield _extract(ui, fileobj, tmpname, tmpfp)
222 yield _extract(ui, fileobj, tmpname, tmpfp)
223 finally:
223 finally:
@@ -241,8 +241,8 b' def _extract(ui, fileobj, tmpname, tmpfp'
241
241
242 msg = mail.parse(fileobj)
242 msg = mail.parse(fileobj)
243
243
244 subject = msg[r'Subject'] and mail.headdecode(msg[r'Subject'])
244 subject = msg['Subject'] and mail.headdecode(msg['Subject'])
245 data[b'user'] = msg[r'From'] and mail.headdecode(msg[r'From'])
245 data[b'user'] = msg['From'] and mail.headdecode(msg['From'])
246 if not subject and not data[b'user']:
246 if not subject and not data[b'user']:
247 # Not an email, restore parsed headers if any
247 # Not an email, restore parsed headers if any
248 subject = (
248 subject = (
@@ -255,7 +255,7 b' def _extract(ui, fileobj, tmpname, tmpfp'
255 # should try to parse msg['Date']
255 # should try to parse msg['Date']
256 parents = []
256 parents = []
257
257
258 nodeid = msg[r'X-Mercurial-Node']
258 nodeid = msg['X-Mercurial-Node']
259 if nodeid:
259 if nodeid:
260 data[b'nodeid'] = nodeid = mail.headdecode(nodeid)
260 data[b'nodeid'] = nodeid = mail.headdecode(nodeid)
261 ui.debug(b'Node ID: %s\n' % nodeid)
261 ui.debug(b'Node ID: %s\n' % nodeid)
@@ -1225,7 +1225,7 b' the hunk is left unchanged.'
1225 ncpatchfp = None
1225 ncpatchfp = None
1226 try:
1226 try:
1227 # Write the initial patch
1227 # Write the initial patch
1228 f = util.nativeeolwriter(os.fdopen(patchfd, r'wb'))
1228 f = util.nativeeolwriter(os.fdopen(patchfd, 'wb'))
1229 chunk.header.write(f)
1229 chunk.header.write(f)
1230 chunk.write(f)
1230 chunk.write(f)
1231 f.write(
1231 f.write(
@@ -1245,7 +1245,7 b' the hunk is left unchanged.'
1245 ui.warn(_(b"editor exited with exit code %d\n") % ret)
1245 ui.warn(_(b"editor exited with exit code %d\n") % ret)
1246 continue
1246 continue
1247 # Remove comment lines
1247 # Remove comment lines
1248 patchfp = open(patchfn, r'rb')
1248 patchfp = open(patchfn, 'rb')
1249 ncpatchfp = stringio()
1249 ncpatchfp = stringio()
1250 for line in util.iterfile(patchfp):
1250 for line in util.iterfile(patchfp):
1251 line = util.fromnativeeol(line)
1251 line = util.fromnativeeol(line)
@@ -2788,7 +2788,7 b' def diffsinglehunkinline(hunklines):'
2788
2788
2789 def difflabel(func, *args, **kw):
2789 def difflabel(func, *args, **kw):
2790 '''yields 2-tuples of (output, label) based on the output of func()'''
2790 '''yields 2-tuples of (output, label) based on the output of func()'''
2791 if kw.get(r'opts') and kw[r'opts'].worddiff:
2791 if kw.get('opts') and kw['opts'].worddiff:
2792 dodiffhunk = diffsinglehunkinline
2792 dodiffhunk = diffsinglehunkinline
2793 else:
2793 else:
2794 dodiffhunk = diffsinglehunk
2794 dodiffhunk = diffsinglehunk
@@ -29,14 +29,14 b' from .pycompat import getattr'
29 policy = b'allow'
29 policy = b'allow'
30 _packageprefs = {
30 _packageprefs = {
31 # policy: (versioned package, pure package)
31 # policy: (versioned package, pure package)
32 b'c': (r'cext', None),
32 b'c': ('cext', None),
33 b'allow': (r'cext', r'pure'),
33 b'allow': ('cext', 'pure'),
34 b'cffi': (r'cffi', None),
34 b'cffi': ('cffi', None),
35 b'cffi-allow': (r'cffi', r'pure'),
35 b'cffi-allow': ('cffi', 'pure'),
36 b'py': (None, r'pure'),
36 b'py': (None, 'pure'),
37 # For now, rust policies impact importrust only
37 # For now, rust policies impact importrust only
38 b'rust+c': (r'cext', None),
38 b'rust+c': ('cext', None),
39 b'rust+c-allow': (r'cext', r'pure'),
39 b'rust+c-allow': ('cext', 'pure'),
40 }
40 }
41
41
42 try:
42 try:
@@ -50,15 +50,15 b' except ImportError:'
50 #
50 #
51 # The canonical way to do this is to test platform.python_implementation().
51 # The canonical way to do this is to test platform.python_implementation().
52 # But we don't import platform and don't bloat for it here.
52 # But we don't import platform and don't bloat for it here.
53 if r'__pypy__' in sys.builtin_module_names:
53 if '__pypy__' in sys.builtin_module_names:
54 policy = b'cffi'
54 policy = b'cffi'
55
55
56 # Environment variable can always force settings.
56 # Environment variable can always force settings.
57 if sys.version_info[0] >= 3:
57 if sys.version_info[0] >= 3:
58 if r'HGMODULEPOLICY' in os.environ:
58 if 'HGMODULEPOLICY' in os.environ:
59 policy = os.environ[r'HGMODULEPOLICY'].encode(r'utf-8')
59 policy = os.environ['HGMODULEPOLICY'].encode('utf-8')
60 else:
60 else:
61 policy = os.environ.get(r'HGMODULEPOLICY', policy)
61 policy = os.environ.get('HGMODULEPOLICY', policy)
62
62
63
63
64 def _importfrom(pkgname, modname):
64 def _importfrom(pkgname, modname):
@@ -68,7 +68,7 b' def _importfrom(pkgname, modname):'
68 try:
68 try:
69 fakelocals[modname] = mod = getattr(pkg, modname)
69 fakelocals[modname] = mod = getattr(pkg, modname)
70 except AttributeError:
70 except AttributeError:
71 raise ImportError(r'cannot import name %s' % modname)
71 raise ImportError('cannot import name %s' % modname)
72 # force import; fakelocals[modname] may be replaced with the real module
72 # force import; fakelocals[modname] may be replaced with the real module
73 getattr(mod, '__doc__', None)
73 getattr(mod, '__doc__', None)
74 return fakelocals[modname]
74 return fakelocals[modname]
@@ -76,19 +76,19 b' def _importfrom(pkgname, modname):'
76
76
77 # keep in sync with "version" in C modules
77 # keep in sync with "version" in C modules
78 _cextversions = {
78 _cextversions = {
79 (r'cext', r'base85'): 1,
79 ('cext', 'base85'): 1,
80 (r'cext', r'bdiff'): 3,
80 ('cext', 'bdiff'): 3,
81 (r'cext', r'mpatch'): 1,
81 ('cext', 'mpatch'): 1,
82 (r'cext', r'osutil'): 4,
82 ('cext', 'osutil'): 4,
83 (r'cext', r'parsers'): 13,
83 ('cext', 'parsers'): 13,
84 }
84 }
85
85
86 # map import request to other package or module
86 # map import request to other package or module
87 _modredirects = {
87 _modredirects = {
88 (r'cext', r'charencode'): (r'cext', r'parsers'),
88 ('cext', 'charencode'): ('cext', 'parsers'),
89 (r'cffi', r'base85'): (r'pure', r'base85'),
89 ('cffi', 'base85'): ('pure', 'base85'),
90 (r'cffi', r'charencode'): (r'pure', r'charencode'),
90 ('cffi', 'charencode'): ('pure', 'charencode'),
91 (r'cffi', r'parsers'): (r'pure', r'parsers'),
91 ('cffi', 'parsers'): ('pure', 'parsers'),
92 }
92 }
93
93
94
94
@@ -97,8 +97,8 b' def _checkmod(pkgname, modname, mod):'
97 actual = getattr(mod, 'version', None)
97 actual = getattr(mod, 'version', None)
98 if actual != expected:
98 if actual != expected:
99 raise ImportError(
99 raise ImportError(
100 r'cannot import module %s.%s '
100 'cannot import module %s.%s '
101 r'(expected version: %d, actual: %r)'
101 '(expected version: %d, actual: %r)'
102 % (pkgname, modname, expected, actual)
102 % (pkgname, modname, expected, actual)
103 )
103 )
104
104
@@ -108,7 +108,7 b' def importmod(modname):'
108 try:
108 try:
109 verpkg, purepkg = _packageprefs[policy]
109 verpkg, purepkg = _packageprefs[policy]
110 except KeyError:
110 except KeyError:
111 raise ImportError(r'invalid HGMODULEPOLICY %r' % policy)
111 raise ImportError('invalid HGMODULEPOLICY %r' % policy)
112 assert verpkg or purepkg
112 assert verpkg or purepkg
113 if verpkg:
113 if verpkg:
114 pn, mn = _modredirects.get((verpkg, modname), (verpkg, modname))
114 pn, mn = _modredirects.get((verpkg, modname), (verpkg, modname))
@@ -141,7 +141,7 b' def importrust(modname, member=None, def'
141 return default
141 return default
142
142
143 try:
143 try:
144 mod = _importfrom(r'rustext', modname)
144 mod = _importfrom('rustext', modname)
145 except ImportError:
145 except ImportError:
146 if _isrustpermissive():
146 if _isrustpermissive():
147 return default
147 return default
@@ -32,7 +32,7 b' from . import ('
32 pycompat,
32 pycompat,
33 )
33 )
34
34
35 osutil = policy.importmod(r'osutil')
35 osutil = policy.importmod('osutil')
36
36
37 normpath = os.path.normpath
37 normpath = os.path.normpath
38 samestat = os.path.samestat
38 samestat = os.path.samestat
@@ -60,11 +60,11 b' os.umask(umask)'
60
60
61 if not pycompat.ispy3:
61 if not pycompat.ispy3:
62
62
63 def posixfile(name, mode=r'r', buffering=-1):
63 def posixfile(name, mode='r', buffering=-1):
64 fp = open(name, mode=mode, buffering=buffering)
64 fp = open(name, mode=mode, buffering=buffering)
65 # The position when opening in append mode is implementation defined, so
65 # The position when opening in append mode is implementation defined, so
66 # make it consistent by always seeking to the end.
66 # make it consistent by always seeking to the end.
67 if r'a' in mode:
67 if 'a' in mode:
68 fp.seek(0, os.SEEK_END)
68 fp.seek(0, os.SEEK_END)
69 return fp
69 return fp
70
70
@@ -466,7 +466,7 b' if pycompat.isdarwin:'
466 u = s.decode('utf-8')
466 u = s.decode('utf-8')
467
467
468 # Decompose then lowercase (HFS+ technote specifies lower)
468 # Decompose then lowercase (HFS+ technote specifies lower)
469 enc = unicodedata.normalize(r'NFD', u).lower().encode('utf-8')
469 enc = unicodedata.normalize('NFD', u).lower().encode('utf-8')
470 # drop HFS+ ignored characters
470 # drop HFS+ ignored characters
471 return encoding.hfsignoreclean(enc)
471 return encoding.hfsignoreclean(enc)
472
472
@@ -167,9 +167,9 b' def statprofile(ui, fp):'
167 elif profformat == b'hotpath':
167 elif profformat == b'hotpath':
168 # inconsistent config: profiling.showmin
168 # inconsistent config: profiling.showmin
169 limit = ui.configwith(fraction, b'profiling', b'showmin', 0.05)
169 limit = ui.configwith(fraction, b'profiling', b'showmin', 0.05)
170 kwargs[r'limit'] = limit
170 kwargs['limit'] = limit
171 showtime = ui.configbool(b'profiling', b'showtime')
171 showtime = ui.configbool(b'profiling', b'showtime')
172 kwargs[r'showtime'] = showtime
172 kwargs['showtime'] = showtime
173
173
174 statprof.display(fp, data=data, format=displayformat, **kwargs)
174 statprof.display(fp, data=data, format=displayformat, **kwargs)
175
175
@@ -85,6 +85,6 b' def jsonescapeu8fallback(u8chars, parano'
85 jm = _jsonmap
85 jm = _jsonmap
86 # non-BMP char is represented as UTF-16 surrogate pair
86 # non-BMP char is represented as UTF-16 surrogate pair
87 u16b = u8chars.decode('utf-8', _utf8strict).encode('utf-16', _utf8strict)
87 u16b = u8chars.decode('utf-8', _utf8strict).encode('utf-16', _utf8strict)
88 u16codes = array.array(r'H', u16b)
88 u16codes = array.array('H', u16b)
89 u16codes.pop(0) # drop BOM
89 u16codes.pop(0) # drop BOM
90 return b''.join(jm[x] if x < 128 else b'\\u%04x' % x for x in u16codes)
90 return b''.join(jm[x] if x < 128 else b'\\u%04x' % x for x in u16codes)
@@ -218,7 +218,7 b' else:'
218 def _raiseioerror(name):
218 def _raiseioerror(name):
219 err = ctypes.WinError()
219 err = ctypes.WinError()
220 raise IOError(
220 raise IOError(
221 err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror)
221 err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror)
222 )
222 )
223
223
224 class posixfile(object):
224 class posixfile(object):
@@ -280,8 +280,8 b' else:'
280 # unfortunately, f.name is '<fdopen>' at this point -- so we store
280 # unfortunately, f.name is '<fdopen>' at this point -- so we store
281 # the name on this wrapper. We cannot just assign to f.name,
281 # the name on this wrapper. We cannot just assign to f.name,
282 # because that attribute is read-only.
282 # because that attribute is read-only.
283 object.__setattr__(self, r'name', name)
283 object.__setattr__(self, 'name', name)
284 object.__setattr__(self, r'_file', f)
284 object.__setattr__(self, '_file', f)
285
285
286 def __iter__(self):
286 def __iter__(self):
287 return self._file
287 return self._file
@@ -19,7 +19,7 b' import sys'
19 import tempfile
19 import tempfile
20
20
21 ispy3 = sys.version_info[0] >= 3
21 ispy3 = sys.version_info[0] >= 3
22 ispypy = r'__pypy__' in sys.builtin_module_names
22 ispypy = '__pypy__' in sys.builtin_module_names
23
23
24 if not ispy3:
24 if not ispy3:
25 import cookielib
25 import cookielib
@@ -151,7 +151,7 b' if ispy3:'
151 if getattr(sys, 'argv', None) is not None:
151 if getattr(sys, 'argv', None) is not None:
152 sysargv = list(map(os.fsencode, sys.argv))
152 sysargv = list(map(os.fsencode, sys.argv))
153
153
154 bytechr = struct.Struct(r'>B').pack
154 bytechr = struct.Struct('>B').pack
155 byterepr = b'%r'.__mod__
155 byterepr = b'%r'.__mod__
156
156
157 class bytestr(bytes):
157 class bytestr(bytes):
@@ -500,7 +500,7 b' def namedtempfile('
500 mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None, delete=True
500 mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None, delete=True
501 ):
501 ):
502 mode = sysstr(mode)
502 mode = sysstr(mode)
503 assert r'b' in mode
503 assert 'b' in mode
504 return tempfile.NamedTemporaryFile(
504 return tempfile.NamedTemporaryFile(
505 mode, bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete
505 mode, bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete
506 )
506 )
@@ -370,12 +370,12 b' class repoview(object):'
370 """
370 """
371
371
372 def __init__(self, repo, filtername, visibilityexceptions=None):
372 def __init__(self, repo, filtername, visibilityexceptions=None):
373 object.__setattr__(self, r'_unfilteredrepo', repo)
373 object.__setattr__(self, '_unfilteredrepo', repo)
374 object.__setattr__(self, r'filtername', filtername)
374 object.__setattr__(self, 'filtername', filtername)
375 object.__setattr__(self, r'_clcachekey', None)
375 object.__setattr__(self, '_clcachekey', None)
376 object.__setattr__(self, r'_clcache', None)
376 object.__setattr__(self, '_clcache', None)
377 # revs which are exceptions and must not be hidden
377 # revs which are exceptions and must not be hidden
378 object.__setattr__(self, r'_visibilityexceptions', visibilityexceptions)
378 object.__setattr__(self, '_visibilityexceptions', visibilityexceptions)
379
379
380 # not a propertycache on purpose we shall implement a proper cache later
380 # not a propertycache on purpose we shall implement a proper cache later
381 @property
381 @property
@@ -404,8 +404,8 b' class repoview(object):'
404 if cl is None:
404 if cl is None:
405 # Only filter if there's something to filter
405 # Only filter if there's something to filter
406 cl = wrapchangelog(unfichangelog, revs) if revs else unfichangelog
406 cl = wrapchangelog(unfichangelog, revs) if revs else unfichangelog
407 object.__setattr__(self, r'_clcache', cl)
407 object.__setattr__(self, '_clcache', cl)
408 object.__setattr__(self, r'_clcachekey', newkey)
408 object.__setattr__(self, '_clcachekey', newkey)
409 return cl
409 return cl
410
410
411 def unfiltered(self):
411 def unfiltered(self):
@@ -419,7 +419,7 b' class repoview(object):'
419 return self.unfiltered().filtered(name, visibilityexceptions)
419 return self.unfiltered().filtered(name, visibilityexceptions)
420
420
421 def __repr__(self):
421 def __repr__(self):
422 return r'<%s:%s %r>' % (
422 return '<%s:%s %r>' % (
423 self.__class__.__name__,
423 self.__class__.__name__,
424 pycompat.sysstr(self.filtername),
424 pycompat.sysstr(self.filtername),
425 self.unfiltered(),
425 self.unfiltered(),
@@ -102,9 +102,9 b' REVIDX_DEFAULT_FLAGS'
102 REVIDX_FLAGS_ORDER
102 REVIDX_FLAGS_ORDER
103 REVIDX_RAWTEXT_CHANGING_FLAGS
103 REVIDX_RAWTEXT_CHANGING_FLAGS
104
104
105 parsers = policy.importmod(r'parsers')
105 parsers = policy.importmod('parsers')
106 rustancestor = policy.importrust(r'ancestor')
106 rustancestor = policy.importrust('ancestor')
107 rustdagop = policy.importrust(r'dagop')
107 rustdagop = policy.importrust('dagop')
108
108
109 # Aliased for performance.
109 # Aliased for performance.
110 _zlibdecompress = zlib.decompress
110 _zlibdecompress = zlib.decompress
@@ -556,11 +556,11 b' class revlog(object):'
556
556
557 def _indexfp(self, mode=b'r'):
557 def _indexfp(self, mode=b'r'):
558 """file object for the revlog's index file"""
558 """file object for the revlog's index file"""
559 args = {r'mode': mode}
559 args = {'mode': mode}
560 if mode != b'r':
560 if mode != b'r':
561 args[r'checkambig'] = self._checkambig
561 args['checkambig'] = self._checkambig
562 if mode == b'w':
562 if mode == b'w':
563 args[r'atomictemp'] = True
563 args['atomictemp'] = True
564 return self.opener(self.indexfile, **args)
564 return self.opener(self.indexfile, **args)
565
565
566 def _datafp(self, mode=b'r'):
566 def _datafp(self, mode=b'r'):
@@ -55,8 +55,8 b' SD_FILESADDED = 10'
55 SD_FILESREMOVED = 11
55 SD_FILESREMOVED = 11
56
56
57 # internal format constant
57 # internal format constant
58 SIDEDATA_HEADER = struct.Struct(r'>H')
58 SIDEDATA_HEADER = struct.Struct('>H')
59 SIDEDATA_ENTRY = struct.Struct(r'>HL20s')
59 SIDEDATA_ENTRY = struct.Struct('>HL20s')
60
60
61
61
62 def sidedatawriteprocessor(rl, text, sidedata):
62 def sidedatawriteprocessor(rl, text, sidedata):
@@ -84,7 +84,7 b' def termsize(ui):'
84 if not os.isatty(fd):
84 if not os.isatty(fd):
85 continue
85 continue
86 arri = fcntl.ioctl(fd, TIOCGWINSZ, b'\0' * 8)
86 arri = fcntl.ioctl(fd, TIOCGWINSZ, b'\0' * 8)
87 height, width = array.array(r'h', arri)[:2]
87 height, width = array.array('h', arri)[:2]
88 if width > 0 and height > 0:
88 if width > 0 and height > 0:
89 return width, height
89 return width, height
90 except ValueError:
90 except ValueError:
@@ -57,7 +57,7 b' if pycompat.iswindows:'
57 else:
57 else:
58 from . import scmposix as scmplatform
58 from . import scmposix as scmplatform
59
59
60 parsers = policy.importmod(r'parsers')
60 parsers = policy.importmod('parsers')
61
61
62 termsize = scmplatform.termsize
62 termsize = scmplatform.termsize
63
63
@@ -278,7 +278,7 b' class partialdiscovery(object):'
278
278
279
279
280 partialdiscovery = policy.importrust(
280 partialdiscovery = policy.importrust(
281 r'discovery', member=r'PartialDiscovery', default=partialdiscovery
281 'discovery', member='PartialDiscovery', default=partialdiscovery
282 )
282 )
283
283
284
284
@@ -256,7 +256,7 b' class baseset(abstractsmartset):'
256 @util.propertycache
256 @util.propertycache
257 def _list(self):
257 def _list(self):
258 # _list is only lazily constructed if we have _set
258 # _list is only lazily constructed if we have _set
259 assert r'_set' in self.__dict__
259 assert '_set' in self.__dict__
260 return list(self._set)
260 return list(self._set)
261
261
262 def __iter__(self):
262 def __iter__(self):
@@ -294,7 +294,7 b' class baseset(abstractsmartset):'
294 self._istopo = False
294 self._istopo = False
295
295
296 def __len__(self):
296 def __len__(self):
297 if r'_list' in self.__dict__:
297 if '_list' in self.__dict__:
298 return len(self._list)
298 return len(self._list)
299 else:
299 else:
300 return len(self._set)
300 return len(self._set)
@@ -347,8 +347,8 b' class baseset(abstractsmartset):'
347 # try to use native set operations as fast paths
347 # try to use native set operations as fast paths
348 if (
348 if (
349 type(other) is baseset
349 type(other) is baseset
350 and r'_set' in other.__dict__
350 and '_set' in other.__dict__
351 and r'_set' in self.__dict__
351 and '_set' in self.__dict__
352 and self._ascending is not None
352 and self._ascending is not None
353 ):
353 ):
354 s = baseset(
354 s = baseset(
@@ -103,13 +103,13 b' except AttributeError:'
103 # in this legacy code since we don't support SNI.
103 # in this legacy code since we don't support SNI.
104
104
105 args = {
105 args = {
106 r'keyfile': self._keyfile,
106 'keyfile': self._keyfile,
107 r'certfile': self._certfile,
107 'certfile': self._certfile,
108 r'server_side': server_side,
108 'server_side': server_side,
109 r'cert_reqs': self.verify_mode,
109 'cert_reqs': self.verify_mode,
110 r'ssl_version': self.protocol,
110 'ssl_version': self.protocol,
111 r'ca_certs': self._cacerts,
111 'ca_certs': self._cacerts,
112 r'ciphers': self._ciphers,
112 'ciphers': self._ciphers,
113 }
113 }
114
114
115 return ssl.wrap_socket(socket, **args)
115 return ssl.wrap_socket(socket, **args)
@@ -499,7 +499,7 b' def wrapsocket(sock, keyfile, certfile, '
499 # outright. Hopefully the reason for this error is that we require
499 # outright. Hopefully the reason for this error is that we require
500 # TLS 1.1+ and the server only supports TLS 1.0. Whatever the
500 # TLS 1.1+ and the server only supports TLS 1.0. Whatever the
501 # reason, try to emit an actionable warning.
501 # reason, try to emit an actionable warning.
502 if e.reason == r'UNSUPPORTED_PROTOCOL':
502 if e.reason == 'UNSUPPORTED_PROTOCOL':
503 # We attempted TLS 1.0+.
503 # We attempted TLS 1.0+.
504 if settings[b'protocolui'] == b'tls1.0':
504 if settings[b'protocolui'] == b'tls1.0':
505 # We support more than just TLS 1.0+. If this happens,
505 # We support more than just TLS 1.0+. If this happens,
@@ -568,9 +568,7 b' def wrapsocket(sock, keyfile, certfile, '
568 )
568 )
569 )
569 )
570
570
571 elif (
571 elif e.reason == 'CERTIFICATE_VERIFY_FAILED' and pycompat.iswindows:
572 e.reason == r'CERTIFICATE_VERIFY_FAILED' and pycompat.iswindows
573 ):
574
572
575 ui.warn(
573 ui.warn(
576 _(
574 _(
@@ -737,9 +735,9 b' def _verifycert(cert, hostname):'
737 return _(b'no certificate received')
735 return _(b'no certificate received')
738
736
739 dnsnames = []
737 dnsnames = []
740 san = cert.get(r'subjectAltName', [])
738 san = cert.get('subjectAltName', [])
741 for key, value in san:
739 for key, value in san:
742 if key == r'DNS':
740 if key == 'DNS':
743 try:
741 try:
744 if _dnsnamematch(value, hostname):
742 if _dnsnamematch(value, hostname):
745 return
743 return
@@ -750,11 +748,11 b' def _verifycert(cert, hostname):'
750
748
751 if not dnsnames:
749 if not dnsnames:
752 # The subject is only checked when there is no DNS in subjectAltName.
750 # The subject is only checked when there is no DNS in subjectAltName.
753 for sub in cert.get(r'subject', []):
751 for sub in cert.get('subject', []):
754 for key, value in sub:
752 for key, value in sub:
755 # According to RFC 2818 the most specific Common Name must
753 # According to RFC 2818 the most specific Common Name must
756 # be used.
754 # be used.
757 if key == r'commonName':
755 if key == 'commonName':
758 # 'subject' entries are unicode.
756 # 'subject' entries are unicode.
759 try:
757 try:
760 value = value.encode('ascii')
758 value = value.encode('ascii')
@@ -53,7 +53,7 b' class httprangereader(object):'
53 if bytes:
53 if bytes:
54 end = self.pos + bytes - 1
54 end = self.pos + bytes - 1
55 if self.pos or end:
55 if self.pos or end:
56 req.add_header(r'Range', r'bytes=%d-%s' % (self.pos, end))
56 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
57
57
58 try:
58 try:
59 f = self.opener.open(req)
59 f = self.opener.open(req)
@@ -206,7 +206,7 b' state = ProfileState()'
206 class CodeSite(object):
206 class CodeSite(object):
207 cache = {}
207 cache = {}
208
208
209 __slots__ = (r'path', r'lineno', r'function', r'source')
209 __slots__ = ('path', 'lineno', 'function', 'source')
210
210
211 def __init__(self, path, lineno, function):
211 def __init__(self, path, lineno, function):
212 assert isinstance(path, bytes)
212 assert isinstance(path, bytes)
@@ -258,11 +258,11 b' class CodeSite(object):'
258 return os.path.basename(self.path)
258 return os.path.basename(self.path)
259
259
260 def skipname(self):
260 def skipname(self):
261 return r'%s:%s' % (self.filename(), self.function)
261 return '%s:%s' % (self.filename(), self.function)
262
262
263
263
264 class Sample(object):
264 class Sample(object):
265 __slots__ = (r'stack', r'time')
265 __slots__ = ('stack', 'time')
266
266
267 def __init__(self, stack, time):
267 def __init__(self, stack, time):
268 self.stack = stack
268 self.stack = stack
@@ -738,7 +738,7 b' def display_hotpath(data, fp, limit=0.05'
738 for sample in data.samples:
738 for sample in data.samples:
739 root.add(sample.stack[::-1], sample.time - lasttime)
739 root.add(sample.stack[::-1], sample.time - lasttime)
740 lasttime = sample.time
740 lasttime = sample.time
741 showtime = kwargs.get(r'showtime', True)
741 showtime = kwargs.get('showtime', True)
742
742
743 def _write(node, depth, multiple_siblings):
743 def _write(node, depth, multiple_siblings):
744 site = node.site
744 site = node.site
@@ -894,7 +894,7 b' def write_to_chrome(data, fp, minthresho'
894 parent = stackid(stack[1:])
894 parent = stackid(stack[1:])
895 myid = len(stack2id)
895 myid = len(stack2id)
896 stack2id[stack] = myid
896 stack2id[stack] = myid
897 id2stack.append(dict(category=stack[0][0], name=r'%s %s' % stack[0]))
897 id2stack.append(dict(category=stack[0][0], name='%s %s' % stack[0]))
898 if parent is not None:
898 if parent is not None:
899 id2stack[-1].update(parent=parent)
899 id2stack[-1].update(parent=parent)
900 return myid
900 return myid
@@ -931,7 +931,7 b' def write_to_chrome(data, fp, minthresho'
931 sampletime = max(oldtime + clamp, sample.time)
931 sampletime = max(oldtime + clamp, sample.time)
932 samples.append(
932 samples.append(
933 dict(
933 dict(
934 ph=r'E',
934 ph='E',
935 name=oldfunc,
935 name=oldfunc,
936 cat=oldcat,
936 cat=oldcat,
937 sf=oldsid,
937 sf=oldsid,
@@ -949,7 +949,7 b' def write_to_chrome(data, fp, minthresho'
949 stack = tuple(
949 stack = tuple(
950 (
950 (
951 (
951 (
952 r'%s:%d'
952 '%s:%d'
953 % (simplifypath(pycompat.sysstr(frame.path)), frame.lineno),
953 % (simplifypath(pycompat.sysstr(frame.path)), frame.lineno),
954 pycompat.sysstr(frame.function),
954 pycompat.sysstr(frame.function),
955 )
955 )
@@ -971,7 +971,7 b' def write_to_chrome(data, fp, minthresho'
971 sid = stackid(tuple(laststack))
971 sid = stackid(tuple(laststack))
972 samples.append(
972 samples.append(
973 dict(
973 dict(
974 ph=r'B',
974 ph='B',
975 name=name,
975 name=name,
976 cat=path,
976 cat=path,
977 ts=sample.time * 1e6,
977 ts=sample.time * 1e6,
@@ -1030,17 +1030,17 b' def main(argv=None):'
1030
1030
1031 optstart = 2
1031 optstart = 2
1032 displayargs[b'function'] = None
1032 displayargs[b'function'] = None
1033 if argv[1] == r'hotpath':
1033 if argv[1] == 'hotpath':
1034 displayargs[b'format'] = DisplayFormats.Hotpath
1034 displayargs[b'format'] = DisplayFormats.Hotpath
1035 elif argv[1] == r'lines':
1035 elif argv[1] == 'lines':
1036 displayargs[b'format'] = DisplayFormats.ByLine
1036 displayargs[b'format'] = DisplayFormats.ByLine
1037 elif argv[1] == r'functions':
1037 elif argv[1] == 'functions':
1038 displayargs[b'format'] = DisplayFormats.ByMethod
1038 displayargs[b'format'] = DisplayFormats.ByMethod
1039 elif argv[1] == r'function':
1039 elif argv[1] == 'function':
1040 displayargs[b'format'] = DisplayFormats.AboutMethod
1040 displayargs[b'format'] = DisplayFormats.AboutMethod
1041 displayargs[b'function'] = argv[2]
1041 displayargs[b'function'] = argv[2]
1042 optstart = 3
1042 optstart = 3
1043 elif argv[1] == r'flame':
1043 elif argv[1] == 'flame':
1044 displayargs[b'format'] = DisplayFormats.FlameGraph
1044 displayargs[b'format'] = DisplayFormats.FlameGraph
1045 else:
1045 else:
1046 printusage()
1046 printusage()
@@ -1076,7 +1076,7 b' def main(argv=None):'
1076 assert False, b"unhandled option %s" % o
1076 assert False, b"unhandled option %s" % o
1077
1077
1078 if not path:
1078 if not path:
1079 print(r'must specify --file to load')
1079 print('must specify --file to load')
1080 return 1
1080 return 1
1081
1081
1082 load_data(path=path)
1082 load_data(path=path)
@@ -26,7 +26,7 b' from . import ('
26 vfs as vfsmod,
26 vfs as vfsmod,
27 )
27 )
28
28
29 parsers = policy.importmod(r'parsers')
29 parsers = policy.importmod('parsers')
30 # how much bytes should be read from fncache in one read
30 # how much bytes should be read from fncache in one read
31 # It is done to prevent loading large fncache files into memory
31 # It is done to prevent loading large fncache files into memory
32 fncache_chunksize = 10 ** 6
32 fncache_chunksize = 10 ** 6
@@ -69,8 +69,8 b' class SubrepoAbort(error.Abort):'
69 """Exception class used to avoid handling a subrepo error more than once"""
69 """Exception class used to avoid handling a subrepo error more than once"""
70
70
71 def __init__(self, *args, **kw):
71 def __init__(self, *args, **kw):
72 self.subrepo = kw.pop(r'subrepo', None)
72 self.subrepo = kw.pop('subrepo', None)
73 self.cause = kw.pop(r'cause', None)
73 self.cause = kw.pop('cause', None)
74 error.Abort.__init__(self, *args, **kw)
74 error.Abort.__init__(self, *args, **kw)
75
75
76
76
@@ -969,24 +969,24 b' class hgsubrepo(abstractsubrepo):'
969 # 2. update the subrepo to the revision specified in
969 # 2. update the subrepo to the revision specified in
970 # the corresponding substate dictionary
970 # the corresponding substate dictionary
971 self.ui.status(_(b'reverting subrepo %s\n') % substate[0])
971 self.ui.status(_(b'reverting subrepo %s\n') % substate[0])
972 if not opts.get(r'no_backup'):
972 if not opts.get('no_backup'):
973 # Revert all files on the subrepo, creating backups
973 # Revert all files on the subrepo, creating backups
974 # Note that this will not recursively revert subrepos
974 # Note that this will not recursively revert subrepos
975 # We could do it if there was a set:subrepos() predicate
975 # We could do it if there was a set:subrepos() predicate
976 opts = opts.copy()
976 opts = opts.copy()
977 opts[r'date'] = None
977 opts['date'] = None
978 opts[r'rev'] = substate[1]
978 opts['rev'] = substate[1]
979
979
980 self.filerevert(*pats, **opts)
980 self.filerevert(*pats, **opts)
981
981
982 # Update the repo to the revision specified in the given substate
982 # Update the repo to the revision specified in the given substate
983 if not opts.get(r'dry_run'):
983 if not opts.get('dry_run'):
984 self.get(substate, overwrite=True)
984 self.get(substate, overwrite=True)
985
985
986 def filerevert(self, *pats, **opts):
986 def filerevert(self, *pats, **opts):
987 ctx = self._repo[opts[r'rev']]
987 ctx = self._repo[opts['rev']]
988 parents = self._repo.dirstate.parents()
988 parents = self._repo.dirstate.parents()
989 if opts.get(r'all'):
989 if opts.get('all'):
990 pats = [b'set:modified()']
990 pats = [b'set:modified()']
991 else:
991 else:
992 pats = []
992 pats = []
@@ -1066,7 +1066,7 b' class svnsubrepo(abstractsubrepo):'
1066 if not self.ui.interactive():
1066 if not self.ui.interactive():
1067 # Making stdin be a pipe should prevent svn from behaving
1067 # Making stdin be a pipe should prevent svn from behaving
1068 # interactively even if we can't pass --non-interactive.
1068 # interactively even if we can't pass --non-interactive.
1069 extrakw[r'stdin'] = subprocess.PIPE
1069 extrakw['stdin'] = subprocess.PIPE
1070 # Starting in svn 1.5 --non-interactive is a global flag
1070 # Starting in svn 1.5 --non-interactive is a global flag
1071 # instead of being per-command, but we need to support 1.4 so
1071 # instead of being per-command, but we need to support 1.4 so
1072 # we have to be intelligent about what commands take
1072 # we have to be intelligent about what commands take
@@ -1125,14 +1125,14 b' class svnsubrepo(abstractsubrepo):'
1125 # both. We used to store the working directory one.
1125 # both. We used to store the working directory one.
1126 output, err = self._svncommand([b'info', b'--xml'])
1126 output, err = self._svncommand([b'info', b'--xml'])
1127 doc = xml.dom.minidom.parseString(output)
1127 doc = xml.dom.minidom.parseString(output)
1128 entries = doc.getElementsByTagName(r'entry')
1128 entries = doc.getElementsByTagName('entry')
1129 lastrev, rev = b'0', b'0'
1129 lastrev, rev = b'0', b'0'
1130 if entries:
1130 if entries:
1131 rev = pycompat.bytestr(entries[0].getAttribute(r'revision')) or b'0'
1131 rev = pycompat.bytestr(entries[0].getAttribute('revision')) or b'0'
1132 commits = entries[0].getElementsByTagName(r'commit')
1132 commits = entries[0].getElementsByTagName('commit')
1133 if commits:
1133 if commits:
1134 lastrev = (
1134 lastrev = (
1135 pycompat.bytestr(commits[0].getAttribute(r'revision'))
1135 pycompat.bytestr(commits[0].getAttribute('revision'))
1136 or b'0'
1136 or b'0'
1137 )
1137 )
1138 return (lastrev, rev)
1138 return (lastrev, rev)
@@ -1149,23 +1149,23 b' class svnsubrepo(abstractsubrepo):'
1149 output, err = self._svncommand([b'status', b'--xml'])
1149 output, err = self._svncommand([b'status', b'--xml'])
1150 externals, changes, missing = [], [], []
1150 externals, changes, missing = [], [], []
1151 doc = xml.dom.minidom.parseString(output)
1151 doc = xml.dom.minidom.parseString(output)
1152 for e in doc.getElementsByTagName(r'entry'):
1152 for e in doc.getElementsByTagName('entry'):
1153 s = e.getElementsByTagName(r'wc-status')
1153 s = e.getElementsByTagName('wc-status')
1154 if not s:
1154 if not s:
1155 continue
1155 continue
1156 item = s[0].getAttribute(r'item')
1156 item = s[0].getAttribute('item')
1157 props = s[0].getAttribute(r'props')
1157 props = s[0].getAttribute('props')
1158 path = e.getAttribute(r'path').encode('utf8')
1158 path = e.getAttribute('path').encode('utf8')
1159 if item == r'external':
1159 if item == 'external':
1160 externals.append(path)
1160 externals.append(path)
1161 elif item == r'missing':
1161 elif item == 'missing':
1162 missing.append(path)
1162 missing.append(path)
1163 if item not in (
1163 if item not in (
1164 r'',
1164 '',
1165 r'normal',
1165 'normal',
1166 r'unversioned',
1166 'unversioned',
1167 r'external',
1167 'external',
1168 ) or props not in (r'', r'none', r'normal'):
1168 ) or props not in ('', 'none', 'normal'):
1169 changes.append(path)
1169 changes.append(path)
1170 for path in changes:
1170 for path in changes:
1171 for ext in externals:
1171 for ext in externals:
@@ -1291,13 +1291,13 b' class svnsubrepo(abstractsubrepo):'
1291 output = self._svncommand([b'list', b'--recursive', b'--xml'])[0]
1291 output = self._svncommand([b'list', b'--recursive', b'--xml'])[0]
1292 doc = xml.dom.minidom.parseString(output)
1292 doc = xml.dom.minidom.parseString(output)
1293 paths = []
1293 paths = []
1294 for e in doc.getElementsByTagName(r'entry'):
1294 for e in doc.getElementsByTagName('entry'):
1295 kind = pycompat.bytestr(e.getAttribute(r'kind'))
1295 kind = pycompat.bytestr(e.getAttribute('kind'))
1296 if kind != b'file':
1296 if kind != b'file':
1297 continue
1297 continue
1298 name = r''.join(
1298 name = ''.join(
1299 c.data
1299 c.data
1300 for c in e.getElementsByTagName(r'name')[0].childNodes
1300 for c in e.getElementsByTagName('name')[0].childNodes
1301 if c.nodeType == c.TEXT_NODE
1301 if c.nodeType == c.TEXT_NODE
1302 )
1302 )
1303 paths.append(name.encode('utf8'))
1303 paths.append(name.encode('utf8'))
@@ -1808,7 +1808,7 b' class gitsubrepo(abstractsubrepo):'
1808 if exact:
1808 if exact:
1809 rejected.append(f)
1809 rejected.append(f)
1810 continue
1810 continue
1811 if not opts.get(r'dry_run'):
1811 if not opts.get('dry_run'):
1812 self._gitcommand(command + [f])
1812 self._gitcommand(command + [f])
1813
1813
1814 for f in rejected:
1814 for f in rejected:
@@ -1849,7 +1849,7 b' class gitsubrepo(abstractsubrepo):'
1849 # This should be much faster than manually traversing the trees
1849 # This should be much faster than manually traversing the trees
1850 # and objects with many subprocess calls.
1850 # and objects with many subprocess calls.
1851 tarstream = self._gitcommand([b'archive', revision], stream=True)
1851 tarstream = self._gitcommand([b'archive', revision], stream=True)
1852 tar = tarfile.open(fileobj=tarstream, mode=r'r|')
1852 tar = tarfile.open(fileobj=tarstream, mode='r|')
1853 relpath = subrelpath(self)
1853 relpath = subrelpath(self)
1854 progress = self.ui.makeprogress(
1854 progress = self.ui.makeprogress(
1855 _(b'archiving (%s)') % relpath, unit=_(b'files')
1855 _(b'archiving (%s)') % relpath, unit=_(b'files')
@@ -1918,9 +1918,9 b' class gitsubrepo(abstractsubrepo):'
1918 deleted, unknown, ignored, clean = [], [], [], []
1918 deleted, unknown, ignored, clean = [], [], [], []
1919
1919
1920 command = [b'status', b'--porcelain', b'-z']
1920 command = [b'status', b'--porcelain', b'-z']
1921 if opts.get(r'unknown'):
1921 if opts.get('unknown'):
1922 command += [b'--untracked-files=all']
1922 command += [b'--untracked-files=all']
1923 if opts.get(r'ignored'):
1923 if opts.get('ignored'):
1924 command += [b'--ignored']
1924 command += [b'--ignored']
1925 out = self._gitcommand(command)
1925 out = self._gitcommand(command)
1926
1926
@@ -1948,7 +1948,7 b' class gitsubrepo(abstractsubrepo):'
1948 elif st == b'!!':
1948 elif st == b'!!':
1949 ignored.append(filename1)
1949 ignored.append(filename1)
1950
1950
1951 if opts.get(r'clean'):
1951 if opts.get('clean'):
1952 out = self._gitcommand([b'ls-files'])
1952 out = self._gitcommand([b'ls-files'])
1953 for f in out.split(b'\n'):
1953 for f in out.split(b'\n'):
1954 if not f in changedfiles:
1954 if not f in changedfiles:
@@ -1962,7 +1962,7 b' class gitsubrepo(abstractsubrepo):'
1962 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1962 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1963 node1 = self._state[1]
1963 node1 = self._state[1]
1964 cmd = [b'diff', b'--no-renames']
1964 cmd = [b'diff', b'--no-renames']
1965 if opts[r'stat']:
1965 if opts['stat']:
1966 cmd.append(b'--stat')
1966 cmd.append(b'--stat')
1967 else:
1967 else:
1968 # for Git, this also implies '-p'
1968 # for Git, this also implies '-p'
@@ -2007,7 +2007,7 b' class gitsubrepo(abstractsubrepo):'
2007 @annotatesubrepoerror
2007 @annotatesubrepoerror
2008 def revert(self, substate, *pats, **opts):
2008 def revert(self, substate, *pats, **opts):
2009 self.ui.status(_(b'reverting subrepo %s\n') % substate[0])
2009 self.ui.status(_(b'reverting subrepo %s\n') % substate[0])
2010 if not opts.get(r'no_backup'):
2010 if not opts.get('no_backup'):
2011 status = self.status(None)
2011 status = self.status(None)
2012 names = status.modified
2012 names = status.modified
2013 for name in names:
2013 for name in names:
@@ -2023,7 +2023,7 b' class gitsubrepo(abstractsubrepo):'
2023 )
2023 )
2024 util.rename(self.wvfs.join(name), bakname)
2024 util.rename(self.wvfs.join(name), bakname)
2025
2025
2026 if not opts.get(r'dry_run'):
2026 if not opts.get('dry_run'):
2027 self.get(substate, overwrite=True)
2027 self.get(substate, overwrite=True)
2028 return []
2028 return []
2029
2029
@@ -1366,26 +1366,26 b' def makeifileindextests(makefilefn, make'
1366 should find and run it automatically.
1366 should find and run it automatically.
1367 """
1367 """
1368 d = {
1368 d = {
1369 r'_makefilefn': makefilefn,
1369 '_makefilefn': makefilefn,
1370 r'_maketransactionfn': maketransactionfn,
1370 '_maketransactionfn': maketransactionfn,
1371 r'_addrawrevisionfn': addrawrevisionfn,
1371 '_addrawrevisionfn': addrawrevisionfn,
1372 }
1372 }
1373 return type(r'ifileindextests', (ifileindextests,), d)
1373 return type('ifileindextests', (ifileindextests,), d)
1374
1374
1375
1375
1376 def makeifiledatatests(makefilefn, maketransactionfn, addrawrevisionfn):
1376 def makeifiledatatests(makefilefn, maketransactionfn, addrawrevisionfn):
1377 d = {
1377 d = {
1378 r'_makefilefn': makefilefn,
1378 '_makefilefn': makefilefn,
1379 r'_maketransactionfn': maketransactionfn,
1379 '_maketransactionfn': maketransactionfn,
1380 r'_addrawrevisionfn': addrawrevisionfn,
1380 '_addrawrevisionfn': addrawrevisionfn,
1381 }
1381 }
1382 return type(r'ifiledatatests', (ifiledatatests,), d)
1382 return type('ifiledatatests', (ifiledatatests,), d)
1383
1383
1384
1384
1385 def makeifilemutationtests(makefilefn, maketransactionfn, addrawrevisionfn):
1385 def makeifilemutationtests(makefilefn, maketransactionfn, addrawrevisionfn):
1386 d = {
1386 d = {
1387 r'_makefilefn': makefilefn,
1387 '_makefilefn': makefilefn,
1388 r'_maketransactionfn': maketransactionfn,
1388 '_maketransactionfn': maketransactionfn,
1389 r'_addrawrevisionfn': addrawrevisionfn,
1389 '_addrawrevisionfn': addrawrevisionfn,
1390 }
1390 }
1391 return type(r'ifilemutationtests', (ifilemutationtests,), d)
1391 return type('ifilemutationtests', (ifilemutationtests,), d)
@@ -135,7 +135,7 b' class transaction(util.transactional):'
135 validator=None,
135 validator=None,
136 releasefn=None,
136 releasefn=None,
137 checkambigfiles=None,
137 checkambigfiles=None,
138 name=r'<unnamed>',
138 name='<unnamed>',
139 ):
139 ):
140 """Begin a new transaction
140 """Begin a new transaction
141
141
@@ -220,8 +220,8 b' class transaction(util.transactional):'
220 self._abortcallback = {}
220 self._abortcallback = {}
221
221
222 def __repr__(self):
222 def __repr__(self):
223 name = r'/'.join(self._names)
223 name = '/'.join(self._names)
224 return r'<transaction name=%s, count=%d, usages=%d>' % (
224 return '<transaction name=%s, count=%d, usages=%d>' % (
225 name,
225 name,
226 self._count,
226 self._count,
227 self._usages,
227 self._usages,
@@ -414,7 +414,7 b' class transaction(util.transactional):'
414 self._file.flush()
414 self._file.flush()
415
415
416 @active
416 @active
417 def nest(self, name=r'<unnamed>'):
417 def nest(self, name='<unnamed>'):
418 self._count += 1
418 self._count += 1
419 self._usages += 1
419 self._usages += 1
420 self._names.append(name)
420 self._names.append(name)
@@ -428,7 +428,7 b' class ui(object):'
428 self, filename, root=None, trust=False, sections=None, remap=None
428 self, filename, root=None, trust=False, sections=None, remap=None
429 ):
429 ):
430 try:
430 try:
431 fp = open(filename, r'rb')
431 fp = open(filename, 'rb')
432 except IOError:
432 except IOError:
433 if not sections: # ignore unless we were looking for something
433 if not sections: # ignore unless we were looking for something
434 return
434 return
@@ -1087,7 +1087,7 b' class ui(object):'
1087
1087
1088 # inlined _write() for speed
1088 # inlined _write() for speed
1089 if self._buffers:
1089 if self._buffers:
1090 label = opts.get(r'label', b'')
1090 label = opts.get('label', b'')
1091 if label and self._bufferapplylabels:
1091 if label and self._bufferapplylabels:
1092 self._buffers[-1].extend(self.label(a, label) for a in args)
1092 self._buffers[-1].extend(self.label(a, label) for a in args)
1093 else:
1093 else:
@@ -1095,7 +1095,7 b' class ui(object):'
1095 return
1095 return
1096
1096
1097 # inlined _writenobuf() for speed
1097 # inlined _writenobuf() for speed
1098 if not opts.get(r'keepprogressbar', False):
1098 if not opts.get('keepprogressbar', False):
1099 self._progclear()
1099 self._progclear()
1100 msg = b''.join(args)
1100 msg = b''.join(args)
1101
1101
@@ -1108,7 +1108,7 b' class ui(object):'
1108 color.win32print(self, dest.write, msg, **opts)
1108 color.win32print(self, dest.write, msg, **opts)
1109 else:
1109 else:
1110 if self._colormode is not None:
1110 if self._colormode is not None:
1111 label = opts.get(r'label', b'')
1111 label = opts.get('label', b'')
1112 msg = self.label(msg, label)
1112 msg = self.label(msg, label)
1113 dest.write(msg)
1113 dest.write(msg)
1114 except IOError as err:
1114 except IOError as err:
@@ -1124,7 +1124,7 b' class ui(object):'
1124 def _write(self, dest, *args, **opts):
1124 def _write(self, dest, *args, **opts):
1125 # update write() as well if you touch this code
1125 # update write() as well if you touch this code
1126 if self._isbuffered(dest):
1126 if self._isbuffered(dest):
1127 label = opts.get(r'label', b'')
1127 label = opts.get('label', b'')
1128 if label and self._bufferapplylabels:
1128 if label and self._bufferapplylabels:
1129 self._buffers[-1].extend(self.label(a, label) for a in args)
1129 self._buffers[-1].extend(self.label(a, label) for a in args)
1130 else:
1130 else:
@@ -1134,7 +1134,7 b' class ui(object):'
1134
1134
1135 def _writenobuf(self, dest, *args, **opts):
1135 def _writenobuf(self, dest, *args, **opts):
1136 # update write() as well if you touch this code
1136 # update write() as well if you touch this code
1137 if not opts.get(r'keepprogressbar', False):
1137 if not opts.get('keepprogressbar', False):
1138 self._progclear()
1138 self._progclear()
1139 msg = b''.join(args)
1139 msg = b''.join(args)
1140
1140
@@ -1153,7 +1153,7 b' class ui(object):'
1153 color.win32print(self, dest.write, msg, **opts)
1153 color.win32print(self, dest.write, msg, **opts)
1154 else:
1154 else:
1155 if self._colormode is not None:
1155 if self._colormode is not None:
1156 label = opts.get(r'label', b'')
1156 label = opts.get('label', b'')
1157 msg = self.label(msg, label)
1157 msg = self.label(msg, label)
1158 dest.write(msg)
1158 dest.write(msg)
1159 # stderr may be buffered under win32 when redirected to files,
1159 # stderr may be buffered under win32 when redirected to files,
@@ -1588,7 +1588,7 b' class ui(object):'
1588 return self._prompt(msg, default=default)
1588 return self._prompt(msg, default=default)
1589
1589
1590 def _prompt(self, msg, **opts):
1590 def _prompt(self, msg, **opts):
1591 default = opts[r'default']
1591 default = opts['default']
1592 if not self.interactive():
1592 if not self.interactive():
1593 self._writemsg(self._fmsgout, msg, b' ', type=b'prompt', **opts)
1593 self._writemsg(self._fmsgout, msg, b' ', type=b'prompt', **opts)
1594 self._writemsg(
1594 self._writemsg(
@@ -1674,7 +1674,7 b' class ui(object):'
1674 raise EOFError
1674 raise EOFError
1675 return l.rstrip(b'\n')
1675 return l.rstrip(b'\n')
1676 else:
1676 else:
1677 return getpass.getpass(r'')
1677 return getpass.getpass('')
1678 except EOFError:
1678 except EOFError:
1679 raise error.ResponseExpected()
1679 raise error.ResponseExpected()
1680
1680
@@ -1765,7 +1765,7 b' class ui(object):'
1765 prefix=b'hg-' + extra[b'prefix'] + b'-', suffix=suffix, dir=rdir
1765 prefix=b'hg-' + extra[b'prefix'] + b'-', suffix=suffix, dir=rdir
1766 )
1766 )
1767 try:
1767 try:
1768 f = os.fdopen(fd, r'wb')
1768 f = os.fdopen(fd, 'wb')
1769 f.write(util.tonativeeol(text))
1769 f.write(util.tonativeeol(text))
1770 f.close()
1770 f.close()
1771
1771
@@ -1793,7 +1793,7 b' class ui(object):'
1793 blockedtag=b'editor',
1793 blockedtag=b'editor',
1794 )
1794 )
1795
1795
1796 f = open(name, r'rb')
1796 f = open(name, 'rb')
1797 t = util.fromnativeeol(f.read())
1797 t = util.fromnativeeol(f.read())
1798 f.close()
1798 f.close()
1799 finally:
1799 finally:
@@ -1864,7 +1864,7 b' class ui(object):'
1864 )
1864 )
1865 else:
1865 else:
1866 output = traceback.format_exception(exc[0], exc[1], exc[2])
1866 output = traceback.format_exception(exc[0], exc[1], exc[2])
1867 self.write_err(encoding.strtolocal(r''.join(output)))
1867 self.write_err(encoding.strtolocal(''.join(output)))
1868 return self.tracebackflag or force
1868 return self.tracebackflag or force
1869
1869
1870 def geteditor(self):
1870 def geteditor(self):
@@ -2305,6 +2305,6 b' def _writemsgwith(write, dest, *args, **'
2305 isn't a structured channel, so that the message will be colorized.
2305 isn't a structured channel, so that the message will be colorized.
2306 """
2306 """
2307 # TODO: maybe change 'type' to a mandatory option
2307 # TODO: maybe change 'type' to a mandatory option
2308 if r'type' in opts and not getattr(dest, 'structured', False):
2308 if 'type' in opts and not getattr(dest, 'structured', False):
2309 opts[r'label'] = opts.get(r'label', b'') + b' ui.%s' % opts.pop(r'type')
2309 opts['label'] = opts.get('label', b'') + b' ui.%s' % opts.pop('type')
2310 write(dest, *args, **opts)
2310 write(dest, *args, **opts)
@@ -147,7 +147,7 b' class proxyhandler(urlreq.proxyhandler):'
147 # Keys and values need to be str because the standard library
147 # Keys and values need to be str because the standard library
148 # expects them to be.
148 # expects them to be.
149 proxyurl = str(proxy)
149 proxyurl = str(proxy)
150 proxies = {r'http': proxyurl, r'https': proxyurl}
150 proxies = {'http': proxyurl, 'https': proxyurl}
151 ui.debug(b'proxying through %s\n' % util.hidepassword(bytes(proxy)))
151 ui.debug(b'proxying through %s\n' % util.hidepassword(bytes(proxy)))
152 else:
152 else:
153 proxies = {}
153 proxies = {}
@@ -204,8 +204,8 b' class httpconnection(keepalive.HTTPConne'
204 def _generic_start_transaction(handler, h, req):
204 def _generic_start_transaction(handler, h, req):
205 tunnel_host = req._tunnel_host
205 tunnel_host = req._tunnel_host
206 if tunnel_host:
206 if tunnel_host:
207 if tunnel_host[:7] not in [r'http://', r'https:/']:
207 if tunnel_host[:7] not in ['http://', 'https:/']:
208 tunnel_host = r'https://' + tunnel_host
208 tunnel_host = 'https://' + tunnel_host
209 new_tunnel = True
209 new_tunnel = True
210 else:
210 else:
211 tunnel_host = urllibcompat.getselector(req)
211 tunnel_host = urllibcompat.getselector(req)
@@ -228,7 +228,7 b' def _generic_proxytunnel(self):'
228 [
228 [
229 (x, self.headers[x])
229 (x, self.headers[x])
230 for x in self.headers
230 for x in self.headers
231 if x.lower().startswith(r'proxy-')
231 if x.lower().startswith('proxy-')
232 ]
232 ]
233 )
233 )
234 self.send(b'CONNECT %s HTTP/1.0\r\n' % self.realhostport)
234 self.send(b'CONNECT %s HTTP/1.0\r\n' % self.realhostport)
@@ -522,7 +522,7 b' class httpbasicauthhandler(urlreq.httpba'
522 )
522 )
523 if pw is not None:
523 if pw is not None:
524 raw = b"%s:%s" % (pycompat.bytesurl(user), pycompat.bytesurl(pw))
524 raw = b"%s:%s" % (pycompat.bytesurl(user), pycompat.bytesurl(pw))
525 auth = r'Basic %s' % pycompat.strurl(base64.b64encode(raw).strip())
525 auth = 'Basic %s' % pycompat.strurl(base64.b64encode(raw).strip())
526 if req.get_header(self.auth_header, None) == auth:
526 if req.get_header(self.auth_header, None) == auth:
527 return None
527 return None
528 self.auth = auth
528 self.auth = auth
@@ -655,16 +655,16 b' def opener('
655 # do look at this value.
655 # do look at this value.
656 if not useragent:
656 if not useragent:
657 agent = b'mercurial/proto-1.0 (Mercurial %s)' % util.version()
657 agent = b'mercurial/proto-1.0 (Mercurial %s)' % util.version()
658 opener.addheaders = [(r'User-agent', pycompat.sysstr(agent))]
658 opener.addheaders = [('User-agent', pycompat.sysstr(agent))]
659 else:
659 else:
660 opener.addheaders = [(r'User-agent', pycompat.sysstr(useragent))]
660 opener.addheaders = [('User-agent', pycompat.sysstr(useragent))]
661
661
662 # This header should only be needed by wire protocol requests. But it has
662 # This header should only be needed by wire protocol requests. But it has
663 # been sent on all requests since forever. We keep sending it for backwards
663 # been sent on all requests since forever. We keep sending it for backwards
664 # compatibility reasons. Modern versions of the wire protocol use
664 # compatibility reasons. Modern versions of the wire protocol use
665 # X-HgProto-<N> for advertising client support.
665 # X-HgProto-<N> for advertising client support.
666 if sendaccept:
666 if sendaccept:
667 opener.addheaders.append((r'Accept', r'application/mercurial-0.1'))
667 opener.addheaders.append(('Accept', 'application/mercurial-0.1'))
668
668
669 return opener
669 return opener
670
670
@@ -20,7 +20,7 b' class _pycompatstub(object):'
20 """Add items that will be populated at the first access"""
20 """Add items that will be populated at the first access"""
21 items = map(_sysstr, items)
21 items = map(_sysstr, items)
22 self._aliases.update(
22 self._aliases.update(
23 (item.replace(r'_', r'').lower(), (origin, item)) for item in items
23 (item.replace('_', '').lower(), (origin, item)) for item in items
24 )
24 )
25
25
26 def _registeralias(self, origin, attr, name):
26 def _registeralias(self, origin, attr, name):
@@ -102,7 +102,7 b' if pycompat.ispy3:'
102 # urllib.parse.quote() accepts both str and bytes, decodes bytes
102 # urllib.parse.quote() accepts both str and bytes, decodes bytes
103 # (if necessary), and returns str. This is wonky. We provide a custom
103 # (if necessary), and returns str. This is wonky. We provide a custom
104 # implementation that only accepts bytes and emits bytes.
104 # implementation that only accepts bytes and emits bytes.
105 def quote(s, safe=r'/'):
105 def quote(s, safe='/'):
106 # bytestr has an __iter__ that emits characters. quote_from_bytes()
106 # bytestr has an __iter__ that emits characters. quote_from_bytes()
107 # does an iteration and expects ints. We coerce to bytes to appease it.
107 # does an iteration and expects ints. We coerce to bytes to appease it.
108 if isinstance(s, pycompat.bytestr):
108 if isinstance(s, pycompat.bytestr):
@@ -57,11 +57,11 b' from .utils import ('
57 stringutil,
57 stringutil,
58 )
58 )
59
59
60 rustdirs = policy.importrust(r'dirstate', r'Dirs')
60 rustdirs = policy.importrust('dirstate', 'Dirs')
61
61
62 base85 = policy.importmod(r'base85')
62 base85 = policy.importmod('base85')
63 osutil = policy.importmod(r'osutil')
63 osutil = policy.importmod('osutil')
64 parsers = policy.importmod(r'parsers')
64 parsers = policy.importmod('parsers')
65
65
66 b85decode = base85.b85decode
66 b85decode = base85.b85decode
67 b85encode = base85.b85encode
67 b85encode = base85.b85encode
@@ -165,23 +165,23 b' if _dowarn:'
165 # However, module name set through PYTHONWARNINGS was exactly matched, so
165 # However, module name set through PYTHONWARNINGS was exactly matched, so
166 # we cannot set 'mercurial' and have it match eg: 'mercurial.scmutil'. This
166 # we cannot set 'mercurial' and have it match eg: 'mercurial.scmutil'. This
167 # makes the whole PYTHONWARNINGS thing useless for our usecase.
167 # makes the whole PYTHONWARNINGS thing useless for our usecase.
168 warnings.filterwarnings(r'default', r'', DeprecationWarning, r'mercurial')
168 warnings.filterwarnings('default', '', DeprecationWarning, 'mercurial')
169 warnings.filterwarnings(r'default', r'', DeprecationWarning, r'hgext')
169 warnings.filterwarnings('default', '', DeprecationWarning, 'hgext')
170 warnings.filterwarnings(r'default', r'', DeprecationWarning, r'hgext3rd')
170 warnings.filterwarnings('default', '', DeprecationWarning, 'hgext3rd')
171 if _dowarn and pycompat.ispy3:
171 if _dowarn and pycompat.ispy3:
172 # silence warning emitted by passing user string to re.sub()
172 # silence warning emitted by passing user string to re.sub()
173 warnings.filterwarnings(
173 warnings.filterwarnings(
174 r'ignore', r'bad escape', DeprecationWarning, r'mercurial'
174 'ignore', 'bad escape', DeprecationWarning, 'mercurial'
175 )
175 )
176 warnings.filterwarnings(
176 warnings.filterwarnings(
177 r'ignore', r'invalid escape sequence', DeprecationWarning, r'mercurial'
177 'ignore', 'invalid escape sequence', DeprecationWarning, 'mercurial'
178 )
178 )
179 # TODO: reinvent imp.is_frozen()
179 # TODO: reinvent imp.is_frozen()
180 warnings.filterwarnings(
180 warnings.filterwarnings(
181 r'ignore',
181 'ignore',
182 r'the imp module is deprecated',
182 'the imp module is deprecated',
183 DeprecationWarning,
183 DeprecationWarning,
184 r'mercurial',
184 'mercurial',
185 )
185 )
186
186
187
187
@@ -438,42 +438,42 b' class fileobjectproxy(object):'
438 """
438 """
439
439
440 __slots__ = (
440 __slots__ = (
441 r'_orig',
441 '_orig',
442 r'_observer',
442 '_observer',
443 )
443 )
444
444
445 def __init__(self, fh, observer):
445 def __init__(self, fh, observer):
446 object.__setattr__(self, r'_orig', fh)
446 object.__setattr__(self, '_orig', fh)
447 object.__setattr__(self, r'_observer', observer)
447 object.__setattr__(self, '_observer', observer)
448
448
449 def __getattribute__(self, name):
449 def __getattribute__(self, name):
450 ours = {
450 ours = {
451 r'_observer',
451 '_observer',
452 # IOBase
452 # IOBase
453 r'close',
453 'close',
454 # closed if a property
454 # closed if a property
455 r'fileno',
455 'fileno',
456 r'flush',
456 'flush',
457 r'isatty',
457 'isatty',
458 r'readable',
458 'readable',
459 r'readline',
459 'readline',
460 r'readlines',
460 'readlines',
461 r'seek',
461 'seek',
462 r'seekable',
462 'seekable',
463 r'tell',
463 'tell',
464 r'truncate',
464 'truncate',
465 r'writable',
465 'writable',
466 r'writelines',
466 'writelines',
467 # RawIOBase
467 # RawIOBase
468 r'read',
468 'read',
469 r'readall',
469 'readall',
470 r'readinto',
470 'readinto',
471 r'write',
471 'write',
472 # BufferedIOBase
472 # BufferedIOBase
473 # raw is a property
473 # raw is a property
474 r'detach',
474 'detach',
475 # read defined above
475 # read defined above
476 r'read1',
476 'read1',
477 # readinto defined above
477 # readinto defined above
478 # write defined above
478 # write defined above
479 }
479 }
@@ -482,30 +482,30 b' class fileobjectproxy(object):'
482 if name in ours:
482 if name in ours:
483 return object.__getattribute__(self, name)
483 return object.__getattribute__(self, name)
484
484
485 return getattr(object.__getattribute__(self, r'_orig'), name)
485 return getattr(object.__getattribute__(self, '_orig'), name)
486
486
487 def __nonzero__(self):
487 def __nonzero__(self):
488 return bool(object.__getattribute__(self, r'_orig'))
488 return bool(object.__getattribute__(self, '_orig'))
489
489
490 __bool__ = __nonzero__
490 __bool__ = __nonzero__
491
491
492 def __delattr__(self, name):
492 def __delattr__(self, name):
493 return delattr(object.__getattribute__(self, r'_orig'), name)
493 return delattr(object.__getattribute__(self, '_orig'), name)
494
494
495 def __setattr__(self, name, value):
495 def __setattr__(self, name, value):
496 return setattr(object.__getattribute__(self, r'_orig'), name, value)
496 return setattr(object.__getattribute__(self, '_orig'), name, value)
497
497
498 def __iter__(self):
498 def __iter__(self):
499 return object.__getattribute__(self, r'_orig').__iter__()
499 return object.__getattribute__(self, '_orig').__iter__()
500
500
501 def _observedcall(self, name, *args, **kwargs):
501 def _observedcall(self, name, *args, **kwargs):
502 # Call the original object.
502 # Call the original object.
503 orig = object.__getattribute__(self, r'_orig')
503 orig = object.__getattribute__(self, '_orig')
504 res = getattr(orig, name)(*args, **kwargs)
504 res = getattr(orig, name)(*args, **kwargs)
505
505
506 # Call a method on the observer of the same name with arguments
506 # Call a method on the observer of the same name with arguments
507 # so it can react, log, etc.
507 # so it can react, log, etc.
508 observer = object.__getattribute__(self, r'_observer')
508 observer = object.__getattribute__(self, '_observer')
509 fn = getattr(observer, name, None)
509 fn = getattr(observer, name, None)
510 if fn:
510 if fn:
511 fn(res, *args, **kwargs)
511 fn(res, *args, **kwargs)
@@ -513,98 +513,98 b' class fileobjectproxy(object):'
513 return res
513 return res
514
514
515 def close(self, *args, **kwargs):
515 def close(self, *args, **kwargs):
516 return object.__getattribute__(self, r'_observedcall')(
516 return object.__getattribute__(self, '_observedcall')(
517 r'close', *args, **kwargs
517 'close', *args, **kwargs
518 )
518 )
519
519
520 def fileno(self, *args, **kwargs):
520 def fileno(self, *args, **kwargs):
521 return object.__getattribute__(self, r'_observedcall')(
521 return object.__getattribute__(self, '_observedcall')(
522 r'fileno', *args, **kwargs
522 'fileno', *args, **kwargs
523 )
523 )
524
524
525 def flush(self, *args, **kwargs):
525 def flush(self, *args, **kwargs):
526 return object.__getattribute__(self, r'_observedcall')(
526 return object.__getattribute__(self, '_observedcall')(
527 r'flush', *args, **kwargs
527 'flush', *args, **kwargs
528 )
528 )
529
529
530 def isatty(self, *args, **kwargs):
530 def isatty(self, *args, **kwargs):
531 return object.__getattribute__(self, r'_observedcall')(
531 return object.__getattribute__(self, '_observedcall')(
532 r'isatty', *args, **kwargs
532 'isatty', *args, **kwargs
533 )
533 )
534
534
535 def readable(self, *args, **kwargs):
535 def readable(self, *args, **kwargs):
536 return object.__getattribute__(self, r'_observedcall')(
536 return object.__getattribute__(self, '_observedcall')(
537 r'readable', *args, **kwargs
537 'readable', *args, **kwargs
538 )
538 )
539
539
540 def readline(self, *args, **kwargs):
540 def readline(self, *args, **kwargs):
541 return object.__getattribute__(self, r'_observedcall')(
541 return object.__getattribute__(self, '_observedcall')(
542 r'readline', *args, **kwargs
542 'readline', *args, **kwargs
543 )
543 )
544
544
545 def readlines(self, *args, **kwargs):
545 def readlines(self, *args, **kwargs):
546 return object.__getattribute__(self, r'_observedcall')(
546 return object.__getattribute__(self, '_observedcall')(
547 r'readlines', *args, **kwargs
547 'readlines', *args, **kwargs
548 )
548 )
549
549
550 def seek(self, *args, **kwargs):
550 def seek(self, *args, **kwargs):
551 return object.__getattribute__(self, r'_observedcall')(
551 return object.__getattribute__(self, '_observedcall')(
552 r'seek', *args, **kwargs
552 'seek', *args, **kwargs
553 )
553 )
554
554
555 def seekable(self, *args, **kwargs):
555 def seekable(self, *args, **kwargs):
556 return object.__getattribute__(self, r'_observedcall')(
556 return object.__getattribute__(self, '_observedcall')(
557 r'seekable', *args, **kwargs
557 'seekable', *args, **kwargs
558 )
558 )
559
559
560 def tell(self, *args, **kwargs):
560 def tell(self, *args, **kwargs):
561 return object.__getattribute__(self, r'_observedcall')(
561 return object.__getattribute__(self, '_observedcall')(
562 r'tell', *args, **kwargs
562 'tell', *args, **kwargs
563 )
563 )
564
564
565 def truncate(self, *args, **kwargs):
565 def truncate(self, *args, **kwargs):
566 return object.__getattribute__(self, r'_observedcall')(
566 return object.__getattribute__(self, '_observedcall')(
567 r'truncate', *args, **kwargs
567 'truncate', *args, **kwargs
568 )
568 )
569
569
570 def writable(self, *args, **kwargs):
570 def writable(self, *args, **kwargs):
571 return object.__getattribute__(self, r'_observedcall')(
571 return object.__getattribute__(self, '_observedcall')(
572 r'writable', *args, **kwargs
572 'writable', *args, **kwargs
573 )
573 )
574
574
575 def writelines(self, *args, **kwargs):
575 def writelines(self, *args, **kwargs):
576 return object.__getattribute__(self, r'_observedcall')(
576 return object.__getattribute__(self, '_observedcall')(
577 r'writelines', *args, **kwargs
577 'writelines', *args, **kwargs
578 )
578 )
579
579
580 def read(self, *args, **kwargs):
580 def read(self, *args, **kwargs):
581 return object.__getattribute__(self, r'_observedcall')(
581 return object.__getattribute__(self, '_observedcall')(
582 r'read', *args, **kwargs
582 'read', *args, **kwargs
583 )
583 )
584
584
585 def readall(self, *args, **kwargs):
585 def readall(self, *args, **kwargs):
586 return object.__getattribute__(self, r'_observedcall')(
586 return object.__getattribute__(self, '_observedcall')(
587 r'readall', *args, **kwargs
587 'readall', *args, **kwargs
588 )
588 )
589
589
590 def readinto(self, *args, **kwargs):
590 def readinto(self, *args, **kwargs):
591 return object.__getattribute__(self, r'_observedcall')(
591 return object.__getattribute__(self, '_observedcall')(
592 r'readinto', *args, **kwargs
592 'readinto', *args, **kwargs
593 )
593 )
594
594
595 def write(self, *args, **kwargs):
595 def write(self, *args, **kwargs):
596 return object.__getattribute__(self, r'_observedcall')(
596 return object.__getattribute__(self, '_observedcall')(
597 r'write', *args, **kwargs
597 'write', *args, **kwargs
598 )
598 )
599
599
600 def detach(self, *args, **kwargs):
600 def detach(self, *args, **kwargs):
601 return object.__getattribute__(self, r'_observedcall')(
601 return object.__getattribute__(self, '_observedcall')(
602 r'detach', *args, **kwargs
602 'detach', *args, **kwargs
603 )
603 )
604
604
605 def read1(self, *args, **kwargs):
605 def read1(self, *args, **kwargs):
606 return object.__getattribute__(self, r'_observedcall')(
606 return object.__getattribute__(self, '_observedcall')(
607 r'read1', *args, **kwargs
607 'read1', *args, **kwargs
608 )
608 )
609
609
610
610
@@ -651,18 +651,18 b' class observedbufferedinputpipe(buffered'
651
651
652
652
653 PROXIED_SOCKET_METHODS = {
653 PROXIED_SOCKET_METHODS = {
654 r'makefile',
654 'makefile',
655 r'recv',
655 'recv',
656 r'recvfrom',
656 'recvfrom',
657 r'recvfrom_into',
657 'recvfrom_into',
658 r'recv_into',
658 'recv_into',
659 r'send',
659 'send',
660 r'sendall',
660 'sendall',
661 r'sendto',
661 'sendto',
662 r'setblocking',
662 'setblocking',
663 r'settimeout',
663 'settimeout',
664 r'gettimeout',
664 'gettimeout',
665 r'setsockopt',
665 'setsockopt',
666 }
666 }
667
667
668
668
@@ -676,39 +676,39 b' class socketproxy(object):'
676 """
676 """
677
677
678 __slots__ = (
678 __slots__ = (
679 r'_orig',
679 '_orig',
680 r'_observer',
680 '_observer',
681 )
681 )
682
682
683 def __init__(self, sock, observer):
683 def __init__(self, sock, observer):
684 object.__setattr__(self, r'_orig', sock)
684 object.__setattr__(self, '_orig', sock)
685 object.__setattr__(self, r'_observer', observer)
685 object.__setattr__(self, '_observer', observer)
686
686
687 def __getattribute__(self, name):
687 def __getattribute__(self, name):
688 if name in PROXIED_SOCKET_METHODS:
688 if name in PROXIED_SOCKET_METHODS:
689 return object.__getattribute__(self, name)
689 return object.__getattribute__(self, name)
690
690
691 return getattr(object.__getattribute__(self, r'_orig'), name)
691 return getattr(object.__getattribute__(self, '_orig'), name)
692
692
693 def __delattr__(self, name):
693 def __delattr__(self, name):
694 return delattr(object.__getattribute__(self, r'_orig'), name)
694 return delattr(object.__getattribute__(self, '_orig'), name)
695
695
696 def __setattr__(self, name, value):
696 def __setattr__(self, name, value):
697 return setattr(object.__getattribute__(self, r'_orig'), name, value)
697 return setattr(object.__getattribute__(self, '_orig'), name, value)
698
698
699 def __nonzero__(self):
699 def __nonzero__(self):
700 return bool(object.__getattribute__(self, r'_orig'))
700 return bool(object.__getattribute__(self, '_orig'))
701
701
702 __bool__ = __nonzero__
702 __bool__ = __nonzero__
703
703
704 def _observedcall(self, name, *args, **kwargs):
704 def _observedcall(self, name, *args, **kwargs):
705 # Call the original object.
705 # Call the original object.
706 orig = object.__getattribute__(self, r'_orig')
706 orig = object.__getattribute__(self, '_orig')
707 res = getattr(orig, name)(*args, **kwargs)
707 res = getattr(orig, name)(*args, **kwargs)
708
708
709 # Call a method on the observer of the same name with arguments
709 # Call a method on the observer of the same name with arguments
710 # so it can react, log, etc.
710 # so it can react, log, etc.
711 observer = object.__getattribute__(self, r'_observer')
711 observer = object.__getattribute__(self, '_observer')
712 fn = getattr(observer, name, None)
712 fn = getattr(observer, name, None)
713 if fn:
713 if fn:
714 fn(res, *args, **kwargs)
714 fn(res, *args, **kwargs)
@@ -716,13 +716,13 b' class socketproxy(object):'
716 return res
716 return res
717
717
718 def makefile(self, *args, **kwargs):
718 def makefile(self, *args, **kwargs):
719 res = object.__getattribute__(self, r'_observedcall')(
719 res = object.__getattribute__(self, '_observedcall')(
720 r'makefile', *args, **kwargs
720 'makefile', *args, **kwargs
721 )
721 )
722
722
723 # The file object may be used for I/O. So we turn it into a
723 # The file object may be used for I/O. So we turn it into a
724 # proxy using our observer.
724 # proxy using our observer.
725 observer = object.__getattribute__(self, r'_observer')
725 observer = object.__getattribute__(self, '_observer')
726 return makeloggingfileobject(
726 return makeloggingfileobject(
727 observer.fh,
727 observer.fh,
728 res,
728 res,
@@ -734,58 +734,58 b' class socketproxy(object):'
734 )
734 )
735
735
736 def recv(self, *args, **kwargs):
736 def recv(self, *args, **kwargs):
737 return object.__getattribute__(self, r'_observedcall')(
737 return object.__getattribute__(self, '_observedcall')(
738 r'recv', *args, **kwargs
738 'recv', *args, **kwargs
739 )
739 )
740
740
741 def recvfrom(self, *args, **kwargs):
741 def recvfrom(self, *args, **kwargs):
742 return object.__getattribute__(self, r'_observedcall')(
742 return object.__getattribute__(self, '_observedcall')(
743 r'recvfrom', *args, **kwargs
743 'recvfrom', *args, **kwargs
744 )
744 )
745
745
746 def recvfrom_into(self, *args, **kwargs):
746 def recvfrom_into(self, *args, **kwargs):
747 return object.__getattribute__(self, r'_observedcall')(
747 return object.__getattribute__(self, '_observedcall')(
748 r'recvfrom_into', *args, **kwargs
748 'recvfrom_into', *args, **kwargs
749 )
749 )
750
750
751 def recv_into(self, *args, **kwargs):
751 def recv_into(self, *args, **kwargs):
752 return object.__getattribute__(self, r'_observedcall')(
752 return object.__getattribute__(self, '_observedcall')(
753 r'recv_info', *args, **kwargs
753 'recv_info', *args, **kwargs
754 )
754 )
755
755
756 def send(self, *args, **kwargs):
756 def send(self, *args, **kwargs):
757 return object.__getattribute__(self, r'_observedcall')(
757 return object.__getattribute__(self, '_observedcall')(
758 r'send', *args, **kwargs
758 'send', *args, **kwargs
759 )
759 )
760
760
761 def sendall(self, *args, **kwargs):
761 def sendall(self, *args, **kwargs):
762 return object.__getattribute__(self, r'_observedcall')(
762 return object.__getattribute__(self, '_observedcall')(
763 r'sendall', *args, **kwargs
763 'sendall', *args, **kwargs
764 )
764 )
765
765
766 def sendto(self, *args, **kwargs):
766 def sendto(self, *args, **kwargs):
767 return object.__getattribute__(self, r'_observedcall')(
767 return object.__getattribute__(self, '_observedcall')(
768 r'sendto', *args, **kwargs
768 'sendto', *args, **kwargs
769 )
769 )
770
770
771 def setblocking(self, *args, **kwargs):
771 def setblocking(self, *args, **kwargs):
772 return object.__getattribute__(self, r'_observedcall')(
772 return object.__getattribute__(self, '_observedcall')(
773 r'setblocking', *args, **kwargs
773 'setblocking', *args, **kwargs
774 )
774 )
775
775
776 def settimeout(self, *args, **kwargs):
776 def settimeout(self, *args, **kwargs):
777 return object.__getattribute__(self, r'_observedcall')(
777 return object.__getattribute__(self, '_observedcall')(
778 r'settimeout', *args, **kwargs
778 'settimeout', *args, **kwargs
779 )
779 )
780
780
781 def gettimeout(self, *args, **kwargs):
781 def gettimeout(self, *args, **kwargs):
782 return object.__getattribute__(self, r'_observedcall')(
782 return object.__getattribute__(self, '_observedcall')(
783 r'gettimeout', *args, **kwargs
783 'gettimeout', *args, **kwargs
784 )
784 )
785
785
786 def setsockopt(self, *args, **kwargs):
786 def setsockopt(self, *args, **kwargs):
787 return object.__getattribute__(self, r'_observedcall')(
787 return object.__getattribute__(self, '_observedcall')(
788 r'setsockopt', *args, **kwargs
788 'setsockopt', *args, **kwargs
789 )
789 )
790
790
791
791
@@ -1362,7 +1362,7 b' class _lrucachenode(object):'
1362 pair for the dictionary entry.
1362 pair for the dictionary entry.
1363 """
1363 """
1364
1364
1365 __slots__ = (r'next', r'prev', r'key', r'value', r'cost')
1365 __slots__ = ('next', 'prev', 'key', 'value', 'cost')
1366
1366
1367 def __init__(self):
1367 def __init__(self):
1368 self.next = None
1368 self.next = None
@@ -46,20 +46,20 b' SEMANTIC_TAG_FINITE_SET = 258'
46
46
47 # Indefinite types begin with their major type ORd with information value 31.
47 # Indefinite types begin with their major type ORd with information value 31.
48 BEGIN_INDEFINITE_BYTESTRING = struct.pack(
48 BEGIN_INDEFINITE_BYTESTRING = struct.pack(
49 r'>B', MAJOR_TYPE_BYTESTRING << 5 | SUBTYPE_INDEFINITE
49 '>B', MAJOR_TYPE_BYTESTRING << 5 | SUBTYPE_INDEFINITE
50 )
50 )
51 BEGIN_INDEFINITE_ARRAY = struct.pack(
51 BEGIN_INDEFINITE_ARRAY = struct.pack(
52 r'>B', MAJOR_TYPE_ARRAY << 5 | SUBTYPE_INDEFINITE
52 '>B', MAJOR_TYPE_ARRAY << 5 | SUBTYPE_INDEFINITE
53 )
53 )
54 BEGIN_INDEFINITE_MAP = struct.pack(
54 BEGIN_INDEFINITE_MAP = struct.pack(
55 r'>B', MAJOR_TYPE_MAP << 5 | SUBTYPE_INDEFINITE
55 '>B', MAJOR_TYPE_MAP << 5 | SUBTYPE_INDEFINITE
56 )
56 )
57
57
58 ENCODED_LENGTH_1 = struct.Struct(r'>B')
58 ENCODED_LENGTH_1 = struct.Struct('>B')
59 ENCODED_LENGTH_2 = struct.Struct(r'>BB')
59 ENCODED_LENGTH_2 = struct.Struct('>BB')
60 ENCODED_LENGTH_3 = struct.Struct(r'>BH')
60 ENCODED_LENGTH_3 = struct.Struct('>BH')
61 ENCODED_LENGTH_4 = struct.Struct(r'>BL')
61 ENCODED_LENGTH_4 = struct.Struct('>BL')
62 ENCODED_LENGTH_5 = struct.Struct(r'>BQ')
62 ENCODED_LENGTH_5 = struct.Struct('>BQ')
63
63
64 # The break ends an indefinite length item.
64 # The break ends an indefinite length item.
65 BREAK = b'\xff'
65 BREAK = b'\xff'
@@ -262,7 +262,7 b' else:'
262 return ord(b[i])
262 return ord(b[i])
263
263
264
264
265 STRUCT_BIG_UBYTE = struct.Struct(r'>B')
265 STRUCT_BIG_UBYTE = struct.Struct('>B')
266 STRUCT_BIG_USHORT = struct.Struct(b'>H')
266 STRUCT_BIG_USHORT = struct.Struct(b'>H')
267 STRUCT_BIG_ULONG = struct.Struct(b'>L')
267 STRUCT_BIG_ULONG = struct.Struct(b'>L')
268 STRUCT_BIG_ULONGLONG = struct.Struct(b'>Q')
268 STRUCT_BIG_ULONGLONG = struct.Struct(b'>Q')
@@ -29,8 +29,7 b" SERVERROLE = b'server'"
29 CLIENTROLE = b'client'
29 CLIENTROLE = b'client'
30
30
31 compewireprotosupport = collections.namedtuple(
31 compewireprotosupport = collections.namedtuple(
32 r'compenginewireprotosupport',
32 'compenginewireprotosupport', ('name', 'serverpriority', 'clientpriority'),
33 (r'name', r'serverpriority', r'clientpriority'),
34 )
33 )
35
34
36
35
@@ -223,7 +223,7 b' def parsedate(date, formats=None, bias=N'
223 if date == b'now' or date == _(b'now'):
223 if date == b'now' or date == _(b'now'):
224 return makedate()
224 return makedate()
225 if date == b'today' or date == _(b'today'):
225 if date == b'today' or date == _(b'today'):
226 date = datetime.date.today().strftime(r'%b %d')
226 date = datetime.date.today().strftime('%b %d')
227 date = encoding.strtolocal(date)
227 date = encoding.strtolocal(date)
228 elif date == b'yesterday' or date == _(b'yesterday'):
228 elif date == b'yesterday' or date == _(b'yesterday'):
229 date = (datetime.date.today() - datetime.timedelta(days=1)).strftime(
229 date = (datetime.date.today() - datetime.timedelta(days=1)).strftime(
@@ -32,7 +32,7 b' from .. import ('
32 pycompat,
32 pycompat,
33 )
33 )
34
34
35 osutil = policy.importmod(r'osutil')
35 osutil = policy.importmod('osutil')
36
36
37 stderr = pycompat.stderr
37 stderr = pycompat.stderr
38 stdin = pycompat.stdin
38 stdin = pycompat.stdin
@@ -52,11 +52,11 b' def isatty(fp):'
52 if isatty(stdout):
52 if isatty(stdout):
53 if pycompat.iswindows:
53 if pycompat.iswindows:
54 # Windows doesn't support line buffering
54 # Windows doesn't support line buffering
55 stdout = os.fdopen(stdout.fileno(), r'wb', 0)
55 stdout = os.fdopen(stdout.fileno(), 'wb', 0)
56 elif not pycompat.ispy3:
56 elif not pycompat.ispy3:
57 # on Python 3, stdout (sys.stdout.buffer) is already line buffered and
57 # on Python 3, stdout (sys.stdout.buffer) is already line buffered and
58 # buffering=1 is not handled in binary mode
58 # buffering=1 is not handled in binary mode
59 stdout = os.fdopen(stdout.fileno(), r'wb', 1)
59 stdout = os.fdopen(stdout.fileno(), 'wb', 1)
60
60
61 if pycompat.iswindows:
61 if pycompat.iswindows:
62 from .. import windows as platform
62 from .. import windows as platform
@@ -211,7 +211,7 b' def tempfilter(s, cmd):'
211 inname, outname = None, None
211 inname, outname = None, None
212 try:
212 try:
213 infd, inname = pycompat.mkstemp(prefix=b'hg-filter-in-')
213 infd, inname = pycompat.mkstemp(prefix=b'hg-filter-in-')
214 fp = os.fdopen(infd, r'wb')
214 fp = os.fdopen(infd, 'wb')
215 fp.write(s)
215 fp.write(s)
216 fp.close()
216 fp.close()
217 outfd, outname = pycompat.mkstemp(prefix=b'hg-filter-out-')
217 outfd, outname = pycompat.mkstemp(prefix=b'hg-filter-out-')
@@ -277,7 +277,7 b' def hgexecutable():'
277 """
277 """
278 if _hgexecutable is None:
278 if _hgexecutable is None:
279 hg = encoding.environ.get(b'HG')
279 hg = encoding.environ.get(b'HG')
280 mainmod = sys.modules[r'__main__']
280 mainmod = sys.modules['__main__']
281 if hg:
281 if hg:
282 _sethgexecutable(hg)
282 _sethgexecutable(hg)
283 elif mainfrozen():
283 elif mainfrozen():
@@ -340,11 +340,11 b' def protectstdio(uin, uout):'
340 nullfd = os.open(os.devnull, os.O_RDONLY)
340 nullfd = os.open(os.devnull, os.O_RDONLY)
341 os.dup2(nullfd, uin.fileno())
341 os.dup2(nullfd, uin.fileno())
342 os.close(nullfd)
342 os.close(nullfd)
343 fin = os.fdopen(newfd, r'rb')
343 fin = os.fdopen(newfd, 'rb')
344 if _testfileno(uout, stdout):
344 if _testfileno(uout, stdout):
345 newfd = os.dup(uout.fileno())
345 newfd = os.dup(uout.fileno())
346 os.dup2(stderr.fileno(), uout.fileno())
346 os.dup2(stderr.fileno(), uout.fileno())
347 fout = os.fdopen(newfd, r'wb')
347 fout = os.fdopen(newfd, 'wb')
348 return fin, fout
348 return fin, fout
349
349
350
350
@@ -719,7 +719,7 b' def _MBTextWrapper(**kwargs):'
719
719
720 # First chunk on line is whitespace -- drop it, unless this
720 # First chunk on line is whitespace -- drop it, unless this
721 # is the very beginning of the text (i.e. no lines started yet).
721 # is the very beginning of the text (i.e. no lines started yet).
722 if self.drop_whitespace and chunks[-1].strip() == r'' and lines:
722 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
723 del chunks[-1]
723 del chunks[-1]
724
724
725 while chunks:
725 while chunks:
@@ -750,7 +750,7 b' def _MBTextWrapper(**kwargs):'
750 # Convert current line back to a string and store it in list
750 # Convert current line back to a string and store it in list
751 # of all lines (return value).
751 # of all lines (return value).
752 if cur_line:
752 if cur_line:
753 lines.append(indent + r''.join(cur_line))
753 lines.append(indent + ''.join(cur_line))
754
754
755 return lines
755 return lines
756
756
@@ -592,7 +592,7 b' class closewrapbase(object):'
592 """
592 """
593
593
594 def __init__(self, fh):
594 def __init__(self, fh):
595 object.__setattr__(self, r'_origfh', fh)
595 object.__setattr__(self, '_origfh', fh)
596
596
597 def __getattr__(self, attr):
597 def __getattr__(self, attr):
598 return getattr(self._origfh, attr)
598 return getattr(self._origfh, attr)
@@ -622,7 +622,7 b' class delayclosedfile(closewrapbase):'
622
622
623 def __init__(self, fh, closer):
623 def __init__(self, fh, closer):
624 super(delayclosedfile, self).__init__(fh)
624 super(delayclosedfile, self).__init__(fh)
625 object.__setattr__(self, r'_closer', closer)
625 object.__setattr__(self, '_closer', closer)
626
626
627 def __exit__(self, exc_type, exc_value, exc_tb):
627 def __exit__(self, exc_type, exc_value, exc_tb):
628 self._closer.close(self._origfh)
628 self._closer.close(self._origfh)
@@ -736,7 +736,7 b' class checkambigatclosing(closewrapbase)'
736
736
737 def __init__(self, fh):
737 def __init__(self, fh):
738 super(checkambigatclosing, self).__init__(fh)
738 super(checkambigatclosing, self).__init__(fh)
739 object.__setattr__(self, r'_oldstat', util.filestat.frompath(fh.name))
739 object.__setattr__(self, '_oldstat', util.filestat.frompath(fh.name))
740
740
741 def _checkambig(self):
741 def _checkambig(self):
742 oldstat = self._oldstat
742 oldstat = self._oldstat
@@ -57,21 +57,21 b' elif ctypes.sizeof(ctypes.c_longlong) =='
57
57
58
58
59 class _FILETIME(ctypes.Structure):
59 class _FILETIME(ctypes.Structure):
60 _fields_ = [(r'dwLowDateTime', _DWORD), (r'dwHighDateTime', _DWORD)]
60 _fields_ = [('dwLowDateTime', _DWORD), ('dwHighDateTime', _DWORD)]
61
61
62
62
63 class _BY_HANDLE_FILE_INFORMATION(ctypes.Structure):
63 class _BY_HANDLE_FILE_INFORMATION(ctypes.Structure):
64 _fields_ = [
64 _fields_ = [
65 (r'dwFileAttributes', _DWORD),
65 ('dwFileAttributes', _DWORD),
66 (r'ftCreationTime', _FILETIME),
66 ('ftCreationTime', _FILETIME),
67 (r'ftLastAccessTime', _FILETIME),
67 ('ftLastAccessTime', _FILETIME),
68 (r'ftLastWriteTime', _FILETIME),
68 ('ftLastWriteTime', _FILETIME),
69 (r'dwVolumeSerialNumber', _DWORD),
69 ('dwVolumeSerialNumber', _DWORD),
70 (r'nFileSizeHigh', _DWORD),
70 ('nFileSizeHigh', _DWORD),
71 (r'nFileSizeLow', _DWORD),
71 ('nFileSizeLow', _DWORD),
72 (r'nNumberOfLinks', _DWORD),
72 ('nNumberOfLinks', _DWORD),
73 (r'nFileIndexHigh', _DWORD),
73 ('nFileIndexHigh', _DWORD),
74 (r'nFileIndexLow', _DWORD),
74 ('nFileIndexLow', _DWORD),
75 ]
75 ]
76
76
77
77
@@ -97,33 +97,33 b' class _BY_HANDLE_FILE_INFORMATION(ctypes'
97
97
98 class _STARTUPINFO(ctypes.Structure):
98 class _STARTUPINFO(ctypes.Structure):
99 _fields_ = [
99 _fields_ = [
100 (r'cb', _DWORD),
100 ('cb', _DWORD),
101 (r'lpReserved', _LPSTR),
101 ('lpReserved', _LPSTR),
102 (r'lpDesktop', _LPSTR),
102 ('lpDesktop', _LPSTR),
103 (r'lpTitle', _LPSTR),
103 ('lpTitle', _LPSTR),
104 (r'dwX', _DWORD),
104 ('dwX', _DWORD),
105 (r'dwY', _DWORD),
105 ('dwY', _DWORD),
106 (r'dwXSize', _DWORD),
106 ('dwXSize', _DWORD),
107 (r'dwYSize', _DWORD),
107 ('dwYSize', _DWORD),
108 (r'dwXCountChars', _DWORD),
108 ('dwXCountChars', _DWORD),
109 (r'dwYCountChars', _DWORD),
109 ('dwYCountChars', _DWORD),
110 (r'dwFillAttribute', _DWORD),
110 ('dwFillAttribute', _DWORD),
111 (r'dwFlags', _DWORD),
111 ('dwFlags', _DWORD),
112 (r'wShowWindow', _WORD),
112 ('wShowWindow', _WORD),
113 (r'cbReserved2', _WORD),
113 ('cbReserved2', _WORD),
114 (r'lpReserved2', ctypes.c_char_p),
114 ('lpReserved2', ctypes.c_char_p),
115 (r'hStdInput', _HANDLE),
115 ('hStdInput', _HANDLE),
116 (r'hStdOutput', _HANDLE),
116 ('hStdOutput', _HANDLE),
117 (r'hStdError', _HANDLE),
117 ('hStdError', _HANDLE),
118 ]
118 ]
119
119
120
120
121 class _PROCESS_INFORMATION(ctypes.Structure):
121 class _PROCESS_INFORMATION(ctypes.Structure):
122 _fields_ = [
122 _fields_ = [
123 (r'hProcess', _HANDLE),
123 ('hProcess', _HANDLE),
124 (r'hThread', _HANDLE),
124 ('hThread', _HANDLE),
125 (r'dwProcessId', _DWORD),
125 ('dwProcessId', _DWORD),
126 (r'dwThreadId', _DWORD),
126 ('dwThreadId', _DWORD),
127 ]
127 ]
128
128
129
129
@@ -132,25 +132,25 b' class _PROCESS_INFORMATION(ctypes.Struct'
132
132
133
133
134 class _COORD(ctypes.Structure):
134 class _COORD(ctypes.Structure):
135 _fields_ = [(r'X', ctypes.c_short), (r'Y', ctypes.c_short)]
135 _fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)]
136
136
137
137
138 class _SMALL_RECT(ctypes.Structure):
138 class _SMALL_RECT(ctypes.Structure):
139 _fields_ = [
139 _fields_ = [
140 (r'Left', ctypes.c_short),
140 ('Left', ctypes.c_short),
141 (r'Top', ctypes.c_short),
141 ('Top', ctypes.c_short),
142 (r'Right', ctypes.c_short),
142 ('Right', ctypes.c_short),
143 (r'Bottom', ctypes.c_short),
143 ('Bottom', ctypes.c_short),
144 ]
144 ]
145
145
146
146
147 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
147 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
148 _fields_ = [
148 _fields_ = [
149 (r'dwSize', _COORD),
149 ('dwSize', _COORD),
150 (r'dwCursorPosition', _COORD),
150 ('dwCursorPosition', _COORD),
151 (r'wAttributes', _WORD),
151 ('wAttributes', _WORD),
152 (r'srWindow', _SMALL_RECT),
152 ('srWindow', _SMALL_RECT),
153 (r'dwMaximumWindowSize', _COORD),
153 ('dwMaximumWindowSize', _COORD),
154 ]
154 ]
155
155
156
156
@@ -359,7 +359,7 b' def _raiseoserror(name):'
359 code -= 2 ** 32
359 code -= 2 ** 32
360 err = ctypes.WinError(code=code)
360 err = ctypes.WinError(code=code)
361 raise OSError(
361 raise OSError(
362 err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror)
362 err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror)
363 )
363 )
364
364
365
365
@@ -32,7 +32,7 b' try:'
32 except ImportError:
32 except ImportError:
33 import winreg
33 import winreg
34
34
35 osutil = policy.importmod(r'osutil')
35 osutil = policy.importmod('osutil')
36
36
37 getfsmountpoint = win32.getvolumename
37 getfsmountpoint = win32.getvolumename
38 getfstype = win32.getfstype
38 getfstype = win32.getfstype
@@ -70,8 +70,8 b' class mixedfilemodewrapper(object):'
70 OPWRITE = 2
70 OPWRITE = 2
71
71
72 def __init__(self, fp):
72 def __init__(self, fp):
73 object.__setattr__(self, r'_fp', fp)
73 object.__setattr__(self, '_fp', fp)
74 object.__setattr__(self, r'_lastop', 0)
74 object.__setattr__(self, '_lastop', 0)
75
75
76 def __enter__(self):
76 def __enter__(self):
77 self._fp.__enter__()
77 self._fp.__enter__()
@@ -90,42 +90,42 b' class mixedfilemodewrapper(object):'
90 self._fp.seek(0, os.SEEK_CUR)
90 self._fp.seek(0, os.SEEK_CUR)
91
91
92 def seek(self, *args, **kwargs):
92 def seek(self, *args, **kwargs):
93 object.__setattr__(self, r'_lastop', self.OPNONE)
93 object.__setattr__(self, '_lastop', self.OPNONE)
94 return self._fp.seek(*args, **kwargs)
94 return self._fp.seek(*args, **kwargs)
95
95
96 def write(self, d):
96 def write(self, d):
97 if self._lastop == self.OPREAD:
97 if self._lastop == self.OPREAD:
98 self._noopseek()
98 self._noopseek()
99
99
100 object.__setattr__(self, r'_lastop', self.OPWRITE)
100 object.__setattr__(self, '_lastop', self.OPWRITE)
101 return self._fp.write(d)
101 return self._fp.write(d)
102
102
103 def writelines(self, *args, **kwargs):
103 def writelines(self, *args, **kwargs):
104 if self._lastop == self.OPREAD:
104 if self._lastop == self.OPREAD:
105 self._noopeseek()
105 self._noopeseek()
106
106
107 object.__setattr__(self, r'_lastop', self.OPWRITE)
107 object.__setattr__(self, '_lastop', self.OPWRITE)
108 return self._fp.writelines(*args, **kwargs)
108 return self._fp.writelines(*args, **kwargs)
109
109
110 def read(self, *args, **kwargs):
110 def read(self, *args, **kwargs):
111 if self._lastop == self.OPWRITE:
111 if self._lastop == self.OPWRITE:
112 self._noopseek()
112 self._noopseek()
113
113
114 object.__setattr__(self, r'_lastop', self.OPREAD)
114 object.__setattr__(self, '_lastop', self.OPREAD)
115 return self._fp.read(*args, **kwargs)
115 return self._fp.read(*args, **kwargs)
116
116
117 def readline(self, *args, **kwargs):
117 def readline(self, *args, **kwargs):
118 if self._lastop == self.OPWRITE:
118 if self._lastop == self.OPWRITE:
119 self._noopseek()
119 self._noopseek()
120
120
121 object.__setattr__(self, r'_lastop', self.OPREAD)
121 object.__setattr__(self, '_lastop', self.OPREAD)
122 return self._fp.readline(*args, **kwargs)
122 return self._fp.readline(*args, **kwargs)
123
123
124 def readlines(self, *args, **kwargs):
124 def readlines(self, *args, **kwargs):
125 if self._lastop == self.OPWRITE:
125 if self._lastop == self.OPWRITE:
126 self._noopseek()
126 self._noopseek()
127
127
128 object.__setattr__(self, r'_lastop', self.OPREAD)
128 object.__setattr__(self, '_lastop', self.OPREAD)
129 return self._fp.readlines(*args, **kwargs)
129 return self._fp.readlines(*args, **kwargs)
130
130
131
131
@@ -176,7 +176,7 b" def posixfile(name, mode=b'r', buffering"
176 except WindowsError as err:
176 except WindowsError as err:
177 # convert to a friendlier exception
177 # convert to a friendlier exception
178 raise IOError(
178 raise IOError(
179 err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror)
179 err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror)
180 )
180 )
181
181
182
182
@@ -215,7 +215,7 b' class winstdout(object):'
215 if inst.errno != 0 and not win32.lasterrorwaspipeerror(inst):
215 if inst.errno != 0 and not win32.lasterrorwaspipeerror(inst):
216 raise
216 raise
217 self.close()
217 self.close()
218 raise IOError(errno.EPIPE, r'Broken pipe')
218 raise IOError(errno.EPIPE, 'Broken pipe')
219
219
220 def flush(self):
220 def flush(self):
221 try:
221 try:
@@ -223,7 +223,7 b' class winstdout(object):'
223 except IOError as inst:
223 except IOError as inst:
224 if not win32.lasterrorwaspipeerror(inst):
224 if not win32.lasterrorwaspipeerror(inst):
225 raise
225 raise
226 raise IOError(errno.EPIPE, r'Broken pipe')
226 raise IOError(errno.EPIPE, 'Broken pipe')
227
227
228
228
229 def _is_win_9x():
229 def _is_win_9x():
@@ -686,4 +686,4 b' def readpipe(pipe):'
686
686
687
687
688 def bindunixsocket(sock, path):
688 def bindunixsocket(sock, path):
689 raise NotImplementedError(r'unsupported platform')
689 raise NotImplementedError('unsupported platform')
@@ -118,7 +118,7 b' FRAME_TYPE_FLAGS = {'
118 FRAME_TYPE_STREAM_SETTINGS: FLAGS_STREAM_ENCODING_SETTINGS,
118 FRAME_TYPE_STREAM_SETTINGS: FLAGS_STREAM_ENCODING_SETTINGS,
119 }
119 }
120
120
121 ARGUMENT_RECORD_HEADER = struct.Struct(r'<HH')
121 ARGUMENT_RECORD_HEADER = struct.Struct('<HH')
122
122
123
123
124 def humanflags(mapping, value):
124 def humanflags(mapping, value):
@@ -191,9 +191,9 b' def makeframe(requestid, streamid, strea'
191 # 4 bits type
191 # 4 bits type
192 # 4 bits flags
192 # 4 bits flags
193
193
194 l = struct.pack(r'<I', len(payload))
194 l = struct.pack('<I', len(payload))
195 frame[0:3] = l[0:3]
195 frame[0:3] = l[0:3]
196 struct.pack_into(r'<HBB', frame, 3, requestid, streamid, streamflags)
196 struct.pack_into('<HBB', frame, 3, requestid, streamid, streamflags)
197 frame[7] = (typeid << 4) | flags
197 frame[7] = (typeid << 4) | flags
198 frame[8:] = payload
198 frame[8:] = payload
199
199
@@ -280,7 +280,7 b' def parseheader(data):'
280 # 4 bits frame flags
280 # 4 bits frame flags
281 # ... payload
281 # ... payload
282 framelength = data[0] + 256 * data[1] + 16384 * data[2]
282 framelength = data[0] + 256 * data[1] + 16384 * data[2]
283 requestid, streamid, streamflags = struct.unpack_from(r'<HBB', data, 3)
283 requestid, streamid, streamflags = struct.unpack_from('<HBB', data, 3)
284 typeflags = data[7]
284 typeflags = data[7]
285
285
286 frametype = (typeflags & 0xF0) >> 4
286 frametype = (typeflags & 0xF0) >> 4
@@ -460,11 +460,11 b' def createalternatelocationresponseframe'
460 }
460 }
461
461
462 for a in (
462 for a in (
463 r'size',
463 'size',
464 r'fullhashes',
464 'fullhashes',
465 r'fullhashseed',
465 'fullhashseed',
466 r'serverdercerts',
466 'serverdercerts',
467 r'servercadercerts',
467 'servercadercerts',
468 ):
468 ):
469 value = getattr(location, a)
469 value = getattr(location, a)
470 if value is not None:
470 if value is not None:
@@ -548,15 +548,13 b' def createtextoutputframe('
548 raise ValueError(b'must use bytes for labels')
548 raise ValueError(b'must use bytes for labels')
549
549
550 # Formatting string must be ASCII.
550 # Formatting string must be ASCII.
551 formatting = formatting.decode(r'ascii', r'replace').encode(r'ascii')
551 formatting = formatting.decode('ascii', 'replace').encode('ascii')
552
552
553 # Arguments must be UTF-8.
553 # Arguments must be UTF-8.
554 args = [a.decode(r'utf-8', r'replace').encode(r'utf-8') for a in args]
554 args = [a.decode('utf-8', 'replace').encode('utf-8') for a in args]
555
555
556 # Labels must be ASCII.
556 # Labels must be ASCII.
557 labels = [
557 labels = [l.decode('ascii', 'strict').encode('ascii') for l in labels]
558 l.decode(r'ascii', r'strict').encode(r'ascii') for l in labels
559 ]
560
558
561 atom = {b'msg': formatting}
559 atom = {b'msg': formatting}
562 if args:
560 if args:
@@ -599,9 +599,9 b' class wirepeer(repository.peer):'
599 # don't pass optional arguments left at their default value
599 # don't pass optional arguments left at their default value
600 opts = {}
600 opts = {}
601 if three is not None:
601 if three is not None:
602 opts[r'three'] = three
602 opts['three'] = three
603 if four is not None:
603 if four is not None:
604 opts[r'four'] = four
604 opts['four'] = four
605 return self._call(b'debugwireargs', one=one, two=two, **opts)
605 return self._call(b'debugwireargs', one=one, two=two, **opts)
606
606
607 def _call(self, cmd, **args):
607 def _call(self, cmd, **args):
@@ -472,7 +472,7 b' class clienthandler(object):'
472 )
472 )
473
473
474 headers = {
474 headers = {
475 r'Accept': redirect.mediatype,
475 'Accept': redirect.mediatype,
476 }
476 }
477
477
478 req = self._requestbuilder(pycompat.strurl(redirect.url), None, headers)
478 req = self._requestbuilder(pycompat.strurl(redirect.url), None, headers)
@@ -36,7 +36,7 b' def countcpus():'
36
36
37 # posix
37 # posix
38 try:
38 try:
39 n = int(os.sysconf(r'SC_NPROCESSORS_ONLN'))
39 n = int(os.sysconf('SC_NPROCESSORS_ONLN'))
40 if n > 0:
40 if n > 0:
41 return n
41 return n
42 except (AttributeError, ValueError):
42 except (AttributeError, ValueError):
@@ -226,7 +226,7 b' def _posixworker(ui, func, staticargs, a'
226 selector = selectors.DefaultSelector()
226 selector = selectors.DefaultSelector()
227 for rfd, wfd in pipes:
227 for rfd, wfd in pipes:
228 os.close(wfd)
228 os.close(wfd)
229 selector.register(os.fdopen(rfd, r'rb', 0), selectors.EVENT_READ)
229 selector.register(os.fdopen(rfd, 'rb', 0), selectors.EVENT_READ)
230
230
231 def cleanup():
231 def cleanup():
232 signal.signal(signal.SIGINT, oldhandler)
232 signal.signal(signal.SIGINT, oldhandler)
@@ -30,8 +30,8 b' configitem('
30 b'fakedirstatewritetime', b'fakenow', default=None,
30 b'fakedirstatewritetime', b'fakenow', default=None,
31 )
31 )
32
32
33 parsers = policy.importmod(r'parsers')
33 parsers = policy.importmod('parsers')
34 rustmod = policy.importrust(r'parsers')
34 rustmod = policy.importrust('parsers')
35
35
36
36
37 def pack_dirstate(fakenow, orig, dmap, copymap, pl, now):
37 def pack_dirstate(fakenow, orig, dmap, copymap, pl, now):
@@ -18,12 +18,12 b' from mercurial.interfaces import reposit'
18
18
19
19
20 def clonecommand(orig, ui, repo, *args, **kwargs):
20 def clonecommand(orig, ui, repo, *args, **kwargs):
21 if kwargs.get(r'include') or kwargs.get(r'exclude'):
21 if kwargs.get('include') or kwargs.get('exclude'):
22 kwargs[r'narrow'] = True
22 kwargs['narrow'] = True
23
23
24 if kwargs.get(r'depth'):
24 if kwargs.get('depth'):
25 try:
25 try:
26 kwargs[r'depth'] = int(kwargs[r'depth'])
26 kwargs['depth'] = int(kwargs['depth'])
27 except ValueError:
27 except ValueError:
28 raise error.Abort(_('--depth must be an integer'))
28 raise error.Abort(_('--depth must be an integer'))
29
29
@@ -20,7 +20,7 b' from mercurial import ('
20 pycompat,
20 pycompat,
21 )
21 )
22
22
23 parsers = policy.importmod(r'parsers')
23 parsers = policy.importmod('parsers')
24
24
25 # original python implementation
25 # original python implementation
26 def gettype(q):
26 def gettype(q):
@@ -6,17 +6,17 b' from mercurial.hgweb import request as r'
6 from mercurial import error
6 from mercurial import error
7
7
8 DEFAULT_ENV = {
8 DEFAULT_ENV = {
9 r'REQUEST_METHOD': r'GET',
9 'REQUEST_METHOD': 'GET',
10 r'SERVER_NAME': r'testserver',
10 'SERVER_NAME': 'testserver',
11 r'SERVER_PORT': r'80',
11 'SERVER_PORT': '80',
12 r'SERVER_PROTOCOL': r'http',
12 'SERVER_PROTOCOL': 'http',
13 r'wsgi.version': (1, 0),
13 'wsgi.version': (1, 0),
14 r'wsgi.url_scheme': r'http',
14 'wsgi.url_scheme': 'http',
15 r'wsgi.input': None,
15 'wsgi.input': None,
16 r'wsgi.errors': None,
16 'wsgi.errors': None,
17 r'wsgi.multithread': False,
17 'wsgi.multithread': False,
18 r'wsgi.multiprocess': True,
18 'wsgi.multiprocess': True,
19 r'wsgi.run_once': False,
19 'wsgi.run_once': False,
20 }
20 }
21
21
22
22
@@ -49,7 +49,7 b' class ParseRequestTests(unittest.TestCas'
49 self.assertEqual(len(r.headers), 0)
49 self.assertEqual(len(r.headers), 0)
50
50
51 def testcustomport(self):
51 def testcustomport(self):
52 r = parse(DEFAULT_ENV, extra={r'SERVER_PORT': r'8000',})
52 r = parse(DEFAULT_ENV, extra={'SERVER_PORT': '8000',})
53
53
54 self.assertEqual(r.url, b'http://testserver:8000')
54 self.assertEqual(r.url, b'http://testserver:8000')
55 self.assertEqual(r.baseurl, b'http://testserver:8000')
55 self.assertEqual(r.baseurl, b'http://testserver:8000')
@@ -58,7 +58,7 b' class ParseRequestTests(unittest.TestCas'
58
58
59 r = parse(
59 r = parse(
60 DEFAULT_ENV,
60 DEFAULT_ENV,
61 extra={r'SERVER_PORT': r'4000', r'wsgi.url_scheme': r'https',},
61 extra={'SERVER_PORT': '4000', 'wsgi.url_scheme': 'https',},
62 )
62 )
63
63
64 self.assertEqual(r.url, b'https://testserver:4000')
64 self.assertEqual(r.url, b'https://testserver:4000')
@@ -67,7 +67,7 b' class ParseRequestTests(unittest.TestCas'
67 self.assertEqual(r.advertisedbaseurl, b'https://testserver:4000')
67 self.assertEqual(r.advertisedbaseurl, b'https://testserver:4000')
68
68
69 def testhttphost(self):
69 def testhttphost(self):
70 r = parse(DEFAULT_ENV, extra={r'HTTP_HOST': r'altserver',})
70 r = parse(DEFAULT_ENV, extra={'HTTP_HOST': 'altserver',})
71
71
72 self.assertEqual(r.url, b'http://altserver')
72 self.assertEqual(r.url, b'http://altserver')
73 self.assertEqual(r.baseurl, b'http://altserver')
73 self.assertEqual(r.baseurl, b'http://altserver')
@@ -75,7 +75,7 b' class ParseRequestTests(unittest.TestCas'
75 self.assertEqual(r.advertisedbaseurl, b'http://testserver')
75 self.assertEqual(r.advertisedbaseurl, b'http://testserver')
76
76
77 def testscriptname(self):
77 def testscriptname(self):
78 r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'',})
78 r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '',})
79
79
80 self.assertEqual(r.url, b'http://testserver')
80 self.assertEqual(r.url, b'http://testserver')
81 self.assertEqual(r.baseurl, b'http://testserver')
81 self.assertEqual(r.baseurl, b'http://testserver')
@@ -85,7 +85,7 b' class ParseRequestTests(unittest.TestCas'
85 self.assertEqual(r.dispatchparts, [])
85 self.assertEqual(r.dispatchparts, [])
86 self.assertIsNone(r.dispatchpath)
86 self.assertIsNone(r.dispatchpath)
87
87
88 r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'/script',})
88 r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '/script',})
89
89
90 self.assertEqual(r.url, b'http://testserver/script')
90 self.assertEqual(r.url, b'http://testserver/script')
91 self.assertEqual(r.baseurl, b'http://testserver')
91 self.assertEqual(r.baseurl, b'http://testserver')
@@ -95,7 +95,7 b' class ParseRequestTests(unittest.TestCas'
95 self.assertEqual(r.dispatchparts, [])
95 self.assertEqual(r.dispatchparts, [])
96 self.assertIsNone(r.dispatchpath)
96 self.assertIsNone(r.dispatchpath)
97
97
98 r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'/multiple words',})
98 r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '/multiple words',})
99
99
100 self.assertEqual(r.url, b'http://testserver/multiple%20words')
100 self.assertEqual(r.url, b'http://testserver/multiple%20words')
101 self.assertEqual(r.baseurl, b'http://testserver')
101 self.assertEqual(r.baseurl, b'http://testserver')
@@ -106,7 +106,7 b' class ParseRequestTests(unittest.TestCas'
106 self.assertIsNone(r.dispatchpath)
106 self.assertIsNone(r.dispatchpath)
107
107
108 def testpathinfo(self):
108 def testpathinfo(self):
109 r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'',})
109 r = parse(DEFAULT_ENV, extra={'PATH_INFO': '',})
110
110
111 self.assertEqual(r.url, b'http://testserver')
111 self.assertEqual(r.url, b'http://testserver')
112 self.assertEqual(r.baseurl, b'http://testserver')
112 self.assertEqual(r.baseurl, b'http://testserver')
@@ -116,7 +116,7 b' class ParseRequestTests(unittest.TestCas'
116 self.assertEqual(r.dispatchparts, [])
116 self.assertEqual(r.dispatchparts, [])
117 self.assertEqual(r.dispatchpath, b'')
117 self.assertEqual(r.dispatchpath, b'')
118
118
119 r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'/pathinfo',})
119 r = parse(DEFAULT_ENV, extra={'PATH_INFO': '/pathinfo',})
120
120
121 self.assertEqual(r.url, b'http://testserver/pathinfo')
121 self.assertEqual(r.url, b'http://testserver/pathinfo')
122 self.assertEqual(r.baseurl, b'http://testserver')
122 self.assertEqual(r.baseurl, b'http://testserver')
@@ -126,7 +126,7 b' class ParseRequestTests(unittest.TestCas'
126 self.assertEqual(r.dispatchparts, [b'pathinfo'])
126 self.assertEqual(r.dispatchparts, [b'pathinfo'])
127 self.assertEqual(r.dispatchpath, b'pathinfo')
127 self.assertEqual(r.dispatchpath, b'pathinfo')
128
128
129 r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'/one/two/',})
129 r = parse(DEFAULT_ENV, extra={'PATH_INFO': '/one/two/',})
130
130
131 self.assertEqual(r.url, b'http://testserver/one/two/')
131 self.assertEqual(r.url, b'http://testserver/one/two/')
132 self.assertEqual(r.baseurl, b'http://testserver')
132 self.assertEqual(r.baseurl, b'http://testserver')
@@ -139,7 +139,7 b' class ParseRequestTests(unittest.TestCas'
139 def testscriptandpathinfo(self):
139 def testscriptandpathinfo(self):
140 r = parse(
140 r = parse(
141 DEFAULT_ENV,
141 DEFAULT_ENV,
142 extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/pathinfo',},
142 extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/pathinfo',},
143 )
143 )
144
144
145 self.assertEqual(r.url, b'http://testserver/script/pathinfo')
145 self.assertEqual(r.url, b'http://testserver/script/pathinfo')
@@ -153,8 +153,8 b' class ParseRequestTests(unittest.TestCas'
153 r = parse(
153 r = parse(
154 DEFAULT_ENV,
154 DEFAULT_ENV,
155 extra={
155 extra={
156 r'SCRIPT_NAME': r'/script1/script2',
156 'SCRIPT_NAME': '/script1/script2',
157 r'PATH_INFO': r'/path1/path2',
157 'PATH_INFO': '/path1/path2',
158 },
158 },
159 )
159 )
160
160
@@ -173,9 +173,9 b' class ParseRequestTests(unittest.TestCas'
173 r = parse(
173 r = parse(
174 DEFAULT_ENV,
174 DEFAULT_ENV,
175 extra={
175 extra={
176 r'HTTP_HOST': r'hostserver',
176 'HTTP_HOST': 'hostserver',
177 r'SCRIPT_NAME': r'/script',
177 'SCRIPT_NAME': '/script',
178 r'PATH_INFO': r'/pathinfo',
178 'PATH_INFO': '/pathinfo',
179 },
179 },
180 )
180 )
181
181
@@ -208,7 +208,7 b' class ParseRequestTests(unittest.TestCas'
208 parse(
208 parse(
209 DEFAULT_ENV,
209 DEFAULT_ENV,
210 reponame=b'repo',
210 reponame=b'repo',
211 extra={r'PATH_INFO': r'/pathinfo',},
211 extra={'PATH_INFO': '/pathinfo',},
212 )
212 )
213
213
214 with self.assertRaisesRegex(
214 with self.assertRaisesRegex(
@@ -217,13 +217,13 b' class ParseRequestTests(unittest.TestCas'
217 parse(
217 parse(
218 DEFAULT_ENV,
218 DEFAULT_ENV,
219 reponame=b'repo',
219 reponame=b'repo',
220 extra={r'PATH_INFO': r'/repoextra/path',},
220 extra={'PATH_INFO': '/repoextra/path',},
221 )
221 )
222
222
223 r = parse(
223 r = parse(
224 DEFAULT_ENV,
224 DEFAULT_ENV,
225 reponame=b'repo',
225 reponame=b'repo',
226 extra={r'PATH_INFO': r'/repo/path1/path2',},
226 extra={'PATH_INFO': '/repo/path1/path2',},
227 )
227 )
228
228
229 self.assertEqual(r.url, b'http://testserver/repo/path1/path2')
229 self.assertEqual(r.url, b'http://testserver/repo/path1/path2')
@@ -238,7 +238,7 b' class ParseRequestTests(unittest.TestCas'
238 r = parse(
238 r = parse(
239 DEFAULT_ENV,
239 DEFAULT_ENV,
240 reponame=b'prefix/repo',
240 reponame=b'prefix/repo',
241 extra={r'PATH_INFO': r'/prefix/repo/path1/path2',},
241 extra={'PATH_INFO': '/prefix/repo/path1/path2',},
242 )
242 )
243
243
244 self.assertEqual(r.url, b'http://testserver/prefix/repo/path1/path2')
244 self.assertEqual(r.url, b'http://testserver/prefix/repo/path1/path2')
@@ -307,7 +307,7 b' class ParseRequestTests(unittest.TestCas'
307 r = parse(
307 r = parse(
308 DEFAULT_ENV,
308 DEFAULT_ENV,
309 altbaseurl=b'http://altserver',
309 altbaseurl=b'http://altserver',
310 extra={r'PATH_INFO': r'/path1/path2',},
310 extra={'PATH_INFO': '/path1/path2',},
311 )
311 )
312 self.assertEqual(r.url, b'http://testserver/path1/path2')
312 self.assertEqual(r.url, b'http://testserver/path1/path2')
313 self.assertEqual(r.baseurl, b'http://testserver')
313 self.assertEqual(r.baseurl, b'http://testserver')
@@ -347,7 +347,7 b' class ParseRequestTests(unittest.TestCas'
347 r = parse(
347 r = parse(
348 DEFAULT_ENV,
348 DEFAULT_ENV,
349 altbaseurl=b'http://altserver/altpath',
349 altbaseurl=b'http://altserver/altpath',
350 extra={r'PATH_INFO': r'/path1/path2',},
350 extra={'PATH_INFO': '/path1/path2',},
351 )
351 )
352 self.assertEqual(r.url, b'http://testserver/path1/path2')
352 self.assertEqual(r.url, b'http://testserver/path1/path2')
353 self.assertEqual(r.baseurl, b'http://testserver')
353 self.assertEqual(r.baseurl, b'http://testserver')
@@ -365,7 +365,7 b' class ParseRequestTests(unittest.TestCas'
365 r = parse(
365 r = parse(
366 DEFAULT_ENV,
366 DEFAULT_ENV,
367 altbaseurl=b'http://altserver/altpath/',
367 altbaseurl=b'http://altserver/altpath/',
368 extra={r'PATH_INFO': r'/path1/path2',},
368 extra={'PATH_INFO': '/path1/path2',},
369 )
369 )
370 self.assertEqual(r.url, b'http://testserver/path1/path2')
370 self.assertEqual(r.url, b'http://testserver/path1/path2')
371 self.assertEqual(r.baseurl, b'http://testserver')
371 self.assertEqual(r.baseurl, b'http://testserver')
@@ -383,7 +383,7 b' class ParseRequestTests(unittest.TestCas'
383 r = parse(
383 r = parse(
384 DEFAULT_ENV,
384 DEFAULT_ENV,
385 altbaseurl=b'http://altserver',
385 altbaseurl=b'http://altserver',
386 extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/path1/path2',},
386 extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/path1/path2',},
387 )
387 )
388 self.assertEqual(r.url, b'http://testserver/script/path1/path2')
388 self.assertEqual(r.url, b'http://testserver/script/path1/path2')
389 self.assertEqual(r.baseurl, b'http://testserver')
389 self.assertEqual(r.baseurl, b'http://testserver')
@@ -399,7 +399,7 b' class ParseRequestTests(unittest.TestCas'
399 r = parse(
399 r = parse(
400 DEFAULT_ENV,
400 DEFAULT_ENV,
401 altbaseurl=b'http://altserver/altroot',
401 altbaseurl=b'http://altserver/altroot',
402 extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/path1/path2',},
402 extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/path1/path2',},
403 )
403 )
404 self.assertEqual(r.url, b'http://testserver/script/path1/path2')
404 self.assertEqual(r.url, b'http://testserver/script/path1/path2')
405 self.assertEqual(r.baseurl, b'http://testserver')
405 self.assertEqual(r.baseurl, b'http://testserver')
@@ -418,10 +418,7 b' class ParseRequestTests(unittest.TestCas'
418 DEFAULT_ENV,
418 DEFAULT_ENV,
419 reponame=b'repo',
419 reponame=b'repo',
420 altbaseurl=b'http://altserver/altroot',
420 altbaseurl=b'http://altserver/altroot',
421 extra={
421 extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/repo/path1/path2',},
422 r'SCRIPT_NAME': r'/script',
423 r'PATH_INFO': r'/repo/path1/path2',
424 },
425 )
422 )
426
423
427 self.assertEqual(r.url, b'http://testserver/script/repo/path1/path2')
424 self.assertEqual(r.url, b'http://testserver/script/repo/path1/path2')
General Comments 0
You need to be logged in to leave comments. Login now