diff --git a/contrib/hgclient.py b/contrib/hgclient.py --- a/contrib/hgclient.py +++ b/contrib/hgclient.py @@ -39,7 +39,7 @@ def connectpipe(path=None, extraargs=()) cmdline.extend(extraargs) def tonative(cmdline): - if os.name != r'nt': + if os.name != 'nt': return cmdline return [arg.decode("utf-8") for arg in cmdline] diff --git a/contrib/perf.py b/contrib/perf.py --- a/contrib/perf.py +++ b/contrib/perf.py @@ -726,8 +726,8 @@ def clearfilecache(obj, attrname): def clearchangelog(repo): if repo is not repo.unfiltered(): - object.__setattr__(repo, r'_clcachekey', None) - object.__setattr__(repo, r'_clcache', None) + object.__setattr__(repo, '_clcachekey', None) + object.__setattr__(repo, '_clcache', None) clearfilecache(repo.unfiltered(), 'changelog') @@ -1652,12 +1652,12 @@ def perfstartup(ui, repo, **opts): timer, fm = gettimer(ui, opts) def d(): - if os.name != r'nt': + if os.name != 'nt': os.system( b"HGRCPATH= %s version -q > /dev/null" % fsencode(sys.argv[0]) ) else: - os.environ[r'HGRCPATH'] = r' ' + os.environ['HGRCPATH'] = r' ' os.system("%s version -q > NUL" % sys.argv[0]) timer(d) @@ -1844,7 +1844,7 @@ def perftemplating(ui, repo, testedtempl opts = _byteskwargs(opts) nullui = ui.copy() - nullui.fout = open(os.devnull, r'wb') + nullui.fout = open(os.devnull, 'wb') nullui.disablepager() revs = opts.get(b'rev') if not revs: diff --git a/contrib/python3-ratchet.py b/contrib/python3-ratchet.py --- a/contrib/python3-ratchet.py +++ b/contrib/python3-ratchet.py @@ -60,7 +60,7 @@ def main(argv=()): ) p.add_argument( '-j', - default=os.sysconf(r'SC_NPROCESSORS_ONLN'), + default=os.sysconf('SC_NPROCESSORS_ONLN'), type=int, help='Number of parallel tests to run.', ) diff --git a/doc/gendoc.py b/doc/gendoc.py --- a/doc/gendoc.py +++ b/doc/gendoc.py @@ -20,7 +20,7 @@ except ImportError: # This script is executed during installs and may not have C extensions # available. Relax C module requirements. -os.environ[r'HGMODULEPOLICY'] = r'allow' +os.environ['HGMODULEPOLICY'] = 'allow' # import from the live mercurial repo sys.path.insert(0, "..") from mercurial import demandimport diff --git a/hgdemandimport/demandimportpy2.py b/hgdemandimport/demandimportpy2.py --- a/hgdemandimport/demandimportpy2.py +++ b/hgdemandimport/demandimportpy2.py @@ -135,8 +135,8 @@ class _demandmod(object): if locals: if locals.get(head) is self: locals[head] = mod - elif locals.get(head + r'mod') is self: - locals[head + r'mod'] = mod + elif locals.get(head + 'mod') is self: + locals[head + 'mod'] = mod for modname in modrefs: modref = sys.modules.get(modname, None) diff --git a/hgext/acl.py b/hgext/acl.py --- a/hgext/acl.py +++ b/hgext/acl.py @@ -369,8 +369,8 @@ def hook(ui, repo, hooktype, node=None, return user = None - if source == b'serve' and r'url' in kwargs: - url = kwargs[r'url'].split(b':') + if source == b'serve' and 'url' in kwargs: + url = kwargs['url'].split(b':') if url[0] == b'remote' and url[1].startswith(b'http'): user = urlreq.unquote(url[3]) @@ -386,9 +386,9 @@ def hook(ui, repo, hooktype, node=None, def _pkhook(ui, repo, hooktype, node, source, user, **kwargs): - if kwargs[r'namespace'] == b'bookmarks': - bookmark = kwargs[r'key'] - ctx = kwargs[r'new'] + if kwargs['namespace'] == b'bookmarks': + bookmark = kwargs['key'] + ctx = kwargs['new'] allowbookmarks = buildmatch(ui, None, user, b'acl.allow.bookmarks') denybookmarks = buildmatch(ui, None, user, b'acl.deny.bookmarks') diff --git a/hgext/beautifygraph.py b/hgext/beautifygraph.py --- a/hgext/beautifygraph.py +++ b/hgext/beautifygraph.py @@ -94,7 +94,7 @@ def extsetup(ui): ui.warn(_(b'beautifygraph: unsupported encoding, UTF-8 required\n')) return - if r'A' in encoding._wide: + if 'A' in encoding._wide: ui.warn( _( b'beautifygraph: unsupported terminal settings, ' diff --git a/hgext/blackbox.py b/hgext/blackbox.py --- a/hgext/blackbox.py +++ b/hgext/blackbox.py @@ -201,7 +201,7 @@ def blackbox(ui, repo, *revs, **opts): if not repo.vfs.exists(b'blackbox.log'): return - limit = opts.get(r'limit') + limit = opts.get('limit') fp = repo.vfs(b'blackbox.log', b'r') lines = fp.read().split(b'\n') diff --git a/hgext/bookflow.py b/hgext/bookflow.py --- a/hgext/bookflow.py +++ b/hgext/bookflow.py @@ -101,7 +101,7 @@ def commands_pull(orig, ui, repo, *args, def commands_branch(orig, ui, repo, label=None, **opts): - if label and not opts.get(r'clean') and not opts.get(r'rev'): + if label and not opts.get('clean') and not opts.get('rev'): raise error.Abort( _( b"creating named branches is disabled and you should use bookmarks" diff --git a/hgext/bugzilla.py b/hgext/bugzilla.py --- a/hgext/bugzilla.py +++ b/hgext/bugzilla.py @@ -612,7 +612,7 @@ class bzmysql(bzaccess): self.ui.warn(_(b"Bugzilla/MySQL cannot update bug state\n")) (user, userid) = self.get_bugzilla_user(committer) - now = time.strftime(r'%Y-%m-%d %H:%M:%S') + now = time.strftime('%Y-%m-%d %H:%M:%S') self.run( '''insert into longdescs (bug_id, who, bug_when, thetext) diff --git a/hgext/churn.py b/hgext/churn.py --- a/hgext/churn.py +++ b/hgext/churn.py @@ -197,7 +197,7 @@ def churn(ui, repo, *pats, **opts): return s + b" " * (l - encoding.colwidth(s)) amap = {} - aliases = opts.get(r'aliases') + aliases = opts.get('aliases') if not aliases and os.path.exists(repo.wjoin(b'.hgchurn')): aliases = repo.wjoin(b'.hgchurn') if aliases: @@ -215,7 +215,7 @@ def churn(ui, repo, *pats, **opts): if not rate: return - if opts.get(r'sort'): + if opts.get('sort'): rate.sort() else: rate.sort(key=lambda x: (-sum(x[1]), x)) @@ -228,7 +228,7 @@ def churn(ui, repo, *pats, **opts): ui.debug(b"assuming %i character terminal\n" % ttywidth) width = ttywidth - maxname - 2 - 2 - 2 - if opts.get(r'diffstat'): + if opts.get('diffstat'): width -= 15 def format(name, diffstat): diff --git a/hgext/commitextras.py b/hgext/commitextras.py --- a/hgext/commitextras.py +++ b/hgext/commitextras.py @@ -58,7 +58,7 @@ def _commit(orig, ui, repo, *pats, **opt class repoextra(repo.__class__): def commit(self, *innerpats, **inneropts): - extras = opts.get(r'extra') + extras = opts.get('extra') for raw in extras: if b'=' not in raw: msg = _( @@ -82,7 +82,7 @@ def _commit(orig, ui, repo, *pats, **opt b"manually" ) raise error.Abort(msg % k) - inneropts[r'extra'][k] = v + inneropts['extra'][k] = v return super(repoextra, self).commit(*innerpats, **inneropts) repo.__class__ = repoextra diff --git a/hgext/convert/common.py b/hgext/convert/common.py --- a/hgext/convert/common.py +++ b/hgext/convert/common.py @@ -57,7 +57,7 @@ class _shlexpy3proxy(object): def shlexer(data=None, filepath=None, wordchars=None, whitespace=None): if data is None: if pycompat.ispy3: - data = open(filepath, b'r', encoding=r'latin1') + data = open(filepath, b'r', encoding='latin1') else: data = open(filepath, b'r') else: diff --git a/hgext/convert/gnuarch.py b/hgext/convert/gnuarch.py --- a/hgext/convert/gnuarch.py +++ b/hgext/convert/gnuarch.py @@ -302,25 +302,25 @@ class gnuarch_source(common.converter_so # Commit date self.changes[rev].date = dateutil.datestr( - dateutil.strdate(catlog[r'Standard-date'], b'%Y-%m-%d %H:%M:%S') + dateutil.strdate(catlog['Standard-date'], b'%Y-%m-%d %H:%M:%S') ) # Commit author - self.changes[rev].author = self.recode(catlog[r'Creator']) + self.changes[rev].author = self.recode(catlog['Creator']) # Commit description self.changes[rev].summary = b'\n\n'.join( ( - self.recode(catlog[r'Summary']), + self.recode(catlog['Summary']), self.recode(catlog.get_payload()), ) ) self.changes[rev].summary = self.recode(self.changes[rev].summary) # Commit revision origin when dealing with a branch or tag - if r'Continuation-of' in catlog: + if 'Continuation-of' in catlog: self.changes[rev].continuationof = self.recode( - catlog[r'Continuation-of'] + catlog['Continuation-of'] ) except Exception: raise error.Abort(_(b'could not parse cat-log of %s') % rev) diff --git a/hgext/convert/monotone.py b/hgext/convert/monotone.py --- a/hgext/convert/monotone.py +++ b/hgext/convert/monotone.py @@ -96,7 +96,7 @@ class monotone_source(common.converter_s return self.mtnrunsingle(*args, **kwargs) def mtnrunsingle(self, *args, **kwargs): - kwargs[r'd'] = self.path + kwargs['d'] = self.path return self.run0(b'automate', *args, **kwargs) def mtnrunstdio(self, *args, **kwargs): diff --git a/hgext/convert/subversion.py b/hgext/convert/subversion.py --- a/hgext/convert/subversion.py +++ b/hgext/convert/subversion.py @@ -1359,11 +1359,11 @@ class svn_sink(converter_sink, commandli m = set() output = self.run0(b'ls', recursive=True, xml=True) doc = xml.dom.minidom.parseString(output) - for e in doc.getElementsByTagName(r'entry'): + for e in doc.getElementsByTagName('entry'): for n in e.childNodes: - if n.nodeType != n.ELEMENT_NODE or n.tagName != r'name': + if n.nodeType != n.ELEMENT_NODE or n.tagName != 'name': continue - name = r''.join( + name = ''.join( c.data for c in n.childNodes if c.nodeType == c.TEXT_NODE ) # Entries are compared with names coming from @@ -1502,7 +1502,7 @@ class svn_sink(converter_sink, commandli self.setexec = [] fd, messagefile = pycompat.mkstemp(prefix=b'hg-convert-') - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(util.tonativeeol(commit.desc)) fp.close() try: diff --git a/hgext/extdiff.py b/hgext/extdiff.py --- a/hgext/extdiff.py +++ b/hgext/extdiff.py @@ -655,7 +655,7 @@ class savedcmd(object): # in an unknown encoding anyway), but avoid double separators on # Windows docpath = stringutil.escapestr(path).replace(b'\\\\', b'\\') - self.__doc__ %= {r'path': pycompat.sysstr(stringutil.uirepr(docpath))} + self.__doc__ %= {'path': pycompat.sysstr(stringutil.uirepr(docpath))} self._cmdline = cmdline self._isgui = isgui diff --git a/hgext/fastannotate/commands.py b/hgext/fastannotate/commands.py --- a/hgext/fastannotate/commands.py +++ b/hgext/fastannotate/commands.py @@ -82,7 +82,7 @@ def _matchpaths(repo, rev, pats, opts, a fastannotatecommandargs = { - r'options': [ + 'options': [ (b'r', b'rev', b'.', _(b'annotate the specified revision'), _(b'REV')), (b'u', b'user', None, _(b'list the author (long with -v)')), (b'f', b'file', None, _(b'list the filename')), @@ -133,8 +133,8 @@ fastannotatecommandargs = { + commands.diffwsopts + commands.walkopts + commands.formatteropts, - r'synopsis': _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'), - r'inferrepo': True, + 'synopsis': _(b'[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'), + 'inferrepo': True, } @@ -257,7 +257,7 @@ def fastannotate(ui, repo, *pats, **opts _newopts = set() _knownopts = { opt[1].replace(b'-', b'_') - for opt in (fastannotatecommandargs[r'options'] + commands.globalopts) + for opt in (fastannotatecommandargs['options'] + commands.globalopts) } @@ -269,10 +269,10 @@ def _annotatewrapper(orig, ui, repo, *pa # treat the file as text (skip the isbinary check) if ui.configbool(b'fastannotate', b'forcetext'): - opts[r'text'] = True + opts['text'] = True # check if we need to do prefetch (client-side) - rev = opts.get(r'rev') + rev = opts.get('rev') if util.safehasattr(repo, 'prefetchfastannotate') and rev is not None: paths = list(_matchpaths(repo, rev, pats, pycompat.byteskwargs(opts))) repo.prefetchfastannotate(paths) diff --git a/hgext/githelp.py b/hgext/githelp.py --- a/hgext/githelp.py +++ b/hgext/githelp.py @@ -92,9 +92,9 @@ def parseoptions(ui, cmdoptions, args): except getopt.GetoptError as ex: if "requires argument" in ex.msg: raise - if (r'--' + ex.opt) in ex.msg: + if ('--' + ex.opt) in ex.msg: flag = b'--' + pycompat.bytestr(ex.opt) - elif (r'-' + ex.opt) in ex.msg: + elif ('-' + ex.opt) in ex.msg: flag = b'-' + pycompat.bytestr(ex.opt) else: raise error.Abort( diff --git a/hgext/gpg.py b/hgext/gpg.py --- a/hgext/gpg.py +++ b/hgext/gpg.py @@ -69,11 +69,11 @@ class gpg(object): try: # create temporary files fd, sigfile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".sig") - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(sig) fp.close() fd, datafile = pycompat.mkstemp(prefix=b"hg-gpg-", suffix=b".txt") - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(data) fp.close() gpgcmd = ( @@ -121,7 +121,7 @@ class gpg(object): def newgpg(ui, **opts): """create a new gpg instance""" gpgpath = ui.config(b"gpg", b"cmd") - gpgkey = opts.get(r'key') + gpgkey = opts.get('key') if not gpgkey: gpgkey = ui.config(b"gpg", b"key") return gpg(gpgpath, gpgkey) diff --git a/hgext/graphlog.py b/hgext/graphlog.py --- a/hgext/graphlog.py +++ b/hgext/graphlog.py @@ -121,5 +121,5 @@ def glog(ui, repo, *pats, **opts): This is an alias to :hg:`log -G`. """ - opts[r'graph'] = True + opts['graph'] = True return commands.log(ui, repo, *pats, **opts) diff --git a/hgext/hgk.py b/hgext/hgk.py --- a/hgext/hgk.py +++ b/hgext/hgk.py @@ -115,7 +115,7 @@ def difftree(ui, repo, node1=None, node2 ## while True: - if opts[r'stdin']: + if opts['stdin']: line = ui.fin.readline() if not line: break @@ -131,8 +131,8 @@ def difftree(ui, repo, node1=None, node2 else: node2 = node1 node1 = repo.changelog.parents(node1)[0] - if opts[r'patch']: - if opts[r'pretty']: + if opts['patch']: + if opts['pretty']: catcommit(ui, repo, node2, b"") m = scmutil.match(repo[node1], files) diffopts = patch.difffeatureopts(ui) @@ -142,7 +142,7 @@ def difftree(ui, repo, node1=None, node2 ui.write(chunk) else: __difftree(repo, node1, node2, files=files) - if not opts[r'stdin']: + if not opts['stdin']: break @@ -201,7 +201,7 @@ def catfile(ui, repo, type=None, r=None, # strings # prefix = b"" - if opts[r'stdin']: + if opts['stdin']: line = ui.fin.readline() if not line: return @@ -218,7 +218,7 @@ def catfile(ui, repo, type=None, r=None, return 1 n = repo.lookup(r) catcommit(ui, repo, n, prefix) - if opts[r'stdin']: + if opts['stdin']: line = ui.fin.readline() if not line: break @@ -363,7 +363,7 @@ def revlist(ui, repo, *revs, **opts): else: full = None copy = [x for x in revs] - revtree(ui, copy, repo, full, opts[r'max_count'], opts[r'parents']) + revtree(ui, copy, repo, full, opts['max_count'], opts[r'parents']) @command( diff --git a/hgext/histedit.py b/hgext/histedit.py --- a/hgext/histedit.py +++ b/hgext/histedit.py @@ -624,9 +624,9 @@ def commitfuncfor(repo, src): def commitfunc(**kwargs): overrides = {(b'phases', b'new-commit'): phasemin} with repo.ui.configoverride(overrides, b'histedit'): - extra = kwargs.get(r'extra', {}).copy() + extra = kwargs.get('extra', {}).copy() extra[b'histedit_source'] = src.hex() - kwargs[r'extra'] = extra + kwargs['extra'] = extra return repo.commit(**kwargs) return commitfunc @@ -1674,7 +1674,7 @@ def _chistedit(ui, repo, *freeargs, **op # Curses requires setting the locale or it will default to the C # locale. This sets the locale to the user's default system # locale. - locale.setlocale(locale.LC_ALL, r'') + locale.setlocale(locale.LC_ALL, '') rc = curses.wrapper(functools.partial(_chisteditmain, repo, ctxs)) curses.echo() curses.endwin() diff --git a/hgext/infinitepush/__init__.py b/hgext/infinitepush/__init__.py --- a/hgext/infinitepush/__init__.py +++ b/hgext/infinitepush/__init__.py @@ -195,7 +195,7 @@ scratchbranchparttype = bundleparts.scra revsetpredicate = registrar.revsetpredicate() templatekeyword = registrar.templatekeyword() _scratchbranchmatcher = lambda x: False -_maybehash = re.compile(r'^[a-f0-9]+$').search +_maybehash = re.compile('^[a-f0-9]+$').search def _buildexternalbundlestore(ui): @@ -1031,7 +1031,7 @@ def storetobundlestore(orig, repo, op, u fd, bundlefile = pycompat.mkstemp() try: try: - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(buf.read()) finally: fp.close() @@ -1122,7 +1122,7 @@ def processparts(orig, repo, op, unbundl fd, bundlefile = pycompat.mkstemp() try: try: - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(buf.read()) finally: fp.close() @@ -1254,7 +1254,7 @@ def bundle2scratchbranch(op, part): fd, bundlefile = pycompat.mkstemp() try: try: - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(buf.read()) finally: fp.close() diff --git a/hgext/infinitepush/common.py b/hgext/infinitepush/common.py --- a/hgext/infinitepush/common.py +++ b/hgext/infinitepush/common.py @@ -37,7 +37,7 @@ def _makebundlefromraw(data): fd, bundlefile = pycompat.mkstemp() try: # guards bundlefile try: # guards fp - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(data) finally: fp.close() diff --git a/hgext/journal.py b/hgext/journal.py --- a/hgext/journal.py +++ b/hgext/journal.py @@ -149,7 +149,7 @@ def _mergeentriesiter(*iterables, **kwar Note that by default entries go from most recent to oldest. """ - order = kwargs.pop(r'order', max) + order = kwargs.pop('order', max) iterables = [iter(it) for it in iterables] # this tracks still active iterables; iterables are deleted as they are # exhausted, which is why this is a dictionary and why each entry also @@ -214,8 +214,8 @@ def unsharejournal(orig, ui, repo, repop class journalentry( collections.namedtuple( - r'journalentry', - r'timestamp user command namespace name oldhashes newhashes', + 'journalentry', + 'timestamp user command namespace name oldhashes newhashes', ) ): """Individual journal entry diff --git a/hgext/keyword.py b/hgext/keyword.py --- a/hgext/keyword.py +++ b/hgext/keyword.py @@ -482,16 +482,16 @@ def demo(ui, repo, *args, **opts): ui.setconfig(b'keywordset', b'svn', svn, b'keyword') uikwmaps = ui.configitems(b'keywordmaps') - if args or opts.get(r'rcfile'): + if args or opts.get('rcfile'): ui.status(_(b'\n\tconfiguration using custom keyword template maps\n')) if uikwmaps: ui.status(_(b'\textending current template maps\n')) - if opts.get(r'default') or not uikwmaps: + if opts.get('default') or not uikwmaps: if svn: ui.status(_(b'\toverriding default svn keywordset\n')) else: ui.status(_(b'\toverriding default cvs keywordset\n')) - if opts.get(r'rcfile'): + if opts.get('rcfile'): ui.readconfig(opts.get(b'rcfile')) if args: # simulate hgrc parsing @@ -499,7 +499,7 @@ def demo(ui, repo, *args, **opts): repo.vfs.write(b'hgrc', rcmaps) ui.readconfig(repo.vfs.join(b'hgrc')) kwmaps = dict(ui.configitems(b'keywordmaps')) - elif opts.get(r'default'): + elif opts.get('default'): if svn: ui.status(_(b'\n\tconfiguration using default svn keywordset\n')) else: diff --git a/hgext/largefiles/lfcommands.py b/hgext/largefiles/lfcommands.py --- a/hgext/largefiles/lfcommands.py +++ b/hgext/largefiles/lfcommands.py @@ -648,7 +648,7 @@ def lfpull(ui, repo, source=b"default", """ repo.lfpullsource = source - revs = opts.get(r'rev', []) + revs = opts.get('rev', []) if not revs: raise error.Abort(_(b'no revisions specified')) revs = scmutil.revrange(repo, revs) diff --git a/hgext/largefiles/overrides.py b/hgext/largefiles/overrides.py --- a/hgext/largefiles/overrides.py +++ b/hgext/largefiles/overrides.py @@ -84,9 +84,9 @@ def composenormalfilematcher(match, mani def addlargefiles(ui, repo, isaddremove, matcher, uipathfn, **opts): - large = opts.get(r'large') + large = opts.get('large') lfsize = lfutil.getminsize( - ui, lfutil.islfilesrepo(repo), opts.get(r'lfsize') + ui, lfutil.islfilesrepo(repo), opts.get('lfsize') ) lfmatcher = None @@ -131,7 +131,7 @@ def addlargefiles(ui, repo, isaddremove, # Need to lock, otherwise there could be a race condition between # when standins are created and added to the repo. with repo.wlock(): - if not opts.get(r'dry_run'): + if not opts.get('dry_run'): standins = [] lfdirstate = lfutil.openlfdirstate(ui, repo) for f in lfnames: @@ -169,7 +169,7 @@ def lfstatus(repo): def removelargefiles(ui, repo, isaddremove, matcher, uipathfn, dryrun, **opts): - after = opts.get(r'after') + after = opts.get('after') m = composelargefilematcher(matcher, repo[None].manifest()) with lfstatus(repo): s = repo.status(match=m, clean=not isaddremove) @@ -269,7 +269,7 @@ def decodepath(orig, path): ], ) def overrideadd(orig, ui, repo, *pats, **opts): - if opts.get(r'normal') and opts.get(r'large'): + if opts.get('normal') and opts.get('large'): raise error.Abort(_(b'--normal cannot be used with --large')) return orig(ui, repo, *pats, **opts) @@ -277,7 +277,7 @@ def overrideadd(orig, ui, repo, *pats, * @eh.wrapfunction(cmdutil, b'add') def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts): # The --normal flag short circuits this override - if opts.get(r'normal'): + if opts.get('normal'): return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts) ladded, lbad = addlargefiles(ui, repo, False, matcher, uipathfn, **opts) @@ -477,9 +477,9 @@ def overridelog(orig, ui, repo, *pats, * ], ) def overrideverify(orig, ui, repo, *pats, **opts): - large = opts.pop(r'large', False) - all = opts.pop(r'lfa', False) - contents = opts.pop(r'lfc', False) + large = opts.pop('large', False) + all = opts.pop('lfa', False) + contents = opts.pop('lfc', False) result = orig(ui, repo, *pats, **opts) if large or all or contents: @@ -492,7 +492,7 @@ def overrideverify(orig, ui, repo, *pats opts=[(b'', b'large', None, _(b'display largefiles dirstate'))], ) def overridedebugstate(orig, ui, repo, *pats, **opts): - large = opts.pop(r'large', False) + large = opts.pop('large', False) if large: class fakerepo(object): @@ -975,8 +975,8 @@ def overridepull(orig, ui, repo, source= repo.lfpullsource = source result = orig(ui, repo, source, **opts) revspostpull = len(repo) - lfrevs = opts.get(r'lfrev', []) - if opts.get(r'all_largefiles'): + lfrevs = opts.get('lfrev', []) + if opts.get('all_largefiles'): lfrevs.append(b'pulled()') if lfrevs and revspostpull > revsprepull: numcached = 0 @@ -1006,9 +1006,9 @@ def overridepull(orig, ui, repo, source= ) def overridepush(orig, ui, repo, *args, **kwargs): """Override push command and store --lfrev parameters in opargs""" - lfrevs = kwargs.pop(r'lfrev', None) + lfrevs = kwargs.pop('lfrev', None) if lfrevs: - opargs = kwargs.setdefault(r'opargs', {}) + opargs = kwargs.setdefault('opargs', {}) opargs[b'lfrevs'] = scmutil.revrange(repo, lfrevs) return orig(ui, repo, *args, **kwargs) @@ -1016,7 +1016,7 @@ def overridepush(orig, ui, repo, *args, @eh.wrapfunction(exchange, b'pushoperation') def exchangepushoperation(orig, *args, **kwargs): """Override pushoperation constructor and store lfrevs parameter""" - lfrevs = kwargs.pop(r'lfrevs', None) + lfrevs = kwargs.pop('lfrevs', None) pushop = orig(*args, **kwargs) pushop.lfrevs = lfrevs return pushop @@ -1064,7 +1064,7 @@ def overrideclone(orig, ui, source, dest d = dest if d is None: d = hg.defaultdest(source) - if opts.get(r'all_largefiles') and not hg.islocal(d): + if opts.get('all_largefiles') and not hg.islocal(d): raise error.Abort( _(b'--all-largefiles is incompatible with non-local destination %s') % d @@ -1104,7 +1104,7 @@ def overriderebase(orig, ui, repo, **opt if not util.safehasattr(repo, b'_largefilesenabled'): return orig(ui, repo, **opts) - resuming = opts.get(r'continue') + resuming = opts.get('continue') repo._lfcommithooks.append(lfutil.automatedcommithook(resuming)) repo._lfstatuswriters.append(lambda *msg, **opts: None) try: @@ -1596,7 +1596,7 @@ def overriderollback(orig, ui, repo, **o @eh.wrapcommand(b'transplant', extension=b'transplant') def overridetransplant(orig, ui, repo, *revs, **opts): - resuming = opts.get(r'continue') + resuming = opts.get('continue') repo._lfcommithooks.append(lfutil.automatedcommithook(resuming)) repo._lfstatuswriters.append(lambda *msg, **opts: None) try: @@ -1681,7 +1681,7 @@ def overridecat(orig, ui, repo, file1, * @eh.wrapfunction(merge, b'update') def mergeupdate(orig, repo, node, branchmerge, force, *args, **kwargs): - matcher = kwargs.get(r'matcher', None) + matcher = kwargs.get('matcher', None) # note if this is a partial update partial = matcher and not matcher.always() with repo.wlock(): @@ -1741,7 +1741,7 @@ def mergeupdate(orig, repo, node, branch # Make sure the merge runs on disk, not in-memory. largefiles is not a # good candidate for in-memory merge (large files, custom dirstate, # matcher usage). - kwargs[r'wc'] = repo[None] + kwargs['wc'] = repo[None] result = orig(repo, node, branchmerge, force, *args, **kwargs) newstandins = lfutil.getstandinsstate(repo) diff --git a/hgext/largefiles/proto.py b/hgext/largefiles/proto.py --- a/hgext/largefiles/proto.py +++ b/hgext/largefiles/proto.py @@ -116,7 +116,7 @@ def wirereposetup(ui, repo): b'putlfile', data=fd, sha=sha, - headers={r'content-type': r'application/mercurial-0.1'}, + headers={'content-type': 'application/mercurial-0.1'}, ) try: d, output = res.split(b'\n', 1) @@ -206,7 +206,7 @@ def sshrepocallstream(self, cmd, **args) if cmd == b'heads' and self.capable(b'largefiles'): cmd = b'lheads' if cmd == b'batch' and self.capable(b'largefiles'): - args[r'cmds'] = args[r'cmds'].replace(b'heads ', b'lheads ') + args['cmds'] = args[r'cmds'].replace(b'heads ', b'lheads ') return ssholdcallstream(self, cmd, **args) @@ -217,5 +217,5 @@ def httprepocallstream(self, cmd, **args if cmd == b'heads' and self.capable(b'largefiles'): cmd = b'lheads' if cmd == b'batch' and self.capable(b'largefiles'): - args[r'cmds'] = headsre.sub(b'lheads', args[r'cmds']) + args['cmds'] = headsre.sub(b'lheads', args['cmds']) return httpoldcallstream(self, cmd, **args) diff --git a/hgext/lfs/__init__.py b/hgext/lfs/__init__.py --- a/hgext/lfs/__init__.py +++ b/hgext/lfs/__init__.py @@ -241,12 +241,12 @@ def _reposetup(ui, repo): if b'lfs' in repo.requirements: return 0 - last = kwargs.get(r'node_last') + last = kwargs.get('node_last') _bin = node.bin if last: - s = repo.set(b'%n:%n', _bin(kwargs[r'node']), _bin(last)) + s = repo.set(b'%n:%n', _bin(kwargs['node']), _bin(last)) else: - s = repo.set(b'%n', _bin(kwargs[r'node'])) + s = repo.set(b'%n', _bin(kwargs['node'])) match = repo._storenarrowmatch for ctx in s: # TODO: is there a way to just walk the files in the commit? @@ -399,6 +399,6 @@ def lfsfiles(context, mapping): ) def debuglfsupload(ui, repo, **opts): """upload lfs blobs added by the working copy parent or given revisions""" - revs = opts.get(r'rev', []) + revs = opts.get('rev', []) pointers = wrapper.extractpointers(repo, scmutil.revrange(repo, revs)) wrapper.uploadblobs(repo, pointers) diff --git a/hgext/lfs/blobstore.py b/hgext/lfs/blobstore.py --- a/hgext/lfs/blobstore.py +++ b/hgext/lfs/blobstore.py @@ -280,11 +280,11 @@ class lfsauthhandler(util.urlreq.basehan """Enforces that any authentication performed is HTTP Basic Authentication. No authentication is also acceptable. """ - authreq = headers.get(r'www-authenticate', None) + authreq = headers.get('www-authenticate', None) if authreq: scheme = authreq.split()[0] - if scheme.lower() != r'basic': + if scheme.lower() != 'basic': msg = _(b'the server must support Basic Authentication') raise util.urlerr.httperror( req.get_full_url(), @@ -324,18 +324,18 @@ class _gitlfsremote(object): See https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md """ objects = [ - {r'oid': pycompat.strurl(p.oid()), r'size': p.size()} + {'oid': pycompat.strurl(p.oid()), 'size': p.size()} for p in pointers ] requestdata = pycompat.bytesurl( json.dumps( - {r'objects': objects, r'operation': pycompat.strurl(action),} + {'objects': objects, 'operation': pycompat.strurl(action),} ) ) url = b'%s/objects/batch' % self.baseurl batchreq = util.urlreq.request(pycompat.strurl(url), data=requestdata) - batchreq.add_header(r'Accept', r'application/vnd.git-lfs+json') - batchreq.add_header(r'Content-Type', r'application/vnd.git-lfs+json') + batchreq.add_header('Accept', 'application/vnd.git-lfs+json') + batchreq.add_header('Content-Type', 'application/vnd.git-lfs+json') try: with contextlib.closing(self.urlopener.open(batchreq)) as rsp: rawjson = rsp.read() @@ -376,9 +376,9 @@ class _gitlfsremote(object): headers = pycompat.bytestr(rsp.info()).strip() self.ui.debug(b'%s\n' % b'\n'.join(sorted(headers.splitlines()))) - if r'objects' in response: - response[r'objects'] = sorted( - response[r'objects'], key=lambda p: p[r'oid'] + if 'objects' in response: + response['objects'] = sorted( + response['objects'], key=lambda p: p['oid'] ) self.ui.debug( b'%s\n' @@ -386,7 +386,7 @@ class _gitlfsremote(object): json.dumps( response, indent=2, - separators=(r'', r': '), + separators=('', ': '), sort_keys=True, ) ) @@ -483,8 +483,8 @@ class _gitlfsremote(object): ) request.data = filewithprogress(localstore.open(oid), None) request.get_method = lambda: r'PUT' - request.add_header(r'Content-Type', r'application/octet-stream') - request.add_header(r'Content-Length', len(request.data)) + request.add_header('Content-Type', 'application/octet-stream') + request.add_header('Content-Length', len(request.data)) for k, v in headers: request.add_header(pycompat.strurl(k), pycompat.strurl(v)) diff --git a/hgext/lfs/wireprotolfsserver.py b/hgext/lfs/wireprotolfsserver.py --- a/hgext/lfs/wireprotolfsserver.py +++ b/hgext/lfs/wireprotolfsserver.py @@ -136,7 +136,7 @@ def _processbatchrequest(repo, req, res) lfsreq = pycompat.json_loads(req.bodyfh.read()) # If no transfer handlers are explicitly requested, 'basic' is assumed. - if r'basic' not in lfsreq.get(r'transfers', [r'basic']): + if 'basic' not in lfsreq.get('transfers', ['basic']): _sethttperror( res, HTTP_BAD_REQUEST, @@ -144,7 +144,7 @@ def _processbatchrequest(repo, req, res) ) return True - operation = lfsreq.get(r'operation') + operation = lfsreq.get('operation') operation = pycompat.bytestr(operation) if operation not in (b'upload', b'download'): @@ -160,13 +160,13 @@ def _processbatchrequest(repo, req, res) objects = [ p for p in _batchresponseobjects( - req, lfsreq.get(r'objects', []), operation, localstore + req, lfsreq.get('objects', []), operation, localstore ) ] rsp = { - r'transfer': r'basic', - r'objects': objects, + 'transfer': 'basic', + 'objects': objects, } res.status = hgwebcommon.statusmessage(HTTP_OK) @@ -206,12 +206,12 @@ def _batchresponseobjects(req, objects, for obj in objects: # Convert unicode to ASCII to create a filesystem path - soid = obj.get(r'oid') - oid = soid.encode(r'ascii') + soid = obj.get('oid') + oid = soid.encode('ascii') rsp = { - r'oid': soid, - r'size': obj.get(r'size'), # XXX: should this check the local size? - # r'authenticated': True, + 'oid': soid, + 'size': obj.get('size'), # XXX: should this check the local size? + # 'authenticated': True, } exists = True @@ -234,9 +234,9 @@ def _batchresponseobjects(req, objects, if inst.errno != errno.ENOENT: _logexception(req) - rsp[r'error'] = { - r'code': 500, - r'message': inst.strerror or r'Internal Server Server', + rsp['error'] = { + 'code': 500, + 'message': inst.strerror or 'Internal Server Server', } yield rsp continue @@ -247,17 +247,17 @@ def _batchresponseobjects(req, objects, # IFF they already exist locally. if action == b'download': if not exists: - rsp[r'error'] = { - r'code': 404, - r'message': "The object does not exist", + rsp['error'] = { + 'code': 404, + 'message': "The object does not exist", } yield rsp continue elif not verifies: - rsp[r'error'] = { - r'code': 422, # XXX: is this the right code? - r'message': "The object is corrupt", + rsp['error'] = { + 'code': 422, # XXX: is this the right code? + 'message': "The object is corrupt", } yield rsp continue @@ -272,23 +272,23 @@ def _batchresponseobjects(req, objects, # The spec doesn't mention the Accept header here, but avoid # a gratuitous deviation from lfs-test-server in the test # output. - hdr = {r'Accept': r'application/vnd.git-lfs'} + hdr = {'Accept': 'application/vnd.git-lfs'} auth = req.headers.get(b'Authorization', b'') if auth.startswith(b'Basic '): - hdr[r'Authorization'] = pycompat.strurl(auth) + hdr['Authorization'] = pycompat.strurl(auth) return hdr - rsp[r'actions'] = { - r'%s' + rsp['actions'] = { + '%s' % pycompat.strurl(action): { - r'href': pycompat.strurl( + 'href': pycompat.strurl( b'%s%s/.hg/lfs/objects/%s' % (req.baseurl, req.apppath, oid) ), # datetime.isoformat() doesn't include the 'Z' suffix - "expires_at": expiresat.strftime(r'%Y-%m-%dT%H:%M:%SZ'), - r'header': _buildheader(), + "expires_at": expiresat.strftime('%Y-%m-%dT%H:%M:%SZ'), + 'header': _buildheader(), } } diff --git a/hgext/mq.py b/hgext/mq.py --- a/hgext/mq.py +++ b/hgext/mq.py @@ -490,7 +490,7 @@ class queue(object): def __init__(self, ui, baseui, path, patchdir=None): self.basepath = path try: - with open(os.path.join(path, b'patches.queue'), r'rb') as fh: + with open(os.path.join(path, b'patches.queue'), 'rb') as fh: cur = fh.read().rstrip() if not cur: @@ -2777,7 +2777,7 @@ def init(ui, repo, **opts): This command is deprecated. Without -c, it's implied by other relevant commands. With -c, use :hg:`init --mq` instead.""" - return qinit(ui, repo, create=opts.get(r'create_repo')) + return qinit(ui, repo, create=opts.get('create_repo')) @command( @@ -2933,7 +2933,7 @@ def series(ui, repo, **opts): Returns 0 on success.""" repo.mq.qseries( - repo, missing=opts.get(r'missing'), summary=opts.get(r'summary') + repo, missing=opts.get('missing'), summary=opts.get('summary') ) return 0 @@ -2960,7 +2960,7 @@ def top(ui, repo, **opts): start=t - 1, length=1, status=b'A', - summary=opts.get(r'summary'), + summary=opts.get('summary'), ) else: ui.write(_(b"no patches applied\n")) @@ -2982,7 +2982,7 @@ def next(ui, repo, **opts): if end == len(q.series): ui.write(_(b"all patches applied\n")) return 1 - q.qseries(repo, start=end, length=1, summary=opts.get(r'summary')) + q.qseries(repo, start=end, length=1, summary=opts.get('summary')) @command( @@ -3005,7 +3005,7 @@ def prev(ui, repo, **opts): return 1 idx = q.series.index(q.applied[-2].name) q.qseries( - repo, start=idx, length=1, status=b'A', summary=opts.get(r'summary') + repo, start=idx, length=1, status=b'A', summary=opts.get('summary') ) @@ -3356,8 +3356,8 @@ def guard(ui, repo, *args, **opts): applied = set(p.name for p in q.applied) patch = None args = list(args) - if opts.get(r'list'): - if args or opts.get(r'none'): + if opts.get('list'): + if args or opts.get('none'): raise error.Abort( _(b'cannot mix -l/--list with options or arguments') ) @@ -3372,7 +3372,7 @@ def guard(ui, repo, *args, **opts): patch = args.pop(0) if patch is None: raise error.Abort(_(b'no patch to work with')) - if args or opts.get(r'none'): + if args or opts.get('none'): idx = q.findseries(patch) if idx is None: raise error.Abort(_(b'no patch named %s') % patch) @@ -3634,9 +3634,7 @@ def restore(ui, repo, rev, **opts): This command is deprecated, use :hg:`rebase` instead.""" rev = repo.lookup(rev) q = repo.mq - q.restore( - repo, rev, delete=opts.get(r'delete'), qupdate=opts.get(r'update') - ) + q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update')) q.savedirty() return 0 @@ -3841,9 +3839,9 @@ def finish(ui, repo, *revrange, **opts): Returns 0 on success. """ - if not opts.get(r'applied') and not revrange: + if not opts.get('applied') and not revrange: raise error.Abort(_(b'no revisions specified')) - elif opts.get(r'applied'): + elif opts.get('applied'): revrange = (b'qbase::qtip',) + revrange q = repo.mq @@ -4072,9 +4070,9 @@ def reposetup(ui, repo): def invalidateall(self): super(mqrepo, self).invalidateall() - if localrepo.hasunfilteredcache(self, r'mq'): + if localrepo.hasunfilteredcache(self, 'mq'): # recreate mq in case queue path was changed - delattr(self.unfiltered(), r'mq') + delattr(self.unfiltered(), 'mq') def abortifwdirpatched(self, errmsg, force=False): if self.mq.applied and self.mq.checkapplied and not force: @@ -4172,16 +4170,16 @@ def reposetup(ui, repo): def mqimport(orig, ui, repo, *args, **kwargs): if util.safehasattr(repo, b'abortifwdirpatched') and not kwargs.get( - r'no_commit', False + 'no_commit', False ): repo.abortifwdirpatched( - _(b'cannot import over an applied patch'), kwargs.get(r'force') + _(b'cannot import over an applied patch'), kwargs.get('force') ) return orig(ui, repo, *args, **kwargs) def mqinit(orig, ui, *args, **kwargs): - mq = kwargs.pop(r'mq', None) + mq = kwargs.pop('mq', None) if not mq: return orig(ui, *args, **kwargs) @@ -4206,7 +4204,7 @@ def mqcommand(orig, ui, repo, *args, **k """Add --mq option to operate on patch repository instead of main""" # some commands do not like getting unknown options - mq = kwargs.pop(r'mq', None) + mq = kwargs.pop('mq', None) if not mq: return orig(ui, repo, *args, **kwargs) diff --git a/hgext/narrow/narrowbundle2.py b/hgext/narrow/narrowbundle2.py --- a/hgext/narrow/narrowbundle2.py +++ b/hgext/narrow/narrowbundle2.py @@ -62,8 +62,8 @@ def getbundlechangegrouppart_narrow( raise ValueError(_(b'no common changegroup version')) version = max(cgversions) - include = sorted(filter(bool, kwargs.get(r'includepats', []))) - exclude = sorted(filter(bool, kwargs.get(r'excludepats', []))) + include = sorted(filter(bool, kwargs.get('includepats', []))) + exclude = sorted(filter(bool, kwargs.get('excludepats', []))) generateellipsesbundle2( bundler, repo, @@ -72,7 +72,7 @@ def getbundlechangegrouppart_narrow( version, common, heads, - kwargs.get(r'depth', None), + kwargs.get('depth', None), ) @@ -316,7 +316,7 @@ def setup(): if repo.ui.has_section(_NARROWACL_SECTION): kwargs = exchange.applynarrowacl(repo, kwargs) - if kwargs.get(r'narrow', False) and repo.ui.configbool( + if kwargs.get('narrow', False) and repo.ui.configbool( b'experimental', b'narrowservebrokenellipses' ): getbundlechangegrouppart_narrow(*args, **kwargs) diff --git a/hgext/narrow/narrowcommands.py b/hgext/narrow/narrowcommands.py --- a/hgext/narrow/narrowcommands.py +++ b/hgext/narrow/narrowcommands.py @@ -136,8 +136,8 @@ def pullnarrowcmd(orig, ui, repo, *args, def pullbundle2extraprepare_widen(orig, pullop, kwargs): orig(pullop, kwargs) - if opts.get(r'depth'): - kwargs[b'depth'] = opts[r'depth'] + if opts.get('depth'): + kwargs[b'depth'] = opts['depth'] wrappedextraprepare = extensions.wrappedfunction( exchange, b'_pullbundle2extraprepare', pullbundle2extraprepare_widen @@ -151,15 +151,15 @@ def archivenarrowcmd(orig, ui, repo, *ar """Wraps archive command to narrow the default includes.""" if repository.NARROW_REQUIREMENT in repo.requirements: repo_includes, repo_excludes = repo.narrowpats - includes = set(opts.get(r'include', [])) - excludes = set(opts.get(r'exclude', [])) + includes = set(opts.get('include', [])) + excludes = set(opts.get('exclude', [])) includes, excludes, unused_invalid = narrowspec.restrictpatterns( includes, excludes, repo_includes, repo_excludes ) if includes: - opts[r'include'] = includes + opts['include'] = includes if excludes: - opts[r'exclude'] = excludes + opts['exclude'] = excludes return orig(ui, repo, *args, **opts) diff --git a/hgext/narrow/narrowwirepeer.py b/hgext/narrow/narrowwirepeer.py --- a/hgext/narrow/narrowwirepeer.py +++ b/hgext/narrow/narrowwirepeer.py @@ -139,12 +139,12 @@ def narrow_widen( def peernarrowwiden(remote, **kwargs): - for ch in (r'commonheads', r'known'): + for ch in ('commonheads', 'known'): kwargs[ch] = wireprototypes.encodelist(kwargs[ch]) - for ch in (r'oldincludes', r'newincludes', r'oldexcludes', r'newexcludes'): + for ch in ('oldincludes', 'newincludes', 'oldexcludes', 'newexcludes'): kwargs[ch] = b','.join(kwargs[ch]) - kwargs[r'ellipses'] = b'%i' % bool(kwargs[r'ellipses']) + kwargs['ellipses'] = b'%i' % bool(kwargs['ellipses']) f = remote._callcompressable(b'narrow_widen', **kwargs) return bundle2.getunbundler(remote.ui, f) diff --git a/hgext/notify.py b/hgext/notify.py --- a/hgext/notify.py +++ b/hgext/notify.py @@ -388,13 +388,13 @@ class notifier(object): raise error.Abort(inst) # store sender and subject - sender = msg[r'From'] - subject = msg[r'Subject'] + sender = msg['From'] + subject = msg['Subject'] if sender is not None: sender = mail.headdecode(sender) if subject is not None: subject = mail.headdecode(subject) - del msg[r'From'], msg[r'Subject'] + del msg['From'], msg['Subject'] if not msg.is_multipart(): # create fresh mime message from scratch @@ -407,7 +407,7 @@ class notifier(object): for k, v in headers: msg[k] = v - msg[r'Date'] = encoding.strfromlocal( + msg['Date'] = encoding.strfromlocal( dateutil.datestr(format=b"%a, %d %b %Y %H:%M:%S %1%2") ) @@ -421,7 +421,7 @@ class notifier(object): maxsubject = int(self.ui.config(b'notify', b'maxsubject')) if maxsubject: subject = stringutil.ellipsis(subject, maxsubject) - msg[r'Subject'] = encoding.strfromlocal( + msg['Subject'] = encoding.strfromlocal( mail.headencode(self.ui, subject, self.charsets, self.test) ) @@ -430,14 +430,14 @@ class notifier(object): sender = self.ui.config(b'email', b'from') or self.ui.username() if b'@' not in sender or b'@localhost' in sender: sender = self.fixmail(sender) - msg[r'From'] = encoding.strfromlocal( + msg['From'] = encoding.strfromlocal( mail.addressencode(self.ui, sender, self.charsets, self.test) ) - msg[r'X-Hg-Notification'] = r'changeset %s' % ctx - if not msg[r'Message-Id']: - msg[r'Message-Id'] = messageid(ctx, self.domain, self.messageidseed) - msg[r'To'] = encoding.strfromlocal(b', '.join(sorted(subs))) + msg['X-Hg-Notification'] = 'changeset %s' % ctx + if not msg['Message-Id']: + msg['Message-Id'] = messageid(ctx, self.domain, self.messageidseed) + msg['To'] = encoding.strfromlocal(b', '.join(sorted(subs))) msgtext = msg.as_bytes() if pycompat.ispy3 else msg.as_string() if self.test: @@ -451,7 +451,7 @@ class notifier(object): ) mail.sendmail( self.ui, - emailutils.parseaddr(msg[r'From'])[1], + emailutils.parseaddr(msg['From'])[1], subs, msgtext, mbox=self.mbox, diff --git a/hgext/patchbomb.py b/hgext/patchbomb.py --- a/hgext/patchbomb.py +++ b/hgext/patchbomb.py @@ -306,8 +306,8 @@ def makepatch( disposition = r'inline' if opts.get(b'attach'): disposition = r'attachment' - p[r'Content-Disposition'] = ( - disposition + r'; filename=' + encoding.strfromlocal(patchname) + p['Content-Disposition'] = ( + disposition + '; filename=' + encoding.strfromlocal(patchname) ) msg.attach(p) else: @@ -358,7 +358,7 @@ def _getbundle(repo, dest, **opts): tmpfn = os.path.join(tmpdir, b'bundle') btype = ui.config(b'patchbomb', b'bundletype') if btype: - opts[r'type'] = btype + opts['type'] = btype try: commands.bundle(ui, repo, tmpfn, dest, **opts) return util.readfile(tmpfn) @@ -379,8 +379,8 @@ def _getdescription(repo, defaultbody, s the user through the editor. """ ui = repo.ui - if opts.get(r'desc'): - body = open(opts.get(r'desc')).read() + if opts.get('desc'): + body = open(opts.get('desc')).read() else: ui.write( _(b'\nWrite the introductory message for the patch series.\n\n') @@ -403,25 +403,25 @@ def _getbundlemsgs(repo, sender, bundle, """ ui = repo.ui _charsets = mail._charsets(ui) - subj = opts.get(r'subject') or prompt( + subj = opts.get('subject') or prompt( ui, b'Subject:', b'A bundle for your repository' ) body = _getdescription(repo, b'', sender, **opts) msg = emimemultipart.MIMEMultipart() if body: - msg.attach(mail.mimeencode(ui, body, _charsets, opts.get(r'test'))) - datapart = emimebase.MIMEBase(r'application', r'x-mercurial-bundle') + msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test'))) + datapart = emimebase.MIMEBase('application', 'x-mercurial-bundle') datapart.set_payload(bundle) - bundlename = b'%s.hg' % opts.get(r'bundlename', b'bundle') + bundlename = b'%s.hg' % opts.get('bundlename', b'bundle') datapart.add_header( - r'Content-Disposition', - r'attachment', + 'Content-Disposition', + 'attachment', filename=encoding.strfromlocal(bundlename), ) emailencoders.encode_base64(datapart) msg.attach(datapart) - msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get(r'test')) + msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test')) return [(msg, subj, None)] @@ -434,9 +434,9 @@ def _makeintro(repo, sender, revs, patch # use the last revision which is likely to be a bookmarked head prefix = _formatprefix( - ui, repo, revs.last(), opts.get(r'flag'), 0, len(patches), numbered=True + ui, repo, revs.last(), opts.get('flag'), 0, len(patches), numbered=True ) - subj = opts.get(r'subject') or prompt( + subj = opts.get('subject') or prompt( ui, b'(optional) Subject: ', rest=prefix, default=b'' ) if not subj: @@ -445,7 +445,7 @@ def _makeintro(repo, sender, revs, patch subj = prefix + b' ' + subj body = b'' - if opts.get(r'diffstat'): + if opts.get('diffstat'): # generate a cumulative diffstat of the whole patch series diffstat = patch.diffstat(sum(patches, [])) body = b'\n' + diffstat @@ -453,8 +453,8 @@ def _makeintro(repo, sender, revs, patch diffstat = None body = _getdescription(repo, body, sender, **opts) - msg = mail.mimeencode(ui, body, _charsets, opts.get(r'test')) - msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get(r'test')) + msg = mail.mimeencode(ui, body, _charsets, opts.get('test')) + msg[b'Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test')) return (msg, subj, diffstat) @@ -847,7 +847,7 @@ def email(ui, repo, *revs, **opts): stropts = pycompat.strkwargs(opts) bundledata = _getbundle(repo, dest, **stropts) bundleopts = stropts.copy() - bundleopts.pop(r'bundle', None) # already processed + bundleopts.pop('bundle', None) # already processed msgs = _getbundlemsgs(repo, sender, bundledata, **bundleopts) else: msgs = _getpatchmsgs(repo, sender, revs, **pycompat.strkwargs(opts)) diff --git a/hgext/phabricator.py b/hgext/phabricator.py --- a/hgext/phabricator.py +++ b/hgext/phabricator.py @@ -167,13 +167,13 @@ def vcrcommand(name, flags, spec, helpca return request def sanitiseresponse(response): - if r'set-cookie' in response[r'headers']: - del response[r'headers'][r'set-cookie'] + if 'set-cookie' in response['headers']: + del response['headers']['set-cookie'] return response def decorate(fn): def inner(*args, **kwargs): - cassette = pycompat.fsdecode(kwargs.pop(r'test_vcr', None)) + cassette = pycompat.fsdecode(kwargs.pop('test_vcr', None)) if cassette: import hgdemandimport @@ -182,24 +182,24 @@ def vcrcommand(name, flags, spec, helpca import vcr.stubs as stubs vcr = vcrmod.VCR( - serializer=r'json', + serializer='json', before_record_request=sanitiserequest, before_record_response=sanitiseresponse, custom_patches=[ ( urlmod, - r'httpconnection', + 'httpconnection', stubs.VCRHTTPConnection, ), ( urlmod, - r'httpsconnection', + 'httpsconnection', stubs.VCRHTTPSConnection, ), ], ) - vcr.register_matcher(r'hgmatcher', hgmatcher) - with vcr.use_cassette(cassette, match_on=[r'hgmatcher']): + vcr.register_matcher('hgmatcher', hgmatcher) + with vcr.use_cassette(cassette, match_on=['hgmatcher']): return fn(*args, **kwargs) return fn(*args, **kwargs) @@ -408,7 +408,7 @@ def getoldnodedrevmap(repo, nodelist): # Check commit message m = _differentialrevisiondescre.search(ctx.description()) if m: - toconfirm[node] = (1, set(precnodes), int(m.group(r'id'))) + toconfirm[node] = (1, set(precnodes), int(m.group('id'))) # Double check if tags are genuine by collecting all old nodes from # Phabricator, and expect precursors overlap with it. @@ -1088,7 +1088,7 @@ def phabsend(ui, repo, *revs, **opts): # Create a local tag to note the association, if commit message # does not have it already m = _differentialrevisiondescre.search(ctx.description()) - if not m or int(m.group(r'id')) != newrevid: + if not m or int(m.group('id')) != newrevid: tagname = b'D%d' % newrevid tags.tag( repo, @@ -1635,7 +1635,7 @@ def template_review(context, mapping): m = _differentialrevisiondescre.search(ctx.description()) if m: return templateutil.hybriddict( - {b'url': m.group(r'url'), b'id': b"D%s" % m.group(r'id'),} + {b'url': m.group('url'), b'id': b"D%s" % m.group('id'),} ) else: tags = ctx.repo().nodetags(ctx.node()) diff --git a/hgext/rebase.py b/hgext/rebase.py --- a/hgext/rebase.py +++ b/hgext/rebase.py @@ -2127,15 +2127,15 @@ def clearrebased( def pullrebase(orig, ui, repo, *args, **opts): b'Call rebase after pull if the latter has been invoked with --rebase' - if opts.get(r'rebase'): + if opts.get('rebase'): if ui.configbool(b'commands', b'rebase.requiredest'): msg = _(b'rebase destination required by configuration') hint = _(b'use hg pull followed by hg rebase -d DEST') raise error.Abort(msg, hint=hint) with repo.wlock(), repo.lock(): - if opts.get(r'update'): - del opts[r'update'] + if opts.get('update'): + del opts['update'] ui.debug( b'--update and --rebase are not compatible, ignoring ' b'the update flag\n' @@ -2165,15 +2165,15 @@ def pullrebase(orig, ui, repo, *args, ** if revspostpull > revsprepull: # --rev option from pull conflict with rebase own --rev # dropping it - if r'rev' in opts: - del opts[r'rev'] + if 'rev' in opts: + del opts['rev'] # positional argument from pull conflicts with rebase's own # --source. - if r'source' in opts: - del opts[r'source'] + if 'source' in opts: + del opts['source'] # revsprepull is the len of the repo, not revnum of tip. destspace = list(repo.changelog.revs(start=revsprepull)) - opts[r'_destspace'] = destspace + opts['_destspace'] = destspace try: rebase(ui, repo, **opts) except error.NoMergeDestAbort: @@ -2187,7 +2187,7 @@ def pullrebase(orig, ui, repo, *args, ** # with warning and trumpets commands.update(ui, repo) else: - if opts.get(r'tool'): + if opts.get('tool'): raise error.Abort(_(b'--tool can only be used with --rebase')) ret = orig(ui, repo, *args, **opts) diff --git a/hgext/record.py b/hgext/record.py --- a/hgext/record.py +++ b/hgext/record.py @@ -79,7 +79,7 @@ def record(ui, repo, *pats, **opts): def qrefresh(origfn, ui, repo, *pats, **opts): - if not opts[r'interactive']: + if not opts['interactive']: return origfn(ui, repo, *pats, **opts) mq = extensions.find(b'mq') @@ -123,7 +123,7 @@ def _qrecord(cmdsuggest, ui, repo, patch repo.mq.checkpatchname(patch) def committomq(ui, repo, *pats, **opts): - opts[r'checkname'] = False + opts['checkname'] = False mq.new(ui, repo, patch, *pats, **opts) overrides = {(b'experimental', b'crecord'): False} @@ -142,7 +142,7 @@ def _qrecord(cmdsuggest, ui, repo, patch def qnew(origfn, ui, repo, patch, *args, **opts): - if opts[r'interactive']: + if opts['interactive']: return _qrecord(None, ui, repo, patch, *args, **opts) return origfn(ui, repo, patch, *args, **opts) diff --git a/hgext/remotefilelog/__init__.py b/hgext/remotefilelog/__init__.py --- a/hgext/remotefilelog/__init__.py +++ b/hgext/remotefilelog/__init__.py @@ -288,7 +288,7 @@ def uisetup(ui): # Prevent 'hg manifest --all' def _manifest(orig, ui, repo, *args, **opts): - if isenabled(repo) and opts.get(r'all'): + if isenabled(repo) and opts.get('all'): raise error.Abort(_(b"--all is not supported in a shallow repo")) return orig(ui, repo, *args, **opts) @@ -344,7 +344,7 @@ def uisetup(ui): def cloneshallow(orig, ui, repo, *args, **opts): - if opts.get(r'shallow'): + if opts.get('shallow'): repos = [] def pull_shallow(orig, self, *args, **kwargs): @@ -381,13 +381,9 @@ def cloneshallow(orig, ui, repo, *args, if constants.NETWORK_CAP_LEGACY_SSH_GETFILES in caps: opts = {} if repo.includepattern: - opts[r'includepattern'] = b'\0'.join( - repo.includepattern - ) + opts['includepattern'] = b'\0'.join(repo.includepattern) if repo.excludepattern: - opts[r'excludepattern'] = b'\0'.join( - repo.excludepattern - ) + opts['excludepattern'] = b'\0'.join(repo.excludepattern) return remote._callstream(b'stream_out_shallow', **opts) else: return orig() @@ -424,7 +420,7 @@ def cloneshallow(orig, ui, repo, *args, try: orig(ui, repo, *args, **opts) finally: - if opts.get(r'shallow'): + if opts.get('shallow'): for r in repos: if util.safehasattr(r, b'fileservice'): r.fileservice.close() @@ -991,14 +987,14 @@ def log(orig, ui, repo, *pats, **opts): if not isenabled(repo): return orig(ui, repo, *pats, **opts) - follow = opts.get(r'follow') - revs = opts.get(r'rev') + follow = opts.get('follow') + revs = opts.get('rev') if pats: # Force slowpath for non-follow patterns and follows that start from # non-working-copy-parent revs. if not follow or revs: # This forces the slowpath - opts[r'removed'] = True + opts['removed'] = True # If this is a non-follow log without any revs specified, recommend that # the user add -f to speed it up. @@ -1279,20 +1275,20 @@ def prefetch(ui, repo, *pats, **opts): _(b'hg repack [OPTIONS]'), ) def repack_(ui, repo, *pats, **opts): - if opts.get(r'background'): + if opts.get('background'): ensurestart = repo.ui.configbool(b'devel', b'remotefilelog.ensurestart') repackmod.backgroundrepack( repo, - incremental=opts.get(r'incremental'), - packsonly=opts.get(r'packsonly', False), + incremental=opts.get('incremental'), + packsonly=opts.get('packsonly', False), ensurestart=ensurestart, ) return - options = {b'packsonly': opts.get(r'packsonly')} + options = {b'packsonly': opts.get('packsonly')} try: - if opts.get(r'incremental'): + if opts.get('incremental'): repackmod.incrementalrepack(repo, options=options) else: repackmod.fullrepack(repo, options=options) diff --git a/hgext/remotefilelog/basepack.py b/hgext/remotefilelog/basepack.py --- a/hgext/remotefilelog/basepack.py +++ b/hgext/remotefilelog/basepack.py @@ -22,7 +22,7 @@ from mercurial import ( ) from . import shallowutil -osutil = policy.importmod(r'osutil') +osutil = policy.importmod('osutil') # The pack version supported by this implementation. This will need to be # rev'd whenever the byte format changes. Ex: changing the fanout prefix, @@ -390,8 +390,8 @@ class mutablebasepack(versionmixin): self.idxfp, self.idxpath = opener.mkstemp( suffix=self.INDEXSUFFIX + b'-tmp' ) - self.packfp = os.fdopen(self.packfp, r'wb+') - self.idxfp = os.fdopen(self.idxfp, r'wb+') + self.packfp = os.fdopen(self.packfp, 'wb+') + self.idxfp = os.fdopen(self.idxfp, 'wb+') self.sha = hashlib.sha1() self._closed = False @@ -530,11 +530,11 @@ class mutablebasepack(versionmixin): class indexparams(object): __slots__ = ( - r'fanoutprefix', - r'fanoutstruct', - r'fanoutcount', - r'fanoutsize', - r'indexstart', + 'fanoutprefix', + 'fanoutstruct', + 'fanoutcount', + 'fanoutsize', + 'indexstart', ) def __init__(self, prefixsize, version): diff --git a/hgext/remotefilelog/basestore.py b/hgext/remotefilelog/basestore.py --- a/hgext/remotefilelog/basestore.py +++ b/hgext/remotefilelog/basestore.py @@ -420,10 +420,10 @@ class baseunionstore(object): # throw a KeyError, try this many times with a full refresh between # attempts. A repack operation may have moved data from one store to # another while we were running. - self.numattempts = kwargs.get(r'numretries', 0) + 1 + self.numattempts = kwargs.get('numretries', 0) + 1 # If not-None, call this function on every retry and if the attempts are # exhausted. - self.retrylog = kwargs.get(r'retrylog', None) + self.retrylog = kwargs.get('retrylog', None) def markforrefresh(self): for store in self.stores: diff --git a/hgext/remotefilelog/contentstore.py b/hgext/remotefilelog/contentstore.py --- a/hgext/remotefilelog/contentstore.py +++ b/hgext/remotefilelog/contentstore.py @@ -40,12 +40,12 @@ class unioncontentstore(basestore.baseun super(unioncontentstore, self).__init__(*args, **kwargs) self.stores = args - self.writestore = kwargs.get(r'writestore') + self.writestore = kwargs.get('writestore') # If allowincomplete==True then the union store can return partial # delta chains, otherwise it will throw a KeyError if a full # deltachain can't be found. - self.allowincomplete = kwargs.get(r'allowincomplete', False) + self.allowincomplete = kwargs.get('allowincomplete', False) def get(self, name, node): """Fetches the full text revision contents of the given name+node pair. diff --git a/hgext/remotefilelog/debugcommands.py b/hgext/remotefilelog/debugcommands.py --- a/hgext/remotefilelog/debugcommands.py +++ b/hgext/remotefilelog/debugcommands.py @@ -32,7 +32,7 @@ from . import ( def debugremotefilelog(ui, path, **opts): - decompress = opts.get(r'decompress') + decompress = opts.get('decompress') size, firstnode, mapping = parsefileblob(path, decompress) @@ -101,9 +101,9 @@ def buildtemprevlog(repo, file): def debugindex(orig, ui, repo, file_=None, **opts): """dump the contents of an index file""" if ( - opts.get(r'changelog') - or opts.get(r'manifest') - or opts.get(r'dir') + opts.get('changelog') + or opts.get('manifest') + or opts.get('dir') or not shallowutil.isenabled(repo) or not repo.shallowmatch(file_) ): @@ -199,7 +199,7 @@ def debugindexdot(orig, ui, repo, file_) def verifyremotefilelog(ui, path, **opts): - decompress = opts.get(r'decompress') + decompress = opts.get('decompress') for root, dirs, files in os.walk(path): for file in files: @@ -262,13 +262,13 @@ def debugdatapack(ui, *paths, **opts): path = path[: path.index(b'.data')] ui.write(b"%s:\n" % path) dpack = datapack.datapack(path) - node = opts.get(r'node') + node = opts.get('node') if node: deltachain = dpack.getdeltachain(b'', bin(node)) dumpdeltachain(ui, deltachain, **opts) return - if opts.get(r'long'): + if opts.get('long'): hashformatter = hex hashlen = 42 else: diff --git a/hgext/remotefilelog/metadatastore.py b/hgext/remotefilelog/metadatastore.py --- a/hgext/remotefilelog/metadatastore.py +++ b/hgext/remotefilelog/metadatastore.py @@ -12,12 +12,12 @@ class unionmetadatastore(basestore.baseu super(unionmetadatastore, self).__init__(*args, **kwargs) self.stores = args - self.writestore = kwargs.get(r'writestore') + self.writestore = kwargs.get('writestore') # If allowincomplete==True then the union store can return partial # ancestor lists, otherwise it will throw a KeyError if a full # history can't be found. - self.allowincomplete = kwargs.get(r'allowincomplete', False) + self.allowincomplete = kwargs.get('allowincomplete', False) def getancestors(self, name, node, known=None): """Returns as many ancestors as we're aware of. diff --git a/hgext/remotefilelog/remotefilectx.py b/hgext/remotefilelog/remotefilectx.py --- a/hgext/remotefilelog/remotefilectx.py +++ b/hgext/remotefilelog/remotefilectx.py @@ -48,11 +48,11 @@ class remotefilectx(context.filectx): @propertycache def _changeid(self): - if r'_changeid' in self.__dict__: + if '_changeid' in self.__dict__: return self._changeid - elif r'_changectx' in self.__dict__: + elif '_changectx' in self.__dict__: return self._changectx.rev() - elif r'_descendantrev' in self.__dict__: + elif '_descendantrev' in self.__dict__: # this file context was created from a revision with a known # descendant, we can (lazily) correct for linkrev aliases linknode = self._adjustlinknode( @@ -119,7 +119,7 @@ class remotefilectx(context.filectx): """ lkr = self.linkrev() attrs = vars(self) - noctx = not (r'_changeid' in attrs or r'_changectx' in attrs) + noctx = not ('_changeid' in attrs or r'_changectx' in attrs) if noctx or self.rev() == lkr: return lkr linknode = self._adjustlinknode( @@ -246,11 +246,11 @@ class remotefilectx(context.filectx): return linknode commonlogkwargs = { - r'revs': b' '.join([hex(cl.node(rev)) for rev in revs]), - r'fnode': hex(fnode), - r'filepath': path, - r'user': shallowutil.getusername(repo.ui), - r'reponame': shallowutil.getreponame(repo.ui), + 'revs': b' '.join([hex(cl.node(rev)) for rev in revs]), + 'fnode': hex(fnode), + 'filepath': path, + 'user': shallowutil.getusername(repo.ui), + 'reponame': shallowutil.getreponame(repo.ui), } repo.ui.log(b'linkrevfixup', b'adjusting linknode\n', **commonlogkwargs) @@ -439,7 +439,7 @@ class remotefilectx(context.filectx): def annotate(self, *args, **kwargs): introctx = self - prefetchskip = kwargs.pop(r'prefetchskip', None) + prefetchskip = kwargs.pop('prefetchskip', None) if prefetchskip: # use introrev so prefetchskip can be accurately tested introrev = self.introrev() diff --git a/hgext/remotefilelog/repack.py b/hgext/remotefilelog/repack.py --- a/hgext/remotefilelog/repack.py +++ b/hgext/remotefilelog/repack.py @@ -29,7 +29,7 @@ from . import ( shallowutil, ) -osutil = policy.importmod(r'osutil') +osutil = policy.importmod('osutil') class RepackAlreadyRunning(error.Abort): @@ -876,13 +876,13 @@ class repackentry(object): """ __slots__ = ( - r'filename', - r'node', - r'datasource', - r'historysource', - r'datarepacked', - r'historyrepacked', - r'gced', + 'filename', + 'node', + 'datasource', + 'historysource', + 'datarepacked', + 'historyrepacked', + 'gced', ) def __init__(self, filename, node): diff --git a/hgext/remotefilelog/shallowbundle.py b/hgext/remotefilelog/shallowbundle.py --- a/hgext/remotefilelog/shallowbundle.py +++ b/hgext/remotefilelog/shallowbundle.py @@ -153,7 +153,7 @@ def makechangegroup(orig, repo, outgoing try: # if serving, only send files the clients has patterns for if source == b'serve': - bundlecaps = kwargs.get(r'bundlecaps') + bundlecaps = kwargs.get('bundlecaps') includepattern = None excludepattern = None for cap in bundlecaps or []: diff --git a/hgext/share.py b/hgext/share.py --- a/hgext/share.py +++ b/hgext/share.py @@ -122,7 +122,7 @@ def clone(orig, ui, source, *args, **opt if pool: pool = util.expandpath(pool) - opts[r'shareopts'] = { + opts['shareopts'] = { b'pool': pool, b'mode': ui.config(b'share', b'poolnaming'), } diff --git a/hgext/sparse.py b/hgext/sparse.py --- a/hgext/sparse.py +++ b/hgext/sparse.py @@ -153,10 +153,10 @@ def _setuplog(ui): def _clonesparsecmd(orig, ui, repo, *args, **opts): - include_pat = opts.get(r'include') - exclude_pat = opts.get(r'exclude') - enableprofile_pat = opts.get(r'enable_profile') - narrow_pat = opts.get(r'narrow') + include_pat = opts.get('include') + exclude_pat = opts.get('exclude') + enableprofile_pat = opts.get('enable_profile') + narrow_pat = opts.get('narrow') include = exclude = enableprofile = False if include_pat: pat = include_pat @@ -209,7 +209,7 @@ def _setupadd(ui): ) def _add(orig, ui, repo, *pats, **opts): - if opts.get(r'sparse'): + if opts.get('sparse'): dirs = set() for pat in pats: dirname, basename = util.split(pat) diff --git a/hgext/transplant.py b/hgext/transplant.py --- a/hgext/transplant.py +++ b/hgext/transplant.py @@ -235,7 +235,7 @@ class transplanter(object): patchfile = None else: fd, patchfile = pycompat.mkstemp(prefix=b'hg-transplant-') - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') gen = patch.diff(source, parent, node, opts=diffopts) for chunk in gen: fp.write(chunk) @@ -290,7 +290,7 @@ class transplanter(object): self.ui.status(_(b'filtering %s\n') % patchfile) user, date, msg = (changelog[1], changelog[2], changelog[4]) fd, headerfile = pycompat.mkstemp(prefix=b'hg-transplant-') - fp = os.fdopen(fd, r'wb') + fp = os.fdopen(fd, 'wb') fp.write(b"# HG changeset patch\n") fp.write(b"# User %s\n" % user) fp.write(b"# Date %d %d\n" % date) diff --git a/hgext/zeroconf/Zeroconf.py b/hgext/zeroconf/Zeroconf.py --- a/hgext/zeroconf/Zeroconf.py +++ b/hgext/zeroconf/Zeroconf.py @@ -684,7 +684,7 @@ class DNSIncoming(object): break t = len & 0xC0 if t == 0x00: - result = r''.join((result, self.readUTF(off, len) + r'.')) + result = ''.join((result, self.readUTF(off, len) + '.')) off += len elif t == 0xC0: if next < 0: @@ -1425,7 +1425,7 @@ class Zeroconf(object): self.socket.setsockopt( socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, - socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0'), + socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'), ) self.listeners = [] @@ -1841,7 +1841,7 @@ class Zeroconf(object): self.socket.setsockopt( socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, - socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0'), + socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'), ) self.socket.close() diff --git a/hgext/zeroconf/__init__.py b/hgext/zeroconf/__init__.py --- a/hgext/zeroconf/__init__.py +++ b/hgext/zeroconf/__init__.py @@ -55,7 +55,7 @@ def getip(): # finds external-facing interface without sending any packets (Linux) try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect((r'1.0.0.1', 0)) + s.connect(('1.0.0.1', 0)) ip = s.getsockname()[0] return ip except socket.error: @@ -64,17 +64,17 @@ def getip(): # Generic method, sometimes gives useless results try: dumbip = socket.gethostbyaddr(socket.gethostname())[2][0] - if r':' in dumbip: - dumbip = r'127.0.0.1' - if not dumbip.startswith(r'127.'): + if ':' in dumbip: + dumbip = '127.0.0.1' + if not dumbip.startswith('127.'): return dumbip except (socket.gaierror, socket.herror): - dumbip = r'127.0.0.1' + dumbip = '127.0.0.1' # works elsewhere, but actually sends a packet try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect((r'1.0.0.1', 1)) + s.connect(('1.0.0.1', 1)) ip = s.getsockname()[0] return ip except socket.error: @@ -87,20 +87,20 @@ def publish(name, desc, path, port): global server, localip if not server: ip = getip() - if ip.startswith(r'127.'): + if ip.startswith('127.'): # if we have no internet connection, this can happen. return localip = socket.inet_aton(ip) server = Zeroconf.Zeroconf(ip) - hostname = socket.gethostname().split(r'.')[0] - host = hostname + r".local" + hostname = socket.gethostname().split('.')[0] + host = hostname + ".local" name = "%s-%s" % (hostname, name) # advertise to browsers svc = Zeroconf.ServiceInfo( b'_http._tcp.local.', - pycompat.bytestr(name + r'._http._tcp.local.'), + pycompat.bytestr(name + '._http._tcp.local.'), server=host, port=port, properties={b'description': desc, b'path': b"/" + path}, @@ -113,7 +113,7 @@ def publish(name, desc, path, port): # advertise to Mercurial clients svc = Zeroconf.ServiceInfo( b'_hg._tcp.local.', - pycompat.bytestr(name + r'._hg._tcp.local.'), + pycompat.bytestr(name + '._hg._tcp.local.'), server=host, port=port, properties={b'description': desc, b'path': b"/" + path}, @@ -171,7 +171,7 @@ class listener(object): def getzcpaths(): ip = getip() - if ip.startswith(r'127.'): + if ip.startswith('127.'): return server = Zeroconf.Zeroconf(ip) l = listener() diff --git a/mercurial/ancestor.py b/mercurial/ancestor.py --- a/mercurial/ancestor.py +++ b/mercurial/ancestor.py @@ -16,7 +16,7 @@ from . import ( pycompat, ) -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') def commonancestorsheads(pfunc, *nodes): diff --git a/mercurial/archival.py b/mercurial/archival.py --- a/mercurial/archival.py +++ b/mercurial/archival.py @@ -138,8 +138,8 @@ class tarit(object): class GzipFileWithTime(gzip.GzipFile): def __init__(self, *args, **kw): timestamp = None - if r'timestamp' in kw: - timestamp = kw.pop(r'timestamp') + if 'timestamp' in kw: + timestamp = kw.pop('timestamp') if timestamp is None: self.timestamp = time.time() else: @@ -222,7 +222,7 @@ class zipit(object): if isinstance(dest, bytes): dest = pycompat.fsdecode(dest) self.z = zipfile.ZipFile( - dest, r'w', compress and zipfile.ZIP_DEFLATED or zipfile.ZIP_STORED + dest, 'w', compress and zipfile.ZIP_DEFLATED or zipfile.ZIP_STORED ) # Python's zipfile module emits deprecation warnings if we try diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py --- a/mercurial/branchmap.py +++ b/mercurial/branchmap.py @@ -124,7 +124,7 @@ class BranchMapCache(object): def _unknownnode(node): """ raises ValueError when branchcache found a node which does not exists """ - raise ValueError(r'node %s does not exist' % pycompat.sysstr(hex(node))) + raise ValueError('node %s does not exist' % pycompat.sysstr(hex(node))) def _branchcachedesc(repo): @@ -260,7 +260,7 @@ class branchcache(object): ) if not bcache.validfor(repo): # invalidate the cache - raise ValueError(r'tip differs') + raise ValueError('tip differs') bcache.load(repo, lineiter) except (IOError, OSError): return None @@ -294,7 +294,7 @@ class branchcache(object): continue node, state, label = line.split(b" ", 2) if state not in b'oc': - raise ValueError(r'invalid branch state') + raise ValueError('invalid branch state') label = encoding.tolocal(label.strip()) node = bin(node) self._entries.setdefault(label, []).append(node) @@ -646,7 +646,7 @@ class revbranchcache(object): # self.branchinfo = self._branchinfo # # Since we now have data in the cache, we need to drop this bypassing. - if r'branchinfo' in vars(self): + if 'branchinfo' in vars(self): del self.branchinfo def _setcachedata(self, rev, node, branchidx): diff --git a/mercurial/bundle2.py b/mercurial/bundle2.py --- a/mercurial/bundle2.py +++ b/mercurial/bundle2.py @@ -837,11 +837,11 @@ class unbundle20(unpackermixin): ignored or failing. """ if not name: - raise ValueError(r'empty parameter name') + raise ValueError('empty parameter name') if name[0:1] not in pycompat.bytestr( string.ascii_letters # pytype: disable=wrong-arg-types ): - raise ValueError(r'non letter first character: %s' % name) + raise ValueError('non letter first character: %s' % name) try: handler = b2streamparamsmap[name.lower()] except KeyError: @@ -1145,8 +1145,8 @@ class bundlepart(object): headerchunk = b''.join(header) except TypeError: raise TypeError( - r'Found a non-bytes trying to ' - r'build bundle part header: %r' % header + 'Found a non-bytes trying to ' + 'build bundle part header: %r' % header ) outdebug(ui, b'header chunk size: %i' % len(headerchunk)) yield _pack(_fpartheadersize, len(headerchunk)) @@ -1797,7 +1797,7 @@ def _formatrequirementsparams(requiremen def addpartbundlestream2(bundler, repo, **kwargs): - if not kwargs.get(r'stream', False): + if not kwargs.get('stream', False): return if not streamclone.allowservergeneration(repo): @@ -1819,8 +1819,8 @@ def addpartbundlestream2(bundler, repo, bundler.prefercompressed = False # get the includes and excludes - includepats = kwargs.get(r'includepats') - excludepats = kwargs.get(r'excludepats') + includepats = kwargs.get('includepats') + excludepats = kwargs.get('excludepats') narrowstream = repo.ui.configbool( b'experimental', b'server.stream-narrow-clones' @@ -1989,7 +1989,7 @@ def handlechangegroup(op, inpart): extrakwargs = {} targetphase = inpart.params.get(b'targetphase') if targetphase is not None: - extrakwargs[r'targetphase'] = int(targetphase) + extrakwargs['targetphase'] = int(targetphase) ret = _processchangegroup( op, cg, diff --git a/mercurial/bundlerepo.py b/mercurial/bundlerepo.py --- a/mercurial/bundlerepo.py +++ b/mercurial/bundlerepo.py @@ -331,7 +331,7 @@ class bundlerepository(object): fdtemp, temp = self.vfs.mkstemp(prefix=b"hg-bundle-", suffix=suffix) self.tempfile = temp - with os.fdopen(fdtemp, r'wb') as fptemp: + with os.fdopen(fdtemp, 'wb') as fptemp: fptemp.write(header) while True: chunk = readfn(2 ** 18) @@ -393,7 +393,7 @@ class bundlerepository(object): # manifestlog implementation did not consume the manifests from the # changegroup (ex: it might be consuming trees from a separate bundle2 # part instead). So we need to manually consume it. - if r'filestart' not in self.__dict__: + if 'filestart' not in self.__dict__: self._consumemanifest() return self.filestart diff --git a/mercurial/changelog.py b/mercurial/changelog.py --- a/mercurial/changelog.py +++ b/mercurial/changelog.py @@ -211,10 +211,10 @@ class changelogrevision(object): """ __slots__ = ( - r'_offsets', - r'_text', - r'_sidedata', - r'_cpsd', + '_offsets', + '_text', + '_sidedata', + '_cpsd', ) def __new__(cls, text, sidedata, cpsd): diff --git a/mercurial/chgserver.py b/mercurial/chgserver.py --- a/mercurial/chgserver.py +++ b/mercurial/chgserver.py @@ -345,9 +345,9 @@ class channeledsystem(object): _iochannels = [ # server.ch, ui.fp, mode - (b'cin', b'fin', r'rb'), - (b'cout', b'fout', r'wb'), - (b'cerr', b'ferr', r'wb'), + (b'cin', b'fin', 'rb'), + (b'cout', b'fout', 'wb'), + (b'cerr', b'ferr', 'wb'), ] diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py --- a/mercurial/cmdutil.py +++ b/mercurial/cmdutil.py @@ -320,7 +320,7 @@ def parsealiases(cmd): def setupwrapcolorwrite(ui): # wrap ui.write so diff output can be labeled/colorized def wrapwrite(orig, *args, **kw): - label = kw.pop(r'label', b'') + label = kw.pop('label', b'') for chunk, l in patch.difflabel(lambda: args): orig(chunk, label=label + l) @@ -2397,7 +2397,7 @@ def add(ui, repo, match, prefix, uipathf submatch = matchmod.subdirmatcher(subpath, match) subprefix = repo.wvfs.reljoin(prefix, subpath) subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn) - if opts.get(r'subrepos'): + if opts.get('subrepos'): bad.extend( sub.add(ui, submatch, subprefix, subuipathfn, False, **opts) ) @@ -2410,7 +2410,7 @@ def add(ui, repo, match, prefix, uipathf _(b"skipping missing subrepository: %s\n") % uipathfn(subpath) ) - if not opts.get(r'dry_run'): + if not opts.get('dry_run'): rejected = wctx.add(names, prefix) bad.extend(f for f in rejected if f in match.files()) return bad diff --git a/mercurial/color.py b/mercurial/color.py --- a/mercurial/color.py +++ b/mercurial/color.py @@ -184,7 +184,7 @@ def _terminfosetup(ui, mode, formatted): # noisy and use ui.debug(). ui.debug(b"no terminfo entry for %s\n" % e) del ui._terminfoparams[key] - if not curses.tigetstr(r'setaf') or not curses.tigetstr(r'setab'): + if not curses.tigetstr('setaf') or not curses.tigetstr('setab'): # Only warn about missing terminfo entries if we explicitly asked for # terminfo mode and we're in a formatted terminal. if mode == b"terminfo" and formatted: @@ -353,9 +353,9 @@ def _effect_str(ui, effect): else: return curses.tigetstr(pycompat.sysstr(val)) elif bg: - return curses.tparm(curses.tigetstr(r'setab'), val) + return curses.tparm(curses.tigetstr('setab'), val) else: - return curses.tparm(curses.tigetstr(r'setaf'), val) + return curses.tparm(curses.tigetstr('setaf'), val) def _mergeeffects(text, start, stop): @@ -442,23 +442,23 @@ if pycompat.iswindows: _INVALID_HANDLE_VALUE = -1 class _COORD(ctypes.Structure): - _fields_ = [(r'X', ctypes.c_short), (r'Y', ctypes.c_short)] + _fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)] class _SMALL_RECT(ctypes.Structure): _fields_ = [ - (r'Left', ctypes.c_short), - (r'Top', ctypes.c_short), - (r'Right', ctypes.c_short), - (r'Bottom', ctypes.c_short), + ('Left', ctypes.c_short), + ('Top', ctypes.c_short), + ('Right', ctypes.c_short), + ('Bottom', ctypes.c_short), ] class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure): _fields_ = [ - (r'dwSize', _COORD), - (r'dwCursorPosition', _COORD), - (r'wAttributes', _WORD), - (r'srWindow', _SMALL_RECT), - (r'dwMaximumWindowSize', _COORD), + ('dwSize', _COORD), + ('dwCursorPosition', _COORD), + ('wAttributes', _WORD), + ('srWindow', _SMALL_RECT), + ('dwMaximumWindowSize', _COORD), ] _STD_OUTPUT_HANDLE = 0xFFFFFFF5 # (DWORD)-11 @@ -529,7 +529,7 @@ if pycompat.iswindows: ) def win32print(ui, writefunc, text, **opts): - label = opts.get(r'label', b'') + label = opts.get('label', b'') attr = origattr def mapcolor(val, attr): diff --git a/mercurial/commands.py b/mercurial/commands.py --- a/mercurial/commands.py +++ b/mercurial/commands.py @@ -180,7 +180,7 @@ def abort(ui, repo, **opts): use --dry-run/-n to dry run the command. """ - dryrun = opts.get(r'dry_run') + dryrun = opts.get('dry_run') abortstate = cmdutil.getunfinishedstate(repo) if not abortstate: raise error.Abort(_(b'no operation in progress')) @@ -2019,8 +2019,8 @@ def commit(ui, repo, *pats, **opts): def _docommit(ui, repo, *pats, **opts): - if opts.get(r'interactive'): - opts.pop(r'interactive') + if opts.get('interactive'): + opts.pop('interactive') ret = cmdutil.dorecord( ui, repo, commit, None, False, cmdutil.recordfilter, *pats, **opts ) @@ -2295,7 +2295,7 @@ def continuecmd(ui, repo, **opts): use --dry-run/-n to dry run the command. """ - dryrun = opts.get(r'dry_run') + dryrun = opts.get('dry_run') contstate = cmdutil.getunfinishedstate(repo) if not contstate: raise error.Abort(_(b'no operation in progress')) @@ -2375,7 +2375,7 @@ def debugcommands(ui, cmd=b'', *args): def debugcomplete(ui, cmd=b'', **opts): """returns the completion list associated with the given command""" - if opts.get(r'options'): + if opts.get('options'): options = [] otables = [globalopts] if cmd: @@ -3456,13 +3456,13 @@ def grep(ui, repo, pattern, *pats, **opt def difflinestates(a, b): sm = difflib.SequenceMatcher(None, a, b) for tag, alo, ahi, blo, bhi in sm.get_opcodes(): - if tag == r'insert': + if tag == 'insert': for i in pycompat.xrange(blo, bhi): yield (b'+', b[i]) - elif tag == r'delete': + elif tag == 'delete': for i in pycompat.xrange(alo, ahi): yield (b'-', a[i]) - elif tag == r'replace': + elif tag == 'replace': for i in pycompat.xrange(alo, ahi): yield (b'-', a[i]) for i in pycompat.xrange(blo, bhi): @@ -3789,7 +3789,7 @@ def help_(ui, name=None, **opts): Returns 0 if successful. """ - keep = opts.get(r'system') or [] + keep = opts.get('system') or [] if len(keep) == 0: if pycompat.sysplatform.startswith(b'win'): keep.append(b'windows') @@ -5699,7 +5699,7 @@ def recover(ui, repo, **opts): """ ret = repo.recover() if ret: - if opts[r'verify']: + if opts['verify']: return hg.verify(repo) else: msg = _( @@ -6344,7 +6344,7 @@ def rollback(ui, repo, **opts): _(b'rollback is disabled because it is unsafe'), hint=b'see `hg help -v rollback` for information', ) - return repo.rollback(dryrun=opts.get(r'dry_run'), force=opts.get(r'force')) + return repo.rollback(dryrun=opts.get('dry_run'), force=opts.get('force')) @command( @@ -7494,7 +7494,7 @@ def unbundle(ui, repo, fname1, *fnames, ) modheads = bundle2.combinechangegroupresults(op) - return postincoming(ui, repo, modheads, opts.get(r'update'), None, None) + return postincoming(ui, repo, modheads, opts.get('update'), None, None) @command( @@ -7655,11 +7655,11 @@ def update(ui, repo, node=None, **opts): Returns 0 on success, 1 if there are unresolved files. """ - rev = opts.get(r'rev') - date = opts.get(r'date') - clean = opts.get(r'clean') - check = opts.get(r'check') - merge = opts.get(r'merge') + rev = opts.get('rev') + date = opts.get('date') + clean = opts.get('clean') + check = opts.get('check') + merge = opts.get('merge') if rev and node: raise error.Abort(_(b"please specify just one revision")) @@ -7702,7 +7702,7 @@ def update(ui, repo, node=None, **opts): ctx = scmutil.revsingle(repo, rev, default=None) rev = ctx.rev() hidden = ctx.hidden() - overrides = {(b'ui', b'forcemerge'): opts.get(r'tool', b'')} + overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')} with ui.configoverride(overrides, b'update'): ret = hg.updatetotally( ui, repo, rev, brev, clean=clean, updatecheck=updatecheck diff --git a/mercurial/commandserver.py b/mercurial/commandserver.py --- a/mercurial/commandserver.py +++ b/mercurial/commandserver.py @@ -64,7 +64,7 @@ class channeledoutput(object): self.out.flush() def __getattr__(self, attr): - if attr in (r'isatty', r'fileno', r'tell', r'seek'): + if attr in ('isatty', 'fileno', 'tell', 'seek'): raise AttributeError(attr) return getattr(self.out, attr) @@ -180,7 +180,7 @@ class channeledinput(object): __next__ = next def __getattr__(self, attr): - if attr in (r'isatty', r'fileno', r'tell', r'seek'): + if attr in ('isatty', 'fileno', 'tell', 'seek'): raise AttributeError(attr) return getattr(self.in_, attr) @@ -450,8 +450,8 @@ def _initworkerprocess(): def _serverequest(ui, repo, conn, createcmdserver, prereposetups): - fin = conn.makefile(r'rb') - fout = conn.makefile(r'wb') + fin = conn.makefile('rb') + fout = conn.makefile('wb') sv = None try: sv = createcmdserver(repo, conn, fin, fout, prereposetups) diff --git a/mercurial/config.py b/mercurial/config.py --- a/mercurial/config.py +++ b/mercurial/config.py @@ -212,7 +212,7 @@ class config(object): def read(self, path, fp=None, sections=None, remap=None): if not fp: fp = util.posixfile(path, b'rb') - assert getattr(fp, 'mode', r'rb') == r'rb', ( + assert getattr(fp, 'mode', 'rb') == 'rb', ( b'config files must be opened in binary mode, got fp=%r mode=%r' % (fp, fp.mode,) ) diff --git a/mercurial/context.py b/mercurial/context.py --- a/mercurial/context.py +++ b/mercurial/context.py @@ -265,14 +265,14 @@ class basectx(object): return self._repo[nullrev] def _fileinfo(self, path): - if r'_manifest' in self.__dict__: + if '_manifest' in self.__dict__: try: return self._manifest[path], self._manifest.flags(path) except KeyError: raise error.ManifestLookupError( self._node, path, _(b'not found in manifest') ) - if r'_manifestdelta' in self.__dict__ or path in self.files(): + if '_manifestdelta' in self.__dict__ or path in self.files(): if path in self._manifestdelta: return ( self._manifestdelta[path], @@ -746,9 +746,9 @@ class basefilectx(object): @propertycache def _changeid(self): - if r'_changectx' in self.__dict__: + if '_changectx' in self.__dict__: return self._changectx.rev() - elif r'_descendantrev' in self.__dict__: + elif '_descendantrev' in self.__dict__: # this file context was created from a revision with a known # descendant, we can (lazily) correct for linkrev aliases return self._adjustlinkrev(self._descendantrev) @@ -757,7 +757,7 @@ class basefilectx(object): @propertycache def _filenode(self): - if r'_fileid' in self.__dict__: + if '_fileid' in self.__dict__: return self._filelog.lookup(self._fileid) else: return self._changectx.filenode(self._path) @@ -1024,16 +1024,16 @@ class basefilectx(object): """ toprev = None attrs = vars(self) - if r'_changeid' in attrs: + if '_changeid' in attrs: # We have a cached value already toprev = self._changeid - elif r'_changectx' in attrs: + elif '_changectx' in attrs: # We know which changelog entry we are coming from toprev = self._changectx.rev() if toprev is not None: return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev) - elif r'_descendantrev' in attrs: + elif '_descendantrev' in attrs: introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev) # be nice and cache the result of the computation if introrev is not None: @@ -1053,14 +1053,14 @@ class basefilectx(object): def _parentfilectx(self, path, fileid, filelog): """create parent filectx keeping ancestry info for _adjustlinkrev()""" fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog) - if r'_changeid' in vars(self) or r'_changectx' in vars(self): + if '_changeid' in vars(self) or '_changectx' in vars(self): # If self is associated with a changeset (probably explicitly # fed), ensure the created filectx is associated with a # changeset that is an ancestor of self.changectx. # This lets us later use _adjustlinkrev to get a correct link. fctx._descendantrev = self.rev() fctx._ancestrycontext = getattr(self, '_ancestrycontext', None) - elif r'_descendantrev' in vars(self): + elif '_descendantrev' in vars(self): # Otherwise propagate _descendantrev if we have one associated. fctx._descendantrev = self._descendantrev fctx._ancestrycontext = getattr(self, '_ancestrycontext', None) @@ -1120,7 +1120,7 @@ class basefilectx(object): # renamed filectx won't have a filelog yet, so set it # from the cache to save time for p in pl: - if not r'_filelog' in p.__dict__: + if not '_filelog' in p.__dict__: p._filelog = getlog(p.path()) return pl @@ -1534,7 +1534,7 @@ class workingctx(committablectx): return self._repo.dirstate.flagfunc(self._buildflagfunc) def flags(self, path): - if r'_manifest' in self.__dict__: + if '_manifest' in self.__dict__: try: return self._manifest.flags(path) except KeyError: diff --git a/mercurial/crecord.py b/mercurial/crecord.py --- a/mercurial/crecord.py +++ b/mercurial/crecord.py @@ -522,7 +522,7 @@ class uihunk(patchnode): return getattr(self._hunk, name) def __repr__(self): - return r'' % (self.filename(), self.fromline) + return '' % (self.filename(), self.fromline) def filterpatch(ui, chunks, chunkselector, operation=None): @@ -569,7 +569,7 @@ def chunkselector(ui, headerlist, operat chunkselector = curseschunkselector(headerlist, ui, operation) # This is required for ncurses to display non-ASCII characters in # default user locale encoding correctly. --immerrr - locale.setlocale(locale.LC_ALL, r'') + locale.setlocale(locale.LC_ALL, '') origsigtstp = sentinel = object() if util.safehasattr(signal, b'SIGTSTP'): origsigtstp = signal.getsignal(signal.SIGTSTP) diff --git a/mercurial/debugcommands.py b/mercurial/debugcommands.py --- a/mercurial/debugcommands.py +++ b/mercurial/debugcommands.py @@ -393,7 +393,7 @@ def _debugbundle2(ui, gen, all=None, **o if not isinstance(gen, bundle2.unbundle20): raise error.Abort(_(b'not a bundle2 file')) ui.write((b'Stream params: %s\n' % _quasirepr(gen.params))) - parttypes = opts.get(r'part_type', []) + parttypes = opts.get('part_type', []) for part in gen.iterparts(): if parttypes and part.type not in parttypes: continue @@ -492,7 +492,7 @@ def debugcheckstate(ui, repo): def debugcolor(ui, repo, **opts): """show available color, effects or style""" ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode)) - if opts.get(r'style'): + if opts.get('style'): return _debugdisplaystyle(ui) else: return _debugdisplaycolor(ui) @@ -573,8 +573,8 @@ def debugdag(ui, repo, file_=None, *revs Otherwise, the changelog DAG of the current repo is emitted. """ - spaces = opts.get(r'spaces') - dots = opts.get(r'dots') + spaces = opts.get('spaces') + dots = opts.get('dots') if file_: rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_) revs = set((int(r) for r in revs)) @@ -587,8 +587,8 @@ def debugdag(ui, repo, file_=None, *revs elif repo: cl = repo.changelog - tags = opts.get(r'tags') - branches = opts.get(r'branches') + tags = opts.get('tags') + branches = opts.get('branches') if tags: labels = {} for l, n in repo.tags().items(): @@ -861,10 +861,10 @@ def debugdeltachain(ui, repo, file_=None def debugstate(ui, repo, **opts): """show the contents of the current dirstate""" - nodates = not opts[r'dates'] - if opts.get(r'nodates') is not None: + nodates = not opts['dates'] + if opts.get('nodates') is not None: nodates = True - datesort = opts.get(r'datesort') + datesort = opts.get('datesort') if datesort: keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename @@ -1298,11 +1298,11 @@ def debuggetbundle(ui, repopath, bundlep raise error.Abort(b"getbundle() not supported by target repository") args = {} if common: - args[r'common'] = [bin(s) for s in common] + args['common'] = [bin(s) for s in common] if head: - args[r'heads'] = [bin(s) for s in head] + args['heads'] = [bin(s) for s in head] # TODO: get desired bundlecaps from command line. - args[r'bundlecaps'] = None + args['bundlecaps'] = None bundle = repo.getbundle(b'debug', **args) bundletype = opts.get(b'type', b'bzip2').lower() @@ -1775,21 +1775,21 @@ def debuglocks(ui, repo, **opts): """ - if opts.get(r'force_lock'): + if opts.get('force_lock'): repo.svfs.unlink(b'lock') - if opts.get(r'force_wlock'): + if opts.get('force_wlock'): repo.vfs.unlink(b'wlock') - if opts.get(r'force_lock') or opts.get(r'force_wlock'): + if opts.get('force_lock') or opts.get('force_wlock'): return 0 locks = [] try: - if opts.get(r'set_wlock'): + if opts.get('set_wlock'): try: locks.append(repo.wlock(False)) except error.LockHeld: raise error.Abort(_(b'wlock is already held')) - if opts.get(r'set_lock'): + if opts.get('set_lock'): try: locks.append(repo.lock(False)) except error.LockHeld: @@ -1871,7 +1871,7 @@ def debugmanifestfulltextcache(ui, repo, ) raise error.Abort(msg) - if opts.get(r'clear'): + if opts.get('clear'): with repo.wlock(): cache = getcache() cache.clear(clear_persisted_data=True) @@ -2265,7 +2265,7 @@ def debugpathcomplete(ui, repo, *specs, if fixpaths: spec = spec.replace(pycompat.ossep, b'/') speclen = len(spec) - fullpaths = opts[r'full'] + fullpaths = opts['full'] files, dirs = set(), set() adddir, addfile = dirs.add, files.add for f, st in pycompat.iteritems(dirstate): @@ -2283,11 +2283,11 @@ def debugpathcomplete(ui, repo, *specs, return files, dirs acceptable = b'' - if opts[r'normal']: + if opts['normal']: acceptable += b'nm' - if opts[r'added']: + if opts['added']: acceptable += b'a' - if opts[r'removed']: + if opts['removed']: acceptable += b'r' cwd = repo.getcwd() if not specs: @@ -2526,7 +2526,7 @@ def debugrebuilddirstate(ui, repo, rev, dirstate = repo.dirstate changedfiles = None # See command doc for what minimal does. - if opts.get(r'minimal'): + if opts.get('minimal'): manifestfiles = set(ctx.manifest().keys()) dirstatefiles = set(dirstate) manifestonly = manifestfiles - dirstatefiles @@ -3147,13 +3147,13 @@ def debugrevspec(ui, repo, expr, **opts) ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b') sm = difflib.SequenceMatcher(None, arevs, brevs) for tag, alo, ahi, blo, bhi in sm.get_opcodes(): - if tag in (r'delete', r'replace'): + if tag in ('delete', 'replace'): for c in arevs[alo:ahi]: ui.write(b'-%d\n' % c, label=b'diff.deleted') - if tag in (r'insert', r'replace'): + if tag in ('insert', 'replace'): for c in brevs[blo:bhi]: ui.write(b'+%d\n' % c, label=b'diff.inserted') - if tag == r'equal': + if tag == 'equal': for c in arevs[alo:ahi]: ui.write(b' %d\n' % c) return 1 @@ -3202,12 +3202,12 @@ def debugserve(ui, repo, **opts): if opts[b'logiofd']: # Line buffered because output is line based. try: - logfh = os.fdopen(int(opts[b'logiofd']), r'ab', 1) + logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 1) except OSError as e: if e.errno != errno.ESPIPE: raise # can't seek a pipe, so `ab` mode fails on py3 - logfh = os.fdopen(int(opts[b'logiofd']), r'wb', 1) + logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 1) elif opts[b'logiofile']: logfh = open(opts[b'logiofile'], b'ab', 1) @@ -3391,7 +3391,7 @@ def debugsuccessorssets(ui, repo, *revs, ctx = repo[rev] ui.write(b'%s\n' % ctx2str(ctx)) for succsset in obsutil.successorssets( - repo, ctx.node(), closest=opts[r'closest'], cache=cache + repo, ctx.node(), closest=opts['closest'], cache=cache ): if succsset: ui.write(b' ') @@ -3421,15 +3421,15 @@ def debugtemplate(ui, repo, tmpl, **opts Use --verbose to print the parsed tree. """ revs = None - if opts[r'rev']: + if opts['rev']: if repo is None: raise error.RepoError( _(b'there is no Mercurial repository here (.hg not found)') ) - revs = scmutil.revrange(repo, opts[r'rev']) + revs = scmutil.revrange(repo, opts['rev']) props = {} - for d in opts[r'define']: + for d in opts['define']: try: k, v = (e.strip() for e in d.split(b'=', 1)) if not k or k == b'ui': @@ -3985,27 +3985,27 @@ def debugwireproto(ui, repo, path=None, url, authinfo = u.authinfo() openerargs = { - r'useragent': b'Mercurial debugwireproto', + 'useragent': b'Mercurial debugwireproto', } # Turn pipes/sockets into observers so we can log I/O. if ui.verbose: openerargs.update( { - r'loggingfh': ui, - r'loggingname': b's', - r'loggingopts': {r'logdata': True, r'logdataapis': False,}, + 'loggingfh': ui, + 'loggingname': b's', + 'loggingopts': {'logdata': True, 'logdataapis': False,}, } ) if ui.debugflag: - openerargs[r'loggingopts'][r'logdataapis'] = True + openerargs['loggingopts']['logdataapis'] = True # Don't send default headers when in raw mode. This allows us to # bypass most of the behavior of our URL handling code so we can # have near complete control over what's sent on the wire. if opts[b'peer'] == b'raw': - openerargs[r'sendaccept'] = False + openerargs['sendaccept'] = False opener = urlmod.opener(ui, authinfo, **openerargs) @@ -4105,7 +4105,7 @@ def debugwireproto(ui, repo, path=None, ui.status(_(b'sending %s command\n') % command) if b'PUSHFILE' in args: - with open(args[b'PUSHFILE'], r'rb') as fh: + with open(args[b'PUSHFILE'], 'rb') as fh: del args[b'PUSHFILE'] res, output = peer._callpush( command, fh, **pycompat.strkwargs(args) @@ -4213,8 +4213,8 @@ def debugwireproto(ui, repo, path=None, getattr(e, 'read', lambda: None)() continue - ct = res.headers.get(r'Content-Type') - if ct == r'application/mercurial-cbor': + ct = res.headers.get('Content-Type') + if ct == 'application/mercurial-cbor': ui.write( _(b'cbor> %s\n') % stringutil.pprint( diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py --- a/mercurial/dirstate.py +++ b/mercurial/dirstate.py @@ -36,8 +36,8 @@ from .interfaces import ( util as interfaceutil, ) -parsers = policy.importmod(r'parsers') -rustmod = policy.importrust(r'dirstate') +parsers = policy.importmod('parsers') +rustmod = policy.importrust('dirstate') propertycache = util.propertycache filecache = scmutil.filecache diff --git a/mercurial/dispatch.py b/mercurial/dispatch.py --- a/mercurial/dispatch.py +++ b/mercurial/dispatch.py @@ -658,10 +658,10 @@ class cmdalias(object): def __getattr__(self, name): adefaults = { - r'norepo': True, - r'intents': set(), - r'optionalrepo': False, - r'inferrepo': False, + 'norepo': True, + 'intents': set(), + 'optionalrepo': False, + 'inferrepo': False, } if name not in adefaults: raise AttributeError(name) diff --git a/mercurial/encoding.py b/mercurial/encoding.py --- a/mercurial/encoding.py +++ b/mercurial/encoding.py @@ -37,7 +37,7 @@ if not globals(): # hide this from non- _Tlocalstr = TypeVar('_Tlocalstr', bound=localstr) -charencode = policy.importmod(r'charencode') +charencode = policy.importmod('charencode') isasciistr = charencode.isasciistr asciilower = charencode.asciilower @@ -87,7 +87,7 @@ else: # preferred encoding isn't known yet; use utf-8 to avoid unicode error # and recreate it once encoding is settled environ = dict( - (k.encode(r'utf-8'), v.encode(r'utf-8')) + (k.encode('utf-8'), v.encode('utf-8')) for k, v in os.environ.items() # re-exports ) @@ -280,7 +280,7 @@ if not _nativeenviron: # now encoding and helper functions are available, recreate the environ # dict to be exported to other modules environ = dict( - (tolocal(k.encode(r'utf-8')), tolocal(v.encode(r'utf-8'))) + (tolocal(k.encode('utf-8')), tolocal(v.encode('utf-8'))) for k, v in os.environ.items() # re-exports ) @@ -307,7 +307,7 @@ else: def colwidth(s): # type: (bytes) -> int b"Find the column width of a string for display in the local encoding" - return ucolwidth(s.decode(_sysstr(encoding), r'replace')) + return ucolwidth(s.decode(_sysstr(encoding), 'replace')) def ucolwidth(d): diff --git a/mercurial/error.py b/mercurial/error.py --- a/mercurial/error.py +++ b/mercurial/error.py @@ -34,7 +34,7 @@ class Hint(object): """ def __init__(self, *args, **kw): - self.hint = kw.pop(r'hint', None) + self.hint = kw.pop('hint', None) super(Hint, self).__init__(*args, **kw) diff --git a/mercurial/exchange.py b/mercurial/exchange.py --- a/mercurial/exchange.py +++ b/mercurial/exchange.py @@ -2197,8 +2197,8 @@ def applynarrowacl(repo, kwargs): b'path:.' if p == b'*' else b'path:' + p for p in user_excludes ] - req_includes = set(kwargs.get(r'includepats', [])) - req_excludes = set(kwargs.get(r'excludepats', [])) + req_includes = set(kwargs.get('includepats', [])) + req_excludes = set(kwargs.get('excludepats', [])) req_includes, req_excludes, invalid_includes = narrowspec.restrictpatterns( req_includes, req_excludes, user_includes, user_excludes @@ -2213,11 +2213,11 @@ def applynarrowacl(repo, kwargs): new_args = {} new_args.update(kwargs) - new_args[r'narrow'] = True - new_args[r'narrow_acl'] = True - new_args[r'includepats'] = req_includes + new_args['narrow'] = True + new_args['narrow_acl'] = True + new_args['includepats'] = req_includes if req_excludes: - new_args[r'excludepats'] = req_excludes + new_args['excludepats'] = req_excludes return new_args @@ -2480,7 +2480,7 @@ def _getbundlechangegrouppart( **kwargs ): """add a changegroup part to the requested bundle""" - if not kwargs.get(r'cg', True): + if not kwargs.get('cg', True): return version = b'01' @@ -2499,9 +2499,9 @@ def _getbundlechangegrouppart( if not outgoing.missing: return - if kwargs.get(r'narrow', False): - include = sorted(filter(bool, kwargs.get(r'includepats', []))) - exclude = sorted(filter(bool, kwargs.get(r'excludepats', []))) + if kwargs.get('narrow', False): + include = sorted(filter(bool, kwargs.get('includepats', []))) + exclude = sorted(filter(bool, kwargs.get('excludepats', []))) matcher = narrowspec.match(repo.root, include=include, exclude=exclude) else: matcher = None @@ -2523,8 +2523,8 @@ def _getbundlechangegrouppart( part.addparam(b'exp-sidedata', b'1') if ( - kwargs.get(r'narrow', False) - and kwargs.get(r'narrow_acl', False) + kwargs.get('narrow', False) + and kwargs.get('narrow_acl', False) and (include or exclude) ): # this is mandatory because otherwise ACL clients won't work @@ -2540,7 +2540,7 @@ def _getbundlebookmarkpart( bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs ): """add a bookmark part to the requested bundle""" - if not kwargs.get(r'bookmarks', False): + if not kwargs.get('bookmarks', False): return if b'bookmarks' not in b2caps: raise error.Abort(_(b'no common bookmarks exchange method')) @@ -2555,7 +2555,7 @@ def _getbundlelistkeysparts( bundler, repo, source, bundlecaps=None, b2caps=None, **kwargs ): """add parts containing listkeys namespaces to the requested bundle""" - listkeys = kwargs.get(r'listkeys', ()) + listkeys = kwargs.get('listkeys', ()) for namespace in listkeys: part = bundler.newpart(b'listkeys') part.addparam(b'namespace', namespace) @@ -2568,7 +2568,7 @@ def _getbundleobsmarkerpart( bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs ): """add an obsolescence markers part to the requested bundle""" - if kwargs.get(r'obsmarkers', False): + if kwargs.get('obsmarkers', False): if heads is None: heads = repo.heads() subset = [c.node() for c in repo.set(b'::%ln', heads)] @@ -2582,7 +2582,7 @@ def _getbundlephasespart( bundler, repo, source, bundlecaps=None, b2caps=None, heads=None, **kwargs ): """add phase heads part to the requested bundle""" - if kwargs.get(r'phases', False): + if kwargs.get('phases', False): if not b'heads' in b2caps.get(b'phases'): raise error.Abort(_(b'no common phases exchange method')) if heads is None: @@ -2647,7 +2647,7 @@ def _getbundletagsfnodes( # Don't send unless: # - changeset are being exchanged, # - the client supports it. - if not (kwargs.get(r'cg', True) and b'hgtagsfnodes' in b2caps): + if not (kwargs.get('cg', True) and b'hgtagsfnodes' in b2caps): return outgoing = _computeoutgoing(repo, heads, common) @@ -2680,9 +2680,9 @@ def _getbundlerevbranchcache( # - the client supports it. # - narrow bundle isn't in play (not currently compatible). if ( - not kwargs.get(r'cg', True) + not kwargs.get('cg', True) or b'rev-branch-cache' not in b2caps - or kwargs.get(r'narrow', False) + or kwargs.get('narrow', False) or repo.ui.has_section(_NARROWACL_SECTION) ): return diff --git a/mercurial/extensions.py b/mercurial/extensions.py --- a/mercurial/extensions.py +++ b/mercurial/extensions.py @@ -834,7 +834,7 @@ def _walkcommand(node): continue if not isinstance(d.func, ast.Name): continue - if d.func.id != r'command': + if d.func.id != 'command': continue yield d diff --git a/mercurial/help.py b/mercurial/help.py --- a/mercurial/help.py +++ b/mercurial/help.py @@ -805,7 +805,7 @@ def help_( appendcmds(catfns) ex = opts.get - anyopts = ex(r'keyword') or not (ex(r'command') or ex(r'extension')) + anyopts = ex('keyword') or not (ex('command') or ex('extension')) if not name and anyopts: exts = listexts( _(b'enabled extensions:'), diff --git a/mercurial/hgweb/__init__.py b/mercurial/hgweb/__init__.py --- a/mercurial/hgweb/__init__.py +++ b/mercurial/hgweb/__init__.py @@ -77,19 +77,19 @@ class httpservice(object): else: prefix = b'' - port = r':%d' % self.httpd.port - if port == r':80': - port = r'' + port = ':%d' % self.httpd.port + if port == ':80': + port = '' bindaddr = self.httpd.addr - if bindaddr == r'0.0.0.0': - bindaddr = r'*' - elif r':' in bindaddr: # IPv6 - bindaddr = r'[%s]' % bindaddr + if bindaddr == '0.0.0.0': + bindaddr = '*' + elif ':' in bindaddr: # IPv6 + bindaddr = '[%s]' % bindaddr fqaddr = self.httpd.fqaddr - if r':' in fqaddr: - fqaddr = r'[%s]' % fqaddr + if ':' in fqaddr: + fqaddr = '[%s]' % fqaddr url = b'http://%s%s/%s' % ( pycompat.sysbytes(fqaddr), diff --git a/mercurial/hgweb/common.py b/mercurial/hgweb/common.py --- a/mercurial/hgweb/common.py +++ b/mercurial/hgweb/common.py @@ -143,9 +143,7 @@ class continuereader(object): def _statusmessage(code): responses = httpserver.basehttprequesthandler.responses - return pycompat.bytesurl( - responses.get(code, (r'Error', r'Unknown error'))[0] - ) + return pycompat.bytesurl(responses.get(code, ('Error', 'Unknown error'))[0]) def statusmessage(code, message=None): diff --git a/mercurial/hgweb/server.py b/mercurial/hgweb/server.py --- a/mercurial/hgweb/server.py +++ b/mercurial/hgweb/server.py @@ -43,8 +43,8 @@ def _splitURI(uri): Just like CGI environment, the path is unquoted, the query is not. """ - if r'?' in uri: - path, query = uri.split(r'?', 1) + if '?' in uri: + path, query = uri.split('?', 1) else: path, query = uri, r'' return urlreq.unquote(path), query @@ -97,18 +97,18 @@ class _httprequesthandler(httpservermod. def log_message(self, format, *args): self._log_any(self.server.accesslog, format, *args) - def log_request(self, code=r'-', size=r'-'): + def log_request(self, code='-', size='-'): xheaders = [] if util.safehasattr(self, b'headers'): xheaders = [ - h for h in self.headers.items() if h[0].startswith(r'x-') + h for h in self.headers.items() if h[0].startswith('x-') ] self.log_message( - r'"%s" %s %s%s', + '"%s" %s %s%s', self.requestline, str(code), str(size), - r''.join([r' %s:%s' % h for h in sorted(xheaders)]), + ''.join([' %s:%s' % h for h in sorted(xheaders)]), ) def do_write(self): @@ -160,72 +160,72 @@ class _httprequesthandler(httpservermod. self.server.prefix + b'/' ): self._start_response(pycompat.strurl(common.statusmessage(404)), []) - if self.command == r'POST': + if self.command == 'POST': # Paranoia: tell the client we're going to close the # socket so they don't try and reuse a socket that # might have a POST body waiting to confuse us. We do # this by directly munging self.saved_headers because # self._start_response ignores Connection headers. - self.saved_headers = [(r'Connection', r'Close')] + self.saved_headers = [('Connection', 'Close')] self._write(b"Not Found") self._done() return env = {} - env[r'GATEWAY_INTERFACE'] = r'CGI/1.1' - env[r'REQUEST_METHOD'] = self.command - env[r'SERVER_NAME'] = self.server.server_name - env[r'SERVER_PORT'] = str(self.server.server_port) - env[r'REQUEST_URI'] = self.path - env[r'SCRIPT_NAME'] = pycompat.sysstr(self.server.prefix) - env[r'PATH_INFO'] = pycompat.sysstr(path[len(self.server.prefix) :]) - env[r'REMOTE_HOST'] = self.client_address[0] - env[r'REMOTE_ADDR'] = self.client_address[0] - env[r'QUERY_STRING'] = query or r'' + env['GATEWAY_INTERFACE'] = 'CGI/1.1' + env['REQUEST_METHOD'] = self.command + env['SERVER_NAME'] = self.server.server_name + env['SERVER_PORT'] = str(self.server.server_port) + env['REQUEST_URI'] = self.path + env['SCRIPT_NAME'] = pycompat.sysstr(self.server.prefix) + env['PATH_INFO'] = pycompat.sysstr(path[len(self.server.prefix) :]) + env['REMOTE_HOST'] = self.client_address[0] + env['REMOTE_ADDR'] = self.client_address[0] + env['QUERY_STRING'] = query or '' if pycompat.ispy3: if self.headers.get_content_type() is None: - env[r'CONTENT_TYPE'] = self.headers.get_default_type() + env['CONTENT_TYPE'] = self.headers.get_default_type() else: - env[r'CONTENT_TYPE'] = self.headers.get_content_type() - length = self.headers.get(r'content-length') + env['CONTENT_TYPE'] = self.headers.get_content_type() + length = self.headers.get('content-length') else: if self.headers.typeheader is None: - env[r'CONTENT_TYPE'] = self.headers.type + env['CONTENT_TYPE'] = self.headers.type else: - env[r'CONTENT_TYPE'] = self.headers.typeheader - length = self.headers.getheader(r'content-length') + env['CONTENT_TYPE'] = self.headers.typeheader + length = self.headers.getheader('content-length') if length: - env[r'CONTENT_LENGTH'] = length + env['CONTENT_LENGTH'] = length for header in [ h for h in self.headers.keys() - if h.lower() not in (r'content-type', r'content-length') + if h.lower() not in ('content-type', 'content-length') ]: - hkey = r'HTTP_' + header.replace(r'-', r'_').upper() + hkey = 'HTTP_' + header.replace('-', '_').upper() hval = self.headers.get(header) - hval = hval.replace(r'\n', r'').strip() + hval = hval.replace('\n', '').strip() if hval: env[hkey] = hval - env[r'SERVER_PROTOCOL'] = self.request_version - env[r'wsgi.version'] = (1, 0) - env[r'wsgi.url_scheme'] = pycompat.sysstr(self.url_scheme) - if env.get(r'HTTP_EXPECT', b'').lower() == b'100-continue': + env['SERVER_PROTOCOL'] = self.request_version + env['wsgi.version'] = (1, 0) + env['wsgi.url_scheme'] = pycompat.sysstr(self.url_scheme) + if env.get('HTTP_EXPECT', b'').lower() == b'100-continue': self.rfile = common.continuereader(self.rfile, self.wfile.write) - env[r'wsgi.input'] = self.rfile - env[r'wsgi.errors'] = _error_logger(self) - env[r'wsgi.multithread'] = isinstance( + env['wsgi.input'] = self.rfile + env['wsgi.errors'] = _error_logger(self) + env['wsgi.multithread'] = isinstance( self.server, socketserver.ThreadingMixIn ) if util.safehasattr(socketserver, b'ForkingMixIn'): - env[r'wsgi.multiprocess'] = isinstance( + env['wsgi.multiprocess'] = isinstance( self.server, socketserver.ForkingMixIn ) else: - env[r'wsgi.multiprocess'] = False + env['wsgi.multiprocess'] = False - env[r'wsgi.run_once'] = 0 + env['wsgi.run_once'] = 0 wsgiref.validate.check_environ(env) @@ -251,17 +251,16 @@ class _httprequesthandler(httpservermod. self._chunked = False for h in self.saved_headers: self.send_header(*h) - if h[0].lower() == r'content-length': + if h[0].lower() == 'content-length': self.length = int(h[1]) if self.length is None and saved_status[0] != common.HTTP_NOT_MODIFIED: self._chunked = ( - not self.close_connection - and self.request_version == r'HTTP/1.1' + not self.close_connection and self.request_version == 'HTTP/1.1' ) if self._chunked: - self.send_header(r'Transfer-Encoding', r'chunked') + self.send_header('Transfer-Encoding', 'chunked') else: - self.send_header(r'Connection', r'close') + self.send_header('Connection', 'close') self.end_headers() self.sent_headers = True @@ -270,7 +269,7 @@ class _httprequesthandler(httpservermod. code, msg = http_status.split(None, 1) code = int(code) self.saved_status = http_status - bad_headers = (r'connection', r'transfer-encoding') + bad_headers = ('connection', 'transfer-encoding') self.saved_headers = [ h for h in headers if h[0].lower() not in bad_headers ] diff --git a/mercurial/hgweb/wsgicgi.py b/mercurial/hgweb/wsgicgi.py --- a/mercurial/hgweb/wsgicgi.py +++ b/mercurial/hgweb/wsgicgi.py @@ -25,28 +25,28 @@ def launch(application): procutil.setbinary(procutil.stdout) environ = dict(pycompat.iteritems(os.environ)) # re-exports - environ.setdefault(r'PATH_INFO', b'') - if environ.get(r'SERVER_SOFTWARE', r'').startswith(r'Microsoft-IIS'): + environ.setdefault('PATH_INFO', b'') + if environ.get('SERVER_SOFTWARE', '').startswith('Microsoft-IIS'): # IIS includes script_name in PATH_INFO - scriptname = environ[r'SCRIPT_NAME'] - if environ[r'PATH_INFO'].startswith(scriptname): - environ[r'PATH_INFO'] = environ[r'PATH_INFO'][len(scriptname) :] + scriptname = environ['SCRIPT_NAME'] + if environ['PATH_INFO'].startswith(scriptname): + environ['PATH_INFO'] = environ['PATH_INFO'][len(scriptname) :] stdin = procutil.stdin - if environ.get(r'HTTP_EXPECT', r'').lower() == r'100-continue': + if environ.get('HTTP_EXPECT', '').lower() == '100-continue': stdin = common.continuereader(stdin, procutil.stdout.write) - environ[r'wsgi.input'] = stdin - environ[r'wsgi.errors'] = procutil.stderr - environ[r'wsgi.version'] = (1, 0) - environ[r'wsgi.multithread'] = False - environ[r'wsgi.multiprocess'] = True - environ[r'wsgi.run_once'] = True + environ['wsgi.input'] = stdin + environ['wsgi.errors'] = procutil.stderr + environ['wsgi.version'] = (1, 0) + environ['wsgi.multithread'] = False + environ['wsgi.multiprocess'] = True + environ['wsgi.run_once'] = True - if environ.get(r'HTTPS', r'off').lower() in (r'on', r'1', r'yes'): - environ[r'wsgi.url_scheme'] = r'https' + if environ.get('HTTPS', 'off').lower() in ('on', '1', 'yes'): + environ['wsgi.url_scheme'] = 'https' else: - environ[r'wsgi.url_scheme'] = r'http' + environ['wsgi.url_scheme'] = 'http' headers_set = [] headers_sent = [] diff --git a/mercurial/httppeer.py b/mercurial/httppeer.py --- a/mercurial/httppeer.py +++ b/mercurial/httppeer.py @@ -63,7 +63,7 @@ def encodevalueinheaders(value, header, # and using an r-string to make it portable between Python 2 and 3 # doesn't work because then the \r is a literal backslash-r # instead of a carriage return. - valuelen = limit - len(fmt % r'000') - len(b': \r\n') + valuelen = limit - len(fmt % '000') - len(b': \r\n') result = [] n = 0 @@ -158,7 +158,7 @@ def makev1commandrequest( argsio = io.BytesIO(strargs) argsio.length = len(strargs) data = _multifile(argsio, data) - headers[r'X-HgArgs-Post'] = len(strargs) + headers['X-HgArgs-Post'] = len(strargs) elif args: # Calling self.capable() can infinite loop if we are calling # "capabilities". But that command should never accept wire @@ -187,8 +187,8 @@ def makev1commandrequest( size = data.length elif data is not None: size = len(data) - if data is not None and r'Content-Type' not in headers: - headers[r'Content-Type'] = r'application/mercurial-0.1' + if data is not None and 'Content-Type' not in headers: + headers['Content-Type'] = 'application/mercurial-0.1' # Tell the server we accept application/mercurial-0.2 and multiple # compression formats if the server is capable of emitting those @@ -228,17 +228,17 @@ def makev1commandrequest( varyheaders = [] for header in headers: - if header.lower().startswith(r'x-hg'): + if header.lower().startswith('x-hg'): varyheaders.append(header) if varyheaders: - headers[r'Vary'] = r','.join(sorted(varyheaders)) + headers['Vary'] = ','.join(sorted(varyheaders)) req = requestbuilder(pycompat.strurl(cu), data, headers) if data is not None: ui.debug(b"sending %d bytes\n" % size) - req.add_unredirected_header(r'Content-Length', r'%d' % size) + req.add_unredirected_header('Content-Length', '%d' % size) return req, cu, qs @@ -348,9 +348,9 @@ def parsev1commandresponse( ui.warn(_(b'real URL is %s\n') % respurl) try: - proto = pycompat.bytesurl(resp.getheader(r'content-type', r'')) + proto = pycompat.bytesurl(resp.getheader('content-type', '')) except AttributeError: - proto = pycompat.bytesurl(resp.headers.get(r'content-type', r'')) + proto = pycompat.bytesurl(resp.headers.get('content-type', '')) safeurl = util.hidepassword(baseurl) if proto.startswith(b'application/hg-error'): @@ -517,7 +517,7 @@ class httppeer(wireprotov1peer.wirepeer) tempname = bundle2.writebundle(self.ui, cg, None, type) fp = httpconnection.httpsendfile(self.ui, tempname, b"rb") - headers = {r'Content-Type': r'application/mercurial-0.1'} + headers = {'Content-Type': 'application/mercurial-0.1'} try: r = self._call(cmd, data=fp, headers=headers, **args) @@ -550,7 +550,7 @@ class httppeer(wireprotov1peer.wirepeer) d = fp.read(4096) # start http push with httpconnection.httpsendfile(self.ui, filename, b"rb") as fp_: - headers = {r'Content-Type': r'application/mercurial-0.1'} + headers = {'Content-Type': 'application/mercurial-0.1'} return self._callstream(cmd, data=fp_, headers=headers, **args) finally: if filename is not None: @@ -621,12 +621,12 @@ def sendv2request( # TODO modify user-agent to reflect v2 headers = { - r'Accept': wireprotov2server.FRAMINGTYPE, - r'Content-Type': wireprotov2server.FRAMINGTYPE, + 'Accept': wireprotov2server.FRAMINGTYPE, + 'Content-Type': wireprotov2server.FRAMINGTYPE, } req = requestbuilder(pycompat.strurl(url), body, headers) - req.add_unredirected_header(r'Content-Length', r'%d' % len(body)) + req.add_unredirected_header('Content-Length', '%d' % len(body)) try: res = opener.open(req) @@ -965,7 +965,7 @@ def performhandshake(ui, url, opener, re if advertisev2: args[b'headers'] = { - r'X-HgProto-1': r'cbor', + 'X-HgProto-1': 'cbor', } args[b'headers'].update( diff --git a/mercurial/i18n.py b/mercurial/i18n.py --- a/mercurial/i18n.py +++ b/mercurial/i18n.py @@ -50,8 +50,8 @@ if ( def setdatapath(datapath): datapath = pycompat.fsdecode(datapath) - localedir = os.path.join(datapath, r'locale') - t = gettextmod.translation(r'hg', localedir, _languages, fallback=True) + localedir = os.path.join(datapath, 'locale') + t = gettextmod.translation('hg', localedir, _languages, fallback=True) global _ugettext try: _ugettext = t.ugettext diff --git a/mercurial/keepalive.py b/mercurial/keepalive.py --- a/mercurial/keepalive.py +++ b/mercurial/keepalive.py @@ -331,9 +331,9 @@ class KeepAliveHandler(object): headers.update(sorted(req.unredirected_hdrs.items())) headers = util.sortdict((n.lower(), v) for n, v in headers.items()) skipheaders = {} - for n in (r'host', r'accept-encoding'): + for n in ('host', 'accept-encoding'): if n in headers: - skipheaders[r'skip_' + n.replace(r'-', r'_')] = 1 + skipheaders['skip_' + n.replace('-', '_')] = 1 try: if urllibcompat.hasdata(req): data = urllibcompat.getdata(req) @@ -342,12 +342,12 @@ class KeepAliveHandler(object): urllibcompat.getselector(req), **skipheaders ) - if r'content-type' not in headers: + if 'content-type' not in headers: h.putheader( - r'Content-type', r'application/x-www-form-urlencoded' + 'Content-type', 'application/x-www-form-urlencoded' ) - if r'content-length' not in headers: - h.putheader(r'Content-length', r'%d' % len(data)) + if 'content-length' not in headers: + h.putheader('Content-length', '%d' % len(data)) else: h.putrequest( req.get_method(), @@ -401,8 +401,8 @@ class HTTPResponse(httplib.HTTPResponse) def __init__(self, sock, debuglevel=0, strict=0, method=None): extrakw = {} if not pycompat.ispy3: - extrakw[r'strict'] = True - extrakw[r'buffering'] = True + extrakw['strict'] = True + extrakw['buffering'] = True httplib.HTTPResponse.__init__( self, sock, debuglevel=debuglevel, method=method, **extrakw ) diff --git a/mercurial/linelog.py b/mercurial/linelog.py --- a/mercurial/linelog.py +++ b/mercurial/linelog.py @@ -99,7 +99,7 @@ class _jge(_llinstruction): self._target = op2 def __str__(self): - return r'JGE %d %d' % (self._cmprev, self._target) + return 'JGE %d %d' % (self._cmprev, self._target) def __eq__(self, other): return ( @@ -126,7 +126,7 @@ class _jump(_llinstruction): self._target = op2 def __str__(self): - return r'JUMP %d' % (self._target) + return 'JUMP %d' % (self._target) def __eq__(self, other): return type(self) == type(other) and self._target == other._target @@ -168,7 +168,7 @@ class _jl(_llinstruction): self._target = op2 def __str__(self): - return r'JL %d %d' % (self._cmprev, self._target) + return 'JL %d %d' % (self._cmprev, self._target) def __eq__(self, other): return ( @@ -196,7 +196,7 @@ class _line(_llinstruction): self._origlineno = op2 def __str__(self): - return r'LINE %d %d' % (self._rev, self._origlineno) + return 'LINE %d %d' % (self._rev, self._origlineno) def __eq__(self, other): return ( @@ -262,7 +262,7 @@ class linelog(object): ) def debugstr(self): - fmt = r'%%%dd %%s' % len(str(len(self._program))) + fmt = '%%%dd %%s' % len(str(len(self._program))) return pycompat.sysstr(b'\n').join( fmt % (idx, i) for idx, i in enumerate(self._program[1:], 1) ) diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py --- a/mercurial/localrepo.py +++ b/mercurial/localrepo.py @@ -2459,9 +2459,9 @@ class localrepository(object): def invalidatecaches(self): - if r'_tagscache' in vars(self): + if '_tagscache' in vars(self): # can't use delattr on proxy - del self.__dict__[r'_tagscache'] + del self.__dict__['_tagscache'] self._branchcaches.clear() self.invalidatevolatilesets() @@ -2480,13 +2480,13 @@ class localrepository(object): rereads the dirstate. Use dirstate.invalidate() if you want to explicitly read the dirstate again (i.e. restoring it to a previous known good state).''' - if hasunfilteredcache(self, r'dirstate'): + if hasunfilteredcache(self, 'dirstate'): for k in self.dirstate._filecache: try: delattr(self.dirstate, k) except AttributeError: pass - delattr(self.unfiltered(), r'dirstate') + delattr(self.unfiltered(), 'dirstate') def invalidate(self, clearfilecache=False): '''Invalidates both store and non-store parts other than dirstate @@ -2536,7 +2536,7 @@ class localrepository(object): """Reload stats of cached files so that they are flagged as valid""" for k, ce in self._filecache.items(): k = pycompat.sysstr(k) - if k == r'dirstate' or k not in self.__dict__: + if k == 'dirstate' or k not in self.__dict__: continue ce.refresh() @@ -3363,10 +3363,10 @@ class localrepository(object): if tr is not None: hookargs.update(tr.hookargs) hookargs = pycompat.strkwargs(hookargs) - hookargs[r'namespace'] = namespace - hookargs[r'key'] = key - hookargs[r'old'] = old - hookargs[r'new'] = new + hookargs['namespace'] = namespace + hookargs['key'] = key + hookargs['old'] = old + hookargs['new'] = new self.hook(b'prepushkey', throw=True, **hookargs) except error.HookAbort as exc: self.ui.write_err(_(b"pushkey-abort: %s\n") % exc) @@ -3706,7 +3706,7 @@ def poisonrepository(repo): # of repos call close() on repo references. class poisonedrepository(object): def __getattribute__(self, item): - if item == r'close': + if item == 'close': return object.__getattribute__(self, item) raise error.ProgrammingError( @@ -3718,4 +3718,4 @@ def poisonrepository(repo): # We may have a repoview, which intercepts __setattr__. So be sure # we operate at the lowest level possible. - object.__setattr__(repo, r'__class__', poisonedrepository) + object.__setattr__(repo, '__class__', poisonedrepository) diff --git a/mercurial/lsprof.py b/mercurial/lsprof.py --- a/mercurial/lsprof.py +++ b/mercurial/lsprof.py @@ -135,9 +135,9 @@ def label(code): mname = _fn2mod[code.co_filename] = k break else: - mname = _fn2mod[code.co_filename] = r'<%s>' % code.co_filename + mname = _fn2mod[code.co_filename] = '<%s>' % code.co_filename - res = r'%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name) + res = '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name) if sys.version_info.major >= 3: res = res.encode('latin-1') diff --git a/mercurial/mail.py b/mercurial/mail.py --- a/mercurial/mail.py +++ b/mercurial/mail.py @@ -94,7 +94,7 @@ class SMTPS(smtplib.SMTP): ui=self._ui, serverhostname=self._host, ) - self.file = new_socket.makefile(r'rb') + self.file = new_socket.makefile('rb') return new_socket @@ -201,7 +201,7 @@ def _mbox(mbox, sender, recipients, msg) fp = open(mbox, b'ab+') # Should be time.asctime(), but Windows prints 2-characters day # of month instead of one. Make them print the same thing. - date = time.strftime(r'%a %b %d %H:%M:%S %Y', time.localtime()) + date = time.strftime('%a %b %d %H:%M:%S %Y', time.localtime()) fp.write( b'From %s %s\n' % (encoding.strtolocal(sender), encoding.strtolocal(date)) @@ -403,7 +403,7 @@ def addrlistencode(ui, addrs, charsets=N A single element of input list may contain multiple addresses, but output always has one address per item''' for a in addrs: - assert isinstance(a, bytes), r'%r unexpectedly not a bytestr' % a + assert isinstance(a, bytes), '%r unexpectedly not a bytestr' % a if display: return [a.strip() for a in addrs if a.strip()] @@ -436,7 +436,7 @@ if pycompat.ispy3: # I have no idea if ascii/surrogateescape is correct, but that's # what the standard Python email parser does. fp = io.TextIOWrapper( - fp, encoding=r'ascii', errors=r'surrogateescape', newline=chr(10) + fp, encoding='ascii', errors='surrogateescape', newline=chr(10) ) try: return ep.parse(fp) diff --git a/mercurial/manifest.py b/mercurial/manifest.py --- a/mercurial/manifest.py +++ b/mercurial/manifest.py @@ -33,7 +33,7 @@ from .interfaces import ( util as interfaceutil, ) -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') propertycache = util.propertycache # Allow tests to more easily test the alternate path in manifestdict.fastdelta() diff --git a/mercurial/match.py b/mercurial/match.py --- a/mercurial/match.py +++ b/mercurial/match.py @@ -24,7 +24,7 @@ from . import ( ) from .utils import stringutil -rustmod = policy.importrust(r'filepatterns') +rustmod = policy.importrust('filepatterns') allpatternkinds = ( b're', diff --git a/mercurial/mdiff.py b/mercurial/mdiff.py --- a/mercurial/mdiff.py +++ b/mercurial/mdiff.py @@ -27,8 +27,8 @@ from .utils import dateutil _missing_newline_marker = b"\\ No newline at end of file\n" -bdiff = policy.importmod(r'bdiff') -mpatch = policy.importmod(r'mpatch') +bdiff = policy.importmod('bdiff') +mpatch = policy.importmod('mpatch') blocks = bdiff.blocks fixws = bdiff.fixws diff --git a/mercurial/obsolete.py b/mercurial/obsolete.py --- a/mercurial/obsolete.py +++ b/mercurial/obsolete.py @@ -87,7 +87,7 @@ from . import ( ) from .utils import dateutil -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') _pack = struct.pack _unpack = struct.unpack @@ -580,7 +580,7 @@ class obsstore(object): return len(self._all) def __nonzero__(self): - if not self._cached(r'_all'): + if not self._cached('_all'): try: return self.svfs.stat(b'obsstore').st_size > 1 except OSError as inst: @@ -641,7 +641,7 @@ class obsstore(object): raise ValueError(succ) if prec in succs: raise ValueError( - r'in-marker cycle with %s' % pycompat.sysstr(node.hex(prec)) + 'in-marker cycle with %s' % pycompat.sysstr(node.hex(prec)) ) metadata = tuple(sorted(pycompat.iteritems(metadata))) @@ -752,11 +752,11 @@ class obsstore(object): markers = list(markers) # to allow repeated iteration self._data = self._data + rawdata self._all.extend(markers) - if self._cached(r'successors'): + if self._cached('successors'): _addsuccessors(self.successors, markers) - if self._cached(r'predecessors'): + if self._cached('predecessors'): _addpredecessors(self.predecessors, markers) - if self._cached(r'children'): + if self._cached('children'): _addchildren(self.children, markers) _checkinvalidmarkers(markers) @@ -802,7 +802,7 @@ def makestore(ui, repo): # rely on obsstore class default when possible. kwargs = {} if defaultformat is not None: - kwargs[r'defaultformat'] = defaultformat + kwargs['defaultformat'] = defaultformat readonly = not isenabled(repo, createmarkersopt) store = obsstore(repo.svfs, readonly=readonly, **kwargs) if store and readonly: diff --git a/mercurial/patch.py b/mercurial/patch.py --- a/mercurial/patch.py +++ b/mercurial/patch.py @@ -217,7 +217,7 @@ def extract(ui, fileobj): fileobj did not contain a patch. Caller must unlink filename when done.''' fd, tmpname = pycompat.mkstemp(prefix=b'hg-patch-') - tmpfp = os.fdopen(fd, r'wb') + tmpfp = os.fdopen(fd, 'wb') try: yield _extract(ui, fileobj, tmpname, tmpfp) finally: @@ -241,8 +241,8 @@ def _extract(ui, fileobj, tmpname, tmpfp msg = mail.parse(fileobj) - subject = msg[r'Subject'] and mail.headdecode(msg[r'Subject']) - data[b'user'] = msg[r'From'] and mail.headdecode(msg[r'From']) + subject = msg['Subject'] and mail.headdecode(msg['Subject']) + data[b'user'] = msg['From'] and mail.headdecode(msg['From']) if not subject and not data[b'user']: # Not an email, restore parsed headers if any subject = ( @@ -255,7 +255,7 @@ def _extract(ui, fileobj, tmpname, tmpfp # should try to parse msg['Date'] parents = [] - nodeid = msg[r'X-Mercurial-Node'] + nodeid = msg['X-Mercurial-Node'] if nodeid: data[b'nodeid'] = nodeid = mail.headdecode(nodeid) ui.debug(b'Node ID: %s\n' % nodeid) @@ -1225,7 +1225,7 @@ the hunk is left unchanged. ncpatchfp = None try: # Write the initial patch - f = util.nativeeolwriter(os.fdopen(patchfd, r'wb')) + f = util.nativeeolwriter(os.fdopen(patchfd, 'wb')) chunk.header.write(f) chunk.write(f) f.write( @@ -1245,7 +1245,7 @@ the hunk is left unchanged. ui.warn(_(b"editor exited with exit code %d\n") % ret) continue # Remove comment lines - patchfp = open(patchfn, r'rb') + patchfp = open(patchfn, 'rb') ncpatchfp = stringio() for line in util.iterfile(patchfp): line = util.fromnativeeol(line) @@ -2788,7 +2788,7 @@ def diffsinglehunkinline(hunklines): def difflabel(func, *args, **kw): '''yields 2-tuples of (output, label) based on the output of func()''' - if kw.get(r'opts') and kw[r'opts'].worddiff: + if kw.get('opts') and kw['opts'].worddiff: dodiffhunk = diffsinglehunkinline else: dodiffhunk = diffsinglehunk diff --git a/mercurial/policy.py b/mercurial/policy.py --- a/mercurial/policy.py +++ b/mercurial/policy.py @@ -29,14 +29,14 @@ from .pycompat import getattr policy = b'allow' _packageprefs = { # policy: (versioned package, pure package) - b'c': (r'cext', None), - b'allow': (r'cext', r'pure'), - b'cffi': (r'cffi', None), - b'cffi-allow': (r'cffi', r'pure'), - b'py': (None, r'pure'), + b'c': ('cext', None), + b'allow': ('cext', 'pure'), + b'cffi': ('cffi', None), + b'cffi-allow': ('cffi', 'pure'), + b'py': (None, 'pure'), # For now, rust policies impact importrust only - b'rust+c': (r'cext', None), - b'rust+c-allow': (r'cext', r'pure'), + b'rust+c': ('cext', None), + b'rust+c-allow': ('cext', 'pure'), } try: @@ -50,15 +50,15 @@ except ImportError: # # The canonical way to do this is to test platform.python_implementation(). # But we don't import platform and don't bloat for it here. -if r'__pypy__' in sys.builtin_module_names: +if '__pypy__' in sys.builtin_module_names: policy = b'cffi' # Environment variable can always force settings. if sys.version_info[0] >= 3: - if r'HGMODULEPOLICY' in os.environ: - policy = os.environ[r'HGMODULEPOLICY'].encode(r'utf-8') + if 'HGMODULEPOLICY' in os.environ: + policy = os.environ['HGMODULEPOLICY'].encode('utf-8') else: - policy = os.environ.get(r'HGMODULEPOLICY', policy) + policy = os.environ.get('HGMODULEPOLICY', policy) def _importfrom(pkgname, modname): @@ -68,7 +68,7 @@ def _importfrom(pkgname, modname): try: fakelocals[modname] = mod = getattr(pkg, modname) except AttributeError: - raise ImportError(r'cannot import name %s' % modname) + raise ImportError('cannot import name %s' % modname) # force import; fakelocals[modname] may be replaced with the real module getattr(mod, '__doc__', None) return fakelocals[modname] @@ -76,19 +76,19 @@ def _importfrom(pkgname, modname): # keep in sync with "version" in C modules _cextversions = { - (r'cext', r'base85'): 1, - (r'cext', r'bdiff'): 3, - (r'cext', r'mpatch'): 1, - (r'cext', r'osutil'): 4, - (r'cext', r'parsers'): 13, + ('cext', 'base85'): 1, + ('cext', 'bdiff'): 3, + ('cext', 'mpatch'): 1, + ('cext', 'osutil'): 4, + ('cext', 'parsers'): 13, } # map import request to other package or module _modredirects = { - (r'cext', r'charencode'): (r'cext', r'parsers'), - (r'cffi', r'base85'): (r'pure', r'base85'), - (r'cffi', r'charencode'): (r'pure', r'charencode'), - (r'cffi', r'parsers'): (r'pure', r'parsers'), + ('cext', 'charencode'): ('cext', 'parsers'), + ('cffi', 'base85'): ('pure', 'base85'), + ('cffi', 'charencode'): ('pure', 'charencode'), + ('cffi', 'parsers'): ('pure', 'parsers'), } @@ -97,8 +97,8 @@ def _checkmod(pkgname, modname, mod): actual = getattr(mod, 'version', None) if actual != expected: raise ImportError( - r'cannot import module %s.%s ' - r'(expected version: %d, actual: %r)' + 'cannot import module %s.%s ' + '(expected version: %d, actual: %r)' % (pkgname, modname, expected, actual) ) @@ -108,7 +108,7 @@ def importmod(modname): try: verpkg, purepkg = _packageprefs[policy] except KeyError: - raise ImportError(r'invalid HGMODULEPOLICY %r' % policy) + raise ImportError('invalid HGMODULEPOLICY %r' % policy) assert verpkg or purepkg if verpkg: pn, mn = _modredirects.get((verpkg, modname), (verpkg, modname)) @@ -141,7 +141,7 @@ def importrust(modname, member=None, def return default try: - mod = _importfrom(r'rustext', modname) + mod = _importfrom('rustext', modname) except ImportError: if _isrustpermissive(): return default diff --git a/mercurial/posix.py b/mercurial/posix.py --- a/mercurial/posix.py +++ b/mercurial/posix.py @@ -32,7 +32,7 @@ from . import ( pycompat, ) -osutil = policy.importmod(r'osutil') +osutil = policy.importmod('osutil') normpath = os.path.normpath samestat = os.path.samestat @@ -60,11 +60,11 @@ os.umask(umask) if not pycompat.ispy3: - def posixfile(name, mode=r'r', buffering=-1): + def posixfile(name, mode='r', buffering=-1): fp = open(name, mode=mode, buffering=buffering) # The position when opening in append mode is implementation defined, so # make it consistent by always seeking to the end. - if r'a' in mode: + if 'a' in mode: fp.seek(0, os.SEEK_END) return fp @@ -466,7 +466,7 @@ if pycompat.isdarwin: u = s.decode('utf-8') # Decompose then lowercase (HFS+ technote specifies lower) - enc = unicodedata.normalize(r'NFD', u).lower().encode('utf-8') + enc = unicodedata.normalize('NFD', u).lower().encode('utf-8') # drop HFS+ ignored characters return encoding.hfsignoreclean(enc) diff --git a/mercurial/profiling.py b/mercurial/profiling.py --- a/mercurial/profiling.py +++ b/mercurial/profiling.py @@ -167,9 +167,9 @@ def statprofile(ui, fp): elif profformat == b'hotpath': # inconsistent config: profiling.showmin limit = ui.configwith(fraction, b'profiling', b'showmin', 0.05) - kwargs[r'limit'] = limit + kwargs['limit'] = limit showtime = ui.configbool(b'profiling', b'showtime') - kwargs[r'showtime'] = showtime + kwargs['showtime'] = showtime statprof.display(fp, data=data, format=displayformat, **kwargs) diff --git a/mercurial/pure/charencode.py b/mercurial/pure/charencode.py --- a/mercurial/pure/charencode.py +++ b/mercurial/pure/charencode.py @@ -85,6 +85,6 @@ def jsonescapeu8fallback(u8chars, parano jm = _jsonmap # non-BMP char is represented as UTF-16 surrogate pair u16b = u8chars.decode('utf-8', _utf8strict).encode('utf-16', _utf8strict) - u16codes = array.array(r'H', u16b) + u16codes = array.array('H', u16b) u16codes.pop(0) # drop BOM return b''.join(jm[x] if x < 128 else b'\\u%04x' % x for x in u16codes) diff --git a/mercurial/pure/osutil.py b/mercurial/pure/osutil.py --- a/mercurial/pure/osutil.py +++ b/mercurial/pure/osutil.py @@ -218,7 +218,7 @@ else: def _raiseioerror(name): err = ctypes.WinError() raise IOError( - err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror) + err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror) ) class posixfile(object): @@ -280,8 +280,8 @@ else: # unfortunately, f.name is '' at this point -- so we store # the name on this wrapper. We cannot just assign to f.name, # because that attribute is read-only. - object.__setattr__(self, r'name', name) - object.__setattr__(self, r'_file', f) + object.__setattr__(self, 'name', name) + object.__setattr__(self, '_file', f) def __iter__(self): return self._file diff --git a/mercurial/pycompat.py b/mercurial/pycompat.py --- a/mercurial/pycompat.py +++ b/mercurial/pycompat.py @@ -19,7 +19,7 @@ import sys import tempfile ispy3 = sys.version_info[0] >= 3 -ispypy = r'__pypy__' in sys.builtin_module_names +ispypy = '__pypy__' in sys.builtin_module_names if not ispy3: import cookielib @@ -151,7 +151,7 @@ if ispy3: if getattr(sys, 'argv', None) is not None: sysargv = list(map(os.fsencode, sys.argv)) - bytechr = struct.Struct(r'>B').pack + bytechr = struct.Struct('>B').pack byterepr = b'%r'.__mod__ class bytestr(bytes): @@ -500,7 +500,7 @@ def namedtempfile( mode=b'w+b', bufsize=-1, suffix=b'', prefix=b'tmp', dir=None, delete=True ): mode = sysstr(mode) - assert r'b' in mode + assert 'b' in mode return tempfile.NamedTemporaryFile( mode, bufsize, suffix=suffix, prefix=prefix, dir=dir, delete=delete ) diff --git a/mercurial/repoview.py b/mercurial/repoview.py --- a/mercurial/repoview.py +++ b/mercurial/repoview.py @@ -370,12 +370,12 @@ class repoview(object): """ def __init__(self, repo, filtername, visibilityexceptions=None): - object.__setattr__(self, r'_unfilteredrepo', repo) - object.__setattr__(self, r'filtername', filtername) - object.__setattr__(self, r'_clcachekey', None) - object.__setattr__(self, r'_clcache', None) + object.__setattr__(self, '_unfilteredrepo', repo) + object.__setattr__(self, 'filtername', filtername) + object.__setattr__(self, '_clcachekey', None) + object.__setattr__(self, '_clcache', None) # revs which are exceptions and must not be hidden - object.__setattr__(self, r'_visibilityexceptions', visibilityexceptions) + object.__setattr__(self, '_visibilityexceptions', visibilityexceptions) # not a propertycache on purpose we shall implement a proper cache later @property @@ -404,8 +404,8 @@ class repoview(object): if cl is None: # Only filter if there's something to filter cl = wrapchangelog(unfichangelog, revs) if revs else unfichangelog - object.__setattr__(self, r'_clcache', cl) - object.__setattr__(self, r'_clcachekey', newkey) + object.__setattr__(self, '_clcache', cl) + object.__setattr__(self, '_clcachekey', newkey) return cl def unfiltered(self): @@ -419,7 +419,7 @@ class repoview(object): return self.unfiltered().filtered(name, visibilityexceptions) def __repr__(self): - return r'<%s:%s %r>' % ( + return '<%s:%s %r>' % ( self.__class__.__name__, pycompat.sysstr(self.filtername), self.unfiltered(), diff --git a/mercurial/revlog.py b/mercurial/revlog.py --- a/mercurial/revlog.py +++ b/mercurial/revlog.py @@ -102,9 +102,9 @@ REVIDX_DEFAULT_FLAGS REVIDX_FLAGS_ORDER REVIDX_RAWTEXT_CHANGING_FLAGS -parsers = policy.importmod(r'parsers') -rustancestor = policy.importrust(r'ancestor') -rustdagop = policy.importrust(r'dagop') +parsers = policy.importmod('parsers') +rustancestor = policy.importrust('ancestor') +rustdagop = policy.importrust('dagop') # Aliased for performance. _zlibdecompress = zlib.decompress @@ -556,11 +556,11 @@ class revlog(object): def _indexfp(self, mode=b'r'): """file object for the revlog's index file""" - args = {r'mode': mode} + args = {'mode': mode} if mode != b'r': - args[r'checkambig'] = self._checkambig + args['checkambig'] = self._checkambig if mode == b'w': - args[r'atomictemp'] = True + args['atomictemp'] = True return self.opener(self.indexfile, **args) def _datafp(self, mode=b'r'): diff --git a/mercurial/revlogutils/sidedata.py b/mercurial/revlogutils/sidedata.py --- a/mercurial/revlogutils/sidedata.py +++ b/mercurial/revlogutils/sidedata.py @@ -55,8 +55,8 @@ SD_FILESADDED = 10 SD_FILESREMOVED = 11 # internal format constant -SIDEDATA_HEADER = struct.Struct(r'>H') -SIDEDATA_ENTRY = struct.Struct(r'>HL20s') +SIDEDATA_HEADER = struct.Struct('>H') +SIDEDATA_ENTRY = struct.Struct('>HL20s') def sidedatawriteprocessor(rl, text, sidedata): diff --git a/mercurial/scmposix.py b/mercurial/scmposix.py --- a/mercurial/scmposix.py +++ b/mercurial/scmposix.py @@ -84,7 +84,7 @@ def termsize(ui): if not os.isatty(fd): continue arri = fcntl.ioctl(fd, TIOCGWINSZ, b'\0' * 8) - height, width = array.array(r'h', arri)[:2] + height, width = array.array('h', arri)[:2] if width > 0 and height > 0: return width, height except ValueError: diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py --- a/mercurial/scmutil.py +++ b/mercurial/scmutil.py @@ -57,7 +57,7 @@ if pycompat.iswindows: else: from . import scmposix as scmplatform -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') termsize = scmplatform.termsize diff --git a/mercurial/setdiscovery.py b/mercurial/setdiscovery.py --- a/mercurial/setdiscovery.py +++ b/mercurial/setdiscovery.py @@ -278,7 +278,7 @@ class partialdiscovery(object): partialdiscovery = policy.importrust( - r'discovery', member=r'PartialDiscovery', default=partialdiscovery + 'discovery', member='PartialDiscovery', default=partialdiscovery ) diff --git a/mercurial/smartset.py b/mercurial/smartset.py --- a/mercurial/smartset.py +++ b/mercurial/smartset.py @@ -256,7 +256,7 @@ class baseset(abstractsmartset): @util.propertycache def _list(self): # _list is only lazily constructed if we have _set - assert r'_set' in self.__dict__ + assert '_set' in self.__dict__ return list(self._set) def __iter__(self): @@ -294,7 +294,7 @@ class baseset(abstractsmartset): self._istopo = False def __len__(self): - if r'_list' in self.__dict__: + if '_list' in self.__dict__: return len(self._list) else: return len(self._set) @@ -347,8 +347,8 @@ class baseset(abstractsmartset): # try to use native set operations as fast paths if ( type(other) is baseset - and r'_set' in other.__dict__ - and r'_set' in self.__dict__ + and '_set' in other.__dict__ + and '_set' in self.__dict__ and self._ascending is not None ): s = baseset( diff --git a/mercurial/sslutil.py b/mercurial/sslutil.py --- a/mercurial/sslutil.py +++ b/mercurial/sslutil.py @@ -103,13 +103,13 @@ except AttributeError: # in this legacy code since we don't support SNI. args = { - r'keyfile': self._keyfile, - r'certfile': self._certfile, - r'server_side': server_side, - r'cert_reqs': self.verify_mode, - r'ssl_version': self.protocol, - r'ca_certs': self._cacerts, - r'ciphers': self._ciphers, + 'keyfile': self._keyfile, + 'certfile': self._certfile, + 'server_side': server_side, + 'cert_reqs': self.verify_mode, + 'ssl_version': self.protocol, + 'ca_certs': self._cacerts, + 'ciphers': self._ciphers, } return ssl.wrap_socket(socket, **args) @@ -499,7 +499,7 @@ def wrapsocket(sock, keyfile, certfile, # outright. Hopefully the reason for this error is that we require # TLS 1.1+ and the server only supports TLS 1.0. Whatever the # reason, try to emit an actionable warning. - if e.reason == r'UNSUPPORTED_PROTOCOL': + if e.reason == 'UNSUPPORTED_PROTOCOL': # We attempted TLS 1.0+. if settings[b'protocolui'] == b'tls1.0': # We support more than just TLS 1.0+. If this happens, @@ -568,9 +568,7 @@ def wrapsocket(sock, keyfile, certfile, ) ) - elif ( - e.reason == r'CERTIFICATE_VERIFY_FAILED' and pycompat.iswindows - ): + elif e.reason == 'CERTIFICATE_VERIFY_FAILED' and pycompat.iswindows: ui.warn( _( @@ -737,9 +735,9 @@ def _verifycert(cert, hostname): return _(b'no certificate received') dnsnames = [] - san = cert.get(r'subjectAltName', []) + san = cert.get('subjectAltName', []) for key, value in san: - if key == r'DNS': + if key == 'DNS': try: if _dnsnamematch(value, hostname): return @@ -750,11 +748,11 @@ def _verifycert(cert, hostname): if not dnsnames: # The subject is only checked when there is no DNS in subjectAltName. - for sub in cert.get(r'subject', []): + for sub in cert.get('subject', []): for key, value in sub: # According to RFC 2818 the most specific Common Name must # be used. - if key == r'commonName': + if key == 'commonName': # 'subject' entries are unicode. try: value = value.encode('ascii') diff --git a/mercurial/statichttprepo.py b/mercurial/statichttprepo.py --- a/mercurial/statichttprepo.py +++ b/mercurial/statichttprepo.py @@ -53,7 +53,7 @@ class httprangereader(object): if bytes: end = self.pos + bytes - 1 if self.pos or end: - req.add_header(r'Range', r'bytes=%d-%s' % (self.pos, end)) + req.add_header('Range', 'bytes=%d-%s' % (self.pos, end)) try: f = self.opener.open(req) diff --git a/mercurial/statprof.py b/mercurial/statprof.py --- a/mercurial/statprof.py +++ b/mercurial/statprof.py @@ -206,7 +206,7 @@ state = ProfileState() class CodeSite(object): cache = {} - __slots__ = (r'path', r'lineno', r'function', r'source') + __slots__ = ('path', 'lineno', 'function', 'source') def __init__(self, path, lineno, function): assert isinstance(path, bytes) @@ -258,11 +258,11 @@ class CodeSite(object): return os.path.basename(self.path) def skipname(self): - return r'%s:%s' % (self.filename(), self.function) + return '%s:%s' % (self.filename(), self.function) class Sample(object): - __slots__ = (r'stack', r'time') + __slots__ = ('stack', 'time') def __init__(self, stack, time): self.stack = stack @@ -738,7 +738,7 @@ def display_hotpath(data, fp, limit=0.05 for sample in data.samples: root.add(sample.stack[::-1], sample.time - lasttime) lasttime = sample.time - showtime = kwargs.get(r'showtime', True) + showtime = kwargs.get('showtime', True) def _write(node, depth, multiple_siblings): site = node.site @@ -894,7 +894,7 @@ def write_to_chrome(data, fp, minthresho parent = stackid(stack[1:]) myid = len(stack2id) stack2id[stack] = myid - id2stack.append(dict(category=stack[0][0], name=r'%s %s' % stack[0])) + id2stack.append(dict(category=stack[0][0], name='%s %s' % stack[0])) if parent is not None: id2stack[-1].update(parent=parent) return myid @@ -931,7 +931,7 @@ def write_to_chrome(data, fp, minthresho sampletime = max(oldtime + clamp, sample.time) samples.append( dict( - ph=r'E', + ph='E', name=oldfunc, cat=oldcat, sf=oldsid, @@ -949,7 +949,7 @@ def write_to_chrome(data, fp, minthresho stack = tuple( ( ( - r'%s:%d' + '%s:%d' % (simplifypath(pycompat.sysstr(frame.path)), frame.lineno), pycompat.sysstr(frame.function), ) @@ -971,7 +971,7 @@ def write_to_chrome(data, fp, minthresho sid = stackid(tuple(laststack)) samples.append( dict( - ph=r'B', + ph='B', name=name, cat=path, ts=sample.time * 1e6, @@ -1030,17 +1030,17 @@ def main(argv=None): optstart = 2 displayargs[b'function'] = None - if argv[1] == r'hotpath': + if argv[1] == 'hotpath': displayargs[b'format'] = DisplayFormats.Hotpath - elif argv[1] == r'lines': + elif argv[1] == 'lines': displayargs[b'format'] = DisplayFormats.ByLine - elif argv[1] == r'functions': + elif argv[1] == 'functions': displayargs[b'format'] = DisplayFormats.ByMethod - elif argv[1] == r'function': + elif argv[1] == 'function': displayargs[b'format'] = DisplayFormats.AboutMethod displayargs[b'function'] = argv[2] optstart = 3 - elif argv[1] == r'flame': + elif argv[1] == 'flame': displayargs[b'format'] = DisplayFormats.FlameGraph else: printusage() @@ -1076,7 +1076,7 @@ def main(argv=None): assert False, b"unhandled option %s" % o if not path: - print(r'must specify --file to load') + print('must specify --file to load') return 1 load_data(path=path) diff --git a/mercurial/store.py b/mercurial/store.py --- a/mercurial/store.py +++ b/mercurial/store.py @@ -26,7 +26,7 @@ from . import ( vfs as vfsmod, ) -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') # how much bytes should be read from fncache in one read # It is done to prevent loading large fncache files into memory fncache_chunksize = 10 ** 6 diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py --- a/mercurial/subrepo.py +++ b/mercurial/subrepo.py @@ -69,8 +69,8 @@ class SubrepoAbort(error.Abort): """Exception class used to avoid handling a subrepo error more than once""" def __init__(self, *args, **kw): - self.subrepo = kw.pop(r'subrepo', None) - self.cause = kw.pop(r'cause', None) + self.subrepo = kw.pop('subrepo', None) + self.cause = kw.pop('cause', None) error.Abort.__init__(self, *args, **kw) @@ -969,24 +969,24 @@ class hgsubrepo(abstractsubrepo): # 2. update the subrepo to the revision specified in # the corresponding substate dictionary self.ui.status(_(b'reverting subrepo %s\n') % substate[0]) - if not opts.get(r'no_backup'): + if not opts.get('no_backup'): # Revert all files on the subrepo, creating backups # Note that this will not recursively revert subrepos # We could do it if there was a set:subrepos() predicate opts = opts.copy() - opts[r'date'] = None - opts[r'rev'] = substate[1] + opts['date'] = None + opts['rev'] = substate[1] self.filerevert(*pats, **opts) # Update the repo to the revision specified in the given substate - if not opts.get(r'dry_run'): + if not opts.get('dry_run'): self.get(substate, overwrite=True) def filerevert(self, *pats, **opts): - ctx = self._repo[opts[r'rev']] + ctx = self._repo[opts['rev']] parents = self._repo.dirstate.parents() - if opts.get(r'all'): + if opts.get('all'): pats = [b'set:modified()'] else: pats = [] @@ -1066,7 +1066,7 @@ class svnsubrepo(abstractsubrepo): if not self.ui.interactive(): # Making stdin be a pipe should prevent svn from behaving # interactively even if we can't pass --non-interactive. - extrakw[r'stdin'] = subprocess.PIPE + extrakw['stdin'] = subprocess.PIPE # Starting in svn 1.5 --non-interactive is a global flag # instead of being per-command, but we need to support 1.4 so # we have to be intelligent about what commands take @@ -1125,14 +1125,14 @@ class svnsubrepo(abstractsubrepo): # both. We used to store the working directory one. output, err = self._svncommand([b'info', b'--xml']) doc = xml.dom.minidom.parseString(output) - entries = doc.getElementsByTagName(r'entry') + entries = doc.getElementsByTagName('entry') lastrev, rev = b'0', b'0' if entries: - rev = pycompat.bytestr(entries[0].getAttribute(r'revision')) or b'0' - commits = entries[0].getElementsByTagName(r'commit') + rev = pycompat.bytestr(entries[0].getAttribute('revision')) or b'0' + commits = entries[0].getElementsByTagName('commit') if commits: lastrev = ( - pycompat.bytestr(commits[0].getAttribute(r'revision')) + pycompat.bytestr(commits[0].getAttribute('revision')) or b'0' ) return (lastrev, rev) @@ -1149,23 +1149,23 @@ class svnsubrepo(abstractsubrepo): output, err = self._svncommand([b'status', b'--xml']) externals, changes, missing = [], [], [] doc = xml.dom.minidom.parseString(output) - for e in doc.getElementsByTagName(r'entry'): - s = e.getElementsByTagName(r'wc-status') + for e in doc.getElementsByTagName('entry'): + s = e.getElementsByTagName('wc-status') if not s: continue - item = s[0].getAttribute(r'item') - props = s[0].getAttribute(r'props') - path = e.getAttribute(r'path').encode('utf8') - if item == r'external': + item = s[0].getAttribute('item') + props = s[0].getAttribute('props') + path = e.getAttribute('path').encode('utf8') + if item == 'external': externals.append(path) - elif item == r'missing': + elif item == 'missing': missing.append(path) if item not in ( - r'', - r'normal', - r'unversioned', - r'external', - ) or props not in (r'', r'none', r'normal'): + '', + 'normal', + 'unversioned', + 'external', + ) or props not in ('', 'none', 'normal'): changes.append(path) for path in changes: for ext in externals: @@ -1291,13 +1291,13 @@ class svnsubrepo(abstractsubrepo): output = self._svncommand([b'list', b'--recursive', b'--xml'])[0] doc = xml.dom.minidom.parseString(output) paths = [] - for e in doc.getElementsByTagName(r'entry'): - kind = pycompat.bytestr(e.getAttribute(r'kind')) + for e in doc.getElementsByTagName('entry'): + kind = pycompat.bytestr(e.getAttribute('kind')) if kind != b'file': continue - name = r''.join( + name = ''.join( c.data - for c in e.getElementsByTagName(r'name')[0].childNodes + for c in e.getElementsByTagName('name')[0].childNodes if c.nodeType == c.TEXT_NODE ) paths.append(name.encode('utf8')) @@ -1808,7 +1808,7 @@ class gitsubrepo(abstractsubrepo): if exact: rejected.append(f) continue - if not opts.get(r'dry_run'): + if not opts.get('dry_run'): self._gitcommand(command + [f]) for f in rejected: @@ -1849,7 +1849,7 @@ class gitsubrepo(abstractsubrepo): # This should be much faster than manually traversing the trees # and objects with many subprocess calls. tarstream = self._gitcommand([b'archive', revision], stream=True) - tar = tarfile.open(fileobj=tarstream, mode=r'r|') + tar = tarfile.open(fileobj=tarstream, mode='r|') relpath = subrelpath(self) progress = self.ui.makeprogress( _(b'archiving (%s)') % relpath, unit=_(b'files') @@ -1918,9 +1918,9 @@ class gitsubrepo(abstractsubrepo): deleted, unknown, ignored, clean = [], [], [], [] command = [b'status', b'--porcelain', b'-z'] - if opts.get(r'unknown'): + if opts.get('unknown'): command += [b'--untracked-files=all'] - if opts.get(r'ignored'): + if opts.get('ignored'): command += [b'--ignored'] out = self._gitcommand(command) @@ -1948,7 +1948,7 @@ class gitsubrepo(abstractsubrepo): elif st == b'!!': ignored.append(filename1) - if opts.get(r'clean'): + if opts.get('clean'): out = self._gitcommand([b'ls-files']) for f in out.split(b'\n'): if not f in changedfiles: @@ -1962,7 +1962,7 @@ class gitsubrepo(abstractsubrepo): def diff(self, ui, diffopts, node2, match, prefix, **opts): node1 = self._state[1] cmd = [b'diff', b'--no-renames'] - if opts[r'stat']: + if opts['stat']: cmd.append(b'--stat') else: # for Git, this also implies '-p' @@ -2007,7 +2007,7 @@ class gitsubrepo(abstractsubrepo): @annotatesubrepoerror def revert(self, substate, *pats, **opts): self.ui.status(_(b'reverting subrepo %s\n') % substate[0]) - if not opts.get(r'no_backup'): + if not opts.get('no_backup'): status = self.status(None) names = status.modified for name in names: @@ -2023,7 +2023,7 @@ class gitsubrepo(abstractsubrepo): ) util.rename(self.wvfs.join(name), bakname) - if not opts.get(r'dry_run'): + if not opts.get('dry_run'): self.get(substate, overwrite=True) return [] diff --git a/mercurial/testing/storage.py b/mercurial/testing/storage.py --- a/mercurial/testing/storage.py +++ b/mercurial/testing/storage.py @@ -1366,26 +1366,26 @@ def makeifileindextests(makefilefn, make should find and run it automatically. """ d = { - r'_makefilefn': makefilefn, - r'_maketransactionfn': maketransactionfn, - r'_addrawrevisionfn': addrawrevisionfn, + '_makefilefn': makefilefn, + '_maketransactionfn': maketransactionfn, + '_addrawrevisionfn': addrawrevisionfn, } - return type(r'ifileindextests', (ifileindextests,), d) + return type('ifileindextests', (ifileindextests,), d) def makeifiledatatests(makefilefn, maketransactionfn, addrawrevisionfn): d = { - r'_makefilefn': makefilefn, - r'_maketransactionfn': maketransactionfn, - r'_addrawrevisionfn': addrawrevisionfn, + '_makefilefn': makefilefn, + '_maketransactionfn': maketransactionfn, + '_addrawrevisionfn': addrawrevisionfn, } - return type(r'ifiledatatests', (ifiledatatests,), d) + return type('ifiledatatests', (ifiledatatests,), d) def makeifilemutationtests(makefilefn, maketransactionfn, addrawrevisionfn): d = { - r'_makefilefn': makefilefn, - r'_maketransactionfn': maketransactionfn, - r'_addrawrevisionfn': addrawrevisionfn, + '_makefilefn': makefilefn, + '_maketransactionfn': maketransactionfn, + '_addrawrevisionfn': addrawrevisionfn, } - return type(r'ifilemutationtests', (ifilemutationtests,), d) + return type('ifilemutationtests', (ifilemutationtests,), d) diff --git a/mercurial/transaction.py b/mercurial/transaction.py --- a/mercurial/transaction.py +++ b/mercurial/transaction.py @@ -135,7 +135,7 @@ class transaction(util.transactional): validator=None, releasefn=None, checkambigfiles=None, - name=r'', + name='', ): """Begin a new transaction @@ -220,8 +220,8 @@ class transaction(util.transactional): self._abortcallback = {} def __repr__(self): - name = r'/'.join(self._names) - return r'' % ( + name = '/'.join(self._names) + return '' % ( name, self._count, self._usages, @@ -414,7 +414,7 @@ class transaction(util.transactional): self._file.flush() @active - def nest(self, name=r''): + def nest(self, name=''): self._count += 1 self._usages += 1 self._names.append(name) diff --git a/mercurial/ui.py b/mercurial/ui.py --- a/mercurial/ui.py +++ b/mercurial/ui.py @@ -428,7 +428,7 @@ class ui(object): self, filename, root=None, trust=False, sections=None, remap=None ): try: - fp = open(filename, r'rb') + fp = open(filename, 'rb') except IOError: if not sections: # ignore unless we were looking for something return @@ -1087,7 +1087,7 @@ class ui(object): # inlined _write() for speed if self._buffers: - label = opts.get(r'label', b'') + label = opts.get('label', b'') if label and self._bufferapplylabels: self._buffers[-1].extend(self.label(a, label) for a in args) else: @@ -1095,7 +1095,7 @@ class ui(object): return # inlined _writenobuf() for speed - if not opts.get(r'keepprogressbar', False): + if not opts.get('keepprogressbar', False): self._progclear() msg = b''.join(args) @@ -1108,7 +1108,7 @@ class ui(object): color.win32print(self, dest.write, msg, **opts) else: if self._colormode is not None: - label = opts.get(r'label', b'') + label = opts.get('label', b'') msg = self.label(msg, label) dest.write(msg) except IOError as err: @@ -1124,7 +1124,7 @@ class ui(object): def _write(self, dest, *args, **opts): # update write() as well if you touch this code if self._isbuffered(dest): - label = opts.get(r'label', b'') + label = opts.get('label', b'') if label and self._bufferapplylabels: self._buffers[-1].extend(self.label(a, label) for a in args) else: @@ -1134,7 +1134,7 @@ class ui(object): def _writenobuf(self, dest, *args, **opts): # update write() as well if you touch this code - if not opts.get(r'keepprogressbar', False): + if not opts.get('keepprogressbar', False): self._progclear() msg = b''.join(args) @@ -1153,7 +1153,7 @@ class ui(object): color.win32print(self, dest.write, msg, **opts) else: if self._colormode is not None: - label = opts.get(r'label', b'') + label = opts.get('label', b'') msg = self.label(msg, label) dest.write(msg) # stderr may be buffered under win32 when redirected to files, @@ -1588,7 +1588,7 @@ class ui(object): return self._prompt(msg, default=default) def _prompt(self, msg, **opts): - default = opts[r'default'] + default = opts['default'] if not self.interactive(): self._writemsg(self._fmsgout, msg, b' ', type=b'prompt', **opts) self._writemsg( @@ -1674,7 +1674,7 @@ class ui(object): raise EOFError return l.rstrip(b'\n') else: - return getpass.getpass(r'') + return getpass.getpass('') except EOFError: raise error.ResponseExpected() @@ -1765,7 +1765,7 @@ class ui(object): prefix=b'hg-' + extra[b'prefix'] + b'-', suffix=suffix, dir=rdir ) try: - f = os.fdopen(fd, r'wb') + f = os.fdopen(fd, 'wb') f.write(util.tonativeeol(text)) f.close() @@ -1793,7 +1793,7 @@ class ui(object): blockedtag=b'editor', ) - f = open(name, r'rb') + f = open(name, 'rb') t = util.fromnativeeol(f.read()) f.close() finally: @@ -1864,7 +1864,7 @@ class ui(object): ) else: output = traceback.format_exception(exc[0], exc[1], exc[2]) - self.write_err(encoding.strtolocal(r''.join(output))) + self.write_err(encoding.strtolocal(''.join(output))) return self.tracebackflag or force def geteditor(self): @@ -2305,6 +2305,6 @@ def _writemsgwith(write, dest, *args, ** isn't a structured channel, so that the message will be colorized. """ # TODO: maybe change 'type' to a mandatory option - if r'type' in opts and not getattr(dest, 'structured', False): - opts[r'label'] = opts.get(r'label', b'') + b' ui.%s' % opts.pop(r'type') + if 'type' in opts and not getattr(dest, 'structured', False): + opts['label'] = opts.get('label', b'') + b' ui.%s' % opts.pop('type') write(dest, *args, **opts) diff --git a/mercurial/url.py b/mercurial/url.py --- a/mercurial/url.py +++ b/mercurial/url.py @@ -147,7 +147,7 @@ class proxyhandler(urlreq.proxyhandler): # Keys and values need to be str because the standard library # expects them to be. proxyurl = str(proxy) - proxies = {r'http': proxyurl, r'https': proxyurl} + proxies = {'http': proxyurl, 'https': proxyurl} ui.debug(b'proxying through %s\n' % util.hidepassword(bytes(proxy))) else: proxies = {} @@ -204,8 +204,8 @@ class httpconnection(keepalive.HTTPConne def _generic_start_transaction(handler, h, req): tunnel_host = req._tunnel_host if tunnel_host: - if tunnel_host[:7] not in [r'http://', r'https:/']: - tunnel_host = r'https://' + tunnel_host + if tunnel_host[:7] not in ['http://', 'https:/']: + tunnel_host = 'https://' + tunnel_host new_tunnel = True else: tunnel_host = urllibcompat.getselector(req) @@ -228,7 +228,7 @@ def _generic_proxytunnel(self): [ (x, self.headers[x]) for x in self.headers - if x.lower().startswith(r'proxy-') + if x.lower().startswith('proxy-') ] ) self.send(b'CONNECT %s HTTP/1.0\r\n' % self.realhostport) @@ -522,7 +522,7 @@ class httpbasicauthhandler(urlreq.httpba ) if pw is not None: raw = b"%s:%s" % (pycompat.bytesurl(user), pycompat.bytesurl(pw)) - auth = r'Basic %s' % pycompat.strurl(base64.b64encode(raw).strip()) + auth = 'Basic %s' % pycompat.strurl(base64.b64encode(raw).strip()) if req.get_header(self.auth_header, None) == auth: return None self.auth = auth @@ -655,16 +655,16 @@ def opener( # do look at this value. if not useragent: agent = b'mercurial/proto-1.0 (Mercurial %s)' % util.version() - opener.addheaders = [(r'User-agent', pycompat.sysstr(agent))] + opener.addheaders = [('User-agent', pycompat.sysstr(agent))] else: - opener.addheaders = [(r'User-agent', pycompat.sysstr(useragent))] + opener.addheaders = [('User-agent', pycompat.sysstr(useragent))] # This header should only be needed by wire protocol requests. But it has # been sent on all requests since forever. We keep sending it for backwards # compatibility reasons. Modern versions of the wire protocol use # X-HgProto- for advertising client support. if sendaccept: - opener.addheaders.append((r'Accept', r'application/mercurial-0.1')) + opener.addheaders.append(('Accept', 'application/mercurial-0.1')) return opener diff --git a/mercurial/urllibcompat.py b/mercurial/urllibcompat.py --- a/mercurial/urllibcompat.py +++ b/mercurial/urllibcompat.py @@ -20,7 +20,7 @@ class _pycompatstub(object): """Add items that will be populated at the first access""" items = map(_sysstr, items) self._aliases.update( - (item.replace(r'_', r'').lower(), (origin, item)) for item in items + (item.replace('_', '').lower(), (origin, item)) for item in items ) def _registeralias(self, origin, attr, name): @@ -102,7 +102,7 @@ if pycompat.ispy3: # urllib.parse.quote() accepts both str and bytes, decodes bytes # (if necessary), and returns str. This is wonky. We provide a custom # implementation that only accepts bytes and emits bytes. - def quote(s, safe=r'/'): + def quote(s, safe='/'): # bytestr has an __iter__ that emits characters. quote_from_bytes() # does an iteration and expects ints. We coerce to bytes to appease it. if isinstance(s, pycompat.bytestr): diff --git a/mercurial/util.py b/mercurial/util.py --- a/mercurial/util.py +++ b/mercurial/util.py @@ -57,11 +57,11 @@ from .utils import ( stringutil, ) -rustdirs = policy.importrust(r'dirstate', r'Dirs') - -base85 = policy.importmod(r'base85') -osutil = policy.importmod(r'osutil') -parsers = policy.importmod(r'parsers') +rustdirs = policy.importrust('dirstate', 'Dirs') + +base85 = policy.importmod('base85') +osutil = policy.importmod('osutil') +parsers = policy.importmod('parsers') b85decode = base85.b85decode b85encode = base85.b85encode @@ -165,23 +165,23 @@ if _dowarn: # However, module name set through PYTHONWARNINGS was exactly matched, so # we cannot set 'mercurial' and have it match eg: 'mercurial.scmutil'. This # makes the whole PYTHONWARNINGS thing useless for our usecase. - warnings.filterwarnings(r'default', r'', DeprecationWarning, r'mercurial') - warnings.filterwarnings(r'default', r'', DeprecationWarning, r'hgext') - warnings.filterwarnings(r'default', r'', DeprecationWarning, r'hgext3rd') + warnings.filterwarnings('default', '', DeprecationWarning, 'mercurial') + warnings.filterwarnings('default', '', DeprecationWarning, 'hgext') + warnings.filterwarnings('default', '', DeprecationWarning, 'hgext3rd') if _dowarn and pycompat.ispy3: # silence warning emitted by passing user string to re.sub() warnings.filterwarnings( - r'ignore', r'bad escape', DeprecationWarning, r'mercurial' + 'ignore', 'bad escape', DeprecationWarning, 'mercurial' ) warnings.filterwarnings( - r'ignore', r'invalid escape sequence', DeprecationWarning, r'mercurial' + 'ignore', 'invalid escape sequence', DeprecationWarning, 'mercurial' ) # TODO: reinvent imp.is_frozen() warnings.filterwarnings( - r'ignore', - r'the imp module is deprecated', + 'ignore', + 'the imp module is deprecated', DeprecationWarning, - r'mercurial', + 'mercurial', ) @@ -438,42 +438,42 @@ class fileobjectproxy(object): """ __slots__ = ( - r'_orig', - r'_observer', + '_orig', + '_observer', ) def __init__(self, fh, observer): - object.__setattr__(self, r'_orig', fh) - object.__setattr__(self, r'_observer', observer) + object.__setattr__(self, '_orig', fh) + object.__setattr__(self, '_observer', observer) def __getattribute__(self, name): ours = { - r'_observer', + '_observer', # IOBase - r'close', + 'close', # closed if a property - r'fileno', - r'flush', - r'isatty', - r'readable', - r'readline', - r'readlines', - r'seek', - r'seekable', - r'tell', - r'truncate', - r'writable', - r'writelines', + 'fileno', + 'flush', + 'isatty', + 'readable', + 'readline', + 'readlines', + 'seek', + 'seekable', + 'tell', + 'truncate', + 'writable', + 'writelines', # RawIOBase - r'read', - r'readall', - r'readinto', - r'write', + 'read', + 'readall', + 'readinto', + 'write', # BufferedIOBase # raw is a property - r'detach', + 'detach', # read defined above - r'read1', + 'read1', # readinto defined above # write defined above } @@ -482,30 +482,30 @@ class fileobjectproxy(object): if name in ours: return object.__getattribute__(self, name) - return getattr(object.__getattribute__(self, r'_orig'), name) + return getattr(object.__getattribute__(self, '_orig'), name) def __nonzero__(self): - return bool(object.__getattribute__(self, r'_orig')) + return bool(object.__getattribute__(self, '_orig')) __bool__ = __nonzero__ def __delattr__(self, name): - return delattr(object.__getattribute__(self, r'_orig'), name) + return delattr(object.__getattribute__(self, '_orig'), name) def __setattr__(self, name, value): - return setattr(object.__getattribute__(self, r'_orig'), name, value) + return setattr(object.__getattribute__(self, '_orig'), name, value) def __iter__(self): - return object.__getattribute__(self, r'_orig').__iter__() + return object.__getattribute__(self, '_orig').__iter__() def _observedcall(self, name, *args, **kwargs): # Call the original object. - orig = object.__getattribute__(self, r'_orig') + orig = object.__getattribute__(self, '_orig') res = getattr(orig, name)(*args, **kwargs) # Call a method on the observer of the same name with arguments # so it can react, log, etc. - observer = object.__getattribute__(self, r'_observer') + observer = object.__getattribute__(self, '_observer') fn = getattr(observer, name, None) if fn: fn(res, *args, **kwargs) @@ -513,98 +513,98 @@ class fileobjectproxy(object): return res def close(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'close', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'close', *args, **kwargs ) def fileno(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'fileno', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'fileno', *args, **kwargs ) def flush(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'flush', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'flush', *args, **kwargs ) def isatty(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'isatty', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'isatty', *args, **kwargs ) def readable(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'readable', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'readable', *args, **kwargs ) def readline(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'readline', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'readline', *args, **kwargs ) def readlines(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'readlines', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'readlines', *args, **kwargs ) def seek(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'seek', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'seek', *args, **kwargs ) def seekable(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'seekable', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'seekable', *args, **kwargs ) def tell(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'tell', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'tell', *args, **kwargs ) def truncate(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'truncate', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'truncate', *args, **kwargs ) def writable(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'writable', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'writable', *args, **kwargs ) def writelines(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'writelines', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'writelines', *args, **kwargs ) def read(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'read', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'read', *args, **kwargs ) def readall(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'readall', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'readall', *args, **kwargs ) def readinto(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'readinto', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'readinto', *args, **kwargs ) def write(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'write', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'write', *args, **kwargs ) def detach(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'detach', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'detach', *args, **kwargs ) def read1(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'read1', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'read1', *args, **kwargs ) @@ -651,18 +651,18 @@ class observedbufferedinputpipe(buffered PROXIED_SOCKET_METHODS = { - r'makefile', - r'recv', - r'recvfrom', - r'recvfrom_into', - r'recv_into', - r'send', - r'sendall', - r'sendto', - r'setblocking', - r'settimeout', - r'gettimeout', - r'setsockopt', + 'makefile', + 'recv', + 'recvfrom', + 'recvfrom_into', + 'recv_into', + 'send', + 'sendall', + 'sendto', + 'setblocking', + 'settimeout', + 'gettimeout', + 'setsockopt', } @@ -676,39 +676,39 @@ class socketproxy(object): """ __slots__ = ( - r'_orig', - r'_observer', + '_orig', + '_observer', ) def __init__(self, sock, observer): - object.__setattr__(self, r'_orig', sock) - object.__setattr__(self, r'_observer', observer) + object.__setattr__(self, '_orig', sock) + object.__setattr__(self, '_observer', observer) def __getattribute__(self, name): if name in PROXIED_SOCKET_METHODS: return object.__getattribute__(self, name) - return getattr(object.__getattribute__(self, r'_orig'), name) + return getattr(object.__getattribute__(self, '_orig'), name) def __delattr__(self, name): - return delattr(object.__getattribute__(self, r'_orig'), name) + return delattr(object.__getattribute__(self, '_orig'), name) def __setattr__(self, name, value): - return setattr(object.__getattribute__(self, r'_orig'), name, value) + return setattr(object.__getattribute__(self, '_orig'), name, value) def __nonzero__(self): - return bool(object.__getattribute__(self, r'_orig')) + return bool(object.__getattribute__(self, '_orig')) __bool__ = __nonzero__ def _observedcall(self, name, *args, **kwargs): # Call the original object. - orig = object.__getattribute__(self, r'_orig') + orig = object.__getattribute__(self, '_orig') res = getattr(orig, name)(*args, **kwargs) # Call a method on the observer of the same name with arguments # so it can react, log, etc. - observer = object.__getattribute__(self, r'_observer') + observer = object.__getattribute__(self, '_observer') fn = getattr(observer, name, None) if fn: fn(res, *args, **kwargs) @@ -716,13 +716,13 @@ class socketproxy(object): return res def makefile(self, *args, **kwargs): - res = object.__getattribute__(self, r'_observedcall')( - r'makefile', *args, **kwargs + res = object.__getattribute__(self, '_observedcall')( + 'makefile', *args, **kwargs ) # The file object may be used for I/O. So we turn it into a # proxy using our observer. - observer = object.__getattribute__(self, r'_observer') + observer = object.__getattribute__(self, '_observer') return makeloggingfileobject( observer.fh, res, @@ -734,58 +734,58 @@ class socketproxy(object): ) def recv(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'recv', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'recv', *args, **kwargs ) def recvfrom(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'recvfrom', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'recvfrom', *args, **kwargs ) def recvfrom_into(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'recvfrom_into', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'recvfrom_into', *args, **kwargs ) def recv_into(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'recv_info', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'recv_info', *args, **kwargs ) def send(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'send', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'send', *args, **kwargs ) def sendall(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'sendall', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'sendall', *args, **kwargs ) def sendto(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'sendto', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'sendto', *args, **kwargs ) def setblocking(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'setblocking', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'setblocking', *args, **kwargs ) def settimeout(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'settimeout', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'settimeout', *args, **kwargs ) def gettimeout(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'gettimeout', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'gettimeout', *args, **kwargs ) def setsockopt(self, *args, **kwargs): - return object.__getattribute__(self, r'_observedcall')( - r'setsockopt', *args, **kwargs + return object.__getattribute__(self, '_observedcall')( + 'setsockopt', *args, **kwargs ) @@ -1362,7 +1362,7 @@ class _lrucachenode(object): pair for the dictionary entry. """ - __slots__ = (r'next', r'prev', r'key', r'value', r'cost') + __slots__ = ('next', 'prev', 'key', 'value', 'cost') def __init__(self): self.next = None diff --git a/mercurial/utils/cborutil.py b/mercurial/utils/cborutil.py --- a/mercurial/utils/cborutil.py +++ b/mercurial/utils/cborutil.py @@ -46,20 +46,20 @@ SEMANTIC_TAG_FINITE_SET = 258 # Indefinite types begin with their major type ORd with information value 31. BEGIN_INDEFINITE_BYTESTRING = struct.pack( - r'>B', MAJOR_TYPE_BYTESTRING << 5 | SUBTYPE_INDEFINITE + '>B', MAJOR_TYPE_BYTESTRING << 5 | SUBTYPE_INDEFINITE ) BEGIN_INDEFINITE_ARRAY = struct.pack( - r'>B', MAJOR_TYPE_ARRAY << 5 | SUBTYPE_INDEFINITE + '>B', MAJOR_TYPE_ARRAY << 5 | SUBTYPE_INDEFINITE ) BEGIN_INDEFINITE_MAP = struct.pack( - r'>B', MAJOR_TYPE_MAP << 5 | SUBTYPE_INDEFINITE + '>B', MAJOR_TYPE_MAP << 5 | SUBTYPE_INDEFINITE ) -ENCODED_LENGTH_1 = struct.Struct(r'>B') -ENCODED_LENGTH_2 = struct.Struct(r'>BB') -ENCODED_LENGTH_3 = struct.Struct(r'>BH') -ENCODED_LENGTH_4 = struct.Struct(r'>BL') -ENCODED_LENGTH_5 = struct.Struct(r'>BQ') +ENCODED_LENGTH_1 = struct.Struct('>B') +ENCODED_LENGTH_2 = struct.Struct('>BB') +ENCODED_LENGTH_3 = struct.Struct('>BH') +ENCODED_LENGTH_4 = struct.Struct('>BL') +ENCODED_LENGTH_5 = struct.Struct('>BQ') # The break ends an indefinite length item. BREAK = b'\xff' @@ -262,7 +262,7 @@ else: return ord(b[i]) -STRUCT_BIG_UBYTE = struct.Struct(r'>B') +STRUCT_BIG_UBYTE = struct.Struct('>B') STRUCT_BIG_USHORT = struct.Struct(b'>H') STRUCT_BIG_ULONG = struct.Struct(b'>L') STRUCT_BIG_ULONGLONG = struct.Struct(b'>Q') diff --git a/mercurial/utils/compression.py b/mercurial/utils/compression.py --- a/mercurial/utils/compression.py +++ b/mercurial/utils/compression.py @@ -29,8 +29,7 @@ SERVERROLE = b'server' CLIENTROLE = b'client' compewireprotosupport = collections.namedtuple( - r'compenginewireprotosupport', - (r'name', r'serverpriority', r'clientpriority'), + 'compenginewireprotosupport', ('name', 'serverpriority', 'clientpriority'), ) diff --git a/mercurial/utils/dateutil.py b/mercurial/utils/dateutil.py --- a/mercurial/utils/dateutil.py +++ b/mercurial/utils/dateutil.py @@ -223,7 +223,7 @@ def parsedate(date, formats=None, bias=N if date == b'now' or date == _(b'now'): return makedate() if date == b'today' or date == _(b'today'): - date = datetime.date.today().strftime(r'%b %d') + date = datetime.date.today().strftime('%b %d') date = encoding.strtolocal(date) elif date == b'yesterday' or date == _(b'yesterday'): date = (datetime.date.today() - datetime.timedelta(days=1)).strftime( diff --git a/mercurial/utils/procutil.py b/mercurial/utils/procutil.py --- a/mercurial/utils/procutil.py +++ b/mercurial/utils/procutil.py @@ -32,7 +32,7 @@ from .. import ( pycompat, ) -osutil = policy.importmod(r'osutil') +osutil = policy.importmod('osutil') stderr = pycompat.stderr stdin = pycompat.stdin @@ -52,11 +52,11 @@ def isatty(fp): if isatty(stdout): if pycompat.iswindows: # Windows doesn't support line buffering - stdout = os.fdopen(stdout.fileno(), r'wb', 0) + stdout = os.fdopen(stdout.fileno(), 'wb', 0) elif not pycompat.ispy3: # on Python 3, stdout (sys.stdout.buffer) is already line buffered and # buffering=1 is not handled in binary mode - stdout = os.fdopen(stdout.fileno(), r'wb', 1) + stdout = os.fdopen(stdout.fileno(), 'wb', 1) if pycompat.iswindows: from .. import windows as platform @@ -211,7 +211,7 @@ def tempfilter(s, cmd): inname, outname = None, None try: infd, inname = pycompat.mkstemp(prefix=b'hg-filter-in-') - fp = os.fdopen(infd, r'wb') + fp = os.fdopen(infd, 'wb') fp.write(s) fp.close() outfd, outname = pycompat.mkstemp(prefix=b'hg-filter-out-') @@ -277,7 +277,7 @@ def hgexecutable(): """ if _hgexecutable is None: hg = encoding.environ.get(b'HG') - mainmod = sys.modules[r'__main__'] + mainmod = sys.modules['__main__'] if hg: _sethgexecutable(hg) elif mainfrozen(): @@ -340,11 +340,11 @@ def protectstdio(uin, uout): nullfd = os.open(os.devnull, os.O_RDONLY) os.dup2(nullfd, uin.fileno()) os.close(nullfd) - fin = os.fdopen(newfd, r'rb') + fin = os.fdopen(newfd, 'rb') if _testfileno(uout, stdout): newfd = os.dup(uout.fileno()) os.dup2(stderr.fileno(), uout.fileno()) - fout = os.fdopen(newfd, r'wb') + fout = os.fdopen(newfd, 'wb') return fin, fout diff --git a/mercurial/utils/stringutil.py b/mercurial/utils/stringutil.py --- a/mercurial/utils/stringutil.py +++ b/mercurial/utils/stringutil.py @@ -719,7 +719,7 @@ def _MBTextWrapper(**kwargs): # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (i.e. no lines started yet). - if self.drop_whitespace and chunks[-1].strip() == r'' and lines: + if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: @@ -750,7 +750,7 @@ def _MBTextWrapper(**kwargs): # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: - lines.append(indent + r''.join(cur_line)) + lines.append(indent + ''.join(cur_line)) return lines diff --git a/mercurial/vfs.py b/mercurial/vfs.py --- a/mercurial/vfs.py +++ b/mercurial/vfs.py @@ -592,7 +592,7 @@ class closewrapbase(object): """ def __init__(self, fh): - object.__setattr__(self, r'_origfh', fh) + object.__setattr__(self, '_origfh', fh) def __getattr__(self, attr): return getattr(self._origfh, attr) @@ -622,7 +622,7 @@ class delayclosedfile(closewrapbase): def __init__(self, fh, closer): super(delayclosedfile, self).__init__(fh) - object.__setattr__(self, r'_closer', closer) + object.__setattr__(self, '_closer', closer) def __exit__(self, exc_type, exc_value, exc_tb): self._closer.close(self._origfh) @@ -736,7 +736,7 @@ class checkambigatclosing(closewrapbase) def __init__(self, fh): super(checkambigatclosing, self).__init__(fh) - object.__setattr__(self, r'_oldstat', util.filestat.frompath(fh.name)) + object.__setattr__(self, '_oldstat', util.filestat.frompath(fh.name)) def _checkambig(self): oldstat = self._oldstat diff --git a/mercurial/win32.py b/mercurial/win32.py --- a/mercurial/win32.py +++ b/mercurial/win32.py @@ -57,21 +57,21 @@ elif ctypes.sizeof(ctypes.c_longlong) == class _FILETIME(ctypes.Structure): - _fields_ = [(r'dwLowDateTime', _DWORD), (r'dwHighDateTime', _DWORD)] + _fields_ = [('dwLowDateTime', _DWORD), ('dwHighDateTime', _DWORD)] class _BY_HANDLE_FILE_INFORMATION(ctypes.Structure): _fields_ = [ - (r'dwFileAttributes', _DWORD), - (r'ftCreationTime', _FILETIME), - (r'ftLastAccessTime', _FILETIME), - (r'ftLastWriteTime', _FILETIME), - (r'dwVolumeSerialNumber', _DWORD), - (r'nFileSizeHigh', _DWORD), - (r'nFileSizeLow', _DWORD), - (r'nNumberOfLinks', _DWORD), - (r'nFileIndexHigh', _DWORD), - (r'nFileIndexLow', _DWORD), + ('dwFileAttributes', _DWORD), + ('ftCreationTime', _FILETIME), + ('ftLastAccessTime', _FILETIME), + ('ftLastWriteTime', _FILETIME), + ('dwVolumeSerialNumber', _DWORD), + ('nFileSizeHigh', _DWORD), + ('nFileSizeLow', _DWORD), + ('nNumberOfLinks', _DWORD), + ('nFileIndexHigh', _DWORD), + ('nFileIndexLow', _DWORD), ] @@ -97,33 +97,33 @@ class _BY_HANDLE_FILE_INFORMATION(ctypes class _STARTUPINFO(ctypes.Structure): _fields_ = [ - (r'cb', _DWORD), - (r'lpReserved', _LPSTR), - (r'lpDesktop', _LPSTR), - (r'lpTitle', _LPSTR), - (r'dwX', _DWORD), - (r'dwY', _DWORD), - (r'dwXSize', _DWORD), - (r'dwYSize', _DWORD), - (r'dwXCountChars', _DWORD), - (r'dwYCountChars', _DWORD), - (r'dwFillAttribute', _DWORD), - (r'dwFlags', _DWORD), - (r'wShowWindow', _WORD), - (r'cbReserved2', _WORD), - (r'lpReserved2', ctypes.c_char_p), - (r'hStdInput', _HANDLE), - (r'hStdOutput', _HANDLE), - (r'hStdError', _HANDLE), + ('cb', _DWORD), + ('lpReserved', _LPSTR), + ('lpDesktop', _LPSTR), + ('lpTitle', _LPSTR), + ('dwX', _DWORD), + ('dwY', _DWORD), + ('dwXSize', _DWORD), + ('dwYSize', _DWORD), + ('dwXCountChars', _DWORD), + ('dwYCountChars', _DWORD), + ('dwFillAttribute', _DWORD), + ('dwFlags', _DWORD), + ('wShowWindow', _WORD), + ('cbReserved2', _WORD), + ('lpReserved2', ctypes.c_char_p), + ('hStdInput', _HANDLE), + ('hStdOutput', _HANDLE), + ('hStdError', _HANDLE), ] class _PROCESS_INFORMATION(ctypes.Structure): _fields_ = [ - (r'hProcess', _HANDLE), - (r'hThread', _HANDLE), - (r'dwProcessId', _DWORD), - (r'dwThreadId', _DWORD), + ('hProcess', _HANDLE), + ('hThread', _HANDLE), + ('dwProcessId', _DWORD), + ('dwThreadId', _DWORD), ] @@ -132,25 +132,25 @@ class _PROCESS_INFORMATION(ctypes.Struct class _COORD(ctypes.Structure): - _fields_ = [(r'X', ctypes.c_short), (r'Y', ctypes.c_short)] + _fields_ = [('X', ctypes.c_short), ('Y', ctypes.c_short)] class _SMALL_RECT(ctypes.Structure): _fields_ = [ - (r'Left', ctypes.c_short), - (r'Top', ctypes.c_short), - (r'Right', ctypes.c_short), - (r'Bottom', ctypes.c_short), + ('Left', ctypes.c_short), + ('Top', ctypes.c_short), + ('Right', ctypes.c_short), + ('Bottom', ctypes.c_short), ] class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure): _fields_ = [ - (r'dwSize', _COORD), - (r'dwCursorPosition', _COORD), - (r'wAttributes', _WORD), - (r'srWindow', _SMALL_RECT), - (r'dwMaximumWindowSize', _COORD), + ('dwSize', _COORD), + ('dwCursorPosition', _COORD), + ('wAttributes', _WORD), + ('srWindow', _SMALL_RECT), + ('dwMaximumWindowSize', _COORD), ] @@ -359,7 +359,7 @@ def _raiseoserror(name): code -= 2 ** 32 err = ctypes.WinError(code=code) raise OSError( - err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror) + err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror) ) diff --git a/mercurial/windows.py b/mercurial/windows.py --- a/mercurial/windows.py +++ b/mercurial/windows.py @@ -32,7 +32,7 @@ try: except ImportError: import winreg -osutil = policy.importmod(r'osutil') +osutil = policy.importmod('osutil') getfsmountpoint = win32.getvolumename getfstype = win32.getfstype @@ -70,8 +70,8 @@ class mixedfilemodewrapper(object): OPWRITE = 2 def __init__(self, fp): - object.__setattr__(self, r'_fp', fp) - object.__setattr__(self, r'_lastop', 0) + object.__setattr__(self, '_fp', fp) + object.__setattr__(self, '_lastop', 0) def __enter__(self): self._fp.__enter__() @@ -90,42 +90,42 @@ class mixedfilemodewrapper(object): self._fp.seek(0, os.SEEK_CUR) def seek(self, *args, **kwargs): - object.__setattr__(self, r'_lastop', self.OPNONE) + object.__setattr__(self, '_lastop', self.OPNONE) return self._fp.seek(*args, **kwargs) def write(self, d): if self._lastop == self.OPREAD: self._noopseek() - object.__setattr__(self, r'_lastop', self.OPWRITE) + object.__setattr__(self, '_lastop', self.OPWRITE) return self._fp.write(d) def writelines(self, *args, **kwargs): if self._lastop == self.OPREAD: self._noopeseek() - object.__setattr__(self, r'_lastop', self.OPWRITE) + object.__setattr__(self, '_lastop', self.OPWRITE) return self._fp.writelines(*args, **kwargs) def read(self, *args, **kwargs): if self._lastop == self.OPWRITE: self._noopseek() - object.__setattr__(self, r'_lastop', self.OPREAD) + object.__setattr__(self, '_lastop', self.OPREAD) return self._fp.read(*args, **kwargs) def readline(self, *args, **kwargs): if self._lastop == self.OPWRITE: self._noopseek() - object.__setattr__(self, r'_lastop', self.OPREAD) + object.__setattr__(self, '_lastop', self.OPREAD) return self._fp.readline(*args, **kwargs) def readlines(self, *args, **kwargs): if self._lastop == self.OPWRITE: self._noopseek() - object.__setattr__(self, r'_lastop', self.OPREAD) + object.__setattr__(self, '_lastop', self.OPREAD) return self._fp.readlines(*args, **kwargs) @@ -176,7 +176,7 @@ def posixfile(name, mode=b'r', buffering except WindowsError as err: # convert to a friendlier exception raise IOError( - err.errno, r'%s: %s' % (encoding.strfromlocal(name), err.strerror) + err.errno, '%s: %s' % (encoding.strfromlocal(name), err.strerror) ) @@ -215,7 +215,7 @@ class winstdout(object): if inst.errno != 0 and not win32.lasterrorwaspipeerror(inst): raise self.close() - raise IOError(errno.EPIPE, r'Broken pipe') + raise IOError(errno.EPIPE, 'Broken pipe') def flush(self): try: @@ -223,7 +223,7 @@ class winstdout(object): except IOError as inst: if not win32.lasterrorwaspipeerror(inst): raise - raise IOError(errno.EPIPE, r'Broken pipe') + raise IOError(errno.EPIPE, 'Broken pipe') def _is_win_9x(): @@ -686,4 +686,4 @@ def readpipe(pipe): def bindunixsocket(sock, path): - raise NotImplementedError(r'unsupported platform') + raise NotImplementedError('unsupported platform') diff --git a/mercurial/wireprotoframing.py b/mercurial/wireprotoframing.py --- a/mercurial/wireprotoframing.py +++ b/mercurial/wireprotoframing.py @@ -118,7 +118,7 @@ FRAME_TYPE_FLAGS = { FRAME_TYPE_STREAM_SETTINGS: FLAGS_STREAM_ENCODING_SETTINGS, } -ARGUMENT_RECORD_HEADER = struct.Struct(r'> 4 @@ -460,11 +460,11 @@ def createalternatelocationresponseframe } for a in ( - r'size', - r'fullhashes', - r'fullhashseed', - r'serverdercerts', - r'servercadercerts', + 'size', + 'fullhashes', + 'fullhashseed', + 'serverdercerts', + 'servercadercerts', ): value = getattr(location, a) if value is not None: @@ -548,15 +548,13 @@ def createtextoutputframe( raise ValueError(b'must use bytes for labels') # Formatting string must be ASCII. - formatting = formatting.decode(r'ascii', r'replace').encode(r'ascii') + formatting = formatting.decode('ascii', 'replace').encode('ascii') # Arguments must be UTF-8. - args = [a.decode(r'utf-8', r'replace').encode(r'utf-8') for a in args] + args = [a.decode('utf-8', 'replace').encode('utf-8') for a in args] # Labels must be ASCII. - labels = [ - l.decode(r'ascii', r'strict').encode(r'ascii') for l in labels - ] + labels = [l.decode('ascii', 'strict').encode('ascii') for l in labels] atom = {b'msg': formatting} if args: diff --git a/mercurial/wireprotov1peer.py b/mercurial/wireprotov1peer.py --- a/mercurial/wireprotov1peer.py +++ b/mercurial/wireprotov1peer.py @@ -599,9 +599,9 @@ class wirepeer(repository.peer): # don't pass optional arguments left at their default value opts = {} if three is not None: - opts[r'three'] = three + opts['three'] = three if four is not None: - opts[r'four'] = four + opts['four'] = four return self._call(b'debugwireargs', one=one, two=two, **opts) def _call(self, cmd, **args): diff --git a/mercurial/wireprotov2peer.py b/mercurial/wireprotov2peer.py --- a/mercurial/wireprotov2peer.py +++ b/mercurial/wireprotov2peer.py @@ -472,7 +472,7 @@ class clienthandler(object): ) headers = { - r'Accept': redirect.mediatype, + 'Accept': redirect.mediatype, } req = self._requestbuilder(pycompat.strurl(redirect.url), None, headers) diff --git a/mercurial/worker.py b/mercurial/worker.py --- a/mercurial/worker.py +++ b/mercurial/worker.py @@ -36,7 +36,7 @@ def countcpus(): # posix try: - n = int(os.sysconf(r'SC_NPROCESSORS_ONLN')) + n = int(os.sysconf('SC_NPROCESSORS_ONLN')) if n > 0: return n except (AttributeError, ValueError): @@ -226,7 +226,7 @@ def _posixworker(ui, func, staticargs, a selector = selectors.DefaultSelector() for rfd, wfd in pipes: os.close(wfd) - selector.register(os.fdopen(rfd, r'rb', 0), selectors.EVENT_READ) + selector.register(os.fdopen(rfd, 'rb', 0), selectors.EVENT_READ) def cleanup(): signal.signal(signal.SIGINT, oldhandler) diff --git a/tests/fakedirstatewritetime.py b/tests/fakedirstatewritetime.py --- a/tests/fakedirstatewritetime.py +++ b/tests/fakedirstatewritetime.py @@ -30,8 +30,8 @@ configitem( b'fakedirstatewritetime', b'fakenow', default=None, ) -parsers = policy.importmod(r'parsers') -rustmod = policy.importrust(r'parsers') +parsers = policy.importmod('parsers') +rustmod = policy.importrust('parsers') def pack_dirstate(fakenow, orig, dmap, copymap, pl, now): diff --git a/tests/pullext.py b/tests/pullext.py --- a/tests/pullext.py +++ b/tests/pullext.py @@ -18,12 +18,12 @@ from mercurial.interfaces import reposit def clonecommand(orig, ui, repo, *args, **kwargs): - if kwargs.get(r'include') or kwargs.get(r'exclude'): - kwargs[r'narrow'] = True + if kwargs.get('include') or kwargs.get('exclude'): + kwargs['narrow'] = True - if kwargs.get(r'depth'): + if kwargs.get('depth'): try: - kwargs[r'depth'] = int(kwargs[r'depth']) + kwargs['depth'] = int(kwargs['depth']) except ValueError: raise error.Abort(_('--depth must be an integer')) diff --git a/tests/test-parseindex2.py b/tests/test-parseindex2.py --- a/tests/test-parseindex2.py +++ b/tests/test-parseindex2.py @@ -20,7 +20,7 @@ from mercurial import ( pycompat, ) -parsers = policy.importmod(r'parsers') +parsers = policy.importmod('parsers') # original python implementation def gettype(q): diff --git a/tests/test-wsgirequest.py b/tests/test-wsgirequest.py --- a/tests/test-wsgirequest.py +++ b/tests/test-wsgirequest.py @@ -6,17 +6,17 @@ from mercurial.hgweb import request as r from mercurial import error DEFAULT_ENV = { - r'REQUEST_METHOD': r'GET', - r'SERVER_NAME': r'testserver', - r'SERVER_PORT': r'80', - r'SERVER_PROTOCOL': r'http', - r'wsgi.version': (1, 0), - r'wsgi.url_scheme': r'http', - r'wsgi.input': None, - r'wsgi.errors': None, - r'wsgi.multithread': False, - r'wsgi.multiprocess': True, - r'wsgi.run_once': False, + 'REQUEST_METHOD': 'GET', + 'SERVER_NAME': 'testserver', + 'SERVER_PORT': '80', + 'SERVER_PROTOCOL': 'http', + 'wsgi.version': (1, 0), + 'wsgi.url_scheme': 'http', + 'wsgi.input': None, + 'wsgi.errors': None, + 'wsgi.multithread': False, + 'wsgi.multiprocess': True, + 'wsgi.run_once': False, } @@ -49,7 +49,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(len(r.headers), 0) def testcustomport(self): - r = parse(DEFAULT_ENV, extra={r'SERVER_PORT': r'8000',}) + r = parse(DEFAULT_ENV, extra={'SERVER_PORT': '8000',}) self.assertEqual(r.url, b'http://testserver:8000') self.assertEqual(r.baseurl, b'http://testserver:8000') @@ -58,7 +58,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, - extra={r'SERVER_PORT': r'4000', r'wsgi.url_scheme': r'https',}, + extra={'SERVER_PORT': '4000', 'wsgi.url_scheme': 'https',}, ) self.assertEqual(r.url, b'https://testserver:4000') @@ -67,7 +67,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.advertisedbaseurl, b'https://testserver:4000') def testhttphost(self): - r = parse(DEFAULT_ENV, extra={r'HTTP_HOST': r'altserver',}) + r = parse(DEFAULT_ENV, extra={'HTTP_HOST': 'altserver',}) self.assertEqual(r.url, b'http://altserver') self.assertEqual(r.baseurl, b'http://altserver') @@ -75,7 +75,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.advertisedbaseurl, b'http://testserver') def testscriptname(self): - r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'',}) + r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '',}) self.assertEqual(r.url, b'http://testserver') self.assertEqual(r.baseurl, b'http://testserver') @@ -85,7 +85,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.dispatchparts, []) self.assertIsNone(r.dispatchpath) - r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'/script',}) + r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '/script',}) self.assertEqual(r.url, b'http://testserver/script') self.assertEqual(r.baseurl, b'http://testserver') @@ -95,7 +95,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.dispatchparts, []) self.assertIsNone(r.dispatchpath) - r = parse(DEFAULT_ENV, extra={r'SCRIPT_NAME': r'/multiple words',}) + r = parse(DEFAULT_ENV, extra={'SCRIPT_NAME': '/multiple words',}) self.assertEqual(r.url, b'http://testserver/multiple%20words') self.assertEqual(r.baseurl, b'http://testserver') @@ -106,7 +106,7 @@ class ParseRequestTests(unittest.TestCas self.assertIsNone(r.dispatchpath) def testpathinfo(self): - r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'',}) + r = parse(DEFAULT_ENV, extra={'PATH_INFO': '',}) self.assertEqual(r.url, b'http://testserver') self.assertEqual(r.baseurl, b'http://testserver') @@ -116,7 +116,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.dispatchparts, []) self.assertEqual(r.dispatchpath, b'') - r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'/pathinfo',}) + r = parse(DEFAULT_ENV, extra={'PATH_INFO': '/pathinfo',}) self.assertEqual(r.url, b'http://testserver/pathinfo') self.assertEqual(r.baseurl, b'http://testserver') @@ -126,7 +126,7 @@ class ParseRequestTests(unittest.TestCas self.assertEqual(r.dispatchparts, [b'pathinfo']) self.assertEqual(r.dispatchpath, b'pathinfo') - r = parse(DEFAULT_ENV, extra={r'PATH_INFO': r'/one/two/',}) + r = parse(DEFAULT_ENV, extra={'PATH_INFO': '/one/two/',}) self.assertEqual(r.url, b'http://testserver/one/two/') self.assertEqual(r.baseurl, b'http://testserver') @@ -139,7 +139,7 @@ class ParseRequestTests(unittest.TestCas def testscriptandpathinfo(self): r = parse( DEFAULT_ENV, - extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/pathinfo',}, + extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/pathinfo',}, ) self.assertEqual(r.url, b'http://testserver/script/pathinfo') @@ -153,8 +153,8 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, extra={ - r'SCRIPT_NAME': r'/script1/script2', - r'PATH_INFO': r'/path1/path2', + 'SCRIPT_NAME': '/script1/script2', + 'PATH_INFO': '/path1/path2', }, ) @@ -173,9 +173,9 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, extra={ - r'HTTP_HOST': r'hostserver', - r'SCRIPT_NAME': r'/script', - r'PATH_INFO': r'/pathinfo', + 'HTTP_HOST': 'hostserver', + 'SCRIPT_NAME': '/script', + 'PATH_INFO': '/pathinfo', }, ) @@ -208,7 +208,7 @@ class ParseRequestTests(unittest.TestCas parse( DEFAULT_ENV, reponame=b'repo', - extra={r'PATH_INFO': r'/pathinfo',}, + extra={'PATH_INFO': '/pathinfo',}, ) with self.assertRaisesRegex( @@ -217,13 +217,13 @@ class ParseRequestTests(unittest.TestCas parse( DEFAULT_ENV, reponame=b'repo', - extra={r'PATH_INFO': r'/repoextra/path',}, + extra={'PATH_INFO': '/repoextra/path',}, ) r = parse( DEFAULT_ENV, reponame=b'repo', - extra={r'PATH_INFO': r'/repo/path1/path2',}, + extra={'PATH_INFO': '/repo/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/repo/path1/path2') @@ -238,7 +238,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, reponame=b'prefix/repo', - extra={r'PATH_INFO': r'/prefix/repo/path1/path2',}, + extra={'PATH_INFO': '/prefix/repo/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/prefix/repo/path1/path2') @@ -307,7 +307,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, altbaseurl=b'http://altserver', - extra={r'PATH_INFO': r'/path1/path2',}, + extra={'PATH_INFO': '/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/path1/path2') self.assertEqual(r.baseurl, b'http://testserver') @@ -347,7 +347,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, altbaseurl=b'http://altserver/altpath', - extra={r'PATH_INFO': r'/path1/path2',}, + extra={'PATH_INFO': '/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/path1/path2') self.assertEqual(r.baseurl, b'http://testserver') @@ -365,7 +365,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, altbaseurl=b'http://altserver/altpath/', - extra={r'PATH_INFO': r'/path1/path2',}, + extra={'PATH_INFO': '/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/path1/path2') self.assertEqual(r.baseurl, b'http://testserver') @@ -383,7 +383,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, altbaseurl=b'http://altserver', - extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/path1/path2',}, + extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/script/path1/path2') self.assertEqual(r.baseurl, b'http://testserver') @@ -399,7 +399,7 @@ class ParseRequestTests(unittest.TestCas r = parse( DEFAULT_ENV, altbaseurl=b'http://altserver/altroot', - extra={r'SCRIPT_NAME': r'/script', r'PATH_INFO': r'/path1/path2',}, + extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/script/path1/path2') self.assertEqual(r.baseurl, b'http://testserver') @@ -418,10 +418,7 @@ class ParseRequestTests(unittest.TestCas DEFAULT_ENV, reponame=b'repo', altbaseurl=b'http://altserver/altroot', - extra={ - r'SCRIPT_NAME': r'/script', - r'PATH_INFO': r'/repo/path1/path2', - }, + extra={'SCRIPT_NAME': '/script', 'PATH_INFO': '/repo/path1/path2',}, ) self.assertEqual(r.url, b'http://testserver/script/repo/path1/path2')