diff --git a/contrib/perf.py b/contrib/perf.py --- a/contrib/perf.py +++ b/contrib/perf.py @@ -3634,7 +3634,7 @@ Result is the number of markers in the repo.""" timer, fm = gettimer(ui) svfs = getsvfs(repo) - timer(lambda: len(obsolete.obsstore(svfs))) + timer(lambda: len(obsolete.obsstore(repo, svfs))) fm.end() diff --git a/hgext/absorb.py b/hgext/absorb.py --- a/hgext/absorb.py +++ b/hgext/absorb.py @@ -36,6 +36,10 @@ import collections from mercurial.i18n import _ +from mercurial.node import ( + hex, + short, +) from mercurial import ( cmdutil, commands, @@ -44,7 +48,6 @@ error, linelog, mdiff, - node, obsolete, patch, phases, @@ -98,11 +101,14 @@ class emptyfilecontext(object): """minimal filecontext representing an empty file""" + def __init__(self, repo): + self._repo = repo + def data(self): return b'' def node(self): - return node.nullid + return self._repo.nullid def uniq(lst): @@ -208,7 +214,7 @@ if path in pctx: fctxs.append(pctx[path]) else: - fctxs.append(emptyfilecontext()) + fctxs.append(emptyfilecontext(pctx.repo())) fctxs.reverse() # note: we rely on a property of hg: filerev is not reused for linear @@ -367,7 +373,7 @@ idx = (max(rev - 1, 0)) // 2 self.ui.write( _(b'%s: chunk %d:%d -> %d lines\n') - % (node.short(self.fctxs[idx].node()), a1, a2, len(blines)) + % (short(self.fctxs[idx].node()), a1, a2, len(blines)) ) self.linelog.replacelines(rev, a1, a2, b1, b2) if self.opts.get(b'edit_lines', False): @@ -486,7 +492,7 @@ editortext += _(b'HG: %s/%s %s %s\n') % ( b'|' * i, b'-' * (len(visiblefctxs) - i + 1), - node.short(f.node()), + short(f.node()), f.description().split(b'\n', 1)[0], ) editortext += _(b'HG: %s\n') % (b'|' * len(visiblefctxs)) @@ -816,7 +822,7 @@ if self.ui.debugflag: return b'%d:%s' % (ctx.rev(), ctx.hex()) else: - return b'%d:%s' % (ctx.rev(), node.short(ctx.node())) + return b'%d:%s' % (ctx.rev(), short(ctx.node())) def _getnewfilecontents(self, ctx): """(ctx) -> {path: str} @@ -849,7 +855,7 @@ changes.append((name, hsh)) if self.ui.verbose: self.ui.write( - _(b'moving bookmark %s to %s\n') % (name, node.hex(hsh)) + _(b'moving bookmark %s to %s\n') % (name, hex(hsh)) ) else: changes.append((name, None)) @@ -920,7 +926,7 @@ the commit is a clone from ctx, with a (optionally) different p1, and different file contents replaced by memworkingcopy. """ - parents = p1 and (p1, node.nullid) + parents = p1 and (p1, self.repo.nullid) extra = ctx.extra() if self._useobsolete and self.ui.configbool(b'absorb', b'add-noise'): extra[b'absorb_source'] = ctx.hex() diff --git a/hgext/convert/git.py b/hgext/convert/git.py --- a/hgext/convert/git.py +++ b/hgext/convert/git.py @@ -9,10 +9,10 @@ import os from mercurial.i18n import _ +from mercurial.node import sha1nodeconstants from mercurial import ( config, error, - node as nodemod, pycompat, ) @@ -192,7 +192,7 @@ return heads def catfile(self, rev, ftype): - if rev == nodemod.nullhex: + if rev == sha1nodeconstants.nullhex: raise IOError self.catfilepipe[0].write(rev + b'\n') self.catfilepipe[0].flush() @@ -214,7 +214,7 @@ return data def getfile(self, name, rev): - if rev == nodemod.nullhex: + if rev == sha1nodeconstants.nullhex: return None, None if name == b'.hgsub': data = b'\n'.join([m.hgsub() for m in self.submoditer()]) @@ -228,7 +228,7 @@ return data, mode def submoditer(self): - null = nodemod.nullhex + null = sha1nodeconstants.nullhex for m in sorted(self.submodules, key=lambda p: p.path): if m.node != null: yield m @@ -316,7 +316,7 @@ subexists[0] = True if entry[4] == b'D' or renamesource: subdeleted[0] = True - changes.append((b'.hgsub', nodemod.nullhex)) + changes.append((b'.hgsub', sha1nodeconstants.nullhex)) else: changes.append((b'.hgsub', b'')) elif entry[1] == b'160000' or entry[0] == b':160000': @@ -324,7 +324,7 @@ subexists[0] = True else: if renamesource: - h = nodemod.nullhex + h = sha1nodeconstants.nullhex self.modecache[(f, h)] = (p and b"x") or (s and b"l") or b"" changes.append((f, h)) @@ -361,7 +361,7 @@ if subexists[0]: if subdeleted[0]: - changes.append((b'.hgsubstate', nodemod.nullhex)) + changes.append((b'.hgsubstate', sha1nodeconstants.nullhex)) else: self.retrievegitmodules(version) changes.append((b'.hgsubstate', b'')) diff --git a/hgext/convert/hg.py b/hgext/convert/hg.py --- a/hgext/convert/hg.py +++ b/hgext/convert/hg.py @@ -24,6 +24,11 @@ from mercurial.i18n import _ from mercurial.pycompat import open +from mercurial.node import ( + bin, + hex, + sha1nodeconstants, +) from mercurial import ( bookmarks, context, @@ -32,7 +37,6 @@ hg, lock as lockmod, merge as mergemod, - node as nodemod, phases, pycompat, scmutil, @@ -155,7 +159,7 @@ continue revid = revmap.get(source.lookuprev(s[0])) if not revid: - if s[0] == nodemod.nullhex: + if s[0] == sha1nodeconstants.nullhex: revid = s[0] else: # missing, but keep for hash stability @@ -174,7 +178,7 @@ revid = s[0] subpath = s[1] - if revid != nodemod.nullhex: + if revid != sha1nodeconstants.nullhex: revmap = self.subrevmaps.get(subpath) if revmap is None: revmap = mapfile( @@ -295,13 +299,13 @@ parents = pl nparents = len(parents) if self.filemapmode and nparents == 1: - m1node = self.repo.changelog.read(nodemod.bin(parents[0]))[0] + m1node = self.repo.changelog.read(bin(parents[0]))[0] parent = parents[0] if len(parents) < 2: - parents.append(nodemod.nullid) + parents.append(self.repo.nullid) if len(parents) < 2: - parents.append(nodemod.nullid) + parents.append(self.repo.nullid) p2 = parents.pop(0) text = commit.desc @@ -332,12 +336,12 @@ # Only transplant stores its reference in binary if label == b'transplant_source': - node = nodemod.hex(node) + node = hex(node) newrev = revmap.get(node) if newrev is not None: if label == b'transplant_source': - newrev = nodemod.bin(newrev) + newrev = bin(newrev) extra[label] = newrev @@ -351,7 +355,7 @@ p2 = parents.pop(0) p1ctx = self.repo[p1] p2ctx = None - if p2 != nodemod.nullid: + if p2 != self.repo.nullid: p2ctx = self.repo[p2] fileset = set(files) if full: @@ -389,7 +393,7 @@ origctx = commit.ctx else: origctx = None - node = nodemod.hex(self.repo.commitctx(ctx, origctx=origctx)) + node = hex(self.repo.commitctx(ctx, origctx=origctx)) # If the node value has changed, but the phase is lower than # draft, set it back to draft since it hasn't been exposed @@ -406,7 +410,7 @@ if self.filemapmode and nparents == 1: man = self.repo.manifestlog.getstorage(b'') - mnode = self.repo.changelog.read(nodemod.bin(p2))[0] + mnode = self.repo.changelog.read(bin(p2))[0] closed = b'close' in commit.extra if not closed and not man.cmp(m1node, man.revision(mnode)): self.ui.status(_(b"filtering out empty revision\n")) @@ -416,7 +420,7 @@ def puttags(self, tags): tagparent = self.repo.branchtip(self.tagsbranch, ignoremissing=True) - tagparent = tagparent or nodemod.nullid + tagparent = tagparent or self.repo.nullid oldlines = set() for branch, heads in pycompat.iteritems(self.repo.branchmap()): @@ -468,7 +472,7 @@ extra, ) node = self.repo.commitctx(ctx) - return nodemod.hex(node), nodemod.hex(tagparent) + return hex(node), hex(tagparent) def setfilemapmode(self, active): self.filemapmode = active @@ -484,7 +488,7 @@ self.ui.status(_(b"updating bookmarks\n")) destmarks = self.repo._bookmarks changes = [ - (bookmark, nodemod.bin(updatedbookmark[bookmark])) + (bookmark, bin(updatedbookmark[bookmark])) for bookmark in updatedbookmark ] destmarks.applychanges(self.repo, tr, changes) @@ -577,7 +581,7 @@ return [p for p in ctx.parents() if p and self.keep(p.node())] def getheads(self): - return [nodemod.hex(h) for h in self._heads if self.keep(h)] + return [hex(h) for h in self._heads if self.keep(h)] def getfile(self, name, rev): try: @@ -678,9 +682,7 @@ for t in self.repo.tagslist() if self.repo.tagtype(t[0]) == b'global' ] - return { - name: nodemod.hex(node) for name, node in tags if self.keep(node) - } + return {name: hex(node) for name, node in tags if self.keep(node)} def getchangedfiles(self, rev, i): ctx = self._changectx(rev) @@ -718,7 +720,7 @@ def lookuprev(self, rev): try: - return nodemod.hex(self.repo.lookup(rev)) + return hex(self.repo.lookup(rev)) except (error.RepoError, error.LookupError): return None diff --git a/hgext/extdiff.py b/hgext/extdiff.py --- a/hgext/extdiff.py +++ b/hgext/extdiff.py @@ -91,7 +91,7 @@ from mercurial.i18n import _ from mercurial.node import ( - nullid, + nullrev, short, ) from mercurial import ( @@ -551,7 +551,7 @@ if not revs: ctx1b = repo[None].p2() else: - ctx1b = repo[nullid] + ctx1b = repo[nullrev] node1a = ctx1a.node() node1b = ctx1b.node() @@ -559,7 +559,7 @@ # Disable 3-way merge if there is only one parent if do3way: - if node1b == nullid: + if node1b == repo.nullid: do3way = False matcher = scmutil.match(repo[node2], pats, opts) diff --git a/hgext/fastannotate/context.py b/hgext/fastannotate/context.py --- a/hgext/fastannotate/context.py +++ b/hgext/fastannotate/context.py @@ -17,12 +17,16 @@ open, setattr, ) +from mercurial.node import ( + bin, + hex, + short, +) from mercurial import ( error, linelog as linelogmod, lock as lockmod, mdiff, - node, pycompat, scmutil, util, @@ -150,7 +154,7 @@ diffoptstr = stringutil.pprint( sorted((k, getattr(diffopts, k)) for k in mdiff.diffopts.defaults) ) - return node.hex(hashutil.sha1(diffoptstr).digest())[:6] + return hex(hashutil.sha1(diffoptstr).digest())[:6] _defaultdiffopthash = hashdiffopts(mdiff.defaultopts) @@ -308,7 +312,7 @@ # command could give us a revision number even if the user passes a # commit hash. if isinstance(rev, int): - rev = node.hex(self.repo.changelog.node(rev)) + rev = hex(self.repo.changelog.node(rev)) # fast path: if rev is in the main branch already directly, revfctx = self.canannotatedirectly(rev) @@ -493,7 +497,7 @@ result = True f = None if not isinstance(rev, int) and rev is not None: - hsh = {20: bytes, 40: node.bin}.get(len(rev), lambda x: None)(rev) + hsh = {20: bytes, 40: bin}.get(len(rev), lambda x: None)(rev) if hsh is not None and (hsh, self.path) in self.revmap: f = hsh if f is None: @@ -598,7 +602,7 @@ self.ui.debug( b'fastannotate: reading %s line #%d ' b'to resolve lines %r\n' - % (node.short(hsh), linenum, idxs) + % (short(hsh), linenum, idxs) ) fctx = self._resolvefctx(hsh, revmap.rev2path(rev)) lines = mdiff.splitnewlines(fctx.data()) @@ -610,8 +614,7 @@ # run the annotate and the lines should match to the file content self.ui.debug( - b'fastannotate: annotate %s to resolve lines\n' - % node.short(hsh) + b'fastannotate: annotate %s to resolve lines\n' % short(hsh) ) linelog.annotate(rev) fctx = self._resolvefctx(hsh, revmap.rev2path(rev)) @@ -640,12 +643,10 @@ hsh = f.node() llrev = self.revmap.hsh2rev(hsh) if not llrev: - raise faerror.CorruptedFileError( - b'%s is not in revmap' % node.hex(hsh) - ) + raise faerror.CorruptedFileError(b'%s is not in revmap' % hex(hsh)) if (self.revmap.rev2flag(llrev) & revmapmod.sidebranchflag) != 0: raise faerror.CorruptedFileError( - b'%s is not in revmap mainbranch' % node.hex(hsh) + b'%s is not in revmap mainbranch' % hex(hsh) ) self.linelog.annotate(llrev) result = [ diff --git a/hgext/fastannotate/formatter.py b/hgext/fastannotate/formatter.py --- a/hgext/fastannotate/formatter.py +++ b/hgext/fastannotate/formatter.py @@ -6,9 +6,12 @@ # GNU General Public License version 2 or any later version. from __future__ import absolute_import +from mercurial.node import ( + hex, + short, +) from mercurial import ( encoding, - node, pycompat, templatefilters, util, @@ -116,9 +119,9 @@ @util.propertycache def _hexfunc(self): if self.ui.debugflag or self.opts.get(b'long_hash'): - return node.hex + return hex else: - return node.short + return short def end(self): pass @@ -168,7 +171,7 @@ @util.propertycache def _hexfunc(self): - return node.hex + return hex def end(self): self.ui.write(b'\n]\n') diff --git a/hgext/fix.py b/hgext/fix.py --- a/hgext/fix.py +++ b/hgext/fix.py @@ -131,8 +131,10 @@ import subprocess from mercurial.i18n import _ -from mercurial.node import nullrev -from mercurial.node import wdirrev +from mercurial.node import ( + nullrev, + wdirrev, +) from mercurial.utils import procutil diff --git a/hgext/git/dirstate.py b/hgext/git/dirstate.py --- a/hgext/git/dirstate.py +++ b/hgext/git/dirstate.py @@ -4,11 +4,11 @@ import errno import os +from mercurial.node import sha1nodeconstants from mercurial import ( error, extensions, match as matchmod, - node as nodemod, pycompat, scmutil, util, @@ -81,14 +81,16 @@ except pygit2.GitError: # Typically happens when peeling HEAD fails, as in an # empty repository. - return nodemod.nullid + return sha1nodeconstants.nullid def p2(self): # TODO: MERGE_HEAD? something like that, right? - return nodemod.nullid + return sha1nodeconstants.nullid - def setparents(self, p1, p2=nodemod.nullid): - assert p2 == nodemod.nullid, b'TODO merging support' + def setparents(self, p1, p2=None): + if p2 is None: + p2 = sha1nodeconstants.nullid + assert p2 == sha1nodeconstants.nullid, b'TODO merging support' self.git.head.set_target(gitutil.togitnode(p1)) @util.propertycache @@ -102,7 +104,7 @@ def parents(self): # TODO how on earth do we find p2 if a merge is in flight? - return self.p1(), nodemod.nullid + return self.p1(), sha1nodeconstants.nullid def __iter__(self): return (pycompat.fsencode(f.path) for f in self.git.index) diff --git a/hgext/git/gitlog.py b/hgext/git/gitlog.py --- a/hgext/git/gitlog.py +++ b/hgext/git/gitlog.py @@ -1,6 +1,12 @@ from __future__ import absolute_import from mercurial.i18n import _ +from mercurial.node import ( + bin, + hex, + nullrev, + sha1nodeconstants, +) from mercurial import ( ancestor, @@ -9,7 +15,6 @@ encoding, error, manifest, - node as nodemod, pycompat, ) from mercurial.interfaces import ( @@ -39,7 +44,7 @@ ) def rev(self, n): - if n == nodemod.nullid: + if n == sha1nodeconstants.nullid: return -1 t = self._db.execute( 'SELECT rev FROM changelog WHERE node = ?', (gitutil.togitnode(n),) @@ -49,14 +54,14 @@ return t[0] def node(self, r): - if r == nodemod.nullrev: - return nodemod.nullid + if r == nullrev: + return sha1nodeconstants.nullid t = self._db.execute( 'SELECT node FROM changelog WHERE rev = ?', (r,) ).fetchone() if t is None: raise error.LookupError(r, b'00changelog.i', _(b'no node')) - return nodemod.bin(t[0]) + return bin(t[0]) def hasnode(self, n): t = self._db.execute( @@ -123,10 +128,10 @@ @property def nodemap(self): r = { - nodemod.bin(v[0]): v[1] + bin(v[0]): v[1] for v in self._db.execute('SELECT node, rev FROM changelog') } - r[nodemod.nullid] = nodemod.nullrev + r[sha1nodeconstants.nullid] = nullrev return r def tip(self): @@ -134,8 +139,8 @@ 'SELECT node FROM changelog ORDER BY rev DESC LIMIT 1' ).fetchone() if t: - return nodemod.bin(t[0]) - return nodemod.nullid + return bin(t[0]) + return sha1nodeconstants.nullid def revs(self, start=0, stop=None): if stop is None: @@ -150,23 +155,21 @@ def tiprev(self): t = self._db.execute( - 'SELECT rev FROM changelog ' - 'ORDER BY REV DESC ' - 'LIMIT 1' + 'SELECT rev FROM changelog ' 'ORDER BY REV DESC ' 'LIMIT 1' ) return next(t) def _partialmatch(self, id): - if nodemod.wdirhex.startswith(id): + if sha1nodeconstants.wdirhex.startswith(id): raise error.WdirUnsupported candidates = [ - nodemod.bin(x[0]) + bin(x[0]) for x in self._db.execute( 'SELECT node FROM changelog WHERE node LIKE ?', (id + b'%',) ) ] - if nodemod.nullhex.startswith(id): - candidates.append(nodemod.nullid) + if sha1nodeconstants.nullhex.startswith(id): + candidates.append(sha1nodeconstants.nullid) if len(candidates) > 1: raise error.AmbiguousPrefixLookupError( id, b'00changelog.i', _(b'ambiguous identifier') @@ -179,7 +182,7 @@ return 0 def shortest(self, node, minlength=1): - nodehex = nodemod.hex(node) + nodehex = hex(node) for attempt in pycompat.xrange(minlength, len(nodehex) + 1): candidate = nodehex[:attempt] matches = int( @@ -211,7 +214,7 @@ else: n = nodeorrev # handle looking up nullid - if n == nodemod.nullid: + if n == sha1nodeconstants.nullid: return hgchangelog._changelogrevision(extra={}) hn = gitutil.togitnode(n) # We've got a real commit! @@ -228,7 +231,7 @@ for r in self._db.execute( 'SELECT filename FROM changedfiles ' 'WHERE node = ? and filenode = ?', - (hn, nodemod.nullhex), + (hn, sha1nodeconstants.nullhex), ) ] c = self.gitrepo[hn] @@ -269,7 +272,7 @@ nullrev. """ if common is None: - common = [nodemod.nullrev] + common = [nullrev] return ancestor.incrementalmissingancestors(self.parentrevs, common) @@ -289,7 +292,7 @@ not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: - common = [nodemod.nullid] + common = [sha1nodeconstants.nullid] if heads is None: heads = self.heads() @@ -304,12 +307,12 @@ c = [] p = self.rev(node) for r in self.revs(start=p + 1): - prevs = [pr for pr in self.parentrevs(r) if pr != nodemod.nullrev] + prevs = [pr for pr in self.parentrevs(r) if pr != nullrev] if prevs: for pr in prevs: if pr == p: c.append(self.node(r)) - elif p == nodemod.nullrev: + elif p == nullrev: c.append(self.node(r)) return c @@ -325,7 +328,7 @@ # Cleanup opportunity: this is *identical* to the revlog.py version def isancestorrev(self, a, b): - if a == nodemod.nullrev: + if a == nullrev: return True elif a == b: return True @@ -339,8 +342,8 @@ if hn != gitutil.nullgit: c = self.gitrepo[hn] else: - return nodemod.nullrev, nodemod.nullrev - p1 = p2 = nodemod.nullrev + return nullrev, nullrev + p1 = p2 = nullrev if c.parents: p1 = self.rev(c.parents[0].id.raw) if len(c.parents) > 2: @@ -388,9 +391,9 @@ ): parents = [] hp1, hp2 = gitutil.togitnode(p1), gitutil.togitnode(p2) - if p1 != nodemod.nullid: + if p1 != sha1nodeconstants.nullid: parents.append(hp1) - if p2 and p2 != nodemod.nullid: + if p2 and p2 != sha1nodeconstants.nullid: parents.append(hp2) assert date is not None timestamp, tz = date @@ -421,7 +424,7 @@ return self.get(b'', node) def get(self, relpath, node): - if node == nodemod.nullid: + if node == sha1nodeconstants.nullid: # TODO: this should almost certainly be a memgittreemanifestctx return manifest.memtreemanifestctx(self, relpath) commit = self.gitrepo[gitutil.togitnode(node)] @@ -440,9 +443,10 @@ super(filelog, self).__init__(gr, db) assert isinstance(path, bytes) self.path = path + self.nullid = sha1nodeconstants.nullid def read(self, node): - if node == nodemod.nullid: + if node == sha1nodeconstants.nullid: return b'' return self.gitrepo[gitutil.togitnode(node)].data @@ -452,7 +456,7 @@ if isinstance(node, int): assert False, b'todo revnums for nodes' if len(node) == 40: - node = nodemod.bin(node) + node = bin(node) hnode = gitutil.togitnode(node) if hnode in self.gitrepo: return node @@ -502,7 +506,7 @@ ).fetchone() if maybe is None: raise IndexError('gitlog %r out of range %d' % (self.path, rev)) - return nodemod.bin(maybe[0]) + return bin(maybe[0]) def parents(self, node): gn = gitutil.togitnode(node) @@ -527,7 +531,7 @@ index.fill_in_filelog(self.gitrepo, self._db, commit, gp, gn) return self.parents(node) else: - ps.append(nodemod.bin(p)) + ps.append(bin(p)) return ps def renamed(self, node): diff --git a/hgext/git/gitutil.py b/hgext/git/gitutil.py --- a/hgext/git/gitutil.py +++ b/hgext/git/gitutil.py @@ -1,7 +1,7 @@ """utilities to assist in working with pygit2""" from __future__ import absolute_import -from mercurial.node import bin, hex, nullid +from mercurial.node import bin, hex, sha1nodeconstants from mercurial import pycompat @@ -37,4 +37,4 @@ return bin(n) -nullgit = togitnode(nullid) +nullgit = togitnode(sha1nodeconstants.nullid) diff --git a/hgext/git/index.py b/hgext/git/index.py --- a/hgext/git/index.py +++ b/hgext/git/index.py @@ -5,11 +5,11 @@ import sqlite3 from mercurial.i18n import _ +from mercurial.node import sha1nodeconstants from mercurial import ( encoding, error, - node as nodemod, pycompat, ) @@ -278,7 +278,7 @@ for pos, commit in enumerate(walker): if prog is not None: prog.update(pos) - p1 = p2 = nodemod.nullhex + p1 = p2 = sha1nodeconstants.nullhex if len(commit.parents) > 2: raise error.ProgrammingError( ( @@ -317,7 +317,7 @@ files = { nf.path: nf.id.hex for nf in new_files - if nf.id.raw != nodemod.nullid + if nf.id.raw != sha1nodeconstants.nullid } for p, n in files.items(): # We intentionally set NULLs for any file parentage diff --git a/hgext/gpg.py b/hgext/gpg.py --- a/hgext/gpg.py +++ b/hgext/gpg.py @@ -11,12 +11,16 @@ import os from mercurial.i18n import _ +from mercurial.node import ( + bin, + hex, + short, +) from mercurial import ( cmdutil, error, help, match, - node as hgnode, pycompat, registrar, ) @@ -144,7 +148,7 @@ # read the heads fl = repo.file(b".hgsigs") for r in reversed(fl.heads()): - fn = b".hgsigs|%s" % hgnode.short(r) + fn = b".hgsigs|%s" % short(r) for item in parsefile(fl.read(r).splitlines(), fn): yield item try: @@ -161,7 +165,7 @@ fn, ln = context node, version, sig = sigdata prefix = b"%s:%d" % (fn, ln) - node = hgnode.bin(node) + node = bin(node) data = node2txt(repo, node, version) sig = binascii.a2b_base64(sig) @@ -212,7 +216,7 @@ revs[r].extend(keys) for rev in sorted(revs, reverse=True): for k in revs[rev]: - r = b"%5d:%s" % (rev, hgnode.hex(repo.changelog.node(rev))) + r = b"%5d:%s" % (rev, hex(repo.changelog.node(rev))) ui.write(b"%-30s %s\n" % (keystr(ui, k), r)) @@ -221,7 +225,7 @@ """verify all the signatures there may be for a particular revision""" mygpg = newgpg(ui) rev = repo.lookup(rev) - hexrev = hgnode.hex(rev) + hexrev = hex(rev) keys = [] for data, context in sigwalk(repo): @@ -232,11 +236,11 @@ keys.extend(k) if not keys: - ui.write(_(b"no valid signature for %s\n") % hgnode.short(rev)) + ui.write(_(b"no valid signature for %s\n") % short(rev)) return # print summary - ui.write(_(b"%s is signed by:\n") % hgnode.short(rev)) + ui.write(_(b"%s is signed by:\n") % short(rev)) for key in keys: ui.write(b" %s\n" % keystr(ui, key)) @@ -299,7 +303,7 @@ nodes = [repo.lookup(n) for n in revs] else: nodes = [ - node for node in repo.dirstate.parents() if node != hgnode.nullid + node for node in repo.dirstate.parents() if node != repo.nullid ] if len(nodes) > 1: raise error.Abort( @@ -309,10 +313,8 @@ nodes = [repo.changelog.tip()] for n in nodes: - hexnode = hgnode.hex(n) - ui.write( - _(b"signing %d:%s\n") % (repo.changelog.rev(n), hgnode.short(n)) - ) + hexnode = hex(n) + ui.write(_(b"signing %d:%s\n") % (repo.changelog.rev(n), short(n))) # build data data = node2txt(repo, n, sigver) sig = mygpg.sign(data) @@ -349,10 +351,7 @@ if not message: # we don't translate commit messages message = b"\n".join( - [ - b"Added signature for changeset %s" % hgnode.short(n) - for n in nodes - ] + [b"Added signature for changeset %s" % short(n) for n in nodes] ) try: editor = cmdutil.getcommiteditor( @@ -368,7 +367,7 @@ def node2txt(repo, node, ver): """map a manifest into some text""" if ver == b"0": - return b"%s\n" % hgnode.hex(node) + return b"%s\n" % hex(node) else: raise error.Abort(_(b"unknown signature version")) diff --git a/hgext/hgk.py b/hgext/hgk.py --- a/hgext/hgk.py +++ b/hgext/hgk.py @@ -40,7 +40,6 @@ from mercurial.i18n import _ from mercurial.node import ( - nullid, nullrev, short, ) @@ -93,7 +92,7 @@ mmap2 = repo[node2].manifest() m = scmutil.match(repo[node1], files) st = repo.status(node1, node2, m) - empty = short(nullid) + empty = short(repo.nullid) for f in st.modified: # TODO get file permissions @@ -315,9 +314,9 @@ parentstr = b"" if parents: pp = repo.changelog.parents(n) - if pp[0] != nullid: + if pp[0] != repo.nullid: parentstr += b" " + short(pp[0]) - if pp[1] != nullid: + if pp[1] != repo.nullid: parentstr += b" " + short(pp[1]) if not full: ui.write(b"%s%s\n" % (short(n), parentstr)) diff --git a/hgext/histedit.py b/hgext/histedit.py --- a/hgext/histedit.py +++ b/hgext/histedit.py @@ -209,6 +209,11 @@ getattr, open, ) +from mercurial.node import ( + bin, + hex, + short, +) from mercurial import ( bundle2, cmdutil, @@ -225,7 +230,6 @@ merge as mergemod, mergestate as mergestatemod, mergeutil, - node, obsolete, pycompat, registrar, @@ -392,8 +396,8 @@ def _write(self, fp): fp.write(b'v1\n') - fp.write(b'%s\n' % node.hex(self.parentctxnode)) - fp.write(b'%s\n' % node.hex(self.topmost)) + fp.write(b'%s\n' % hex(self.parentctxnode)) + fp.write(b'%s\n' % hex(self.topmost)) fp.write(b'%s\n' % (b'True' if self.keep else b'False')) fp.write(b'%d\n' % len(self.actions)) for action in self.actions: @@ -403,8 +407,8 @@ fp.write( b'%s%s\n' % ( - node.hex(replacement[0]), - b''.join(node.hex(r) for r in replacement[1]), + hex(replacement[0]), + b''.join(hex(r) for r in replacement[1]), ) ) backupfile = self.backupfile @@ -420,10 +424,10 @@ lines[index] # version number index += 1 - parentctxnode = node.bin(lines[index]) + parentctxnode = bin(lines[index]) index += 1 - topmost = node.bin(lines[index]) + topmost = bin(lines[index]) index += 1 keep = lines[index] == b'True' @@ -446,9 +450,9 @@ index += 1 for i in pycompat.xrange(replacementlen): replacement = lines[index] - original = node.bin(replacement[:40]) + original = bin(replacement[:40]) succ = [ - node.bin(replacement[i : i + 40]) + bin(replacement[i : i + 40]) for i in range(40, len(replacement), 40) ] replacements.append((original, succ)) @@ -483,12 +487,12 @@ # ruleid can be anything from rev numbers, hashes, "bookmarks" etc # Check for validation of rule ids and get the rulehash try: - rev = node.bin(ruleid) + rev = bin(ruleid) except TypeError: try: _ctx = scmutil.revsingle(state.repo, ruleid) rulehash = _ctx.hex() - rev = node.bin(rulehash) + rev = bin(rulehash) except error.RepoLookupError: raise error.ParseError(_(b"invalid changeset %s") % ruleid) return cls(state, rev) @@ -496,7 +500,7 @@ def verify(self, prev, expected, seen): """ Verifies semantic correctness of the rule""" repo = self.repo - ha = node.hex(self.node) + ha = hex(self.node) self.node = scmutil.resolvehexnodeidprefix(repo, ha) if self.node is None: raise error.ParseError(_(b'unknown changeset %s listed') % ha[:12]) @@ -507,14 +511,13 @@ if self.node not in expected: raise error.ParseError( _(b'%s "%s" changeset was not a candidate') - % (self.verb, node.short(self.node)), + % (self.verb, short(self.node)), hint=_(b'only use listed changesets'), ) # and only one command per node if self.node in seen: raise error.ParseError( - _(b'duplicated command for changeset %s') - % node.short(self.node) + _(b'duplicated command for changeset %s') % short(self.node) ) def torule(self): @@ -546,7 +549,7 @@ """Print an action in format used by histedit state files (the first line is a verb, the remainder is the second) """ - return b"%s\n%s" % (self.verb, node.hex(self.node)) + return b"%s\n%s" % (self.verb, hex(self.node)) def run(self): """Runs the action. The default behavior is simply apply the action's @@ -567,8 +570,7 @@ repo.dirstate.setbranch(rulectx.branch()) if stats.unresolvedcount: raise error.InterventionRequired( - _(b'Fix up the change (%s %s)') - % (self.verb, node.short(self.node)), + _(b'Fix up the change (%s %s)') % (self.verb, short(self.node)), hint=_(b'hg histedit --continue to resume'), ) @@ -603,8 +605,7 @@ ctx = self.repo[b'.'] if ctx.node() == self.state.parentctxnode: self.repo.ui.warn( - _(b'%s: skipping changeset (no changes)\n') - % node.short(self.node) + _(b'%s: skipping changeset (no changes)\n') % short(self.node) ) return ctx, [(self.node, tuple())] if ctx.node() == self.node: @@ -673,7 +674,7 @@ for c in ctxs: if not c.mutable(): raise error.ParseError( - _(b"cannot fold into public change %s") % node.short(c.node()) + _(b"cannot fold into public change %s") % short(c.node()) ) base = firstctx.p1() @@ -775,7 +776,7 @@ def run(self): rulectx = self.repo[self.node] if rulectx.p1().node() == self.state.parentctxnode: - self.repo.ui.debug(b'node %s unchanged\n' % node.short(self.node)) + self.repo.ui.debug(b'node %s unchanged\n' % short(self.node)) return rulectx, [] return super(pick, self).run() @@ -790,7 +791,7 @@ applychanges(repo.ui, repo, rulectx, {}) raise error.InterventionRequired( _(b'Editing (%s), you may commit or record as needed now.') - % node.short(self.node), + % short(self.node), hint=_(b'hg histedit --continue to resume'), ) @@ -812,7 +813,7 @@ c = repo[prev.node] if not c.mutable(): raise error.ParseError( - _(b"cannot fold into public change %s") % node.short(c.node()) + _(b"cannot fold into public change %s") % short(c.node()) ) def continuedirty(self): @@ -821,7 +822,7 @@ commit = commitfuncfor(repo, rulectx) commit( - text=b'fold-temp-revision %s' % node.short(self.node), + text=b'fold-temp-revision %s' % short(self.node), user=rulectx.user(), date=rulectx.date(), extra=rulectx.extra(), @@ -833,7 +834,7 @@ rulectx = repo[self.node] parentctxnode = self.state.parentctxnode if ctx.node() == parentctxnode: - repo.ui.warn(_(b'%s: empty changeset\n') % node.short(self.node)) + repo.ui.warn(_(b'%s: empty changeset\n') % short(self.node)) return ctx, [(self.node, (parentctxnode,))] parentctx = repo[parentctxnode] @@ -847,7 +848,7 @@ b'%s: cannot fold - working copy is not a ' b'descendant of previous commit %s\n' ) - % (node.short(self.node), node.short(parentctxnode)) + % (short(self.node), short(parentctxnode)) ) return ctx, [(self.node, (ctx.node(),))] @@ -961,7 +962,7 @@ if self.node in expected: msg = _(b'%s "%s" changeset was an edited list candidate') raise error.ParseError( - msg % (self.verb, node.short(self.node)), + msg % (self.verb, short(self.node)), hint=_(b'base must only use unlisted changesets'), ) @@ -1701,8 +1702,7 @@ revs = between(repo, root, topmost, keep) if not revs: raise error.Abort( - _(b'%s is not an ancestor of working directory') - % node.short(root) + _(b'%s is not an ancestor of working directory') % short(root) ) ctxs = [] @@ -2055,16 +2055,16 @@ if mapping: for prec, succs in pycompat.iteritems(mapping): if not succs: - ui.debug(b'histedit: %s is dropped\n' % node.short(prec)) + ui.debug(b'histedit: %s is dropped\n' % short(prec)) else: ui.debug( b'histedit: %s is replaced by %s\n' - % (node.short(prec), node.short(succs[0])) + % (short(prec), short(succs[0])) ) if len(succs) > 1: m = b'histedit: %s' for n in succs[1:]: - ui.debug(m % node.short(n)) + ui.debug(m % short(n)) if not state.keep: if mapping: @@ -2109,7 +2109,7 @@ try: state.read() __, leafs, tmpnodes, __ = processreplacement(state) - ui.debug(b'restore wc to old parent %s\n' % node.short(state.topmost)) + ui.debug(b'restore wc to old parent %s\n' % short(state.topmost)) # Recover our old commits if necessary if not state.topmost in repo and state.backupfile: @@ -2163,7 +2163,7 @@ state.read() if not rules: comment = geteditcomment( - ui, node.short(state.parentctxnode), node.short(state.topmost) + ui, short(state.parentctxnode), short(state.topmost) ) rules = ruleeditor(repo, ui, state.actions, comment) else: @@ -2204,7 +2204,7 @@ revs = between(repo, root, topmost, state.keep) if not revs: raise error.Abort( - _(b'%s is not an ancestor of working directory') % node.short(root) + _(b'%s is not an ancestor of working directory') % short(root) ) ctxs = [repo[r] for r in revs] @@ -2241,7 +2241,7 @@ ) if not rules: - comment = geteditcomment(ui, node.short(root), node.short(topmost)) + comment = geteditcomment(ui, short(root), short(topmost)) actions = [pick(state, r) for r in revs] rules = ruleeditor(repo, ui, actions, comment) else: @@ -2445,12 +2445,12 @@ actions[:0] = drops elif missing: raise error.ParseError( - _(b'missing rules for changeset %s') % node.short(missing[0]), + _(b'missing rules for changeset %s') % short(missing[0]), hint=_( b'use "drop %s" to discard, see also: ' b"'hg help -e histedit.config'" ) - % node.short(missing[0]), + % short(missing[0]), ) @@ -2604,7 +2604,7 @@ if common_nodes: raise error.Abort( _(b"histedit in progress, can't strip %s") - % b', '.join(node.short(x) for x in common_nodes) + % b', '.join(short(x) for x in common_nodes) ) return orig(ui, repo, nodelist, *args, **kwargs) diff --git a/hgext/infinitepush/bundleparts.py b/hgext/infinitepush/bundleparts.py --- a/hgext/infinitepush/bundleparts.py +++ b/hgext/infinitepush/bundleparts.py @@ -6,13 +6,13 @@ from __future__ import absolute_import from mercurial.i18n import _ +from mercurial.node import hex from mercurial import ( bundle2, changegroup, error, extensions, - node as nodemod, pycompat, revsetlang, util, @@ -54,7 +54,7 @@ params[b'bookprevnode'] = b'' bookmarks = repo._bookmarks if bookmark in bookmarks: - params[b'bookprevnode'] = nodemod.hex(bookmarks[bookmark]) + params[b'bookprevnode'] = hex(bookmarks[bookmark]) # Do not send pushback bundle2 part with bookmarks if remotenames extension # is enabled. It will be handled manually in `_push()` diff --git a/hgext/infinitepush/store.py b/hgext/infinitepush/store.py --- a/hgext/infinitepush/store.py +++ b/hgext/infinitepush/store.py @@ -10,10 +10,9 @@ import subprocess from mercurial.pycompat import open -from mercurial import ( - node, - pycompat, -) +from mercurial.node import hex +from mercurial import pycompat + from mercurial.utils import ( hashutil, procutil, @@ -86,7 +85,7 @@ return os.path.join(self._dirpath(filename), filename) def write(self, data): - filename = node.hex(hashutil.sha1(data).digest()) + filename = hex(hashutil.sha1(data).digest()) dirpath = self._dirpath(filename) if not os.path.exists(dirpath): diff --git a/hgext/journal.py b/hgext/journal.py --- a/hgext/journal.py +++ b/hgext/journal.py @@ -19,6 +19,10 @@ import weakref from mercurial.i18n import _ +from mercurial.node import ( + bin, + hex, +) from mercurial import ( bookmarks, @@ -31,7 +35,6 @@ localrepo, lock, logcmdutil, - node, pycompat, registrar, util, @@ -113,8 +116,8 @@ new = list(new) if util.safehasattr(dirstate, 'journalstorage'): # only record two hashes if there was a merge - oldhashes = old[:1] if old[1] == node.nullid else old - newhashes = new[:1] if new[1] == node.nullid else new + oldhashes = old[:1] if old[1] == dirstate._nodeconstants.nullid else old + newhashes = new[:1] if new[1] == dirstate._nodeconstants.nullid else new dirstate.journalstorage.record( wdirparenttype, b'.', oldhashes, newhashes ) @@ -127,7 +130,7 @@ if util.safehasattr(repo, 'journal'): oldmarks = bookmarks.bmstore(repo) for mark, value in pycompat.iteritems(store): - oldvalue = oldmarks.get(mark, node.nullid) + oldvalue = oldmarks.get(mark, repo.nullid) if value != oldvalue: repo.journal.record(bookmarktype, mark, oldvalue, value) return orig(store, fp) @@ -248,8 +251,8 @@ ) = line.split(b'\n') timestamp, tz = time.split() timestamp, tz = float(timestamp), int(tz) - oldhashes = tuple(node.bin(hash) for hash in oldhashes.split(b',')) - newhashes = tuple(node.bin(hash) for hash in newhashes.split(b',')) + oldhashes = tuple(bin(hash) for hash in oldhashes.split(b',')) + newhashes = tuple(bin(hash) for hash in newhashes.split(b',')) return cls( (timestamp, tz), user, @@ -263,8 +266,8 @@ def __bytes__(self): """bytes representation for storage""" time = b' '.join(map(pycompat.bytestr, self.timestamp)) - oldhashes = b','.join([node.hex(hash) for hash in self.oldhashes]) - newhashes = b','.join([node.hex(hash) for hash in self.newhashes]) + oldhashes = b','.join([hex(hash) for hash in self.oldhashes]) + newhashes = b','.join([hex(hash) for hash in self.newhashes]) return b'\n'.join( ( time, diff --git a/hgext/largefiles/basestore.py b/hgext/largefiles/basestore.py --- a/hgext/largefiles/basestore.py +++ b/hgext/largefiles/basestore.py @@ -10,8 +10,8 @@ from __future__ import absolute_import from mercurial.i18n import _ - -from mercurial import node, util +from mercurial.node import short +from mercurial import util from . import lfutil @@ -134,7 +134,7 @@ filestocheck = [] # list of (cset, filename, expectedhash) for rev in revs: cctx = self.repo[rev] - cset = b"%d:%s" % (cctx.rev(), node.short(cctx.node())) + cset = b"%d:%s" % (cctx.rev(), short(cctx.node())) for standin in cctx: filename = lfutil.splitstandin(standin) diff --git a/hgext/largefiles/lfcommands.py b/hgext/largefiles/lfcommands.py --- a/hgext/largefiles/lfcommands.py +++ b/hgext/largefiles/lfcommands.py @@ -14,6 +14,10 @@ import shutil from mercurial.i18n import _ +from mercurial.node import ( + bin, + hex, +) from mercurial import ( cmdutil, @@ -23,7 +27,6 @@ hg, lock, match as matchmod, - node, pycompat, scmutil, util, @@ -111,7 +114,7 @@ rsrc[ctx] for ctx in rsrc.changelog.nodesbetween(None, rsrc.heads())[0] ) - revmap = {node.nullid: node.nullid} + revmap = {rsrc.nullid: rdst.nullid} if tolfile: # Lock destination to prevent modification while it is converted to. # Don't need to lock src because we are just reading from its @@ -275,7 +278,7 @@ # largefile was modified, update standins m = hashutil.sha1(b'') m.update(ctx[f].data()) - hash = node.hex(m.digest()) + hash = hex(m.digest()) if f not in lfiletohash or lfiletohash[f] != hash: rdst.wwrite(f, ctx[f].data(), ctx[f].flags()) executable = b'x' in ctx[f].flags() @@ -336,7 +339,7 @@ # Generate list of changed files def _getchangedfiles(ctx, parents): files = set(ctx.files()) - if node.nullid not in parents: + if ctx.repo().nullid not in parents: mc = ctx.manifest() for pctx in ctx.parents(): for fn in pctx.manifest().diff(mc): @@ -350,7 +353,7 @@ for p in ctx.parents(): parents.append(revmap[p.node()]) while len(parents) < 2: - parents.append(node.nullid) + parents.append(ctx.repo().nullid) return parents @@ -380,12 +383,12 @@ ui.warn(_(b'skipping incorrectly formatted tag %s\n') % line) continue try: - newid = node.bin(id) + newid = bin(id) except TypeError: ui.warn(_(b'skipping incorrectly formatted id %s\n') % id) continue try: - newdata.append(b'%s %s\n' % (node.hex(revmap[newid]), name)) + newdata.append(b'%s %s\n' % (hex(revmap[newid]), name)) except KeyError: ui.warn(_(b'no mapping for id %s\n') % id) continue diff --git a/hgext/largefiles/lfutil.py b/hgext/largefiles/lfutil.py --- a/hgext/largefiles/lfutil.py +++ b/hgext/largefiles/lfutil.py @@ -24,7 +24,6 @@ error, httpconnection, match as matchmod, - node, pycompat, scmutil, sparse, @@ -204,6 +203,7 @@ repo.root, repo.dirstate._validate, lambda: sparse.matcher(repo), + repo.nodeconstants, ) # If the largefiles dirstate does not exist, populate and create @@ -610,7 +610,7 @@ ) as progress: for i, n in enumerate(missing): progress.update(i) - parents = [p for p in repo[n].parents() if p != node.nullid] + parents = [p for p in repo[n].parents() if p != repo.nullid] with lfstatus(repo, value=False): ctx = repo[n] diff --git a/hgext/lfs/__init__.py b/hgext/lfs/__init__.py --- a/hgext/lfs/__init__.py +++ b/hgext/lfs/__init__.py @@ -125,6 +125,7 @@ import sys from mercurial.i18n import _ +from mercurial.node import bin from mercurial import ( bundlecaches, @@ -137,7 +138,6 @@ filesetlang, localrepo, minifileset, - node, pycompat, revlog, scmutil, @@ -242,11 +242,10 @@ return 0 last = kwargs.get('node_last') - _bin = node.bin if last: - s = repo.set(b'%n:%n', _bin(kwargs['node']), _bin(last)) + s = repo.set(b'%n:%n', bin(kwargs['node']), bin(last)) else: - s = repo.set(b'%n', _bin(kwargs['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? diff --git a/hgext/lfs/blobstore.py b/hgext/lfs/blobstore.py --- a/hgext/lfs/blobstore.py +++ b/hgext/lfs/blobstore.py @@ -17,12 +17,12 @@ from mercurial.i18n import _ from mercurial.pycompat import getattr +from mercurial.node import hex from mercurial import ( encoding, error, httpconnection as httpconnectionmod, - node, pathutil, pycompat, url as urlmod, @@ -174,7 +174,7 @@ ) raise LfsRemoteError(_(msg) % (size, int(content_length))) - realoid = node.hex(sha256.digest()) + realoid = hex(sha256.digest()) if realoid != oid: raise LfsCorruptionError( _(b'corrupt remote lfs object: %s') % oid @@ -225,7 +225,7 @@ # Don't abort if corruption is detected, because `hg verify` will # give more useful info about the corruption- simply don't add the # hardlink. - if verify or node.hex(hashlib.sha256(blob).digest()) == oid: + if verify or hex(hashlib.sha256(blob).digest()) == oid: self.ui.note(_(b'lfs: found %s in the usercache\n') % oid) lfutil.link(self.cachevfs.join(oid), self.vfs.join(oid)) else: @@ -249,7 +249,7 @@ for chunk in util.filechunkiter(fp, size=1048576): sha256.update(chunk) - return oid == node.hex(sha256.digest()) + return oid == hex(sha256.digest()) def has(self, oid): """Returns True if the local blobstore contains the requested blob, @@ -704,7 +704,7 @@ def _verify(oid, content): - realoid = node.hex(hashlib.sha256(content).digest()) + realoid = hex(hashlib.sha256(content).digest()) if realoid != oid: raise LfsCorruptionError( _(b'detected corrupt lfs object: %s') % oid, diff --git a/hgext/lfs/wrapper.py b/hgext/lfs/wrapper.py --- a/hgext/lfs/wrapper.py +++ b/hgext/lfs/wrapper.py @@ -10,7 +10,7 @@ import hashlib from mercurial.i18n import _ -from mercurial.node import bin, hex, nullid, short +from mercurial.node import bin, hex, short from mercurial.pycompat import ( getattr, setattr, @@ -154,7 +154,7 @@ rev = rlog.rev(node) else: node = rlog.node(rev) - if node == nullid: + if node == rlog.nullid: return False flags = rlog.flags(rev) return bool(flags & revlog.REVIDX_EXTSTORED) diff --git a/hgext/mq.py b/hgext/mq.py --- a/hgext/mq.py +++ b/hgext/mq.py @@ -73,7 +73,6 @@ from mercurial.node import ( bin, hex, - nullid, nullrev, short, ) @@ -899,13 +898,13 @@ """ if rev is None: (p1, p2) = repo.dirstate.parents() - if p2 == nullid: + if p2 == repo.nullid: return p1 if not self.applied: return None return self.applied[-1].node p1, p2 = repo.changelog.parents(rev) - if p2 != nullid and p2 in [x.node for x in self.applied]: + if p2 != repo.nullid and p2 in [x.node for x in self.applied]: return p2 return p1 @@ -1582,7 +1581,7 @@ for hs in repo.branchmap().iterheads(): heads.extend(hs) if not heads: - heads = [nullid] + heads = [repo.nullid] if repo.dirstate.p1() not in heads and not exact: self.ui.status(_(b"(working directory not at a head)\n")) @@ -1845,7 +1844,7 @@ fctx = ctx[f] repo.wwrite(f, fctx.data(), fctx.flags()) repo.dirstate.normal(f) - repo.setparents(qp, nullid) + repo.setparents(qp, repo.nullid) for patch in reversed(self.applied[start:end]): self.ui.status(_(b"popping %s\n") % patch.name) del self.applied[start:end] diff --git a/hgext/narrow/narrowbundle2.py b/hgext/narrow/narrowbundle2.py --- a/hgext/narrow/narrowbundle2.py +++ b/hgext/narrow/narrowbundle2.py @@ -11,7 +11,6 @@ import struct from mercurial.i18n import _ -from mercurial.node import nullid from mercurial import ( bundle2, changegroup, @@ -87,7 +86,7 @@ raise error.Abort(_(b'depth must be positive, got %d') % depth) heads = set(heads or repo.heads()) - common = set(common or [nullid]) + common = set(common or [repo.nullid]) visitnodes, relevant_nodes, ellipsisroots = exchange._computeellipsis( repo, common, heads, set(), match, depth=depth @@ -115,7 +114,7 @@ def generate_ellipses_bundle2_for_widening( bundler, repo, oldmatch, newmatch, version, common, known, ): - common = set(common or [nullid]) + common = set(common or [repo.nullid]) # Steps: # 1. Send kill for "$known & ::common" # diff --git a/hgext/narrow/narrowcommands.py b/hgext/narrow/narrowcommands.py --- a/hgext/narrow/narrowcommands.py +++ b/hgext/narrow/narrowcommands.py @@ -10,6 +10,10 @@ import os from mercurial.i18n import _ +from mercurial.node import ( + hex, + short, +) from mercurial import ( bundle2, cmdutil, @@ -21,7 +25,6 @@ extensions, hg, narrowspec, - node, pathutil, pycompat, registrar, @@ -184,9 +187,9 @@ # we have all the nodes if wireprototypes.ELLIPSESCAP1 in pullop.remote.capabilities(): kwargs[b'known'] = [ - node.hex(ctx.node()) + hex(ctx.node()) for ctx in repo.set(b'::%ln', pullop.common) - if ctx.node() != node.nullid + if ctx.node() != repo.nullid ] if not kwargs[b'known']: # Mercurial serializes an empty list as '' and deserializes it as @@ -239,10 +242,10 @@ maxnodes = 10 if ui.verbose or len(visibletostrip) <= maxnodes: for n in visibletostrip: - ui.status(b'%s\n' % node.short(n)) + ui.status(b'%s\n' % short(n)) else: for n in visibletostrip[:maxnodes]: - ui.status(b'%s\n' % node.short(n)) + ui.status(b'%s\n' % short(n)) ui.status( _(b'...and %d more, use --verbose to list all\n') % (len(visibletostrip) - maxnodes) @@ -362,7 +365,7 @@ ds = repo.dirstate p1, p2 = ds.p1(), ds.p2() with ds.parentchange(): - ds.setparents(node.nullid, node.nullid) + ds.setparents(repo.nullid, repo.nullid) if isoldellipses: with wrappedextraprepare: exchange.pull(repo, remote, heads=common) @@ -372,7 +375,7 @@ known = [ ctx.node() for ctx in repo.set(b'::%ln', common) - if ctx.node() != node.nullid + if ctx.node() != repo.nullid ] with remote.commandexecutor() as e: bundle = e.callcommand( diff --git a/hgext/patchbomb.py b/hgext/patchbomb.py --- a/hgext/patchbomb.py +++ b/hgext/patchbomb.py @@ -82,6 +82,7 @@ import socket from mercurial.i18n import _ +from mercurial.node import bin from mercurial.pycompat import open from mercurial import ( cmdutil, @@ -91,7 +92,6 @@ formatter, hg, mail, - node as nodemod, patch, pycompat, registrar, @@ -287,7 +287,7 @@ p = mail.mimetextpatch( b'\n'.join(patchlines), 'x-patch', opts.get(b'test') ) - binnode = nodemod.bin(node) + binnode = bin(node) # if node is mq patch, it will have the patch file's name as a tag if not patchname: patchtags = [ diff --git a/hgext/phabricator.py b/hgext/phabricator.py --- a/hgext/phabricator.py +++ b/hgext/phabricator.py @@ -54,7 +54,7 @@ import operator import re -from mercurial.node import bin, nullid, short +from mercurial.node import bin, short from mercurial.i18n import _ from mercurial.pycompat import getattr from mercurial.thirdparty import attr @@ -526,7 +526,7 @@ tags.tag( repo, tagname, - nullid, + repo.nullid, message=None, user=None, date=None, @@ -1545,7 +1545,7 @@ tags.tag( repo, tagname, - nullid, + repo.nullid, message=None, user=None, date=None, diff --git a/hgext/rebase.py b/hgext/rebase.py --- a/hgext/rebase.py +++ b/hgext/rebase.py @@ -23,6 +23,7 @@ from mercurial.node import ( nullrev, short, + wdirrev, ) from mercurial.pycompat import open from mercurial import ( @@ -37,7 +38,6 @@ merge as mergemod, mergestate as mergestatemod, mergeutil, - node as nodemod, obsolete, obsutil, patch, @@ -1365,7 +1365,7 @@ ) return None - if nodemod.wdirrev in rebaseset: + if wdirrev in rebaseset: raise error.Abort(_(b'cannot rebase the working copy')) rebasingwcp = repo[b'.'].rev() in rebaseset ui.log( diff --git a/hgext/releasenotes.py b/hgext/releasenotes.py --- a/hgext/releasenotes.py +++ b/hgext/releasenotes.py @@ -18,13 +18,13 @@ import re from mercurial.i18n import _ +from mercurial.node import hex from mercurial.pycompat import open from mercurial import ( cmdutil, config, error, minirst, - node, pycompat, registrar, scmutil, @@ -381,7 +381,7 @@ if not paragraphs: repo.ui.warn( _(b"error parsing releasenotes for revision: '%s'\n") - % node.hex(ctx.node()) + % hex(ctx.node()) ) if title: notes.addtitleditem(directive, title, paragraphs) diff --git a/hgext/remotefilelog/__init__.py b/hgext/remotefilelog/__init__.py --- a/hgext/remotefilelog/__init__.py +++ b/hgext/remotefilelog/__init__.py @@ -130,7 +130,10 @@ import time import traceback -from mercurial.node import hex +from mercurial.node import ( + hex, + wdirrev, +) from mercurial.i18n import _ from mercurial.pycompat import open from mercurial import ( @@ -150,7 +153,6 @@ match as matchmod, merge, mergestate as mergestatemod, - node as nodemod, patch, pycompat, registrar, @@ -1092,7 +1094,7 @@ if isenabled(repo): allfiles = [] for rev, match in revmatches: - if rev == nodemod.wdirrev or rev is None: + if rev == wdirrev or rev is None: continue ctx = repo[rev] mf = ctx.manifest() diff --git a/hgext/remotefilelog/basepack.py b/hgext/remotefilelog/basepack.py --- a/hgext/remotefilelog/basepack.py +++ b/hgext/remotefilelog/basepack.py @@ -8,12 +8,12 @@ import time from mercurial.i18n import _ +from mercurial.node import hex from mercurial.pycompat import ( getattr, open, ) from mercurial import ( - node as nodemod, policy, pycompat, util, @@ -429,7 +429,7 @@ return try: - sha = nodemod.hex(self.sha.digest()) + sha = hex(self.sha.digest()) self.packfp.close() self.writeindex() diff --git a/hgext/remotefilelog/contentstore.py b/hgext/remotefilelog/contentstore.py --- a/hgext/remotefilelog/contentstore.py +++ b/hgext/remotefilelog/contentstore.py @@ -2,7 +2,10 @@ import threading -from mercurial.node import hex, nullid +from mercurial.node import ( + hex, + sha1nodeconstants, +) from mercurial.pycompat import getattr from mercurial import ( mdiff, @@ -56,7 +59,7 @@ """ chain = self.getdeltachain(name, node) - if chain[-1][ChainIndicies.BASENODE] != nullid: + if chain[-1][ChainIndicies.BASENODE] != sha1nodeconstants.nullid: # If we didn't receive a full chain, throw raise KeyError((name, hex(node))) @@ -94,7 +97,7 @@ deltabasenode. """ chain = self._getpartialchain(name, node) - while chain[-1][ChainIndicies.BASENODE] != nullid: + while chain[-1][ChainIndicies.BASENODE] != sha1nodeconstants.nullid: x, x, deltabasename, deltabasenode, x = chain[-1] try: morechain = self._getpartialchain(deltabasename, deltabasenode) @@ -189,7 +192,12 @@ # Since remotefilelog content stores only contain full texts, just # return that. revision = self.get(name, node) - return revision, name, nullid, self.getmeta(name, node) + return ( + revision, + name, + sha1nodeconstants.nullid, + self.getmeta(name, node), + ) def getdeltachain(self, name, node): # Since remotefilelog content stores just contain full texts, we return @@ -197,7 +205,7 @@ # The nullid in the deltabasenode slot indicates that the revision is a # fulltext. revision = self.get(name, node) - return [(name, node, None, nullid, revision)] + return [(name, node, None, sha1nodeconstants.nullid, revision)] def getmeta(self, name, node): self._sanitizemetacache() @@ -239,7 +247,12 @@ def getdelta(self, name, node): revision = self.get(name, node) - return revision, name, nullid, self._shared.getmeta(name, node) + return ( + revision, + name, + sha1nodeconstants.nullid, + self._shared.getmeta(name, node), + ) def getdeltachain(self, name, node): # Since our remote content stores just contain full texts, we return a @@ -247,7 +260,7 @@ # The nullid in the deltabasenode slot indicates that the revision is a # fulltext. revision = self.get(name, node) - return [(name, node, None, nullid, revision)] + return [(name, node, None, sha1nodeconstants.nullid, revision)] def getmeta(self, name, node): self._fileservice.prefetch( @@ -278,11 +291,11 @@ def getdelta(self, name, node): revision = self.get(name, node) - return revision, name, nullid, self.getmeta(name, node) + return revision, name, self._cl.nullid, self.getmeta(name, node) def getdeltachain(self, name, node): revision = self.get(name, node) - return [(name, node, None, nullid, revision)] + return [(name, node, None, self._cl.nullid, revision)] def getmeta(self, name, node): rl = self._revlog(name) @@ -306,9 +319,9 @@ missing.discard(ancnode) p1, p2 = rl.parents(ancnode) - if p1 != nullid and p1 not in known: + if p1 != self._cl.nullid and p1 not in known: missing.add(p1) - if p2 != nullid and p2 not in known: + if p2 != self._cl.nullid and p2 not in known: missing.add(p2) linknode = self._cl.node(rl.linkrev(ancrev)) diff --git a/hgext/remotefilelog/datapack.py b/hgext/remotefilelog/datapack.py --- a/hgext/remotefilelog/datapack.py +++ b/hgext/remotefilelog/datapack.py @@ -3,7 +3,10 @@ import struct import zlib -from mercurial.node import hex, nullid +from mercurial.node import ( + hex, + sha1nodeconstants, +) from mercurial.i18n import _ from mercurial import ( pycompat, @@ -458,7 +461,7 @@ rawindex = b'' fmt = self.INDEXFORMAT for node, deltabase, offset, size in entries: - if deltabase == nullid: + if deltabase == sha1nodeconstants.nullid: deltabaselocation = FULLTEXTINDEXMARK else: # Instead of storing the deltabase node in the index, let's diff --git a/hgext/remotefilelog/debugcommands.py b/hgext/remotefilelog/debugcommands.py --- a/hgext/remotefilelog/debugcommands.py +++ b/hgext/remotefilelog/debugcommands.py @@ -9,7 +9,12 @@ import os import zlib -from mercurial.node import bin, hex, nullid, short +from mercurial.node import ( + bin, + hex, + sha1nodeconstants, + short, +) from mercurial.i18n import _ from mercurial.pycompat import open from mercurial import ( @@ -53,9 +58,9 @@ _(b"%s => %s %s %s %s\n") % (short(node), short(p1), short(p2), short(linknode), copyfrom) ) - if p1 != nullid: + if p1 != sha1nodeconstants.nullid: queue.append(p1) - if p2 != nullid: + if p2 != sha1nodeconstants.nullid: queue.append(p2) @@ -148,7 +153,7 @@ try: pp = r.parents(node) except Exception: - pp = [nullid, nullid] + pp = [repo.nullid, repo.nullid] ui.write( b"% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % ( @@ -193,7 +198,7 @@ node = r.node(i) pp = r.parents(node) ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i)) - if pp[1] != nullid: + if pp[1] != repo.nullid: ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i)) ui.write(b"}\n") @@ -208,7 +213,7 @@ filepath = os.path.join(root, file) size, firstnode, mapping = parsefileblob(filepath, decompress) for p1, p2, linknode, copyfrom in pycompat.itervalues(mapping): - if linknode == nullid: + if linknode == sha1nodeconstants.nullid: actualpath = os.path.relpath(root, path) key = fileserverclient.getcachekey( b"reponame", actualpath, file @@ -367,7 +372,7 @@ current = node deltabase = bases[current] - while deltabase != nullid: + while deltabase != sha1nodeconstants.nullid: if deltabase not in nodes: ui.warn( ( @@ -393,7 +398,7 @@ deltabase = bases[current] # Since ``node`` begins a valid chain, reset/memoize its base to nullid # so we don't traverse it again. - bases[node] = nullid + bases[node] = sha1nodeconstants.nullid return failures diff --git a/hgext/remotefilelog/fileserverclient.py b/hgext/remotefilelog/fileserverclient.py --- a/hgext/remotefilelog/fileserverclient.py +++ b/hgext/remotefilelog/fileserverclient.py @@ -14,7 +14,7 @@ import zlib from mercurial.i18n import _ -from mercurial.node import bin, hex, nullid +from mercurial.node import bin, hex from mercurial import ( error, node, @@ -602,9 +602,13 @@ # partition missing nodes into nullid and not-nullid so we can # warn about this filtering potentially shadowing bugs. - nullids = len([None for unused, id in missingids if id == nullid]) + nullids = len( + [None for unused, id in missingids if id == self.repo.nullid] + ) if nullids: - missingids = [(f, id) for f, id in missingids if id != nullid] + missingids = [ + (f, id) for f, id in missingids if id != self.repo.nullid + ] repo.ui.develwarn( ( b'remotefilelog not fetching %d null revs' diff --git a/hgext/remotefilelog/historypack.py b/hgext/remotefilelog/historypack.py --- a/hgext/remotefilelog/historypack.py +++ b/hgext/remotefilelog/historypack.py @@ -2,7 +2,10 @@ import struct -from mercurial.node import hex, nullid +from mercurial.node import ( + hex, + sha1nodeconstants, +) from mercurial import ( pycompat, util, @@ -147,9 +150,9 @@ pending.remove(ancnode) p1node = entry[ANC_P1NODE] p2node = entry[ANC_P2NODE] - if p1node != nullid and p1node not in known: + if p1node != sha1nodeconstants.nullid and p1node not in known: pending.add(p1node) - if p2node != nullid and p2node not in known: + if p2node != sha1nodeconstants.nullid and p2node not in known: pending.add(p2node) yield (ancnode, p1node, p2node, entry[ANC_LINKNODE], copyfrom) @@ -457,9 +460,9 @@ def parentfunc(node): x, p1, p2, x, x, x = entrymap[node] parents = [] - if p1 != nullid: + if p1 != sha1nodeconstants.nullid: parents.append(p1) - if p2 != nullid: + if p2 != sha1nodeconstants.nullid: parents.append(p2) return parents diff --git a/hgext/remotefilelog/metadatastore.py b/hgext/remotefilelog/metadatastore.py --- a/hgext/remotefilelog/metadatastore.py +++ b/hgext/remotefilelog/metadatastore.py @@ -1,6 +1,9 @@ from __future__ import absolute_import -from mercurial.node import hex, nullid +from mercurial.node import ( + hex, + sha1nodeconstants, +) from . import ( basestore, shallowutil, @@ -51,9 +54,9 @@ missing.append((name, node)) continue p1, p2, linknode, copyfrom = value - if p1 != nullid and p1 not in known: + if p1 != sha1nodeconstants.nullid and p1 not in known: queue.append((copyfrom or curname, p1)) - if p2 != nullid and p2 not in known: + if p2 != sha1nodeconstants.nullid and p2 not in known: queue.append((curname, p2)) return missing diff --git a/hgext/remotefilelog/remotefilectx.py b/hgext/remotefilelog/remotefilectx.py --- a/hgext/remotefilelog/remotefilectx.py +++ b/hgext/remotefilelog/remotefilectx.py @@ -9,7 +9,7 @@ import collections import time -from mercurial.node import bin, hex, nullid, nullrev +from mercurial.node import bin, hex, nullrev from mercurial import ( ancestor, context, @@ -35,7 +35,7 @@ ancestormap=None, ): if fileid == nullrev: - fileid = nullid + fileid = repo.nullid if fileid and len(fileid) == 40: fileid = bin(fileid) super(remotefilectx, self).__init__( @@ -78,7 +78,7 @@ @propertycache def _linkrev(self): - if self._filenode == nullid: + if self._filenode == self._repo.nullid: return nullrev ancestormap = self.ancestormap() @@ -174,7 +174,7 @@ p1, p2, linknode, copyfrom = ancestormap[self._filenode] results = [] - if p1 != nullid: + if p1 != repo.nullid: path = copyfrom or self._path flog = repo.file(path) p1ctx = remotefilectx( @@ -183,7 +183,7 @@ p1ctx._descendantrev = self.rev() results.append(p1ctx) - if p2 != nullid: + if p2 != repo.nullid: path = self._path flog = repo.file(path) p2ctx = remotefilectx( @@ -504,25 +504,25 @@ if renamed: p1 = renamed else: - p1 = (path, pcl[0]._manifest.get(path, nullid)) + p1 = (path, pcl[0]._manifest.get(path, self._repo.nullid)) - p2 = (path, nullid) + p2 = (path, self._repo.nullid) if len(pcl) > 1: p2 = (path, pcl[1]._manifest.get(path, nullid)) m = {} - if p1[1] != nullid: + if p1[1] != self._repo.nullid: p1ctx = self._repo.filectx(p1[0], fileid=p1[1]) m.update(p1ctx.filelog().ancestormap(p1[1])) - if p2[1] != nullid: + if p2[1] != self._repo.nullid: p2ctx = self._repo.filectx(p2[0], fileid=p2[1]) m.update(p2ctx.filelog().ancestormap(p2[1])) copyfrom = b'' if renamed: copyfrom = renamed[0] - m[None] = (p1[1], p2[1], nullid, copyfrom) + m[None] = (p1[1], p2[1], self._repo.nullid, copyfrom) self._ancestormap = m return self._ancestormap diff --git a/hgext/remotefilelog/remotefilelog.py b/hgext/remotefilelog/remotefilelog.py --- a/hgext/remotefilelog/remotefilelog.py +++ b/hgext/remotefilelog/remotefilelog.py @@ -10,12 +10,7 @@ import collections import os -from mercurial.node import ( - bin, - nullid, - wdirfilenodeids, - wdirid, -) +from mercurial.node import bin from mercurial.i18n import _ from mercurial import ( ancestor, @@ -100,7 +95,7 @@ pancestors = {} queue = [] - if realp1 != nullid: + if realp1 != self.repo.nullid: p1flog = self if copyfrom: p1flog = remotefilelog(self.opener, copyfrom, self.repo) @@ -108,7 +103,7 @@ pancestors.update(p1flog.ancestormap(realp1)) queue.append(realp1) visited.add(realp1) - if p2 != nullid: + if p2 != self.repo.nullid: pancestors.update(self.ancestormap(p2)) queue.append(p2) visited.add(p2) @@ -129,10 +124,10 @@ pacopyfrom, ) - if pa1 != nullid and pa1 not in visited: + if pa1 != self.repo.nullid and pa1 not in visited: queue.append(pa1) visited.add(pa1) - if pa2 != nullid and pa2 not in visited: + if pa2 != self.repo.nullid and pa2 not in visited: queue.append(pa2) visited.add(pa2) @@ -238,7 +233,7 @@ returns True if text is different than what is stored. """ - if node == nullid: + if node == self.repo.nullid: return True nodetext = self.read(node) @@ -275,13 +270,13 @@ return store.getmeta(self.filename, node).get(constants.METAKEYFLAG, 0) def parents(self, node): - if node == nullid: - return nullid, nullid + if node == self.repo.nullid: + return self.repo.nullid, self.repo.nullid ancestormap = self.repo.metadatastore.getancestors(self.filename, node) p1, p2, linknode, copyfrom = ancestormap[node] if copyfrom: - p1 = nullid + p1 = self.repo.nullid return p1, p2 @@ -316,8 +311,8 @@ if prevnode is None: basenode = prevnode = p1 if basenode == node: - basenode = nullid - if basenode != nullid: + basenode = self.repo.nullid + if basenode != self.repo.nullid: revision = None delta = self.revdiff(basenode, node) else: @@ -377,13 +372,16 @@ this is generally only used for bundling and communicating with vanilla hg clients. """ - if node == nullid: + if node == self.repo.nullid: return b"" if len(node) != 20: raise error.LookupError( node, self.filename, _(b'invalid revision input') ) - if node == wdirid or node in wdirfilenodeids: + if ( + node == self.repo.nodeconstants.wdirid + or node in self.repo.nodeconstants.wdirfilenodeids + ): raise error.WdirUnsupported store = self.repo.contentstore @@ -429,8 +427,8 @@ return self.repo.metadatastore.getancestors(self.filename, node) def ancestor(self, a, b): - if a == nullid or b == nullid: - return nullid + if a == self.repo.nullid or b == self.repo.nullid: + return self.repo.nullid revmap, parentfunc = self._buildrevgraph(a, b) nodemap = {v: k for (k, v) in pycompat.iteritems(revmap)} @@ -439,13 +437,13 @@ if ancs: # choose a consistent winner when there's a tie return min(map(nodemap.__getitem__, ancs)) - return nullid + return self.repo.nullid def commonancestorsheads(self, a, b): """calculate all the heads of the common ancestors of nodes a and b""" - if a == nullid or b == nullid: - return nullid + if a == self.repo.nullid or b == self.repo.nullid: + return self.repo.nullid revmap, parentfunc = self._buildrevgraph(a, b) nodemap = {v: k for (k, v) in pycompat.iteritems(revmap)} @@ -469,10 +467,10 @@ p1, p2, linknode, copyfrom = pdata # Don't follow renames (copyfrom). # remotefilectx.ancestor does that. - if p1 != nullid and not copyfrom: + if p1 != self.repo.nullid and not copyfrom: parents.append(p1) allparents.add(p1) - if p2 != nullid: + if p2 != self.repo.nullid: parents.append(p2) allparents.add(p2) diff --git a/hgext/remotefilelog/remotefilelogserver.py b/hgext/remotefilelog/remotefilelogserver.py --- a/hgext/remotefilelog/remotefilelogserver.py +++ b/hgext/remotefilelog/remotefilelogserver.py @@ -13,7 +13,7 @@ import zlib from mercurial.i18n import _ -from mercurial.node import bin, hex, nullid +from mercurial.node import bin, hex from mercurial.pycompat import open from mercurial import ( changegroup, @@ -242,7 +242,7 @@ filecachepath = os.path.join(cachepath, path, hex(node)) if not os.path.exists(filecachepath) or os.path.getsize(filecachepath) == 0: filectx = repo.filectx(path, fileid=node) - if filectx.node() == nullid: + if filectx.node() == repo.nullid: repo.changelog = changelog.changelog(repo.svfs) filectx = repo.filectx(path, fileid=node) @@ -285,7 +285,7 @@ """ flog = repo.file(path) heads = flog.heads() - return b'\n'.join((hex(head) for head in heads if head != nullid)) + return b'\n'.join((hex(head) for head in heads if head != repo.nullid)) def getfile(repo, proto, file, node): @@ -303,7 +303,7 @@ if not cachepath: cachepath = os.path.join(repo.path, b"remotefilelogcache") node = bin(node.strip()) - if node == nullid: + if node == repo.nullid: return b'0\0' return b'0\0' + _loadfileblob(repo, cachepath, file, node) @@ -329,7 +329,7 @@ break node = bin(request[:40]) - if node == nullid: + if node == repo.nullid: yield b'0\n' continue @@ -382,8 +382,8 @@ ancestortext = b"" for ancestorctx in ancestors: parents = ancestorctx.parents() - p1 = nullid - p2 = nullid + p1 = repo.nullid + p2 = repo.nullid if len(parents) > 0: p1 = parents[0].filenode() if len(parents) > 1: diff --git a/hgext/remotefilelog/repack.py b/hgext/remotefilelog/repack.py --- a/hgext/remotefilelog/repack.py +++ b/hgext/remotefilelog/repack.py @@ -4,10 +4,7 @@ import time from mercurial.i18n import _ -from mercurial.node import ( - nullid, - short, -) +from mercurial.node import short from mercurial import ( encoding, error, @@ -587,7 +584,7 @@ # Create one contiguous chain and reassign deltabases. for i, node in enumerate(orphans): if i == 0: - deltabases[node] = (nullid, 0) + deltabases[node] = (self.repo.nullid, 0) else: parent = orphans[i - 1] deltabases[node] = (parent, deltabases[parent][1] + 1) @@ -677,8 +674,8 @@ # of immediate child deltatuple = deltabases.get(node, None) if deltatuple is None: - deltabase, chainlen = nullid, 0 - deltabases[node] = (nullid, 0) + deltabase, chainlen = self.repo.nullid, 0 + deltabases[node] = (self.repo.nullid, 0) nobase.add(node) else: deltabase, chainlen = deltatuple @@ -693,7 +690,7 @@ # file was copied from elsewhere. So don't attempt to do any # deltas with the other file. if copyfrom: - p1 = nullid + p1 = self.repo.nullid if chainlen < maxchainlen: # Record this child as the delta base for its parents. @@ -701,9 +698,9 @@ # many children, and this will only choose the last one. # TODO: record all children and try all deltas to find # best - if p1 != nullid: + if p1 != self.repo.nullid: deltabases[p1] = (node, chainlen + 1) - if p2 != nullid: + if p2 != self.repo.nullid: deltabases[p2] = (node, chainlen + 1) # experimental config: repack.chainorphansbysize @@ -720,7 +717,7 @@ # TODO: Optimize the deltachain fetching. Since we're # iterating over the different version of the file, we may # be fetching the same deltachain over and over again. - if deltabase != nullid: + if deltabase != self.repo.nullid: deltaentry = self.data.getdelta(filename, node) delta, deltabasename, origdeltabase, meta = deltaentry size = meta.get(constants.METAKEYSIZE) @@ -792,9 +789,9 @@ # If copyfrom == filename, it means the copy history # went to come other file, then came back to this one, so we # should continue processing it. - if p1 != nullid and copyfrom != filename: + if p1 != self.repo.nullid and copyfrom != filename: dontprocess.add(p1) - if p2 != nullid: + if p2 != self.repo.nullid: dontprocess.add(p2) continue @@ -815,9 +812,9 @@ def parentfunc(node): p1, p2, linknode, copyfrom = ancestors[node] parents = [] - if p1 != nullid: + if p1 != self.repo.nullid: parents.append(p1) - if p2 != nullid: + if p2 != self.repo.nullid: parents.append(p2) return parents diff --git a/hgext/remotefilelog/shallowbundle.py b/hgext/remotefilelog/shallowbundle.py --- a/hgext/remotefilelog/shallowbundle.py +++ b/hgext/remotefilelog/shallowbundle.py @@ -7,7 +7,7 @@ from __future__ import absolute_import from mercurial.i18n import _ -from mercurial.node import bin, hex, nullid +from mercurial.node import bin, hex from mercurial import ( bundlerepo, changegroup, @@ -129,7 +129,7 @@ def nodechunk(self, revlog, node, prevnode, linknode): prefix = b'' - if prevnode == nullid: + if prevnode == revlog.nullid: delta = revlog.rawdata(node) prefix = mdiff.trivialdiffheader(len(delta)) else: @@ -229,7 +229,7 @@ processed = set() def available(f, node, depf, depnode): - if depnode != nullid and (depf, depnode) not in processed: + if depnode != repo.nullid and (depf, depnode) not in processed: if not (depf, depnode) in revisiondatas: # It's not in the changegroup, assume it's already # in the repo @@ -251,7 +251,7 @@ dependents = [revisiondata[1], revisiondata[2], revisiondata[4]] for dependent in dependents: - if dependent == nullid or (f, dependent) in revisiondatas: + if dependent == repo.nullid or (f, dependent) in revisiondatas: continue prefetchfiles.append((f, hex(dependent))) @@ -290,7 +290,7 @@ continue for p in [p1, p2]: - if p != nullid: + if p != repo.nullid: if not available(f, node, f, p): continue diff --git a/hgext/remotefilelog/shallowrepo.py b/hgext/remotefilelog/shallowrepo.py --- a/hgext/remotefilelog/shallowrepo.py +++ b/hgext/remotefilelog/shallowrepo.py @@ -9,7 +9,7 @@ import os from mercurial.i18n import _ -from mercurial.node import hex, nullid, nullrev +from mercurial.node import hex, nullrev from mercurial import ( encoding, error, @@ -206,8 +206,8 @@ m1 = ctx.p1().manifest() files = [] for f in ctx.modified() + ctx.added(): - fparent1 = m1.get(f, nullid) - if fparent1 != nullid: + fparent1 = m1.get(f, self.nullid) + if fparent1 != self.nullid: files.append((f, hex(fparent1))) self.fileservice.prefetch(files) return super(shallowrepository, self).commitctx( diff --git a/hgext/remotefilelog/shallowutil.py b/hgext/remotefilelog/shallowutil.py --- a/hgext/remotefilelog/shallowutil.py +++ b/hgext/remotefilelog/shallowutil.py @@ -15,9 +15,9 @@ from mercurial.i18n import _ from mercurial.pycompat import open +from mercurial.node import hex from mercurial import ( error, - node, pycompat, revlog, util, @@ -39,12 +39,12 @@ def getcachekey(reponame, file, id): - pathhash = node.hex(hashutil.sha1(file).digest()) + pathhash = hex(hashutil.sha1(file).digest()) return os.path.join(reponame, pathhash[:2], pathhash[2:], id) def getlocalkey(file, id): - pathhash = node.hex(hashutil.sha1(file).digest()) + pathhash = hex(hashutil.sha1(file).digest()) return os.path.join(pathhash, id) diff --git a/hgext/split.py b/hgext/split.py --- a/hgext/split.py +++ b/hgext/split.py @@ -10,11 +10,7 @@ from __future__ import absolute_import from mercurial.i18n import _ - -from mercurial.node import ( - nullid, - short, -) +from mercurial.node import short from mercurial import ( bookmarks, @@ -78,7 +74,7 @@ ctx = repo[rev] # Handle nullid specially here (instead of leaving for precheck() # below) so we get a nicer message and error code. - if rev is None or ctx.node() == nullid: + if rev is None or ctx.node() == repo.nullid: ui.status(_(b'nothing to split\n')) return 1 if ctx.node() is None: diff --git a/hgext/sqlitestore.py b/hgext/sqlitestore.py --- a/hgext/sqlitestore.py +++ b/hgext/sqlitestore.py @@ -52,8 +52,8 @@ from mercurial.i18n import _ from mercurial.node import ( - nullid, nullrev, + sha1nodeconstants, short, ) from mercurial.thirdparty import attr @@ -304,6 +304,7 @@ """Implements storage for an individual tracked path.""" def __init__(self, db, path, compression): + self.nullid = sha1nodeconstants.nullid self._db = db self._path = path @@ -363,12 +364,12 @@ ) if p1rev == nullrev: - p1node = nullid + p1node = sha1nodeconstants.nullid else: p1node = self._revtonode[p1rev] if p2rev == nullrev: - p2node = nullid + p2node = sha1nodeconstants.nullid else: p2node = self._revtonode[p2rev] @@ -397,7 +398,7 @@ return iter(pycompat.xrange(len(self._revisions))) def hasnode(self, node): - if node == nullid: + if node == sha1nodeconstants.nullid: return False return node in self._nodetorev @@ -408,8 +409,8 @@ ) def parents(self, node): - if node == nullid: - return nullid, nullid + if node == sha1nodeconstants.nullid: + return sha1nodeconstants.nullid, sha1nodeconstants.nullid if node not in self._revisions: raise error.LookupError(node, self._path, _(b'no node')) @@ -428,7 +429,7 @@ return entry.p1rev, entry.p2rev def rev(self, node): - if node == nullid: + if node == sha1nodeconstants.nullid: return nullrev if node not in self._nodetorev: @@ -438,7 +439,7 @@ def node(self, rev): if rev == nullrev: - return nullid + return sha1nodeconstants.nullid if rev not in self._revtonode: raise IndexError(rev) @@ -482,7 +483,7 @@ def heads(self, start=None, stop=None): if start is None and stop is None: if not len(self): - return [nullid] + return [sha1nodeconstants.nullid] startrev = self.rev(start) if start is not None else nullrev stoprevs = {self.rev(n) for n in stop or []} @@ -526,7 +527,7 @@ return len(self.revision(node)) def revision(self, node, raw=False, _verifyhash=True): - if node in (nullid, nullrev): + if node in (sha1nodeconstants.nullid, nullrev): return b'' if isinstance(node, int): @@ -592,7 +593,7 @@ b'unhandled value for nodesorder: %s' % nodesorder ) - nodes = [n for n in nodes if n != nullid] + nodes = [n for n in nodes if n != sha1nodeconstants.nullid] if not nodes: return @@ -689,12 +690,12 @@ raise SQLiteStoreError(b'unhandled revision flag') if maybemissingparents: - if p1 != nullid and not self.hasnode(p1): - p1 = nullid + if p1 != sha1nodeconstants.nullid and not self.hasnode(p1): + p1 = sha1nodeconstants.nullid storeflags |= FLAG_MISSING_P1 - if p2 != nullid and not self.hasnode(p2): - p2 = nullid + if p2 != sha1nodeconstants.nullid and not self.hasnode(p2): + p2 = sha1nodeconstants.nullid storeflags |= FLAG_MISSING_P2 baserev = self.rev(deltabase) @@ -720,7 +721,10 @@ # Possibly reset parents to make them proper. entry = self._revisions[node] - if entry.flags & FLAG_MISSING_P1 and p1 != nullid: + if ( + entry.flags & FLAG_MISSING_P1 + and p1 != sha1nodeconstants.nullid + ): entry.p1node = p1 entry.p1rev = self._nodetorev[p1] entry.flags &= ~FLAG_MISSING_P1 @@ -730,7 +734,10 @@ (self._nodetorev[p1], entry.flags, entry.rid), ) - if entry.flags & FLAG_MISSING_P2 and p2 != nullid: + if ( + entry.flags & FLAG_MISSING_P2 + and p2 != sha1nodeconstants.nullid + ): entry.p2node = p2 entry.p2rev = self._nodetorev[p2] entry.flags &= ~FLAG_MISSING_P2 @@ -745,7 +752,7 @@ empty = False continue - if deltabase == nullid: + if deltabase == sha1nodeconstants.nullid: text = mdiff.patch(b'', delta) storedelta = None else: @@ -992,7 +999,7 @@ assert revisiondata is not None deltabase = p1 - if deltabase == nullid: + if deltabase == sha1nodeconstants.nullid: delta = revisiondata else: delta = mdiff.textdiff( @@ -1001,7 +1008,7 @@ # File index stores a pointer to its delta and the parent delta. # The parent delta is stored via a pointer to the fileindex PK. - if deltabase == nullid: + if deltabase == sha1nodeconstants.nullid: baseid = None else: baseid = self._revisions[deltabase].rid @@ -1035,12 +1042,12 @@ rev = len(self) - if p1 == nullid: + if p1 == sha1nodeconstants.nullid: p1rev = nullrev else: p1rev = self._nodetorev[p1] - if p2 == nullid: + if p2 == sha1nodeconstants.nullid: p2rev = nullrev else: p2rev = self._nodetorev[p2] diff --git a/hgext/transplant.py b/hgext/transplant.py --- a/hgext/transplant.py +++ b/hgext/transplant.py @@ -18,6 +18,11 @@ import os from mercurial.i18n import _ +from mercurial.node import ( + bin, + hex, + short, +) from mercurial.pycompat import open from mercurial import ( bundlerepo, @@ -28,11 +33,9 @@ logcmdutil, match, merge, - node as nodemod, patch, pycompat, registrar, - revlog, revset, scmutil, smartset, @@ -91,7 +94,7 @@ abspath = os.path.join(self.path, self.transplantfile) if self.transplantfile and os.path.exists(abspath): for line in self.opener.read(self.transplantfile).splitlines(): - lnode, rnode = map(revlog.bin, line.split(b':')) + lnode, rnode = map(bin, line.split(b':')) list = self.transplants.setdefault(rnode, []) list.append(transplantentry(lnode, rnode)) @@ -102,7 +105,7 @@ fp = self.opener(self.transplantfile, b'w') for list in pycompat.itervalues(self.transplants): for t in list: - l, r = map(nodemod.hex, (t.lnode, t.rnode)) + l, r = map(hex, (t.lnode, t.rnode)) fp.write(l + b':' + r + b'\n') fp.close() self.dirty = False @@ -125,6 +128,7 @@ class transplanter(object): def __init__(self, ui, repo, opts): self.ui = ui + self.repo = repo self.path = repo.vfs.join(b'transplant') self.opener = vfsmod.vfs(self.path) self.transplants = transplants( @@ -179,7 +183,7 @@ tr = repo.transaction(b'transplant') for rev in revs: node = revmap[rev] - revstr = b'%d:%s' % (rev, nodemod.short(node)) + revstr = b'%d:%s' % (rev, short(node)) if self.applied(repo, node, p1): self.ui.warn( @@ -212,11 +216,11 @@ exchange.pull(repo, source.peer(), heads=[node]) skipmerge = False - if parents[1] != revlog.nullid: + if parents[1] != repo.nullid: if not opts.get(b'parent'): self.ui.note( _(b'skipping merge changeset %d:%s\n') - % (rev, nodemod.short(node)) + % (rev, short(node)) ) skipmerge = True else: @@ -224,7 +228,7 @@ if parent not in parents: raise error.Abort( _(b'%s is not a parent of %s') - % (nodemod.short(parent), nodemod.short(node)) + % (short(parent), short(node)) ) else: parent = parents[0] @@ -259,13 +263,12 @@ raise if n and domerge: self.ui.status( - _(b'%s merged at %s\n') - % (revstr, nodemod.short(n)) + _(b'%s merged at %s\n') % (revstr, short(n)) ) elif n: self.ui.status( _(b'%s transplanted to %s\n') - % (nodemod.short(node), nodemod.short(n)) + % (short(node), short(n)) ) finally: if patchfile: @@ -303,10 +306,7 @@ procutil.shellquote(headerfile), procutil.shellquote(patchfile), ), - environ={ - b'HGUSER': changelog[1], - b'HGREVISION': nodemod.hex(node), - }, + environ={b'HGUSER': changelog[1], b'HGREVISION': hex(node),}, onerr=error.Abort, errprefix=_(b'filter failed'), blockedtag=b'transplant_filter', @@ -329,9 +329,9 @@ if log: # we don't translate messages inserted into commits - message += b'\n(transplanted from %s)' % nodemod.hex(node) + message += b'\n(transplanted from %s)' % hex(node) - self.ui.status(_(b'applying %s\n') % nodemod.short(node)) + self.ui.status(_(b'applying %s\n') % short(node)) self.ui.note(b'%s %s\n%s\n' % (user, date, message)) if not patchfile and not merge: @@ -373,9 +373,7 @@ editor=self.getcommiteditor(), ) if not n: - self.ui.warn( - _(b'skipping emptied changeset %s\n') % nodemod.short(node) - ) + self.ui.warn(_(b'skipping emptied changeset %s\n') % short(node)) return None if not merge: self.transplants.set(n, node) @@ -391,13 +389,11 @@ n, node = self.recover(repo, source, opts) if n: self.ui.status( - _(b'%s transplanted as %s\n') - % (nodemod.short(node), nodemod.short(n)) + _(b'%s transplanted as %s\n') % (short(node), short(n)) ) else: self.ui.status( - _(b'%s skipped due to empty diff\n') - % (nodemod.short(node),) + _(b'%s skipped due to empty diff\n') % (short(node),) ) seriespath = os.path.join(self.path, b'series') if not os.path.exists(seriespath): @@ -426,7 +422,7 @@ if parent not in parents: raise error.Abort( _(b'%s is not a parent of %s') - % (nodemod.short(parent), nodemod.short(node)) + % (short(parent), short(node)) ) else: merge = True @@ -437,7 +433,7 @@ if p1 != parent: raise error.Abort( _(b'working directory not at transplant parent %s') - % nodemod.hex(parent) + % hex(parent) ) if merge: repo.setparents(p1, parents[1]) @@ -490,7 +486,7 @@ if line.startswith(b'# Merges'): cur = merges continue - cur.append(revlog.bin(line)) + cur.append(bin(line)) return (nodes, merges) @@ -502,17 +498,17 @@ os.mkdir(self.path) series = self.opener(b'series', b'w') for rev in sorted(revmap): - series.write(nodemod.hex(revmap[rev]) + b'\n') + series.write(hex(revmap[rev]) + b'\n') if merges: series.write(b'# Merges\n') for m in merges: - series.write(nodemod.hex(m) + b'\n') + series.write(hex(m) + b'\n') series.close() def parselog(self, fp): parents = [] message = [] - node = revlog.nullid + node = self.repo.nullid inmsg = False user = None date = None @@ -524,9 +520,9 @@ elif line.startswith(b'# Date '): date = line[7:] elif line.startswith(b'# Node ID '): - node = revlog.bin(line[10:]) + node = bin(line[10:]) elif line.startswith(b'# Parent '): - parents.append(revlog.bin(line[9:])) + parents.append(bin(line[9:])) elif not line.startswith(b'# '): inmsg = True message.append(line) @@ -544,10 +540,10 @@ fp = self.opener(b'journal', b'w') fp.write(b'# User %s\n' % user) fp.write(b'# Date %s\n' % date) - fp.write(b'# Node ID %s\n' % nodemod.hex(p2)) - fp.write(b'# Parent ' + nodemod.hex(p1) + b'\n') + fp.write(b'# Node ID %s\n' % hex(p2)) + fp.write(b'# Parent ' + hex(p1) + b'\n') if merge: - fp.write(b'# Parent ' + nodemod.hex(p2) + b'\n') + fp.write(b'# Parent ' + hex(p2) + b'\n') fp.write(message.rstrip() + b'\n') fp.close() @@ -564,7 +560,7 @@ def matchfn(node): if self.applied(repo, node, root): return False - if source.changelog.parents(node)[1] != revlog.nullid: + if source.changelog.parents(node)[1] != repo.nullid: return False extra = source.changelog.read(node)[5] cnode = extra.get(b'transplant_source') @@ -800,7 +796,7 @@ tp = transplanter(ui, repo, opts) p1 = repo.dirstate.p1() - if len(repo) > 0 and p1 == revlog.nullid: + if len(repo) > 0 and p1 == repo.nullid: raise error.Abort(_(b'no revision checked out')) if opts.get(b'continue'): if not tp.canresume(): @@ -906,7 +902,7 @@ changeset if any.""" ctx = context.resource(mapping, b'ctx') n = ctx.extra().get(b'transplant_source') - return n and nodemod.hex(n) or b'' + return n and hex(n) or b'' def extsetup(ui): diff --git a/hgext/uncommit.py b/hgext/uncommit.py --- a/hgext/uncommit.py +++ b/hgext/uncommit.py @@ -27,7 +27,6 @@ context, copies as copiesmod, error, - node, obsutil, pathutil, pycompat, @@ -109,7 +108,7 @@ new = context.memctx( repo, - parents=[base.node(), node.nullid], + parents=[base.node(), repo.nullid], text=message, files=files, filectxfn=filectxfn, diff --git a/mercurial/bookmarks.py b/mercurial/bookmarks.py --- a/mercurial/bookmarks.py +++ b/mercurial/bookmarks.py @@ -15,7 +15,6 @@ bin, hex, short, - wdirid, ) from .pycompat import getattr from . import ( @@ -624,7 +623,7 @@ _binaryentry = struct.Struct(b'>20sH') -def binaryencode(bookmarks): +def binaryencode(repo, bookmarks): """encode a '(bookmark, node)' iterable into a binary stream the binary format is: @@ -640,13 +639,13 @@ binarydata = [] for book, node in bookmarks: if not node: # None or '' - node = wdirid + node = repo.nodeconstants.wdirid binarydata.append(_binaryentry.pack(node, len(book))) binarydata.append(book) return b''.join(binarydata) -def binarydecode(stream): +def binarydecode(repo, stream): """decode a binary stream into an '(bookmark, node)' iterable the binary format is: @@ -672,7 +671,7 @@ if len(bookmark) < length: if entry: raise error.Abort(_(b'bad bookmark stream')) - if node == wdirid: + if node == repo.nodeconstants.wdirid: node = None books.append((bookmark, node)) return books diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py --- a/mercurial/branchmap.py +++ b/mercurial/branchmap.py @@ -12,7 +12,6 @@ from .node import ( bin, hex, - nullid, nullrev, ) from . import ( @@ -87,7 +86,7 @@ revs.extend(r for r in extrarevs if r <= bcache.tiprev) else: # nothing to fall back on, start empty. - bcache = branchcache() + bcache = branchcache(repo) revs.extend(cl.revs(start=bcache.tiprev + 1)) if revs: @@ -119,6 +118,7 @@ if rbheads: rtiprev = max((int(clrev(node)) for node in rbheads)) cache = branchcache( + repo, remotebranchmap, repo[rtiprev].node(), rtiprev, @@ -175,8 +175,9 @@ def __init__( self, + repo, entries=(), - tipnode=nullid, + tipnode=None, tiprev=nullrev, filteredhash=None, closednodes=None, @@ -186,7 +187,11 @@ """ hasnode is a function which can be used to verify whether changelog has a given node or not. If it's not provided, we assume that every node we have exists in changelog """ - self.tipnode = tipnode + self._repo = repo + if tipnode is None: + self.tipnode = repo.nullid + else: + self.tipnode = tipnode self.tiprev = tiprev self.filteredhash = filteredhash # closednodes is a set of nodes that close their branch. If the branch @@ -271,6 +276,7 @@ if len(cachekey) > 2: filteredhash = bin(cachekey[2]) bcache = cls( + repo, tipnode=last, tiprev=lrev, filteredhash=filteredhash, @@ -379,6 +385,7 @@ def copy(self): """return an deep copy of the branchcache object""" return type(self)( + self._repo, self._entries, self.tipnode, self.tiprev, @@ -473,7 +480,7 @@ if not self.validfor(repo): # cache key are not valid anymore - self.tipnode = nullid + self.tipnode = repo.nullid self.tiprev = nullrev for heads in self.iterheads(): tiprev = max(cl.rev(node) for node in heads) diff --git a/mercurial/bundle2.py b/mercurial/bundle2.py --- a/mercurial/bundle2.py +++ b/mercurial/bundle2.py @@ -156,12 +156,15 @@ import sys from .i18n import _ +from .node import ( + hex, + short, +) from . import ( bookmarks, changegroup, encoding, error, - node as nodemod, obsolete, phases, pushkey, @@ -2109,7 +2112,7 @@ contains binary encoded (bookmark, node) tuple. If the local state does not marks the one in the part, a PushRaced exception is raised """ - bookdata = bookmarks.binarydecode(inpart) + bookdata = bookmarks.binarydecode(op.repo, inpart) msgstandard = ( b'remote repository changed while pushing - please try again ' @@ -2127,14 +2130,14 @@ currentnode = op.repo._bookmarks.get(book) if currentnode != node: if node is None: - finalmsg = msgexist % (book, nodemod.short(currentnode)) + finalmsg = msgexist % (book, short(currentnode)) elif currentnode is None: - finalmsg = msgmissing % (book, nodemod.short(node)) + finalmsg = msgmissing % (book, short(node)) else: finalmsg = msgstandard % ( book, - nodemod.short(node), - nodemod.short(currentnode), + short(node), + short(currentnode), ) raise error.PushRaced(finalmsg) @@ -2211,7 +2214,7 @@ actualphase = phasecache.phase(unfi, cl.rev(n)) if actualphase != expectedphase: finalmsg = msg % ( - nodemod.short(n), + short(n), phases.phasenames[actualphase], phases.phasenames[expectedphase], ) @@ -2339,7 +2342,7 @@ When mode is 'records', the information is recorded into the 'bookmarks' records of the bundle operation. This behavior is suitable for pulling. """ - changes = bookmarks.binarydecode(inpart) + changes = bookmarks.binarydecode(op.repo, inpart) pushkeycompat = op.repo.ui.configbool( b'server', b'bookmarks-pushkey-compat' @@ -2356,10 +2359,8 @@ hookargs[b'pushkeycompat'] = b'1' hookargs[b'namespace'] = b'bookmarks' hookargs[b'key'] = book - hookargs[b'old'] = nodemod.hex(bookstore.get(book, b'')) - hookargs[b'new'] = nodemod.hex( - node if node is not None else b'' - ) + hookargs[b'old'] = hex(bookstore.get(book, b'')) + hookargs[b'new'] = hex(node if node is not None else b'') allhooks.append(hookargs) for hookargs in allhooks: @@ -2565,7 +2566,7 @@ fullnodes=commonnodes, ) cgdata = packer.generate( - {nodemod.nullid}, + {repo.nullid}, list(commonnodes), False, b'narrow_widen', diff --git a/mercurial/bundlerepo.py b/mercurial/bundlerepo.py --- a/mercurial/bundlerepo.py +++ b/mercurial/bundlerepo.py @@ -17,7 +17,7 @@ import shutil from .i18n import _ -from .node import nullid, nullrev +from .node import nullrev from . import ( bundle2, @@ -172,9 +172,15 @@ class bundlemanifest(bundlerevlog, manifest.manifestrevlog): def __init__( - self, opener, cgunpacker, linkmapper, dirlogstarts=None, dir=b'' + self, + nodeconstants, + opener, + cgunpacker, + linkmapper, + dirlogstarts=None, + dir=b'', ): - manifest.manifestrevlog.__init__(self, opener, tree=dir) + manifest.manifestrevlog.__init__(self, nodeconstants, opener, tree=dir) bundlerevlog.__init__( self, opener, self.indexfile, cgunpacker, linkmapper ) @@ -189,6 +195,7 @@ if d in self._dirlogstarts: self.bundle.seek(self._dirlogstarts[d]) return bundlemanifest( + self.nodeconstants, self.opener, self.bundle, self._linkmapper, @@ -366,7 +373,9 @@ # consume the header if it exists self._cgunpacker.manifestheader() linkmapper = self.unfiltered().changelog.rev - rootstore = bundlemanifest(self.svfs, self._cgunpacker, linkmapper) + rootstore = bundlemanifest( + self.nodeconstants, self.svfs, self._cgunpacker, linkmapper + ) self.filestart = self._cgunpacker.tell() return manifest.manifestlog( @@ -433,7 +442,9 @@ return encoding.getcwd() # always outside the repo # Check if parents exist in localrepo before setting - def setparents(self, p1, p2=nullid): + def setparents(self, p1, p2=None): + if p2 is None: + p2 = self.nullid p1rev = self.changelog.rev(p1) p2rev = self.changelog.rev(p2) msg = _(b"setting parent to node %s that only exists in the bundle\n") diff --git a/mercurial/changegroup.py b/mercurial/changegroup.py --- a/mercurial/changegroup.py +++ b/mercurial/changegroup.py @@ -14,7 +14,6 @@ from .i18n import _ from .node import ( hex, - nullid, nullrev, short, ) @@ -559,7 +558,7 @@ return readexactly(self._fh, n) -def _revisiondeltatochunks(delta, headerfn): +def _revisiondeltatochunks(repo, delta, headerfn): """Serialize a revisiondelta to changegroup chunks.""" # The captured revision delta may be encoded as a delta against @@ -570,7 +569,7 @@ if delta.delta is not None: prefix, data = b'', delta.delta - elif delta.basenode == nullid: + elif delta.basenode == repo.nullid: data = delta.revision prefix = mdiff.trivialdiffheader(len(data)) else: @@ -932,7 +931,9 @@ cl, clnodes, generate=changelog ) for delta in deltas: - for chunk in _revisiondeltatochunks(delta, self._builddeltaheader): + for chunk in _revisiondeltatochunks( + self._repo, delta, self._builddeltaheader + ): size += len(chunk) yield chunk @@ -987,7 +988,9 @@ yield chunk for delta in deltas: - chunks = _revisiondeltatochunks(delta, self._builddeltaheader) + chunks = _revisiondeltatochunks( + self._repo, delta, self._builddeltaheader + ) for chunk in chunks: size += len(chunk) yield chunk @@ -1025,7 +1028,9 @@ yield h for delta in deltas: - chunks = _revisiondeltatochunks(delta, self._builddeltaheader) + chunks = _revisiondeltatochunks( + self._repo, delta, self._builddeltaheader + ) for chunk in chunks: size += len(chunk) yield chunk diff --git a/mercurial/changelog.py b/mercurial/changelog.py --- a/mercurial/changelog.py +++ b/mercurial/changelog.py @@ -11,7 +11,6 @@ from .node import ( bin, hex, - nullid, ) from .thirdparty import attr @@ -191,7 +190,7 @@ # Extensions might modify _defaultextra, so let the constructor below pass # it in extra = attr.ib() - manifest = attr.ib(default=nullid) + manifest = attr.ib() user = attr.ib(default=b'') date = attr.ib(default=(0, 0)) files = attr.ib(default=attr.Factory(list)) @@ -218,9 +217,9 @@ '_changes', ) - def __new__(cls, text, sidedata, cpsd): + def __new__(cls, cl, text, sidedata, cpsd): if not text: - return _changelogrevision(extra=_defaultextra) + return _changelogrevision(extra=_defaultextra, manifest=cl.nullid) self = super(changelogrevision, cls).__new__(cls) # We could return here and implement the following as an __init__. @@ -515,7 +514,7 @@ """ d, s = self._revisiondata(node) c = changelogrevision( - d, s, self._copiesstorage == b'changeset-sidedata' + self, d, s, self._copiesstorage == b'changeset-sidedata' ) return (c.manifest, c.user, c.date, c.files, c.description, c.extra) @@ -523,7 +522,7 @@ """Obtain a ``changelogrevision`` for a node or revision.""" text, sidedata = self._revisiondata(nodeorrev) return changelogrevision( - text, sidedata, self._copiesstorage == b'changeset-sidedata' + self, text, sidedata, self._copiesstorage == b'changeset-sidedata' ) def readfiles(self, node): diff --git a/mercurial/chgserver.py b/mercurial/chgserver.py --- a/mercurial/chgserver.py +++ b/mercurial/chgserver.py @@ -54,13 +54,13 @@ getattr, setattr, ) +from .node import hex from . import ( commandserver, encoding, error, extensions, - node, pycompat, util, ) @@ -74,7 +74,7 @@ def _hashlist(items): """return sha1 hexdigest for a list""" - return node.hex(hashutil.sha1(stringutil.pprint(items)).digest()) + return hex(hashutil.sha1(stringutil.pprint(items)).digest()) # sensitive config sections affecting confighash diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py --- a/mercurial/cmdutil.py +++ b/mercurial/cmdutil.py @@ -15,7 +15,7 @@ from .i18n import _ from .node import ( hex, - nullid, + nullrev, short, ) from .pycompat import ( @@ -1086,7 +1086,7 @@ 'hint' is the usual hint given to Abort exception. """ - if merge and repo.dirstate.p2() != nullid: + if merge and repo.dirstate.p2() != repo.nullid: raise error.StateError(_(b'outstanding uncommitted merge'), hint=hint) st = repo.status() if st.modified or st.added or st.removed or st.deleted: @@ -1926,12 +1926,12 @@ ui.debug(b'message:\n%s\n' % (message or b'')) if len(parents) == 1: - parents.append(repo[nullid]) + parents.append(repo[nullrev]) if opts.get(b'exact'): if not nodeid or not p1: raise error.InputError(_(b'not a Mercurial patch')) p1 = repo[p1] - p2 = repo[p2 or nullid] + p2 = repo[p2 or nullrev] elif p2: try: p1 = repo[p1] @@ -1941,10 +1941,10 @@ # first parent. if p1 != parents[0]: p1 = parents[0] - p2 = repo[nullid] + p2 = repo[nullrev] except error.RepoError: p1, p2 = parents - if p2.node() == nullid: + if p2.node() == repo.nullid: ui.warn( _( b"warning: import the patch as a normal revision\n" @@ -2093,7 +2093,7 @@ if parents: prev = parents[0] else: - prev = nullid + prev = repo.nullid fm.context(ctx=ctx) fm.plain(b'# HG changeset patch\n') @@ -2956,7 +2956,7 @@ ms.reset() # Reroute the working copy parent to the new changeset - repo.setparents(newid, nullid) + repo.setparents(newid, repo.nullid) mapping = {old.node(): (newid,)} obsmetadata = None if opts.get(b'note'): @@ -3310,7 +3310,7 @@ # in case of merge, files that are actually added can be reported as # modified, we need to post process the result - if p2 != nullid: + if p2 != repo.nullid: mergeadd = set(dsmodified) for path in dsmodified: if path in mf: @@ -3580,7 +3580,7 @@ # We're reverting to our parent. If possible, we'd like status # to report the file as clean. We have to use normallookup for # merges to avoid losing information about merged/dirty files. - if p2 != nullid: + if p2 != repo.nullid: normal = repo.dirstate.normallookup else: normal = repo.dirstate.normal @@ -3677,7 +3677,7 @@ repo.dirstate.add(f) normal = repo.dirstate.normallookup - if node == parent and p2 == nullid: + if node == parent and p2 == repo.nullid: normal = repo.dirstate.normal for f in actions[b'undelete'][0]: if interactive: diff --git a/mercurial/commands.py b/mercurial/commands.py --- a/mercurial/commands.py +++ b/mercurial/commands.py @@ -15,10 +15,8 @@ from .i18n import _ from .node import ( hex, - nullid, nullrev, short, - wdirhex, wdirrev, ) from .pycompat import open @@ -479,7 +477,7 @@ return b'%d ' % rev def formathex(h): - if h == wdirhex: + if h == repo.nodeconstants.wdirhex: return b'%s+' % shorthex(hex(ctx.p1().node())) else: return b'%s ' % shorthex(h) @@ -802,9 +800,9 @@ ) p1, p2 = repo.changelog.parents(node) - if p1 == nullid: + if p1 == repo.nullid: raise error.InputError(_(b'cannot backout a change with no parents')) - if p2 != nullid: + if p2 != repo.nullid: if not opts.get(b'parent'): raise error.InputError(_(b'cannot backout a merge changeset')) p = repo.lookup(opts[b'parent']) @@ -1073,7 +1071,7 @@ ) else: node, p2 = repo.dirstate.parents() - if p2 != nullid: + if p2 != repo.nullid: raise error.StateError(_(b'current bisect revision is a merge')) if rev: node = repo[scmutil.revsingle(repo, rev, node)].node() @@ -4773,7 +4771,7 @@ opts = pycompat.byteskwargs(opts) abort = opts.get(b'abort') - if abort and repo.dirstate.p2() == nullid: + if abort and repo.dirstate.p2() == repo.nullid: cmdutil.wrongtooltocontinue(repo, _(b'merge')) cmdutil.check_incompatible_arguments(opts, b'abort', [b'rev', b'preview']) if abort: @@ -5021,7 +5019,7 @@ displayer = logcmdutil.changesetdisplayer(ui, repo, opts) for n in p: - if n != nullid: + if n != repo.nullid: displayer.show(repo[n]) displayer.close() @@ -5904,7 +5902,7 @@ with repo.wlock(): ms = mergestatemod.mergestate.read(repo) - if not (ms.active() or repo.dirstate.p2() != nullid): + if not (ms.active() or repo.dirstate.p2() != repo.nullid): raise error.StateError( _(b'resolve command not applicable when not merging') ) @@ -6022,7 +6020,7 @@ raise ms.commit() - branchmerge = repo.dirstate.p2() != nullid + branchmerge = repo.dirstate.p2() != repo.nullid mergestatemod.recordupdates(repo, ms.actions(), branchmerge, None) if not didwork and pats: @@ -6114,7 +6112,7 @@ opts[b"rev"] = cmdutil.finddate(ui, repo, opts[b"date"]) parent, p2 = repo.dirstate.parents() - if not opts.get(b'rev') and p2 != nullid: + if not opts.get(b'rev') and p2 != repo.nullid: # revert after merge is a trap for new users (issue2915) raise error.InputError( _(b'uncommitted merge with no revision specified'), @@ -6134,7 +6132,7 @@ or opts.get(b'interactive') ): msg = _(b"no files or directories specified") - if p2 != nullid: + if p2 != repo.nullid: hint = _( b"uncommitted merge, use --all to discard all changes," b" or 'hg update -C .' to abort the merge" @@ -7169,7 +7167,7 @@ for n in names: if repo.tagtype(n) == b'global': alltags = tagsmod.findglobaltags(ui, repo) - if alltags[n][0] == nullid: + if alltags[n][0] == repo.nullid: raise error.InputError( _(b"tag '%s' is already removed") % n ) @@ -7196,7 +7194,7 @@ ) if not opts.get(b'local'): p1, p2 = repo.dirstate.parents() - if p2 != nullid: + if p2 != repo.nullid: raise error.StateError(_(b'uncommitted merge')) bheads = repo.branchheads() if not opts.get(b'force') and bheads and p1 not in bheads: diff --git a/mercurial/commit.py b/mercurial/commit.py --- a/mercurial/commit.py +++ b/mercurial/commit.py @@ -10,7 +10,6 @@ from .i18n import _ from .node import ( hex, - nullid, nullrev, ) @@ -262,10 +261,10 @@ """ fname = fctx.path() - fparent1 = manifest1.get(fname, nullid) - fparent2 = manifest2.get(fname, nullid) + fparent1 = manifest1.get(fname, repo.nullid) + fparent2 = manifest2.get(fname, repo.nullid) touched = None - if fparent1 == fparent2 == nullid: + if fparent1 == fparent2 == repo.nullid: touched = 'added' if isinstance(fctx, context.filectx): @@ -276,9 +275,11 @@ if node in [fparent1, fparent2]: repo.ui.debug(b'reusing %s filelog entry\n' % fname) if ( - fparent1 != nullid and manifest1.flags(fname) != fctx.flags() + fparent1 != repo.nullid + and manifest1.flags(fname) != fctx.flags() ) or ( - fparent2 != nullid and manifest2.flags(fname) != fctx.flags() + fparent2 != repo.nullid + and manifest2.flags(fname) != fctx.flags() ): touched = 'modified' return node, touched @@ -312,7 +313,9 @@ newfparent = fparent2 if manifest2: # branch merge - if fparent2 == nullid or cnode is None: # copied on remote side + if ( + fparent2 == repo.nullid or cnode is None + ): # copied on remote side if cfname in manifest2: cnode = manifest2[cfname] newfparent = fparent1 @@ -331,7 +334,7 @@ if includecopymeta: meta[b"copy"] = cfname meta[b"copyrev"] = hex(cnode) - fparent1, fparent2 = nullid, newfparent + fparent1, fparent2 = repo.nullid, newfparent else: repo.ui.warn( _( @@ -341,22 +344,22 @@ % (fname, cfname) ) - elif fparent1 == nullid: - fparent1, fparent2 = fparent2, nullid - elif fparent2 != nullid: + elif fparent1 == repo.nullid: + fparent1, fparent2 = fparent2, repo.nullid + elif fparent2 != repo.nullid: # is one parent an ancestor of the other? fparentancestors = flog.commonancestorsheads(fparent1, fparent2) if fparent1 in fparentancestors: - fparent1, fparent2 = fparent2, nullid + fparent1, fparent2 = fparent2, repo.nullid elif fparent2 in fparentancestors: - fparent2 = nullid + fparent2 = repo.nullid elif not fparentancestors: # TODO: this whole if-else might be simplified much more if ( ms.active() and ms.extras(fname).get(b'filenode-source') == b'other' ): - fparent1, fparent2 = fparent2, nullid + fparent1, fparent2 = fparent2, repo.nullid force_new_node = False # The file might have been deleted by merge code and user explicitly choose @@ -371,9 +374,14 @@ force_new_node = True # is the file changed? text = fctx.data() - if fparent2 != nullid or meta or flog.cmp(fparent1, text) or force_new_node: + if ( + fparent2 != repo.nullid + or meta + or flog.cmp(fparent1, text) + or force_new_node + ): if touched is None: # do not overwrite added - if fparent2 == nullid: + if fparent2 == repo.nullid: touched = 'modified' else: touched = 'merged' diff --git a/mercurial/context.py b/mercurial/context.py --- a/mercurial/context.py +++ b/mercurial/context.py @@ -14,14 +14,9 @@ from .i18n import _ from .node import ( - addednodeid, hex, - modifiednodeid, - nullid, nullrev, short, - wdirfilenodeids, - wdirhex, ) from .pycompat import ( getattr, @@ -140,7 +135,7 @@ removed.append(fn) elif flag1 != flag2: modified.append(fn) - elif node2 not in wdirfilenodeids: + elif node2 not in self._repo.nodeconstants.wdirfilenodeids: # When comparing files between two commits, we save time by # not comparing the file contents when the nodeids differ. # Note that this means we incorrectly report a reverted change @@ -737,7 +732,7 @@ n2 = c2._parents[0]._node cahs = self._repo.changelog.commonancestorsheads(self._node, n2) if not cahs: - anc = nullid + anc = self._repo.nodeconstants.nullid elif len(cahs) == 1: anc = cahs[0] else: @@ -1131,7 +1126,11 @@ _path = self._path fl = self._filelog parents = self._filelog.parents(self._filenode) - pl = [(_path, node, fl) for node in parents if node != nullid] + pl = [ + (_path, node, fl) + for node in parents + if node != self._repo.nodeconstants.nullid + ] r = fl.renamed(self._filenode) if r: @@ -1554,12 +1553,12 @@ return self._repo.dirstate[key] not in b"?r" def hex(self): - return wdirhex + return self._repo.nodeconstants.wdirhex @propertycache def _parents(self): p = self._repo.dirstate.parents() - if p[1] == nullid: + if p[1] == self._repo.nodeconstants.nullid: p = p[:-1] # use unfiltered repo to delay/avoid loading obsmarkers unfi = self._repo.unfiltered() @@ -1570,7 +1569,9 @@ for n in p ] - def setparents(self, p1node, p2node=nullid): + def setparents(self, p1node, p2node=None): + if p2node is None: + p2node = self._repo.nodeconstants.nullid dirstate = self._repo.dirstate with dirstate.parentchange(): copies = dirstate.setparents(p1node, p2node) @@ -1582,7 +1583,7 @@ for f in copies: if f not in pctx and copies[f] in pctx: dirstate.copy(copies[f], f) - if p2node == nullid: + if p2node == self._repo.nodeconstants.nullid: for f, s in sorted(dirstate.copies().items()): if f not in pctx and s not in pctx: dirstate.copy(None, f) @@ -1942,8 +1943,8 @@ ff = self._flagfunc for i, l in ( - (addednodeid, status.added), - (modifiednodeid, status.modified), + (self._repo.nodeconstants.addednodeid, status.added), + (self._repo.nodeconstants.modifiednodeid, status.modified), ): for f in l: man[f] = i @@ -2068,13 +2069,18 @@ path = self.copysource() if not path: return None - return path, self._changectx._parents[0]._manifest.get(path, nullid) + return ( + path, + self._changectx._parents[0]._manifest.get( + path, self._repo.nodeconstants.nullid + ), + ) def parents(self): '''return parent filectxs, following copies if necessary''' def filenode(ctx, path): - return ctx._manifest.get(path, nullid) + return ctx._manifest.get(path, self._repo.nodeconstants.nullid) path = self._path fl = self._filelog @@ -2092,7 +2098,7 @@ return [ self._parentfilectx(p, fileid=n, filelog=l) for p, n, l in pl - if n != nullid + if n != self._repo.nodeconstants.nullid ] def children(self): @@ -2220,7 +2226,9 @@ # ``overlayworkingctx`` (e.g. with --collapse). util.clearcachedproperty(self, b'_manifest') - def setparents(self, p1node, p2node=nullid): + def setparents(self, p1node, p2node=None): + if p2node is None: + p2node = self._repo.nodeconstants.nullid assert p1node == self._wrappedctx.node() self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]] @@ -2246,10 +2254,10 @@ flag = self._flagfunc for path in self.added(): - man[path] = addednodeid + man[path] = self._repo.nodeconstants.addednodeid man.setflag(path, flag(path)) for path in self.modified(): - man[path] = modifiednodeid + man[path] = self._repo.nodeconstants.modifiednodeid man.setflag(path, flag(path)) for path in self.removed(): del man[path] @@ -2825,7 +2833,7 @@ ) self._rev = None self._node = None - parents = [(p or nullid) for p in parents] + parents = [(p or self._repo.nodeconstants.nullid) for p in parents] p1, p2 = parents self._parents = [self._repo[p] for p in (p1, p2)] files = sorted(set(files)) @@ -2864,10 +2872,10 @@ man = pctx.manifest().copy() for f in self._status.modified: - man[f] = modifiednodeid + man[f] = self._repo.nodeconstants.modifiednodeid for f in self._status.added: - man[f] = addednodeid + man[f] = self._repo.nodeconstants.addednodeid for f in self._status.removed: if f in man: @@ -2884,7 +2892,7 @@ # "1 < len(self._parents)" can't be used for checking # existence of the 2nd parent, because "memctx._parents" is # explicitly initialized by the list, of which length is 2. - if p2.node() != nullid: + if p2.node() != self._repo.nodeconstants.nullid: man2 = p2.manifest() managing = lambda f: f in man1 or f in man2 else: @@ -2902,7 +2910,7 @@ return scmutil.status(modified, added, removed, [], [], [], []) def parents(self): - if self._parents[1].node() == nullid: + if self._parents[1].rev() == nullrev: return [self._parents[0]] return self._parents @@ -2999,18 +3007,18 @@ parents = [repo[p] for p in parents if p is not None] parents = parents[:] while len(parents) < 2: - parents.append(repo[nullid]) + parents.append(repo[nullrev]) p1, p2 = self._parents = parents # sanity check to ensure that the reused manifest parents are # manifests of our commit parents mp1, mp2 = self.manifestctx().parents - if p1 != nullid and p1.manifestnode() != mp1: + if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1: raise RuntimeError( r"can't reuse the manifest: its p1 " r"doesn't match the new ctx p1" ) - if p2 != nullid and p2.manifestnode() != mp2: + if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2: raise RuntimeError( r"can't reuse the manifest: " r"its p2 doesn't match the new ctx p2" @@ -3051,7 +3059,7 @@ # "1 < len(self._parents)" can't be used for checking # existence of the 2nd parent, because "metadataonlyctx._parents" is # explicitly initialized by the list, of which length is 2. - if p2.node() != nullid: + if p2.rev() != nullrev: man2 = p2.manifest() managing = lambda f: f in man1 or f in man2 else: diff --git a/mercurial/copies.py b/mercurial/copies.py --- a/mercurial/copies.py +++ b/mercurial/copies.py @@ -11,11 +11,11 @@ import os from .i18n import _ +from .node import nullrev from . import ( match as matchmod, - node, pathutil, pycompat, util, @@ -141,7 +141,7 @@ # optimization, since the ctx.files() for a merge commit is not correct for # this comparison. forwardmissingmatch = match - if b.p1() == a and b.p2().node() == node.nullid: + if b.p1() == a and b.p2().node() == repo.nullid: filesmatcher = matchmod.exact(b.files()) forwardmissingmatch = matchmod.intersectmatchers(match, filesmatcher) missing = _computeforwardmissing(a, b, match=forwardmissingmatch) @@ -222,7 +222,7 @@ if flags(rev) & HASCOPIESINFO: changes = changelogrevision(rev).changes value = (p1, p2, changes) - if p1 != node.nullrev and p2 != node.nullrev: + if p1 != nullrev and p2 != nullrev: # XXX some case we over cache, IGNORE merge_caches[rev] = value return value @@ -249,7 +249,7 @@ def _changesetforwardcopies(a, b, match): - if a.rev() in (node.nullrev, b.rev()): + if a.rev() in (nullrev, b.rev()): return {} repo = a.repo().unfiltered() @@ -262,7 +262,7 @@ roots = set() for r in missingrevs: for p in cl.parentrevs(r): - if p == node.nullrev: + if p == nullrev: continue if p not in children: children[p] = [r] @@ -447,7 +447,7 @@ parents = fctx._filelog.parents(fctx._filenode) nb_parents = 0 for n in parents: - if n != node.nullid: + if n != repo.nullid: nb_parents += 1 return nb_parents >= 2 @@ -621,7 +621,7 @@ if debug: repo.ui.debug(b'debug.copies: search mode: combined\n') base = None - if a.rev() != node.nullrev: + if a.rev() != nullrev: base = x copies = _chain( _backwardrenames(x, a, match=match), diff --git a/mercurial/debugcommands.py b/mercurial/debugcommands.py --- a/mercurial/debugcommands.py +++ b/mercurial/debugcommands.py @@ -29,7 +29,6 @@ from .node import ( bin, hex, - nullid, nullrev, short, ) @@ -1492,7 +1491,7 @@ node = r.node(i) pp = r.parents(node) ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i)) - if pp[1] != nullid: + if pp[1] != repo.nullid: ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i)) ui.write(b"}\n") @@ -1500,7 +1499,7 @@ @command(b'debugindexstats', []) def debugindexstats(ui, repo): """show stats related to the changelog index""" - repo.changelog.shortest(nullid, 1) + repo.changelog.shortest(repo.nullid, 1) index = repo.changelog.index if not util.safehasattr(index, b'stats'): raise error.Abort(_(b'debugindexstats only works with native code')) @@ -2249,7 +2248,7 @@ # arbitrary node identifiers, possibly not present in the # local repository. n = bin(s) - if len(n) != len(nullid): + if len(n) != len(repo.nullid): raise TypeError() return n except TypeError: @@ -3143,7 +3142,7 @@ try: pp = r.parents(node) except Exception: - pp = [nullid, nullid] + pp = [repo.nullid, repo.nullid] if ui.verbose: ui.write( b"% 6d % 9d % 7d % 7d %s %s %s\n" @@ -3545,7 +3544,9 @@ for n in chlist: if limit is not None and count >= limit: break - parents = [True for p in other.changelog.parents(n) if p != nullid] + parents = [ + True for p in other.changelog.parents(n) if p != repo.nullid + ] if opts.get(b"no_merges") and len(parents) == 2: continue count += 1 diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py --- a/mercurial/dirstate.py +++ b/mercurial/dirstate.py @@ -14,7 +14,6 @@ import stat from .i18n import _ -from .node import nullid from .pycompat import delattr from hgdemandimport import tracing @@ -73,13 +72,16 @@ @interfaceutil.implementer(intdirstate.idirstate) class dirstate(object): - def __init__(self, opener, ui, root, validate, sparsematchfn): + def __init__( + self, opener, ui, root, validate, sparsematchfn, nodeconstants + ): '''Create a new dirstate object. opener is an open()-like callable that can be used to open the dirstate file; root is the root of the directory tracked by the dirstate. ''' + self._nodeconstants = nodeconstants self._opener = opener self._validate = validate self._root = root @@ -136,7 +138,9 @@ @propertycache def _map(self): """Return the dirstate contents (see documentation for dirstatemap).""" - self._map = self._mapcls(self._ui, self._opener, self._root) + self._map = self._mapcls( + self._ui, self._opener, self._root, self._nodeconstants + ) return self._map @property @@ -309,7 +313,7 @@ def branch(self): return encoding.tolocal(self._branch) - def setparents(self, p1, p2=nullid): + def setparents(self, p1, p2=None): """Set dirstate parents to p1 and p2. When moving from two parents to one, 'm' merged entries a @@ -318,6 +322,8 @@ See localrepo.setparents() """ + if p2 is None: + p2 = self._nodeconstants.nullid if self._parentwriters == 0: raise ValueError( b"cannot set dirstate parent outside of " @@ -330,7 +336,10 @@ self._origpl = self._pl self._map.setparents(p1, p2) copies = {} - if oldp2 != nullid and p2 == nullid: + if ( + oldp2 != self._nodeconstants.nullid + and p2 == self._nodeconstants.nullid + ): candidatefiles = self._map.nonnormalset.union( self._map.otherparentset ) @@ -454,7 +463,7 @@ def normallookup(self, f): '''Mark a file normal, but possibly dirty.''' - if self._pl[1] != nullid: + if self._pl[1] != self._nodeconstants.nullid: # if there is a merge going on and the file was either # in state 'm' (-1) or coming from other parent (-2) before # being removed, restore that state. @@ -476,7 +485,7 @@ def otherparent(self, f): '''Mark as coming from the other parent, always dirty.''' - if self._pl[1] == nullid: + if self._pl[1] == self._nodeconstants.nullid: raise error.Abort( _(b"setting %r to other parent only allowed in merges") % f ) @@ -498,7 +507,7 @@ self._dirty = True oldstate = self[f] size = 0 - if self._pl[1] != nullid: + if self._pl[1] != self._nodeconstants.nullid: entry = self._map.get(f) if entry is not None: # backup the previous state @@ -514,7 +523,7 @@ def merge(self, f): '''Mark a file merged.''' - if self._pl[1] == nullid: + if self._pl[1] == self._nodeconstants.nullid: return self.normallookup(f) return self.otherparent(f) @@ -633,7 +642,7 @@ if self._origpl is None: self._origpl = self._pl - self._map.setparents(parent, nullid) + self._map.setparents(parent, self._nodeconstants.nullid) for f in to_lookup: self.normallookup(f) @@ -1420,12 +1429,13 @@ denormalized form that they appear as in the dirstate. """ - def __init__(self, ui, opener, root): + def __init__(self, ui, opener, root, nodeconstants): self._ui = ui self._opener = opener self._root = root self._filename = b'dirstate' - self._nodelen = 20 + self._nodeconstants = nodeconstants + self._nodelen = len(nodeconstants.nullid) self._parents = None self._dirtyparents = False @@ -1448,7 +1458,7 @@ def clear(self): self._map.clear() self.copymap.clear() - self.setparents(nullid, nullid) + self.setparents(self._nodeconstants.nullid, self._nodeconstants.nullid) util.clearcachedproperty(self, b"_dirs") util.clearcachedproperty(self, b"_alldirs") util.clearcachedproperty(self, b"filefoldmap") @@ -1625,7 +1635,10 @@ st[self._nodelen : 2 * self._nodelen], ) elif l == 0: - self._parents = (nullid, nullid) + self._parents = ( + self._nodeconstants.nullid, + self._nodeconstants.nullid, + ) else: raise error.Abort( _(b'working directory state appears damaged!') @@ -1724,7 +1737,8 @@ if rustmod is not None: class dirstatemap(object): - def __init__(self, ui, opener, root): + def __init__(self, ui, opener, root, nodeconstants): + self._nodeconstants = nodeconstants self._ui = ui self._opener = opener self._root = root @@ -1782,7 +1796,9 @@ def clear(self): self._rustmap.clear() self._inner_rustmap.clear() - self.setparents(nullid, nullid) + self.setparents( + self._nodeconstants.nullid, self._nodeconstants.nullid + ) util.clearcachedproperty(self, b"_dirs") util.clearcachedproperty(self, b"_alldirs") util.clearcachedproperty(self, b"dirfoldmap") diff --git a/mercurial/discovery.py b/mercurial/discovery.py --- a/mercurial/discovery.py +++ b/mercurial/discovery.py @@ -12,7 +12,6 @@ from .i18n import _ from .node import ( hex, - nullid, short, ) @@ -107,7 +106,7 @@ if missingroots: discbases = [] for n in missingroots: - discbases.extend([p for p in cl.parents(n) if p != nullid]) + discbases.extend([p for p in cl.parents(n) if p != repo.nullid]) # TODO remove call to nodesbetween. # TODO populate attributes on outgoing instance instead of setting # discbases. @@ -116,7 +115,7 @@ ancestorsof = heads commonheads = [n for n in discbases if n not in included] elif not commonheads: - commonheads = [nullid] + commonheads = [repo.nullid] self.commonheads = commonheads self.ancestorsof = ancestorsof self._revlog = cl @@ -270,9 +269,12 @@ # C. Update newmap with outgoing changes. # This will possibly add new heads and remove existing ones. newmap = branchmap.remotebranchcache( - (branch, heads[1]) - for branch, heads in pycompat.iteritems(headssum) - if heads[0] is not None + repo, + ( + (branch, heads[1]) + for branch, heads in pycompat.iteritems(headssum) + if heads[0] is not None + ), ) newmap.update(repo, (ctx.rev() for ctx in missingctx)) for branch, newheads in pycompat.iteritems(newmap): @@ -375,7 +377,7 @@ # - a local outgoing head descended from update # - a remote head that's known locally and not # ancestral to an outgoing head - if remoteheads == [nullid]: + if remoteheads == [repo.nullid]: # remote is empty, nothing to check. return diff --git a/mercurial/exchange.py b/mercurial/exchange.py --- a/mercurial/exchange.py +++ b/mercurial/exchange.py @@ -13,7 +13,6 @@ from .i18n import _ from .node import ( hex, - nullid, nullrev, ) from . import ( @@ -163,7 +162,7 @@ hasnode = cl.hasnode common = [n for n in common if hasnode(n)] else: - common = [nullid] + common = [repo.nullid] if not heads: heads = cl.heads() return discovery.outgoing(repo, common, heads) @@ -814,7 +813,7 @@ data = [] for book, old, new in pushop.outbookmarks: data.append((book, old)) - checkdata = bookmod.binaryencode(data) + checkdata = bookmod.binaryencode(pushop.repo, data) bundler.newpart(b'check:bookmarks', data=checkdata) @@ -1007,7 +1006,7 @@ _abortonsecretctx(pushop, new, book) data.append((book, new)) allactions.append((book, _bmaction(old, new))) - checkdata = bookmod.binaryencode(data) + checkdata = bookmod.binaryencode(pushop.repo, data) bundler.newpart(b'bookmarks', data=checkdata) def handlereply(op): @@ -1801,7 +1800,7 @@ if ( pullop.remote.capable(b'clonebundles') and pullop.heads is None - and list(pullop.common) == [nullid] + and list(pullop.common) == [pullop.repo.nullid] ): kwargs[b'cbattempted'] = pullop.clonebundleattempted @@ -1811,7 +1810,7 @@ pullop.repo.ui.status(_(b"no changes found\n")) pullop.cgresult = 0 else: - if pullop.heads is None and list(pullop.common) == [nullid]: + if pullop.heads is None and list(pullop.common) == [pullop.repo.nullid]: pullop.repo.ui.status(_(b"requesting all changes\n")) if obsolete.isenabled(pullop.repo, obsolete.exchangeopt): remoteversions = bundle2.obsmarkersversion(pullop.remotebundle2caps) @@ -1878,7 +1877,7 @@ pullop.cgresult = 0 return tr = pullop.gettransaction() - if pullop.heads is None and list(pullop.common) == [nullid]: + if pullop.heads is None and list(pullop.common) == [pullop.repo.nullid]: pullop.repo.ui.status(_(b"requesting all changes\n")) elif pullop.heads is None and pullop.remote.capable(b'changegroupsubset'): # issue1320, avoid a race if remote changed after discovery @@ -2389,7 +2388,7 @@ if not b2caps or b'bookmarks' not in b2caps: raise error.Abort(_(b'no common bookmarks exchange method')) books = bookmod.listbinbookmarks(repo) - data = bookmod.binaryencode(books) + data = bookmod.binaryencode(repo, books) if data: bundler.newpart(b'bookmarks', data=data) diff --git a/mercurial/exchangev2.py b/mercurial/exchangev2.py --- a/mercurial/exchangev2.py +++ b/mercurial/exchangev2.py @@ -11,10 +11,7 @@ import weakref from .i18n import _ -from .node import ( - nullid, - short, -) +from .node import short from . import ( bookmarks, error, @@ -297,7 +294,7 @@ if set(remoteheads).issubset(common): fetch = [] - common.discard(nullid) + common.discard(repo.nullid) return common, fetch, remoteheads @@ -404,7 +401,7 @@ # Linknode is always itself for changesets. cset[b'node'], # We always send full revisions. So delta base is not set. - nullid, + repo.nullid, mdiff.trivialdiffheader(len(data)) + data, # Flags not yet supported. 0, @@ -466,7 +463,7 @@ basenode = manifest[b'deltabasenode'] delta = extrafields[b'delta'] elif b'revision' in extrafields: - basenode = nullid + basenode = repo.nullid revision = extrafields[b'revision'] delta = mdiff.trivialdiffheader(len(revision)) + revision else: @@ -596,7 +593,7 @@ basenode = filerevision[b'deltabasenode'] delta = extrafields[b'delta'] elif b'revision' in extrafields: - basenode = nullid + basenode = repo.nullid revision = extrafields[b'revision'] delta = mdiff.trivialdiffheader(len(revision)) + revision else: @@ -689,7 +686,7 @@ basenode = filerevision[b'deltabasenode'] delta = extrafields[b'delta'] elif b'revision' in extrafields: - basenode = nullid + basenode = repo.nullid revision = extrafields[b'revision'] delta = mdiff.trivialdiffheader(len(revision)) + revision else: diff --git a/mercurial/filelog.py b/mercurial/filelog.py --- a/mercurial/filelog.py +++ b/mercurial/filelog.py @@ -8,10 +8,7 @@ from __future__ import absolute_import from .i18n import _ -from .node import ( - nullid, - nullrev, -) +from .node import nullrev from . import ( error, revlog, @@ -32,6 +29,7 @@ # Full name of the user visible file, relative to the repository root. # Used by LFS. self._revlog.filename = path + self.nullid = self._revlog.nullid def __len__(self): return len(self._revlog) @@ -40,7 +38,7 @@ return self._revlog.__iter__() def hasnode(self, node): - if node in (nullid, nullrev): + if node in (self.nullid, nullrev): return False try: diff --git a/mercurial/filemerge.py b/mercurial/filemerge.py --- a/mercurial/filemerge.py +++ b/mercurial/filemerge.py @@ -15,7 +15,6 @@ from .i18n import _ from .node import ( hex, - nullid, short, ) from .pycompat import ( @@ -111,7 +110,7 @@ return None def filenode(self): - return nullid + return self._ctx.repo().nullid _customcmp = True diff --git a/mercurial/hg.py b/mercurial/hg.py --- a/mercurial/hg.py +++ b/mercurial/hg.py @@ -14,7 +14,11 @@ import stat from .i18n import _ -from .node import nullid +from .node import ( + hex, + sha1nodeconstants, + short, +) from .pycompat import getattr from . import ( @@ -35,7 +39,6 @@ merge as mergemod, mergestate as mergestatemod, narrowspec, - node, phases, pycompat, requirements, @@ -108,7 +111,7 @@ raise error.Abort(_(b"dirstate branch not accessible")) branch = lrepo.dirstate.branch() if branch in branchmap: - revs.extend(node.hex(r) for r in reversed(branchmap[branch])) + revs.extend(hex(r) for r in reversed(branchmap[branch])) return True else: return False @@ -754,8 +757,8 @@ b'lookup', {b'key': b'0',} ).result() - if rootnode != node.nullid: - sharepath = os.path.join(sharepool, node.hex(rootnode)) + if rootnode != sha1nodeconstants.nullid: + sharepath = os.path.join(sharepool, hex(rootnode)) else: ui.status( _( @@ -772,7 +775,7 @@ ) elif sharenamemode == b'remote': sharepath = os.path.join( - sharepool, node.hex(hashutil.sha1(source).digest()) + sharepool, hex(hashutil.sha1(source).digest()) ) else: raise error.Abort( @@ -864,9 +867,7 @@ # we need to re-init the repo after manually copying the data # into it destpeer = peer(srcrepo, peeropts, dest) - srcrepo.hook( - b'outgoing', source=b'clone', node=node.hex(node.nullid) - ) + srcrepo.hook(b'outgoing', source=b'clone', node=hex(srcrepo.nullid)) else: try: # only pass ui when no srcrepo @@ -1263,7 +1264,9 @@ for n in chlist: if limit is not None and count >= limit: break - parents = [p for p in other.changelog.parents(n) if p != nullid] + parents = [ + p for p in other.changelog.parents(n) if p != repo.nullid + ] if opts.get(b'no_merges') and len(parents) == 2: continue count += 1 @@ -1321,7 +1324,7 @@ for n in o: if limit is not None and count >= limit: break - parents = [p for p in repo.changelog.parents(n) if p != nullid] + parents = [p for p in repo.changelog.parents(n) if p != repo.nullid] if opts.get(b'no_merges') and len(parents) == 2: continue count += 1 @@ -1360,7 +1363,7 @@ except Exception: repo.ui.warn( _(b'.hgsubstate is corrupt in revision %s\n') - % node.short(ctx.node()) + % short(ctx.node()) ) return ret diff --git a/mercurial/hgweb/webutil.py b/mercurial/hgweb/webutil.py --- a/mercurial/hgweb/webutil.py +++ b/mercurial/hgweb/webutil.py @@ -14,7 +14,7 @@ import re from ..i18n import _ -from ..node import hex, nullid, short +from ..node import hex, short from ..pycompat import setattr from .common import ( @@ -220,7 +220,7 @@ def _siblings(siblings=None, hiderev=None): if siblings is None: siblings = [] - siblings = [s for s in siblings if s.node() != nullid] + siblings = [s for s in siblings if s.node() != s.repo().nullid] if len(siblings) == 1 and siblings[0].rev() == hiderev: siblings = [] return templateutil.mappinggenerator(_ctxsgen, args=(siblings,)) @@ -316,12 +316,16 @@ yield {name: t} -def showtag(repo, t1, node=nullid): +def showtag(repo, t1, node=None): + if node is None: + node = repo.nullid args = (repo.nodetags, node, b'tag') return templateutil.mappinggenerator(_nodenamesgen, args=args, name=t1) -def showbookmark(repo, t1, node=nullid): +def showbookmark(repo, t1, node=None): + if node is None: + node = repo.nullid args = (repo.nodebookmarks, node, b'bookmark') return templateutil.mappinggenerator(_nodenamesgen, args=args, name=t1) diff --git a/mercurial/interfaces/dirstate.py b/mercurial/interfaces/dirstate.py --- a/mercurial/interfaces/dirstate.py +++ b/mercurial/interfaces/dirstate.py @@ -2,13 +2,11 @@ import contextlib -from .. import node as nodemod - from . import util as interfaceutil class idirstate(interfaceutil.Interface): - def __init__(opener, ui, root, validate, sparsematchfn): + def __init__(opener, ui, root, validate, sparsematchfn, nodeconstants): '''Create a new dirstate object. opener is an open()-like callable that can be used to open the @@ -97,7 +95,7 @@ def branch(): pass - def setparents(p1, p2=nodemod.nullid): + def setparents(p1, p2=None): """Set dirstate parents to p1 and p2. When moving from two parents to one, 'm' merged entries a diff --git a/mercurial/interfaces/repository.py b/mercurial/interfaces/repository.py --- a/mercurial/interfaces/repository.py +++ b/mercurial/interfaces/repository.py @@ -519,6 +519,10 @@ * Metadata to facilitate storage. """ + nullid = interfaceutil.Attribute( + """node for the null revision for use as delta base.""" + ) + def __len__(): """Obtain the number of revisions stored for this file.""" @@ -1133,6 +1137,10 @@ class imanifeststorage(interfaceutil.Interface): """Storage interface for manifest data.""" + nodeconstants = interfaceutil.Attribute( + """nodeconstants used by the current repository.""" + ) + tree = interfaceutil.Attribute( """The path to the directory this manifest tracks. @@ -1356,6 +1364,10 @@ tree manifests. """ + nodeconstants = interfaceutil.Attribute( + """nodeconstants used by the current repository.""" + ) + def __getitem__(node): """Obtain a manifest instance for a given binary node. @@ -1424,6 +1436,13 @@ This currently captures the reality of things - not how things should be. """ + nodeconstants = interfaceutil.Attribute( + """Constant nodes matching the hash function used by the repository.""" + ) + nullid = interfaceutil.Attribute( + """null revision for the hash function used by the repository.""" + ) + supportedformats = interfaceutil.Attribute( """Set of requirements that apply to stream clone. diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py --- a/mercurial/localrepo.py +++ b/mercurial/localrepo.py @@ -19,8 +19,8 @@ from .node import ( bin, hex, - nullid, nullrev, + sha1nodeconstants, short, ) from .pycompat import ( @@ -1195,6 +1195,8 @@ self.vfs = hgvfs self.path = hgvfs.base self.requirements = requirements + self.nodeconstants = sha1nodeconstants + self.nullid = self.nodeconstants.nullid self.supported = supportedrequirements self.sharedpath = sharedpath self.store = store @@ -1534,7 +1536,12 @@ sparsematchfn = lambda: sparse.matcher(self) return dirstate.dirstate( - self.vfs, self.ui, self.root, self._dirstatevalidate, sparsematchfn + self.vfs, + self.ui, + self.root, + self._dirstatevalidate, + sparsematchfn, + self.nodeconstants, ) def _dirstatevalidate(self, node): @@ -1548,7 +1555,7 @@ _(b"warning: ignoring unknown working parent %s!\n") % short(node) ) - return nullid + return self.nullid @storecache(narrowspec.FILENAME) def narrowpats(self): @@ -1599,9 +1606,9 @@ @unfilteredpropertycache def _quick_access_changeid_null(self): return { - b'null': (nullrev, nullid), - nullrev: (nullrev, nullid), - nullid: (nullrev, nullid), + b'null': (nullrev, self.nodeconstants.nullid), + nullrev: (nullrev, self.nodeconstants.nullid), + self.nullid: (nullrev, self.nullid), } @unfilteredpropertycache @@ -1611,7 +1618,7 @@ quick = self._quick_access_changeid_null.copy() cl = self.unfiltered().changelog for node in self.dirstate.parents(): - if node == nullid: + if node == self.nullid: continue rev = cl.index.get_rev(node) if rev is None: @@ -1631,7 +1638,7 @@ quick[r] = pair quick[n] = pair p1node = self.dirstate.p1() - if p1node != nullid: + if p1node != self.nullid: quick[b'.'] = quick[p1node] return quick @@ -1887,7 +1894,7 @@ # local encoding. tags = {} for (name, (node, hist)) in pycompat.iteritems(alltags): - if node != nullid: + if node != self.nullid: tags[encoding.tolocal(name)] = node tags[b'tip'] = self.changelog.tip() tagtypes = { @@ -2008,7 +2015,9 @@ def wjoin(self, f, *insidef): return self.vfs.reljoin(self.root, f, *insidef) - def setparents(self, p1, p2=nullid): + def setparents(self, p1, p2=None): + if p2 is None: + p2 = self.nullid self[None].setparents(p1, p2) self._quick_access_changeid_invalidate() @@ -2922,7 +2931,7 @@ subrepoutil.writestate(self, newstate) p1, p2 = self.dirstate.parents() - hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or b'') + hookp1, hookp2 = hex(p1), (p2 != self.nullid and hex(p2) or b'') try: self.hook( b"precommit", throw=True, parent1=hookp1, parent2=hookp2 @@ -3095,7 +3104,7 @@ t = n while True: p = self.changelog.parents(n) - if p[1] != nullid or p[0] == nullid: + if p[1] != self.nullid or p[0] == self.nullid: b.append((t, n, p[0], p[1])) break n = p[0] @@ -3108,7 +3117,7 @@ n, l, i = top, [], 0 f = 1 - while n != bottom and n != nullid: + while n != bottom and n != self.nullid: p = self.changelog.parents(n)[0] if i == f: l.append(n) diff --git a/mercurial/logcmdutil.py b/mercurial/logcmdutil.py --- a/mercurial/logcmdutil.py +++ b/mercurial/logcmdutil.py @@ -12,11 +12,7 @@ import posixpath from .i18n import _ -from .node import ( - nullid, - wdirid, - wdirrev, -) +from .node import wdirrev from .thirdparty import attr @@ -324,7 +320,7 @@ if self.ui.debugflag: mnode = ctx.manifestnode() if mnode is None: - mnode = wdirid + mnode = self.repo.nodeconstants.wdirid mrev = wdirrev else: mrev = self.repo.manifestlog.rev(mnode) @@ -473,7 +469,11 @@ ) if self.ui.debugflag or b'manifest' in datahint: - fm.data(manifest=fm.hexfunc(ctx.manifestnode() or wdirid)) + fm.data( + manifest=fm.hexfunc( + ctx.manifestnode() or self.repo.nodeconstants.wdirid + ) + ) if self.ui.debugflag or b'extra' in datahint: fm.data(extra=fm.formatdict(ctx.extra())) @@ -949,7 +949,7 @@ """Return the initial set of revisions to be filtered or followed""" if wopts.revspec: revs = scmutil.revrange(repo, wopts.revspec) - elif wopts.follow and repo.dirstate.p1() == nullid: + elif wopts.follow and repo.dirstate.p1() == repo.nullid: revs = smartset.baseset() elif wopts.follow: revs = repo.revs(b'.') diff --git a/mercurial/manifest.py b/mercurial/manifest.py --- a/mercurial/manifest.py +++ b/mercurial/manifest.py @@ -16,7 +16,6 @@ from .node import ( bin, hex, - nullid, nullrev, ) from .pycompat import getattr @@ -792,9 +791,13 @@ @interfaceutil.implementer(repository.imanifestdict) class treemanifest(object): - def __init__(self, dir=b'', text=b''): + def __init__(self, nodeconstants, dir=b'', text=b''): self._dir = dir - self._node = nullid + self.nodeconstants = nodeconstants + from .node import sha1nodeconstants + + assert sha1nodeconstants == nodeconstants + self._node = self.nodeconstants.nullid self._loadfunc = _noop self._copyfunc = _noop self._dirty = False @@ -1050,7 +1053,9 @@ if dir: self._loadlazy(dir) if dir not in self._dirs: - self._dirs[dir] = treemanifest(self._subpath(dir)) + self._dirs[dir] = treemanifest( + self.nodeconstants, self._subpath(dir) + ) self._dirs[dir].__setitem__(subpath, n) else: # manifest nodes are either 20 bytes or 32 bytes, @@ -1077,14 +1082,16 @@ if dir: self._loadlazy(dir) if dir not in self._dirs: - self._dirs[dir] = treemanifest(self._subpath(dir)) + self._dirs[dir] = treemanifest( + self.nodeconstants, self._subpath(dir) + ) self._dirs[dir].setflag(subpath, flags) else: self._flags[f] = flags self._dirty = True def copy(self): - copy = treemanifest(self._dir) + copy = treemanifest(self.nodeconstants, self._dir) copy._node = self._node copy._dirty = self._dirty if self._copyfunc is _noop: @@ -1215,7 +1222,7 @@ visit = match.visitchildrenset(self._dir[:-1]) if visit == b'all': return self.copy() - ret = treemanifest(self._dir) + ret = treemanifest(self.nodeconstants, self._dir) if not visit: return ret @@ -1272,7 +1279,7 @@ m2 = m2._matches(match) return m1.diff(m2, clean=clean) result = {} - emptytree = treemanifest() + emptytree = treemanifest(self.nodeconstants) def _iterativediff(t1, t2, stack): """compares two tree manifests and append new tree-manifests which @@ -1369,7 +1376,7 @@ self._load() # for consistency; should never have any effect here m1._load() m2._load() - emptytree = treemanifest() + emptytree = treemanifest(self.nodeconstants) def getnode(m, d): ld = m._lazydirs.get(d) @@ -1387,7 +1394,7 @@ continue subp1 = getnode(m1, d) subp2 = getnode(m2, d) - if subp1 == nullid: + if subp1 == self.nodeconstants.nullid: subp1, subp2 = subp2, subp1 writesubtree(subm, subp1, subp2, match) @@ -1552,6 +1559,7 @@ def __init__( self, + nodeconstants, opener, tree=b'', dirlogcache=None, @@ -1568,6 +1576,13 @@ option takes precedence, so if it is set to True, we ignore whatever value is passed in to the constructor. """ + self.nodeconstants = nodeconstants + from .node import sha1nodeconstants + + assert sha1nodeconstants == nodeconstants, ( + sha1nodeconstants, + nodeconstants, + ) # During normal operations, we expect to deal with not more than four # revs at a time (such as during commit --amend). When rebasing large # stacks of commits, the number can go up, hence the config knob below. @@ -1654,7 +1669,11 @@ assert self._treeondisk if d not in self._dirlogcache: mfrevlog = manifestrevlog( - self.opener, d, self._dirlogcache, treemanifest=self._treeondisk + self.nodeconstants, + self.opener, + d, + self._dirlogcache, + treemanifest=self._treeondisk, ) self._dirlogcache[d] = mfrevlog return self._dirlogcache[d] @@ -1910,6 +1929,10 @@ they receive (i.e. tree or flat or lazily loaded, etc).""" def __init__(self, opener, repo, rootstore, narrowmatch): + self.nodeconstants = repo.nodeconstants + from .node import sha1nodeconstants + + assert sha1nodeconstants == repo.nodeconstants usetreemanifest = False cachesize = 4 @@ -1948,7 +1971,7 @@ if not self._narrowmatch.always(): if not self._narrowmatch.visitdir(tree[:-1]): - return excludeddirmanifestctx(tree, node) + return excludeddirmanifestctx(self.nodeconstants, tree, node) if tree: if self._rootstore._treeondisk: if verify: @@ -1975,7 +1998,7 @@ else: m = manifestctx(self, node) - if node != nullid: + if node != self.nodeconstants.nullid: mancache = self._dirmancache.get(tree) if not mancache: mancache = util.lrucachedict(self._cachesize) @@ -2063,7 +2086,7 @@ def read(self): if self._data is None: - if self._node == nullid: + if self._node == self._manifestlog.nodeconstants.nullid: self._data = manifestdict() else: store = self._storage() @@ -2111,7 +2134,7 @@ def __init__(self, manifestlog, dir=b''): self._manifestlog = manifestlog self._dir = dir - self._treemanifest = treemanifest() + self._treemanifest = treemanifest(manifestlog.nodeconstants) def _storage(self): return self._manifestlog.getstorage(b'') @@ -2161,17 +2184,19 @@ narrowmatch = self._manifestlog._narrowmatch if not narrowmatch.always(): if not narrowmatch.visitdir(self._dir[:-1]): - return excludedmanifestrevlog(self._dir) + return excludedmanifestrevlog( + self._manifestlog.nodeconstants, self._dir + ) return self._manifestlog.getstorage(self._dir) def read(self): if self._data is None: store = self._storage() - if self._node == nullid: - self._data = treemanifest() + if self._node == self._manifestlog.nodeconstants.nullid: + self._data = treemanifest(self._manifestlog.nodeconstants) # TODO accessing non-public API elif store._treeondisk: - m = treemanifest(dir=self._dir) + m = treemanifest(self._manifestlog.nodeconstants, dir=self._dir) def gettext(): return store.revision(self._node) @@ -2191,7 +2216,9 @@ text = store.revision(self._node) arraytext = bytearray(text) store.fulltextcache[self._node] = arraytext - self._data = treemanifest(dir=self._dir, text=text) + self._data = treemanifest( + self._manifestlog.nodeconstants, dir=self._dir, text=text + ) return self._data @@ -2228,7 +2255,7 @@ r0 = store.deltaparent(store.rev(self._node)) m0 = self._manifestlog.get(self._dir, store.node(r0)).read() m1 = self.read() - md = treemanifest(dir=self._dir) + md = treemanifest(self._manifestlog.nodeconstants, dir=self._dir) for f, ((n0, fl0), (n1, fl1)) in pycompat.iteritems(m0.diff(m1)): if n1: md[f] = n1 @@ -2271,8 +2298,11 @@ whose contents are unknown. """ - def __init__(self, dir, node): - super(excludeddir, self).__init__(dir) + def __init__(self, nodeconstants, dir, node): + super(excludeddir, self).__init__(nodeconstants, dir) + from .node import sha1nodeconstants + + assert sha1nodeconstants == nodeconstants self._node = node # Add an empty file, which will be included by iterators and such, # appearing as the directory itself (i.e. something like "dir/") @@ -2291,12 +2321,16 @@ class excludeddirmanifestctx(treemanifestctx): """context wrapper for excludeddir - see that docstring for rationale""" - def __init__(self, dir, node): + def __init__(self, nodeconstants, dir, node): + self.nodeconstants = nodeconstants + from .node import sha1nodeconstants + + assert sha1nodeconstants == nodeconstants self._dir = dir self._node = node def read(self): - return excludeddir(self._dir, self._node) + return excludeddir(self.nodeconstants, self._dir, self._node) def write(self, *args): raise error.ProgrammingError( @@ -2314,7 +2348,11 @@ outside the narrowspec. """ - def __init__(self, dir): + def __init__(self, nodeconstants, dir): + self.nodeconstants = nodeconstants + from .node import sha1nodeconstants + + assert sha1nodeconstants == nodeconstants self._dir = dir def __len__(self): diff --git a/mercurial/merge.py b/mercurial/merge.py --- a/mercurial/merge.py +++ b/mercurial/merge.py @@ -13,12 +13,7 @@ import struct from .i18n import _ -from .node import ( - addednodeid, - modifiednodeid, - nullid, - nullrev, -) +from .node import nullrev from .thirdparty import attr from . import ( copies, @@ -770,7 +765,7 @@ # to flag the change. If wctx is a committed revision, we shouldn't # care for the dirty state of the working directory. if any(wctx.sub(s).dirty() for s in wctx.substate): - m1[b'.hgsubstate'] = modifiednodeid + m1[b'.hgsubstate'] = repo.nodeconstants.modifiednodeid # Don't use m2-vs-ma optimization if: # - ma is the same as m1 or m2, which we're just going to diff again later @@ -932,7 +927,7 @@ mresult.addcommitinfo( f, b'merge-removal-candidate', b'yes' ) - elif n1 == addednodeid: + elif n1 == repo.nodeconstants.addednodeid: # This file was locally added. We should forget it instead of # deleting it. mresult.addfile( @@ -1752,7 +1747,7 @@ if ( fsmonitorwarning and not fsmonitorenabled - and p1node == nullid + and p1node == repo.nullid and num_gets >= fsmonitorthreshold and pycompat.sysplatform.startswith((b'linux', b'darwin')) ): @@ -1880,7 +1875,7 @@ else: if repo.ui.configlist(b'merge', b'preferancestor') == [b'*']: cahs = repo.changelog.commonancestorsheads(p1.node(), p2.node()) - pas = [repo[anc] for anc in (sorted(cahs) or [nullid])] + pas = [repo[anc] for anc in (sorted(cahs) or [repo.nullid])] else: pas = [p1.ancestor(p2, warn=branchmerge)] @@ -2073,7 +2068,7 @@ ### apply phase if not branchmerge: # just jump to the new rev - fp1, fp2, xp1, xp2 = fp2, nullid, xp2, b'' + fp1, fp2, xp1, xp2 = fp2, repo.nullid, xp2, b'' # If we're doing a partial update, we need to skip updating # the dirstate. always = matcher is None or matcher.always() @@ -2236,14 +2231,14 @@ if keepconflictparent and stats.unresolvedcount: pother = ctx.node() else: - pother = nullid + pother = repo.nullid parents = ctx.parents() if keepparent and len(parents) == 2 and base in parents: parents.remove(base) pother = parents[0].node() # Never set both parents equal to each other if pother == pctx.node(): - pother = nullid + pother = repo.nullid if wctx.isinmemory(): wctx.setparents(pctx.node(), pother) diff --git a/mercurial/mergestate.py b/mercurial/mergestate.py --- a/mercurial/mergestate.py +++ b/mercurial/mergestate.py @@ -9,8 +9,6 @@ from .node import ( bin, hex, - nullhex, - nullid, ) from . import ( error, @@ -32,7 +30,7 @@ def _filectxorabsent(hexnode, ctx, f): - if hexnode == nullhex: + if hexnode == ctx.repo().nodeconstants.nullhex: return filemerge.absentfilectx(ctx, f) else: return ctx[f] @@ -248,7 +246,7 @@ note: also write the local version to the `.hg/merge` directory. """ if fcl.isabsent(): - localkey = nullhex + localkey = self._repo.nodeconstants.nullhex else: localkey = mergestate.getlocalkey(fcl.path()) self._make_backup(fcl, localkey) @@ -341,7 +339,7 @@ flo = fco.flags() fla = fca.flags() if b'x' in flags + flo + fla and b'l' not in flags + flo + fla: - if fca.node() == nullid and flags != flo: + if fca.node() == self._repo.nullid and flags != flo: if preresolve: self._repo.ui.warn( _( @@ -354,7 +352,7 @@ flags = flo if preresolve: # restore local - if localkey != nullhex: + if localkey != self._repo.nodeconstants.nullhex: self._restore_backup(wctx[dfile], localkey, flags) else: wctx[dfile].remove(ignoremissing=True) @@ -659,7 +657,10 @@ records.append( (RECORD_PATH_CONFLICT, b'\0'.join([filename] + v)) ) - elif v[1] == nullhex or v[6] == nullhex: + elif ( + v[1] == self._repo.nodeconstants.nullhex + or v[6] == self._repo.nodeconstants.nullhex + ): # Change/Delete or Delete/Change conflicts. These are stored in # 'C' records. v[1] is the local file, and is nullhex when the # file is deleted locally ('dc'). v[6] is the remote file, and diff --git a/mercurial/metadata.py b/mercurial/metadata.py --- a/mercurial/metadata.py +++ b/mercurial/metadata.py @@ -11,9 +11,9 @@ import multiprocessing import struct +from .node import nullrev from . import ( error, - node, pycompat, util, ) @@ -239,11 +239,11 @@ """compute the files changed by a revision""" p1 = ctx.p1() p2 = ctx.p2() - if p1.rev() == node.nullrev and p2.rev() == node.nullrev: + if p1.rev() == nullrev and p2.rev() == nullrev: return _process_root(ctx) - elif p1.rev() != node.nullrev and p2.rev() == node.nullrev: + elif p1.rev() != nullrev and p2.rev() == nullrev: return _process_linear(p1, ctx) - elif p1.rev() == node.nullrev and p2.rev() != node.nullrev: + elif p1.rev() == nullrev and p2.rev() != nullrev: # In the wild, one can encounter changeset where p1 is null but p2 is not return _process_linear(p1, ctx, parent=2) elif p1.rev() == p2.rev(): @@ -425,7 +425,7 @@ p1_ctx.node(), p2_ctx.node() ) if not cahs: - cahs = [node.nullrev] + cahs = [nullrev] mas = [ctx.repo()[r].manifest() for r in cahs] copy_candidates = [] @@ -563,7 +563,7 @@ p2n = p2.node() cahs = ctx.repo().changelog.commonancestorsheads(p1n, p2n) if not cahs: - cahs = [node.nullrev] + cahs = [nullrev] return [ctx.repo()[r].manifest() for r in cahs] def deletionfromparent(f): @@ -602,7 +602,7 @@ if f in ctx: fctx = ctx[f] parents = fctx._filelog.parents(fctx._filenode) - if parents[1] != node.nullid: + if parents[1] != ctx.repo().nullid: merged.append(f) return merged diff --git a/mercurial/node.py b/mercurial/node.py --- a/mercurial/node.py +++ b/mercurial/node.py @@ -22,28 +22,46 @@ nullrev = -1 -# In hex, this is '0000000000000000000000000000000000000000' -nullid = b"\0" * 20 -nullhex = hex(nullid) + +# pseudo identifier for working directory +# (experimental, so don't add too many dependencies on it) +wdirrev = 0x7FFFFFFF + + +class sha1nodeconstants(object): + # In hex, this is '0000000000000000000000000000000000000000' + nullid = b"\0" * 20 + nullhex = hex(nullid) -# Phony node value to stand-in for new files in some uses of -# manifests. -# In hex, this is '2121212121212121212121212121212121212121' -newnodeid = b'!!!!!!!!!!!!!!!!!!!!' -# In hex, this is '3030303030303030303030303030306164646564' -addednodeid = b'000000000000000added' -# In hex, this is '3030303030303030303030306d6f646966696564' -modifiednodeid = b'000000000000modified' + # Phony node value to stand-in for new files in some uses of + # manifests. + # In hex, this is '2121212121212121212121212121212121212121' + newnodeid = b'!!!!!!!!!!!!!!!!!!!!' + # In hex, this is '3030303030303030303030303030306164646564' + addednodeid = b'000000000000000added' + # In hex, this is '3030303030303030303030306d6f646966696564' + modifiednodeid = b'000000000000modified' -wdirfilenodeids = {newnodeid, addednodeid, modifiednodeid} + wdirfilenodeids = {newnodeid, addednodeid, modifiednodeid} -# pseudo identifiers for working directory -# (they are experimental, so don't add too many dependencies on them) -wdirrev = 0x7FFFFFFF -# In hex, this is 'ffffffffffffffffffffffffffffffffffffffff' -wdirid = b"\xff" * 20 -wdirhex = hex(wdirid) + # pseudo identifier for working directory + # (experimental, so don't add too many dependencies on it) + # In hex, this is 'ffffffffffffffffffffffffffffffffffffffff' + wdirid = b"\xff" * 20 + wdirhex = hex(wdirid) def short(node): return hex(node[:6]) + + +# legacy starting point for porting modules +# +# nullid = sha1nodeconstants.nullid +# nullhex = sha1nodeconstants.nullhex +# newnodeid = sha1nodeconstants.newnodeid +# addednodeid = sha1nodeconstants.addednodeid +# modifiednodeid = sha1nodeconstants.modifiednodeid +# wdirfilenodeids = sha1nodeconstants.wdirfilenodeids +# wdirid = sha1nodeconstants.wdirid +# wdirhex = sha1nodeconstants.wdirhex diff --git a/mercurial/obsolete.py b/mercurial/obsolete.py --- a/mercurial/obsolete.py +++ b/mercurial/obsolete.py @@ -73,11 +73,14 @@ import struct from .i18n import _ +from .node import ( + bin, + hex, +) from .pycompat import getattr from . import ( encoding, error, - node, obsutil, phases, policy, @@ -235,7 +238,7 @@ parents = () if parents is not None: try: - parents = tuple(node.bin(p) for p in parents) + parents = tuple(bin(p) for p in parents) # if parent content is not a nodeid, drop the data for p in parents: if len(p) != 20: @@ -262,7 +265,7 @@ # mark that we explicitly recorded no parents metadata[b'p0'] = b'' for i, p in enumerate(parents, 1): - metadata[b'p%i' % i] = node.hex(p) + metadata[b'p%i' % i] = hex(p) metadata = _fm0encodemeta(metadata) numsuc = len(sucs) format = _fm0fixed + (_fm0node * numsuc) @@ -522,14 +525,14 @@ children.setdefault(p, set()).add(mark) -def _checkinvalidmarkers(markers): +def _checkinvalidmarkers(repo, markers): """search for marker with invalid data and raise error if needed Exist as a separated function to allow the evolve extension for a more subtle handling. """ for mark in markers: - if node.nullid in mark[1]: + if repo.nullid in mark[1]: raise error.Abort( _( b'bad obsolescence marker detected: ' @@ -556,10 +559,11 @@ # parents: (tuple of nodeid) or None, parents of predecessors # None is used when no data has been recorded - def __init__(self, svfs, defaultformat=_fm1version, readonly=False): + def __init__(self, repo, svfs, defaultformat=_fm1version, readonly=False): # caches for various obsolescence related cache self.caches = {} self.svfs = svfs + self.repo = repo self._defaultformat = defaultformat self._readonly = readonly @@ -639,7 +643,7 @@ raise ValueError(succ) if prec in succs: raise ValueError( - 'in-marker cycle with %s' % pycompat.sysstr(node.hex(prec)) + 'in-marker cycle with %s' % pycompat.sysstr(hex(prec)) ) metadata = tuple(sorted(pycompat.iteritems(metadata))) @@ -722,7 +726,7 @@ return [] self._version, markers = _readmarkers(data) markers = list(markers) - _checkinvalidmarkers(markers) + _checkinvalidmarkers(self.repo, markers) return markers @propertycache @@ -756,7 +760,7 @@ _addpredecessors(self.predecessors, markers) if self._cached('children'): _addchildren(self.children, markers) - _checkinvalidmarkers(markers) + _checkinvalidmarkers(self.repo, markers) def relevantmarkers(self, nodes): """return a set of all obsolescence markers relevant to a set of nodes. @@ -802,7 +806,7 @@ if defaultformat is not None: kwargs['defaultformat'] = defaultformat readonly = not isenabled(repo, createmarkersopt) - store = obsstore(repo.svfs, readonly=readonly, **kwargs) + store = obsstore(repo, repo.svfs, readonly=readonly, **kwargs) if store and readonly: ui.warn( _(b'obsolete feature not enabled but %i markers found!\n') @@ -1032,7 +1036,7 @@ folddigest.update(p.node()) # Since fold only has to compete against fold for the same successors, it # seems fine to use a small ID. Smaller ID save space. - return node.hex(folddigest.digest())[:8] + return hex(folddigest.digest())[:8] def createmarkers( diff --git a/mercurial/obsutil.py b/mercurial/obsutil.py --- a/mercurial/obsutil.py +++ b/mercurial/obsutil.py @@ -10,11 +10,14 @@ import re from .i18n import _ +from .node import ( + hex, + short, +) from . import ( diffutil, encoding, error, - node as nodemod, phases, pycompat, util, @@ -961,13 +964,13 @@ elif fate == b'diverged': return filteredmsgtable[b'diverged'] % changeid elif fate == b'superseded': - single_successor = nodemod.short(successors[0][0]) + single_successor = short(successors[0][0]) return filteredmsgtable[b'superseded'] % (changeid, single_successor) elif fate == b'superseded_split': succs = [] for node_id in successors[0]: - succs.append(nodemod.short(node_id)) + succs.append(short(node_id)) if len(succs) <= 2: fmtsuccs = b', '.join(succs) @@ -1044,7 +1047,7 @@ b'instability': b'content-divergent', b'divergentnodes': divnodes, b'reason': b'predecessor', - b'node': nodemod.hex(dset[b'commonpredecessor']), + b'node': hex(dset[b'commonpredecessor']), } ) return result diff --git a/mercurial/phases.py b/mercurial/phases.py --- a/mercurial/phases.py +++ b/mercurial/phases.py @@ -109,7 +109,6 @@ from .node import ( bin, hex, - nullid, nullrev, short, wdirrev, @@ -826,7 +825,7 @@ node = bin(nhex) phase = int(phase) if phase == public: - if node != nullid: + if node != repo.nullid: repo.ui.warn( _( b'ignoring inconsistent public root' @@ -883,10 +882,10 @@ rev = cl.index.get_rev if not roots: return heads - if not heads or heads == [nullid]: + if not heads or heads == [repo.nullid]: return [] # The logic operated on revisions, convert arguments early for convenience - new_heads = {rev(n) for n in heads if n != nullid} + new_heads = {rev(n) for n in heads if n != repo.nullid} roots = [rev(n) for n in roots] # compute the area we need to remove affected_zone = repo.revs(b"(%ld::%ld)", roots, new_heads) diff --git a/mercurial/pure/parsers.py b/mercurial/pure/parsers.py --- a/mercurial/pure/parsers.py +++ b/mercurial/pure/parsers.py @@ -10,7 +10,10 @@ import struct import zlib -from ..node import nullid, nullrev +from ..node import ( + nullrev, + sha1nodeconstants, +) from .. import ( pycompat, util, @@ -37,7 +40,7 @@ indexfirst = struct.calcsize(b'Q') sizeint = struct.calcsize(b'i') indexsize = struct.calcsize(indexformatng) -nullitem = (0, 0, 0, -1, -1, -1, -1, nullid) +nullitem = (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid) def gettype(q): @@ -57,7 +60,7 @@ @util.propertycache def _nodemap(self): - nodemap = nodemaputil.NodeMap({nullid: nullrev}) + nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) for r in range(0, len(self)): n = self[r][7] nodemap[n] = r diff --git a/mercurial/revlog.py b/mercurial/revlog.py --- a/mercurial/revlog.py +++ b/mercurial/revlog.py @@ -25,13 +25,9 @@ from .node import ( bin, hex, - nullhex, - nullid, nullrev, + sha1nodeconstants, short, - wdirfilenodeids, - wdirhex, - wdirid, wdirrev, ) from .i18n import _ @@ -226,7 +222,7 @@ @util.propertycache def _nodemap(self): - nodemap = nodemaputil.NodeMap({nullid: nullrev}) + nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) for r in range(0, len(self)): n = self[r][7] nodemap[n] = r @@ -264,7 +260,7 @@ def __getitem__(self, i): if i == -1: - return (0, 0, 0, -1, -1, -1, -1, nullid) + return (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid) return list.__getitem__(self, i) @@ -275,7 +271,7 @@ def parseindex(self, data, inline): s = self.size index = [] - nodemap = nodemaputil.NodeMap({nullid: nullrev}) + nodemap = nodemaputil.NodeMap({sha1nodeconstants.nullid: nullrev}) n = off = 0 l = len(data) while off + s <= l: @@ -615,6 +611,10 @@ raise error.RevlogError( _(b'unknown version (%d) in revlog %s') % (fmt, self.indexfile) ) + + self.nodeconstants = sha1nodeconstants + self.nullid = self.nodeconstants.nullid + # sparse-revlog can't be on without general-delta (issue6056) if not self._generaldelta: self._sparserevlog = False @@ -804,7 +804,10 @@ raise except error.RevlogError: # parsers.c radix tree lookup failed - if node == wdirid or node in wdirfilenodeids: + if ( + node == self.nodeconstants.wdirid + or node in self.nodeconstants.wdirfilenodeids + ): raise error.WdirUnsupported raise error.LookupError(node, self.indexfile, _(b'no node')) @@ -1002,7 +1005,7 @@ not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: - common = [nullid] + common = [self.nullid] if heads is None: heads = self.heads() @@ -1108,7 +1111,7 @@ not supplied, uses all of the revlog's heads. If common is not supplied, uses nullid.""" if common is None: - common = [nullid] + common = [self.nullid] if heads is None: heads = self.heads() @@ -1146,11 +1149,15 @@ return nonodes lowestrev = min([self.rev(n) for n in roots]) else: - roots = [nullid] # Everybody's a descendant of nullid + roots = [self.nullid] # Everybody's a descendant of nullid lowestrev = nullrev if (lowestrev == nullrev) and (heads is None): # We want _all_ the nodes! - return ([self.node(r) for r in self], [nullid], list(self.heads())) + return ( + [self.node(r) for r in self], + [self.nullid], + list(self.heads()), + ) if heads is None: # All nodes are ancestors, so the latest ancestor is the last # node. @@ -1176,7 +1183,7 @@ # grab a node to tag n = nodestotag.pop() # Never tag nullid - if n == nullid: + if n == self.nullid: continue # A node's revision number represents its place in a # topologically sorted list of nodes. @@ -1188,7 +1195,7 @@ ancestors.add(n) # Mark as ancestor # Add non-nullid parents to list of nodes to tag. nodestotag.update( - [p for p in self.parents(n) if p != nullid] + [p for p in self.parents(n) if p != self.nullid] ) elif n in heads: # We've seen it before, is it a fake head? # So it is, real heads should not be the ancestors of @@ -1216,7 +1223,7 @@ # We are descending from nullid, and don't need to care about # any other roots. lowestrev = nullrev - roots = [nullid] + roots = [self.nullid] # Transform our roots list into a set. descendants = set(roots) # Also, keep the original roots so we can filter out roots that aren't @@ -1310,7 +1317,7 @@ """ if start is None and stop is None: if not len(self): - return [nullid] + return [self.nullid] return [self.node(r) for r in self.headrevs()] if start is None: @@ -1400,7 +1407,7 @@ if ancs: # choose a consistent winner when there's a tie return min(map(self.node, ancs)) - return nullid + return self.nullid def _match(self, id): if isinstance(id, int): @@ -1438,7 +1445,7 @@ def _partialmatch(self, id): # we don't care wdirfilenodeids as they should be always full hash - maybewdir = wdirhex.startswith(id) + maybewdir = self.nodeconstants.wdirhex.startswith(id) try: partial = self.index.partialmatch(id) if partial and self.hasnode(partial): @@ -1474,8 +1481,8 @@ nl = [ n for n in nl if hex(n).startswith(id) and self.hasnode(n) ] - if nullhex.startswith(id): - nl.append(nullid) + if self.nodeconstants.nullhex.startswith(id): + nl.append(self.nullid) if len(nl) > 0: if len(nl) == 1 and not maybewdir: self._pcache[id] = nl[0] @@ -1535,13 +1542,13 @@ length = max(self.index.shortest(node), minlength) return disambiguate(hexnode, length) except error.RevlogError: - if node != wdirid: + if node != self.nodeconstants.wdirid: raise error.LookupError(node, self.indexfile, _(b'no node')) except AttributeError: # Fall through to pure code pass - if node == wdirid: + if node == self.nodeconstants.wdirid: for length in range(minlength, len(hexnode) + 1): prefix = hexnode[:length] if isvalid(prefix): @@ -1857,7 +1864,7 @@ rev = None # fast path the special `nullid` rev - if node == nullid: + if node == self.nullid: return b"", {} # ``rawtext`` is the text as stored inside the revlog. Might be the @@ -2261,11 +2268,14 @@ - rawtext is optional (can be None); if not set, cachedelta must be set. if both are set, they must correspond to each other. """ - if node == nullid: + if node == self.nullid: raise error.RevlogError( _(b"%s: attempt to add null revision") % self.indexfile ) - if node == wdirid or node in wdirfilenodeids: + if ( + node == self.nodeconstants.wdirid + or node in self.nodeconstants.wdirfilenodeids + ): raise error.RevlogError( _(b"%s: attempt to add wdir revision") % self.indexfile ) diff --git a/mercurial/revset.py b/mercurial/revset.py --- a/mercurial/revset.py +++ b/mercurial/revset.py @@ -11,6 +11,11 @@ from .i18n import _ from .pycompat import getattr +from .node import ( + bin, + nullrev, + wdirrev, +) from . import ( dagop, destutil, @@ -20,7 +25,6 @@ grep as grepmod, hbisect, match as matchmod, - node, obsolete as obsmod, obsutil, pathutil, @@ -55,7 +59,7 @@ fullreposet = smartset.fullreposet # revisions not included in all(), but populated if specified -_virtualrevs = (node.nullrev, node.wdirrev) +_virtualrevs = (nullrev, wdirrev) # Constants for ordering requirement, used in getset(): # @@ -177,9 +181,9 @@ def _makerangeset(repo, subset, m, n, order): if m == n: r = baseset([m]) - elif n == node.wdirrev: + elif n == wdirrev: r = spanset(repo, m, len(repo)) + baseset([n]) - elif m == node.wdirrev: + elif m == wdirrev: r = baseset([m]) + spanset(repo, repo.changelog.tiprev(), n - 1) elif m < n: r = spanset(repo, m, n + 1) @@ -598,7 +602,7 @@ bms.add(repo[bmrev].rev()) else: bms = {repo[r].rev() for r in repo._bookmarks.values()} - bms -= {node.nullrev} + bms -= {nullrev} return subset & bms @@ -723,7 +727,6 @@ cs = set() pr = repo.changelog.parentrevs minrev = parentset.min() - nullrev = node.nullrev for r in subset: if r <= minrev: continue @@ -1404,7 +1407,7 @@ b'_matchfiles expected at most one revision' ) if value == b'': # empty means working directory - rev = node.wdirrev + rev = wdirrev else: rev = value elif prefix == b'd:': @@ -1424,7 +1427,6 @@ # This directly read the changelog data as creating changectx for all # revisions is quite expensive. getfiles = repo.changelog.readfiles - wdirrev = node.wdirrev def matches(x): if x == wdirrev: @@ -1500,15 +1502,15 @@ order = followorder inputset = getset(repo, fullreposet(repo), x, order=order) wdirparents = None - if node.wdirrev in inputset: + if wdirrev in inputset: # a bit slower, but not common so good enough for now wdirparents = [p.rev() for p in repo[None].parents()] inputset = set(inputset) - inputset.discard(node.wdirrev) + inputset.discard(wdirrev) heads = repo.changelog.headrevs(inputset) if wdirparents is not None: heads.difference_update(wdirparents) - heads.add(node.wdirrev) + heads.add(wdirrev) heads = baseset(heads) return subset & heads @@ -1613,7 +1615,6 @@ # i18n: "merge" is a keyword getargs(x, 0, 0, _(b"merge takes no arguments")) cl = repo.changelog - nullrev = node.nullrev def ismerge(r): try: @@ -1709,7 +1710,7 @@ if name not in ns.deprecated: names.update(repo[n].rev() for n in ns.nodes(repo, name)) - names -= {node.nullrev} + names -= {nullrev} return subset & names @@ -1723,9 +1724,9 @@ n = getstring(l[0], _(b"id requires a string")) if len(n) == 40: try: - rn = repo.changelog.rev(node.bin(n)) + rn = repo.changelog.rev(bin(n)) except error.WdirUnsupported: - rn = node.wdirrev + rn = wdirrev except (LookupError, TypeError): rn = None else: @@ -1737,7 +1738,7 @@ except LookupError: pass except error.WdirUnsupported: - rn = node.wdirrev + rn = wdirrev if rn is None: return baseset() @@ -1884,7 +1885,7 @@ ps.add(cl.parentrevs(r)[0]) except error.WdirUnsupported: ps.add(repo[r].p1().rev()) - ps -= {node.nullrev} + ps -= {nullrev} # XXX we should turn this into a baseset instead of a set, smartset may do # some optimizations from the fact this is a baseset. return subset & ps @@ -1913,7 +1914,7 @@ parents = repo[r].parents() if len(parents) == 2: ps.add(parents[1]) - ps -= {node.nullrev} + ps -= {nullrev} # XXX we should turn this into a baseset instead of a set, smartset may do # some optimizations from the fact this is a baseset. return subset & ps @@ -1940,7 +1941,7 @@ up(parentrevs(r)) except error.WdirUnsupported: up(p.rev() for p in repo[r].parents()) - ps -= {node.nullrev} + ps -= {nullrev} return subset & ps @@ -2015,7 +2016,7 @@ else: try: parents = cl.parentrevs(r) - if parents[1] != node.nullrev: + if parents[1] != nullrev: ps.add(parents[1]) except error.WdirUnsupported: parents = repo[r].parents() @@ -2592,8 +2593,8 @@ """Working directory. (EXPERIMENTAL)""" # i18n: "wdir" is a keyword getargs(x, 0, 0, _(b"wdir takes no arguments")) - if node.wdirrev in subset or isinstance(subset, fullreposet): - return baseset([node.wdirrev]) + if wdirrev in subset or isinstance(subset, fullreposet): + return baseset([wdirrev]) return baseset() @@ -2663,7 +2664,7 @@ if not s: return baseset() cl = repo.changelog - ls = [cl.rev(node.bin(r)) for r in s.split(b'\0')] + ls = [cl.rev(bin(r)) for r in s.split(b'\0')] s = subset return baseset([r for r in ls if r in s]) diff --git a/mercurial/revsetlang.py b/mercurial/revsetlang.py --- a/mercurial/revsetlang.py +++ b/mercurial/revsetlang.py @@ -11,9 +11,9 @@ from .i18n import _ from .pycompat import getattr +from .node import hex from . import ( error, - node, parser, pycompat, smartset, @@ -688,7 +688,7 @@ parse(arg) # make sure syntax errors are confined return b'(%s)' % arg elif c == b'n': - return _quote(node.hex(arg)) + return _quote(hex(arg)) elif c == b'b': try: return _quote(arg.branch()) @@ -708,7 +708,7 @@ elif t == b's': return b"_list(%s)" % _quote(b"\0".join(s)) elif t == b'n': - return b"_hexlist('%s')" % b"\0".join(node.hex(a) for a in s) + return b"_hexlist('%s')" % b"\0".join(hex(a) for a in s) elif t == b'b': try: return b"_list('%s')" % b"\0".join(a.branch() for a in s) diff --git a/mercurial/rewriteutil.py b/mercurial/rewriteutil.py --- a/mercurial/rewriteutil.py +++ b/mercurial/rewriteutil.py @@ -10,10 +10,13 @@ import re from .i18n import _ +from .node import ( + hex, + nullrev, +) from . import ( error, - node, obsolete, obsutil, revset, @@ -30,7 +33,7 @@ Make sure this function is called after taking the lock. """ - if node.nullrev in revs: + if nullrev in revs: msg = _(b"cannot %s null changeset") % action hint = _(b"no changeset checked out") raise error.InputError(msg, hint=hint) @@ -113,7 +116,7 @@ if len(successors) == 1 and len(successors[0]) == 1: successor = successors[0][0] if successor is not None: - newhash = node.hex(successor) + newhash = hex(successor) commitmsg = commitmsg.replace(h, newhash[: len(h)]) else: repo.ui.note( diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py --- a/mercurial/scmutil.py +++ b/mercurial/scmutil.py @@ -19,10 +19,8 @@ from .node import ( bin, hex, - nullid, nullrev, short, - wdirid, wdirrev, ) from .pycompat import getattr @@ -454,7 +452,7 @@ """Return binary node id for a given basectx""" node = ctx.node() if node is None: - return wdirid + return ctx.repo().nodeconstants.wdirid return node @@ -1112,7 +1110,7 @@ if roots: newnode = roots[0].node() else: - newnode = nullid + newnode = repo.nullid else: newnode = newnodes[0] moves[oldnode] = newnode @@ -1510,7 +1508,7 @@ oldctx = repo[b'.'] ds = repo.dirstate copies = dict(ds.copies()) - ds.setparents(newctx.node(), nullid) + ds.setparents(newctx.node(), repo.nullid) s = newctx.status(oldctx, match=match) for f in s.modified: if ds[f] == b'r': diff --git a/mercurial/setdiscovery.py b/mercurial/setdiscovery.py --- a/mercurial/setdiscovery.py +++ b/mercurial/setdiscovery.py @@ -46,10 +46,7 @@ import random from .i18n import _ -from .node import ( - nullid, - nullrev, -) +from .node import nullrev from . import ( error, policy, @@ -376,10 +373,10 @@ srvheadhashes, yesno = fheads.result(), fknown.result() - if cl.tip() == nullid: - if srvheadhashes != [nullid]: - return [nullid], True, srvheadhashes - return [nullid], False, [] + if cl.tip() == cl.nullid: + if srvheadhashes != [cl.nullid]: + return [cl.nullid], True, srvheadhashes + return [cl.nullid], False, [] # start actual discovery (we note this before the next "if" for # compatibility reasons) @@ -387,7 +384,7 @@ knownsrvheads = [] # revnos of remote heads that are known locally for node in srvheadhashes: - if node == nullid: + if node == cl.nullid: continue try: @@ -467,17 +464,17 @@ missing = set(result) - set(knownsrvheads) ui.log(b'discovery', msg, len(result), len(missing), roundtrips, elapsed) - if not result and srvheadhashes != [nullid]: + if not result and srvheadhashes != [cl.nullid]: if abortwhenunrelated: raise error.Abort(_(b"repository is unrelated")) else: ui.warn(_(b"warning: repository is unrelated\n")) return ( - {nullid}, + {cl.nullid}, True, srvheadhashes, ) - anyincoming = srvheadhashes != [nullid] + anyincoming = srvheadhashes != [cl.nullid] result = {clnode(r) for r in result} return result, anyincoming, srvheadhashes diff --git a/mercurial/shelve.py b/mercurial/shelve.py --- a/mercurial/shelve.py +++ b/mercurial/shelve.py @@ -29,6 +29,11 @@ from .i18n import _ from .pycompat import open +from .node import ( + bin, + hex, + nullrev, +) from . import ( bookmarks, bundle2, @@ -43,7 +48,6 @@ mdiff, merge, mergestate as mergestatemod, - node as nodemod, patch, phases, pycompat, @@ -196,11 +200,11 @@ def _verifyandtransform(cls, d): """Some basic shelvestate syntactic verification and transformation""" try: - d[b'originalwctx'] = nodemod.bin(d[b'originalwctx']) - d[b'pendingctx'] = nodemod.bin(d[b'pendingctx']) - d[b'parents'] = [nodemod.bin(h) for h in d[b'parents'].split(b' ')] + d[b'originalwctx'] = bin(d[b'originalwctx']) + d[b'pendingctx'] = bin(d[b'pendingctx']) + d[b'parents'] = [bin(h) for h in d[b'parents'].split(b' ')] d[b'nodestoremove'] = [ - nodemod.bin(h) for h in d[b'nodestoremove'].split(b' ') + bin(h) for h in d[b'nodestoremove'].split(b' ') ] except (ValueError, TypeError, KeyError) as err: raise error.CorruptedState(pycompat.bytestr(err)) @@ -296,14 +300,10 @@ ): info = { b"name": name, - b"originalwctx": nodemod.hex(originalwctx.node()), - b"pendingctx": nodemod.hex(pendingctx.node()), - b"parents": b' '.join( - [nodemod.hex(p) for p in repo.dirstate.parents()] - ), - b"nodestoremove": b' '.join( - [nodemod.hex(n) for n in nodestoremove] - ), + b"originalwctx": hex(originalwctx.node()), + b"pendingctx": hex(pendingctx.node()), + b"parents": b' '.join([hex(p) for p in repo.dirstate.parents()]), + b"nodestoremove": b' '.join([hex(n) for n in nodestoremove]), b"branchtorestore": branchtorestore, b"keep": cls._keep if keep else cls._nokeep, b"activebook": activebook or cls._noactivebook, @@ -401,7 +401,7 @@ """return all mutable ancestors for ctx (included) Much faster than the revset ancestors(ctx) & draft()""" - seen = {nodemod.nullrev} + seen = {nullrev} visit = collections.deque() visit.append(ctx) while visit: @@ -465,7 +465,7 @@ def _shelvecreatedcommit(repo, node, name, match): - info = {b'node': nodemod.hex(node)} + info = {b'node': hex(node)} shelvedfile(repo, name, b'shelve').writeinfo(info) bases = list(mutableancestors(repo[node])) shelvedfile(repo, name, b'hg').writebundle(bases, node) @@ -502,7 +502,7 @@ parent = parents[0] origbranch = wctx.branch() - if parent.node() != nodemod.nullid: + if parent.rev() != nullrev: desc = b"changes to: %s" % parent.description().split(b'\n', 1)[0] else: desc = b'(changes in empty repository)' @@ -817,7 +817,7 @@ pendingctx = state.pendingctx with repo.dirstate.parentchange(): - repo.setparents(state.pendingctx.node(), nodemod.nullid) + repo.setparents(state.pendingctx.node(), repo.nullid) repo.dirstate.write(repo.currenttransaction()) targetphase = phases.internal @@ -826,7 +826,7 @@ overrides = {(b'phases', b'new-commit'): targetphase} with repo.ui.configoverride(overrides, b'unshelve'): with repo.dirstate.parentchange(): - repo.setparents(state.parents[0], nodemod.nullid) + repo.setparents(state.parents[0], repo.nullid) newnode, ispartialunshelve = _createunshelvectx( ui, repo, shelvectx, basename, interactive, opts ) @@ -902,7 +902,7 @@ # We might not strip the unbundled changeset, so we should keep track of # the unshelve node in case we need to reuse it (eg: unshelve --keep) if node is None: - info = {b'node': nodemod.hex(shelvectx.node())} + info = {b'node': hex(shelvectx.node())} shelvedfile(repo, basename, b'shelve').writeinfo(info) else: shelvectx = repo[node] @@ -1021,7 +1021,7 @@ raise error.ConflictResolutionRequired(b'unshelve') with repo.dirstate.parentchange(): - repo.setparents(tmpwctx.node(), nodemod.nullid) + repo.setparents(tmpwctx.node(), repo.nullid) newnode, ispartialunshelve = _createunshelvectx( ui, repo, shelvectx, basename, interactive, opts ) diff --git a/mercurial/simplemerge.py b/mercurial/simplemerge.py --- a/mercurial/simplemerge.py +++ b/mercurial/simplemerge.py @@ -19,10 +19,10 @@ from __future__ import absolute_import from .i18n import _ +from .node import nullrev from . import ( error, mdiff, - node as nodemod, pycompat, util, ) @@ -454,7 +454,7 @@ def is_not_null(ctx): if not util.safehasattr(ctx, "node"): return False - return ctx.node() != nodemod.nullid + return ctx.rev() != nullrev def simplemerge(ui, localctx, basectx, otherctx, **opts): diff --git a/mercurial/sparse.py b/mercurial/sparse.py --- a/mercurial/sparse.py +++ b/mercurial/sparse.py @@ -10,10 +10,7 @@ import os from .i18n import _ -from .node import ( - hex, - nullid, -) +from .node import hex from . import ( error, match as matchmod, @@ -177,7 +174,7 @@ revs = [ repo.changelog.rev(node) for node in repo.dirstate.parents() - if node != nullid + if node != repo.nullid ] allincludes = set() @@ -321,7 +318,7 @@ revs = [ repo.changelog.rev(node) for node in repo.dirstate.parents() - if node != nullid + if node != repo.nullid ] signature = configsignature(repo, includetemp=includetemp) diff --git a/mercurial/sslutil.py b/mercurial/sslutil.py --- a/mercurial/sslutil.py +++ b/mercurial/sslutil.py @@ -16,10 +16,10 @@ from .i18n import _ from .pycompat import getattr +from .node import hex from . import ( encoding, error, - node, pycompat, util, ) @@ -763,9 +763,9 @@ # If a certificate fingerprint is pinned, use it and only it to # validate the remote cert. peerfingerprints = { - b'sha1': node.hex(hashutil.sha1(peercert).digest()), - b'sha256': node.hex(hashlib.sha256(peercert).digest()), - b'sha512': node.hex(hashlib.sha512(peercert).digest()), + b'sha1': hex(hashutil.sha1(peercert).digest()), + b'sha256': hex(hashlib.sha256(peercert).digest()), + b'sha512': hex(hashlib.sha512(peercert).digest()), } def fmtfingerprint(s): diff --git a/mercurial/statichttprepo.py b/mercurial/statichttprepo.py --- a/mercurial/statichttprepo.py +++ b/mercurial/statichttprepo.py @@ -12,6 +12,7 @@ import errno from .i18n import _ +from .node import sha1nodeconstants from . import ( branchmap, changelog, @@ -194,6 +195,8 @@ requirements, supportedrequirements ) localrepo.ensurerequirementscompatible(ui, requirements) + self.nodeconstants = sha1nodeconstants + self.nullid = self.nodeconstants.nullid # setup store self.store = localrepo.makestore(requirements, self.path, vfsclass) @@ -203,7 +206,7 @@ self._filecache = {} self.requirements = requirements - rootmanifest = manifest.manifestrevlog(self.svfs) + rootmanifest = manifest.manifestrevlog(self.nodeconstants, self.svfs) self.manifestlog = manifest.manifestlog( self.svfs, self, rootmanifest, self.narrowmatch() ) diff --git a/mercurial/store.py b/mercurial/store.py --- a/mercurial/store.py +++ b/mercurial/store.py @@ -14,11 +14,11 @@ from .i18n import _ from .pycompat import getattr +from .node import hex from . import ( changelog, error, manifest, - node, policy, pycompat, util, @@ -273,7 +273,7 @@ def _hashencode(path, dotencode): - digest = node.hex(hashutil.sha1(path).digest()) + digest = hex(hashutil.sha1(path).digest()) le = lowerencode(path[5:]).split(b'/') # skips prefix 'data/' or 'meta/' parts = _auxencode(le, dotencode) basename = parts[-1] @@ -433,7 +433,7 @@ return changelog.changelog(self.vfs, trypending=trypending) def manifestlog(self, repo, storenarrowmatch): - rootstore = manifest.manifestrevlog(self.vfs) + rootstore = manifest.manifestrevlog(repo.nodeconstants, self.vfs) return manifest.manifestlog(self.vfs, repo, rootstore, storenarrowmatch) def datafiles(self, matcher=None): diff --git a/mercurial/strip.py b/mercurial/strip.py --- a/mercurial/strip.py +++ b/mercurial/strip.py @@ -9,7 +9,6 @@ hg, lock as lockmod, mergestate as mergestatemod, - node as nodemod, pycompat, registrar, repair, @@ -17,7 +16,6 @@ util, ) -nullid = nodemod.nullid release = lockmod.release cmdtable = {} @@ -40,7 +38,7 @@ if ( util.safehasattr(repo, b'mq') - and p2 != nullid + and p2 != repo.nullid and p2 in [x.node for x in repo.mq.applied] ): unode = p2 @@ -214,7 +212,7 @@ # if one of the wdir parent is stripped we'll need # to update away to an earlier revision update = any( - p != nullid and cl.rev(p) in strippedrevs + p != repo.nullid and cl.rev(p) in strippedrevs for p in repo.dirstate.parents() ) diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py --- a/mercurial/subrepo.py +++ b/mercurial/subrepo.py @@ -18,6 +18,11 @@ import xml.dom.minidom from .i18n import _ +from .node import ( + bin, + hex, + short, +) from . import ( cmdutil, encoding, @@ -26,7 +31,6 @@ logcmdutil, match as matchmod, merge as merge, - node, pathutil, phases, pycompat, @@ -61,7 +65,7 @@ def _getstorehashcachename(remotepath): '''get a unique filename for the store hash cache of a remote repository''' - return node.hex(hashutil.sha1(_expandedabspath(remotepath)).digest())[0:12] + return hex(hashutil.sha1(_expandedabspath(remotepath)).digest())[0:12] class SubrepoAbort(error.Abort): @@ -512,7 +516,7 @@ yield b'# %s\n' % _expandedabspath(remotepath) vfs = self._repo.vfs for relname in filelist: - filehash = node.hex(hashutil.sha1(vfs.tryread(relname)).digest()) + filehash = hex(hashutil.sha1(vfs.tryread(relname)).digest()) yield b'%s = %s\n' % (relname, filehash) @propertycache @@ -606,11 +610,11 @@ @annotatesubrepoerror def diff(self, ui, diffopts, node2, match, prefix, **opts): try: - node1 = node.bin(self._state[1]) + node1 = bin(self._state[1]) # We currently expect node2 to come from substate and be # in hex format if node2 is not None: - node2 = node.bin(node2) + node2 = bin(node2) logcmdutil.diffordiffstat( ui, self._repo, @@ -674,7 +678,7 @@ n = self._repo.commit(text, user, date) if not n: return self._repo[b'.'].hex() # different version checked out - return node.hex(n) + return hex(n) @annotatesubrepoerror def phase(self, state): @@ -685,7 +689,7 @@ # we can't fully delete the repository as it may contain # local-only history self.ui.note(_(b'removing subrepo %s\n') % subrelpath(self)) - hg.clean(self._repo, node.nullid, False) + hg.clean(self._repo, self._repo.nullid, False) def _get(self, state): source, revision, kind = state @@ -1024,7 +1028,7 @@ # explicit warning. msg = _(b"subrepo '%s' is hidden in revision %s") % ( self._relpath, - node.short(self._ctx.node()), + short(self._ctx.node()), ) if onpush: @@ -1037,7 +1041,7 @@ # don't treat this as an error for `hg verify`. msg = _(b"subrepo '%s' not found in revision %s") % ( self._relpath, - node.short(self._ctx.node()), + short(self._ctx.node()), ) if onpush: diff --git a/mercurial/tagmerge.py b/mercurial/tagmerge.py --- a/mercurial/tagmerge.py +++ b/mercurial/tagmerge.py @@ -74,17 +74,11 @@ from __future__ import absolute_import from .i18n import _ -from .node import ( - hex, - nullid, -) from . import ( tags as tagsmod, util, ) -hexnullid = hex(nullid) - def readtagsformerge(ui, repo, lines, fn=b'', keeplinenums=False): '''read the .hgtags file into a structure that is suitable for merging @@ -246,8 +240,8 @@ pnlosttagset = basetagset - pntagset for t in pnlosttagset: pntags[t] = basetags[t] - if pntags[t][-1][0] != hexnullid: - pntags[t].append([hexnullid, None]) + if pntags[t][-1][0] != repo.nodeconstants.nullhex: + pntags[t].append([repo.nodeconstants.nullhex, None]) conflictedtags = [] # for reporting purposes mergedtags = util.sortdict(p1tags) diff --git a/mercurial/tags.py b/mercurial/tags.py --- a/mercurial/tags.py +++ b/mercurial/tags.py @@ -18,7 +18,6 @@ from .node import ( bin, hex, - nullid, nullrev, short, ) @@ -96,12 +95,12 @@ return fnodes -def _nulltonone(value): +def _nulltonone(repo, value): """convert nullid to None For tag value, nullid means "deleted". This small utility function helps translating that to None.""" - if value == nullid: + if value == repo.nullid: return None return value @@ -123,14 +122,14 @@ # list of (tag, old, new): None means missing entries = [] for tag, (new, __) in newtags.items(): - new = _nulltonone(new) + new = _nulltonone(repo, new) old, __ = oldtags.pop(tag, (None, None)) - old = _nulltonone(old) + old = _nulltonone(repo, old) if old != new: entries.append((tag, old, new)) # handle deleted tags for tag, (old, __) in oldtags.items(): - old = _nulltonone(old) + old = _nulltonone(repo, old) if old is not None: entries.append((tag, old, None)) entries.sort() @@ -452,7 +451,7 @@ repoheads = repo.heads() # Case 2 (uncommon): empty repo; get out quickly and don't bother # writing an empty cache. - if repoheads == [nullid]: + if repoheads == [repo.nullid]: return ([], {}, valid, {}, False) # Case 3 (uncommon): cache file missing or empty. @@ -496,7 +495,7 @@ cachefnode = {} for node in nodes: fnode = fnodescache.getfnode(node) - if fnode != nullid: + if fnode != repo.nullid: cachefnode[node] = fnode fnodescache.write() @@ -618,7 +617,7 @@ m = name if repo._tagscache.tagtypes and name in repo._tagscache.tagtypes: - old = repo.tags().get(name, nullid) + old = repo.tags().get(name, repo.nullid) fp.write(b'%s %s\n' % (hex(old), m)) fp.write(b'%s %s\n' % (hex(node), m)) fp.close() @@ -746,8 +745,8 @@ If an .hgtags does not exist at the specified revision, nullid is returned. """ - if node == nullid: - return nullid + if node == self._repo.nullid: + return node ctx = self._repo[node] rev = ctx.rev() @@ -799,7 +798,7 @@ fnode = ctx.filenode(b'.hgtags') except error.LookupError: # No .hgtags file on this revision. - fnode = nullid + fnode = self._repo.nullid self._writeentry(offset, properprefix, fnode) return fnode diff --git a/mercurial/templatefilters.py b/mercurial/templatefilters.py --- a/mercurial/templatefilters.py +++ b/mercurial/templatefilters.py @@ -12,10 +12,10 @@ import time from .i18n import _ +from .node import hex from . import ( encoding, error, - node, pycompat, registrar, smartset, @@ -280,7 +280,7 @@ """Any text. Convert a binary Mercurial node identifier into its long hexadecimal representation. """ - return node.hex(text) + return hex(text) @templatefilter(b'hgdate', intype=templateutil.date) diff --git a/mercurial/templatefuncs.py b/mercurial/templatefuncs.py --- a/mercurial/templatefuncs.py +++ b/mercurial/templatefuncs.py @@ -10,10 +10,7 @@ import re from .i18n import _ -from .node import ( - bin, - wdirid, -) +from .node import bin from . import ( color, dagop, @@ -778,7 +775,7 @@ try: node = scmutil.resolvehexnodeidprefix(repo, hexnode) except error.WdirUnsupported: - node = wdirid + node = repo.nodeconstants.wdirid except error.LookupError: return hexnode if not node: diff --git a/mercurial/templatekw.py b/mercurial/templatekw.py --- a/mercurial/templatekw.py +++ b/mercurial/templatekw.py @@ -10,8 +10,6 @@ from .i18n import _ from .node import ( hex, - nullid, - wdirid, wdirrev, ) @@ -412,7 +410,7 @@ def getgraphnodecurrent(repo, ctx, cache): wpnodes = repo.dirstate.parents() - if wpnodes[1] == nullid: + if wpnodes[1] == repo.nullid: wpnodes = wpnodes[:1] if ctx.node() in wpnodes: return b'@' @@ -525,11 +523,12 @@ ctx = context.resource(mapping, b'ctx') mnode = ctx.manifestnode() if mnode is None: - mnode = wdirid + mnode = repo.nodeconstants.wdirid mrev = wdirrev + mhex = repo.nodeconstants.wdirhex else: mrev = repo.manifestlog.rev(mnode) - mhex = hex(mnode) + mhex = hex(mnode) mapping = context.overlaymap(mapping, {b'rev': mrev, b'node': mhex}) f = context.process(b'manifest', mapping) return templateutil.hybriditem( diff --git a/mercurial/testing/storage.py b/mercurial/testing/storage.py --- a/mercurial/testing/storage.py +++ b/mercurial/testing/storage.py @@ -11,7 +11,6 @@ from ..node import ( hex, - nullid, nullrev, ) from ..pycompat import getattr @@ -51,7 +50,7 @@ self.assertFalse(f.hasnode(None)) self.assertFalse(f.hasnode(0)) self.assertFalse(f.hasnode(nullrev)) - self.assertFalse(f.hasnode(nullid)) + self.assertFalse(f.hasnode(f.nullid)) self.assertFalse(f.hasnode(b'0')) self.assertFalse(f.hasnode(b'a' * 20)) @@ -64,8 +63,8 @@ self.assertEqual(list(f.revs(start=20)), []) - # parents() and parentrevs() work with nullid/nullrev. - self.assertEqual(f.parents(nullid), (nullid, nullid)) + # parents() and parentrevs() work with f.nullid/nullrev. + self.assertEqual(f.parents(f.nullid), (f.nullid, f.nullid)) self.assertEqual(f.parentrevs(nullrev), (nullrev, nullrev)) with self.assertRaises(error.LookupError): @@ -78,9 +77,9 @@ with self.assertRaises(IndexError): f.parentrevs(i) - # nullid/nullrev lookup always works. - self.assertEqual(f.rev(nullid), nullrev) - self.assertEqual(f.node(nullrev), nullid) + # f.nullid/nullrev lookup always works. + self.assertEqual(f.rev(f.nullid), nullrev) + self.assertEqual(f.node(nullrev), f.nullid) with self.assertRaises(error.LookupError): f.rev(b'\x01' * 20) @@ -92,16 +91,16 @@ with self.assertRaises(IndexError): f.node(i) - self.assertEqual(f.lookup(nullid), nullid) - self.assertEqual(f.lookup(nullrev), nullid) - self.assertEqual(f.lookup(hex(nullid)), nullid) - self.assertEqual(f.lookup(b'%d' % nullrev), nullid) + self.assertEqual(f.lookup(f.nullid), f.nullid) + self.assertEqual(f.lookup(nullrev), f.nullid) + self.assertEqual(f.lookup(hex(f.nullid)), f.nullid) + self.assertEqual(f.lookup(b'%d' % nullrev), f.nullid) with self.assertRaises(error.LookupError): f.lookup(b'badvalue') with self.assertRaises(error.LookupError): - f.lookup(hex(nullid)[0:12]) + f.lookup(hex(f.nullid)[0:12]) with self.assertRaises(error.LookupError): f.lookup(b'-2') @@ -140,19 +139,19 @@ with self.assertRaises(IndexError): f.iscensored(i) - self.assertEqual(list(f.commonancestorsheads(nullid, nullid)), []) + self.assertEqual(list(f.commonancestorsheads(f.nullid, f.nullid)), []) with self.assertRaises(ValueError): self.assertEqual(list(f.descendants([])), []) self.assertEqual(list(f.descendants([nullrev])), []) - self.assertEqual(f.heads(), [nullid]) - self.assertEqual(f.heads(nullid), [nullid]) - self.assertEqual(f.heads(None, [nullid]), [nullid]) - self.assertEqual(f.heads(nullid, [nullid]), [nullid]) + self.assertEqual(f.heads(), [f.nullid]) + self.assertEqual(f.heads(f.nullid), [f.nullid]) + self.assertEqual(f.heads(None, [f.nullid]), [f.nullid]) + self.assertEqual(f.heads(f.nullid, [f.nullid]), [f.nullid]) - self.assertEqual(f.children(nullid), []) + self.assertEqual(f.children(f.nullid), []) with self.assertRaises(error.LookupError): f.children(b'\x01' * 20) @@ -160,7 +159,7 @@ def testsinglerevision(self): f = self._makefilefn() with self._maketransactionfn() as tr: - node = f.add(b'initial', None, tr, 0, nullid, nullid) + node = f.add(b'initial', None, tr, 0, f.nullid, f.nullid) self.assertEqual(len(f), 1) self.assertEqual(list(f), [0]) @@ -174,7 +173,7 @@ self.assertTrue(f.hasnode(node)) self.assertFalse(f.hasnode(hex(node))) self.assertFalse(f.hasnode(nullrev)) - self.assertFalse(f.hasnode(nullid)) + self.assertFalse(f.hasnode(f.nullid)) self.assertFalse(f.hasnode(node[0:12])) self.assertFalse(f.hasnode(hex(node)[0:20])) @@ -188,7 +187,7 @@ self.assertEqual(list(f.revs(1, 0)), [1, 0]) self.assertEqual(list(f.revs(2, 0)), [2, 1, 0]) - self.assertEqual(f.parents(node), (nullid, nullid)) + self.assertEqual(f.parents(node), (f.nullid, f.nullid)) self.assertEqual(f.parentrevs(0), (nullrev, nullrev)) with self.assertRaises(error.LookupError): @@ -209,7 +208,7 @@ self.assertEqual(f.lookup(node), node) self.assertEqual(f.lookup(0), node) - self.assertEqual(f.lookup(-1), nullid) + self.assertEqual(f.lookup(-1), f.nullid) self.assertEqual(f.lookup(b'0'), node) self.assertEqual(f.lookup(hex(node)), node) @@ -256,9 +255,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) - node1 = f.add(fulltext1, None, tr, 1, node0, nullid) - node2 = f.add(fulltext2, None, tr, 3, node1, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) + node1 = f.add(fulltext1, None, tr, 1, node0, f.nullid) + node2 = f.add(fulltext2, None, tr, 3, node1, f.nullid) self.assertEqual(len(f), 3) self.assertEqual(list(f), [0, 1, 2]) @@ -284,9 +283,9 @@ # TODO this is wrong self.assertEqual(list(f.revs(3, 2)), [3, 2]) - self.assertEqual(f.parents(node0), (nullid, nullid)) - self.assertEqual(f.parents(node1), (node0, nullid)) - self.assertEqual(f.parents(node2), (node1, nullid)) + self.assertEqual(f.parents(node0), (f.nullid, f.nullid)) + self.assertEqual(f.parents(node1), (node0, f.nullid)) + self.assertEqual(f.parents(node2), (node1, f.nullid)) self.assertEqual(f.parentrevs(0), (nullrev, nullrev)) self.assertEqual(f.parentrevs(1), (0, nullrev)) @@ -330,7 +329,7 @@ with self.assertRaises(IndexError): f.iscensored(3) - self.assertEqual(f.commonancestorsheads(node1, nullid), []) + self.assertEqual(f.commonancestorsheads(node1, f.nullid), []) self.assertEqual(f.commonancestorsheads(node1, node0), [node0]) self.assertEqual(f.commonancestorsheads(node1, node1), [node1]) self.assertEqual(f.commonancestorsheads(node0, node1), [node0]) @@ -364,12 +363,12 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(b'0', None, tr, 0, nullid, nullid) - node1 = f.add(b'1', None, tr, 1, node0, nullid) - node2 = f.add(b'2', None, tr, 2, node1, nullid) - node3 = f.add(b'3', None, tr, 3, node0, nullid) - node4 = f.add(b'4', None, tr, 4, node3, nullid) - node5 = f.add(b'5', None, tr, 5, node0, nullid) + node0 = f.add(b'0', None, tr, 0, f.nullid, f.nullid) + node1 = f.add(b'1', None, tr, 1, node0, f.nullid) + node2 = f.add(b'2', None, tr, 2, node1, f.nullid) + node3 = f.add(b'3', None, tr, 3, node0, f.nullid) + node4 = f.add(b'4', None, tr, 4, node3, f.nullid) + node5 = f.add(b'5', None, tr, 5, node0, f.nullid) self.assertEqual(len(f), 6) @@ -427,24 +426,24 @@ with self.assertRaises(IndexError): f.size(i) - self.assertEqual(f.revision(nullid), b'') - self.assertEqual(f.rawdata(nullid), b'') + self.assertEqual(f.revision(f.nullid), b'') + self.assertEqual(f.rawdata(f.nullid), b'') with self.assertRaises(error.LookupError): f.revision(b'\x01' * 20) - self.assertEqual(f.read(nullid), b'') + self.assertEqual(f.read(f.nullid), b'') with self.assertRaises(error.LookupError): f.read(b'\x01' * 20) - self.assertFalse(f.renamed(nullid)) + self.assertFalse(f.renamed(f.nullid)) with self.assertRaises(error.LookupError): f.read(b'\x01' * 20) - self.assertTrue(f.cmp(nullid, b'')) - self.assertTrue(f.cmp(nullid, b'foo')) + self.assertTrue(f.cmp(f.nullid, b'')) + self.assertTrue(f.cmp(f.nullid, b'foo')) with self.assertRaises(error.LookupError): f.cmp(b'\x01' * 20, b'irrelevant') @@ -455,7 +454,7 @@ next(gen) # Emitting null node yields nothing. - gen = f.emitrevisions([nullid]) + gen = f.emitrevisions([f.nullid]) with self.assertRaises(StopIteration): next(gen) @@ -468,7 +467,7 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node = f.add(fulltext, None, tr, 0, nullid, nullid) + node = f.add(fulltext, None, tr, 0, f.nullid, f.nullid) self.assertEqual(f.storageinfo(), {}) self.assertEqual( @@ -496,10 +495,10 @@ rev = next(gen) self.assertEqual(rev.node, node) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertIsNone(rev.revision) self.assertIsNone(rev.delta) @@ -512,10 +511,10 @@ rev = next(gen) self.assertEqual(rev.node, node) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertEqual(rev.revision, fulltext) self.assertIsNone(rev.delta) @@ -534,9 +533,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) - node1 = f.add(fulltext1, None, tr, 1, node0, nullid) - node2 = f.add(fulltext2, None, tr, 3, node1, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) + node1 = f.add(fulltext1, None, tr, 1, node0, f.nullid) + node2 = f.add(fulltext2, None, tr, 3, node1, f.nullid) self.assertEqual(f.storageinfo(), {}) self.assertEqual( @@ -596,10 +595,10 @@ rev = next(gen) self.assertEqual(rev.node, node0) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertEqual(rev.revision, fulltext0) self.assertIsNone(rev.delta) @@ -608,7 +607,7 @@ self.assertEqual(rev.node, node1) self.assertEqual(rev.p1node, node0) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) self.assertEqual(rev.basenode, node0) self.assertIsNone(rev.baserevisionsize) @@ -622,7 +621,7 @@ self.assertEqual(rev.node, node2) self.assertEqual(rev.p1node, node1) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) self.assertEqual(rev.basenode, node1) self.assertIsNone(rev.baserevisionsize) @@ -641,10 +640,10 @@ rev = next(gen) self.assertEqual(rev.node, node0) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertEqual(rev.revision, fulltext0) self.assertIsNone(rev.delta) @@ -653,7 +652,7 @@ self.assertEqual(rev.node, node1) self.assertEqual(rev.p1node, node0) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) self.assertEqual(rev.basenode, node0) self.assertIsNone(rev.baserevisionsize) @@ -667,7 +666,7 @@ self.assertEqual(rev.node, node2) self.assertEqual(rev.p1node, node1) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertIsNone(rev.linknode) self.assertEqual(rev.basenode, node1) self.assertIsNone(rev.baserevisionsize) @@ -700,16 +699,16 @@ rev = next(gen) self.assertEqual(rev.node, node2) self.assertEqual(rev.p1node, node1) - self.assertEqual(rev.p2node, nullid) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.p2node, f.nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertEqual(rev.revision, fulltext2) self.assertIsNone(rev.delta) rev = next(gen) self.assertEqual(rev.node, node0) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) # Delta behavior is storage dependent, so we can't easily test it. with self.assertRaises(StopIteration): @@ -722,8 +721,8 @@ rev = next(gen) self.assertEqual(rev.node, node1) self.assertEqual(rev.p1node, node0) - self.assertEqual(rev.p2node, nullid) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.p2node, f.nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertEqual(rev.revision, fulltext1) self.assertIsNone(rev.delta) @@ -731,7 +730,7 @@ rev = next(gen) self.assertEqual(rev.node, node2) self.assertEqual(rev.p1node, node1) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertEqual(rev.basenode, node1) self.assertIsNone(rev.baserevisionsize) self.assertIsNone(rev.revision) @@ -751,7 +750,7 @@ rev = next(gen) self.assertEqual(rev.node, node1) self.assertEqual(rev.p1node, node0) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertEqual(rev.basenode, node0) self.assertIsNone(rev.baserevisionsize) self.assertIsNone(rev.revision) @@ -768,9 +767,9 @@ rev = next(gen) self.assertEqual(rev.node, node0) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertIsNone(rev.revision) self.assertEqual( @@ -789,9 +788,9 @@ rev = next(gen) self.assertEqual(rev.node, node0) - self.assertEqual(rev.p1node, nullid) - self.assertEqual(rev.p2node, nullid) - self.assertEqual(rev.basenode, nullid) + self.assertEqual(rev.p1node, f.nullid) + self.assertEqual(rev.p2node, f.nullid) + self.assertEqual(rev.basenode, f.nullid) self.assertIsNone(rev.baserevisionsize) self.assertIsNone(rev.revision) self.assertEqual( @@ -802,7 +801,7 @@ rev = next(gen) self.assertEqual(rev.node, node2) self.assertEqual(rev.p1node, node1) - self.assertEqual(rev.p2node, nullid) + self.assertEqual(rev.p2node, f.nullid) self.assertEqual(rev.basenode, node0) with self.assertRaises(StopIteration): @@ -841,11 +840,11 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) - node1 = f.add(fulltext1, meta1, tr, 1, node0, nullid) - node2 = f.add(fulltext2, meta2, tr, 2, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) + node1 = f.add(fulltext1, meta1, tr, 1, node0, f.nullid) + node2 = f.add(fulltext2, meta2, tr, 2, f.nullid, f.nullid) - # Metadata header isn't recognized when parent isn't nullid. + # Metadata header isn't recognized when parent isn't f.nullid. self.assertEqual(f.size(1), len(stored1)) self.assertEqual(f.size(2), len(fulltext2)) @@ -886,8 +885,8 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, {}, tr, 0, nullid, nullid) - node1 = f.add(fulltext1, meta1, tr, 1, nullid, nullid) + node0 = f.add(fulltext0, {}, tr, 0, f.nullid, f.nullid) + node1 = f.add(fulltext1, meta1, tr, 1, f.nullid, f.nullid) # TODO this is buggy. self.assertEqual(f.size(0), len(fulltext0) + 4) @@ -916,15 +915,15 @@ fulltext1 = fulltext0 + b'bar\n' with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) node1 = b'\xaa' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, rawtext=fulltext1 + f, tr, node1, node0, f.nullid, 1, rawtext=fulltext1 ) self.assertEqual(len(f), 2) - self.assertEqual(f.parents(node1), (node0, nullid)) + self.assertEqual(f.parents(node1), (node0, f.nullid)) # revision() raises since it performs hash verification. with self.assertRaises(error.StorageError): @@ -951,11 +950,11 @@ fulltext1 = fulltext0 + b'bar\n' with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) node1 = b'\xaa' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, rawtext=fulltext1 + f, tr, node1, node0, f.nullid, 1, rawtext=fulltext1 ) with self.assertRaises(error.StorageError): @@ -973,11 +972,11 @@ fulltext1 = fulltext0 + b'bar\n' with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) node1 = b'\xaa' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, rawtext=fulltext1 + f, tr, node1, node0, f.nullid, 1, rawtext=fulltext1 ) with self.assertRaises(error.StorageError): @@ -994,22 +993,22 @@ fulltext2 = fulltext1 + b'baz\n' with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) node1 = b'\xaa' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, rawtext=fulltext1 + f, tr, node1, node0, f.nullid, 1, rawtext=fulltext1 ) with self.assertRaises(error.StorageError): f.read(node1) - node2 = storageutil.hashrevisionsha1(fulltext2, node1, nullid) + node2 = storageutil.hashrevisionsha1(fulltext2, node1, f.nullid) with self._maketransactionfn() as tr: delta = mdiff.textdiff(fulltext1, fulltext2) self._addrawrevisionfn( - f, tr, node2, node1, nullid, 2, delta=(1, delta) + f, tr, node2, node1, f.nullid, 2, delta=(1, delta) ) self.assertEqual(len(f), 3) @@ -1024,13 +1023,13 @@ stored1 = storageutil.packmeta({b'censored': b'tombstone',}, b'') with self._maketransactionfn() as tr: - node0 = f.add(b'foo', None, tr, 0, nullid, nullid) + node0 = f.add(b'foo', None, tr, 0, f.nullid, f.nullid) # The node value doesn't matter since we can't verify it. node1 = b'\xbb' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, stored1, censored=True + f, tr, node1, node0, f.nullid, 1, stored1, censored=True ) self.assertTrue(f.iscensored(1)) @@ -1053,13 +1052,13 @@ stored1 = storageutil.packmeta({b'censored': b'tombstone',}, b'') with self._maketransactionfn() as tr: - node0 = f.add(b'foo', None, tr, 0, nullid, nullid) + node0 = f.add(b'foo', None, tr, 0, f.nullid, f.nullid) # The node value doesn't matter since we can't verify it. node1 = b'\xbb' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, stored1, censored=True + f, tr, node1, node0, f.nullid, 1, stored1, censored=True ) with self.assertRaises(error.CensoredNodeError): @@ -1078,10 +1077,10 @@ def testaddnoop(self): f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(b'foo', None, tr, 0, nullid, nullid) - node1 = f.add(b'foo', None, tr, 0, nullid, nullid) + node0 = f.add(b'foo', None, tr, 0, f.nullid, f.nullid) + node1 = f.add(b'foo', None, tr, 0, f.nullid, f.nullid) # Varying by linkrev shouldn't impact hash. - node2 = f.add(b'foo', None, tr, 1, nullid, nullid) + node2 = f.add(b'foo', None, tr, 1, f.nullid, f.nullid) self.assertEqual(node1, node0) self.assertEqual(node2, node0) @@ -1092,7 +1091,9 @@ with self._maketransactionfn() as tr: # Adding a revision with bad node value fails. with self.assertRaises(error.StorageError): - f.addrevision(b'foo', tr, 0, nullid, nullid, node=b'\x01' * 20) + f.addrevision( + b'foo', tr, 0, f.nullid, f.nullid, node=b'\x01' * 20 + ) def testaddrevisionunknownflag(self): f = self._makefilefn() @@ -1103,7 +1104,7 @@ break with self.assertRaises(error.StorageError): - f.addrevision(b'foo', tr, 0, nullid, nullid, flags=flags) + f.addrevision(b'foo', tr, 0, f.nullid, f.nullid, flags=flags) def testaddgroupsimple(self): f = self._makefilefn() @@ -1142,12 +1143,12 @@ delta0 = mdiff.trivialdiffheader(len(fulltext0)) + fulltext0 with self._maketransactionfn() as tr: - node0 = f.add(fulltext0, None, tr, 0, nullid, nullid) + node0 = f.add(fulltext0, None, tr, 0, f.nullid, f.nullid) f = self._makefilefn() deltas = [ - (node0, nullid, nullid, nullid, nullid, delta0, 0), + (node0, f.nullid, f.nullid, f.nullid, f.nullid, delta0, 0), ] with self._maketransactionfn() as tr: @@ -1195,14 +1196,16 @@ nodes = [] with self._maketransactionfn() as tr: for fulltext in fulltexts: - nodes.append(f.add(fulltext, None, tr, 0, nullid, nullid)) + nodes.append(f.add(fulltext, None, tr, 0, f.nullid, f.nullid)) f = self._makefilefn() deltas = [] for i, fulltext in enumerate(fulltexts): delta = mdiff.trivialdiffheader(len(fulltext)) + fulltext - deltas.append((nodes[i], nullid, nullid, nullid, nullid, delta, 0)) + deltas.append( + (nodes[i], f.nullid, f.nullid, f.nullid, f.nullid, delta, 0) + ) with self._maketransactionfn() as tr: newnodes = [] @@ -1235,17 +1238,19 @@ stored1 = storageutil.packmeta({b'censored': b'tombstone',}, b'') with self._maketransactionfn() as tr: - node0 = f.add(b'foo\n' * 30, None, tr, 0, nullid, nullid) + node0 = f.add(b'foo\n' * 30, None, tr, 0, f.nullid, f.nullid) # The node value doesn't matter since we can't verify it. node1 = b'\xbb' * 20 self._addrawrevisionfn( - f, tr, node1, node0, nullid, 1, stored1, censored=True + f, tr, node1, node0, f.nullid, 1, stored1, censored=True ) delta = mdiff.textdiff(b'bar\n' * 30, (b'bar\n' * 30) + b'baz\n') - deltas = [(b'\xcc' * 20, node1, nullid, b'\x01' * 20, node1, delta, 0)] + deltas = [ + (b'\xcc' * 20, node1, f.nullid, b'\x01' * 20, node1, delta, 0) + ] with self._maketransactionfn() as tr: with self.assertRaises(error.CensoredBaseError): @@ -1255,9 +1260,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(b'foo\n' * 30, None, tr, 0, nullid, nullid) - node1 = f.add(b'foo\n' * 31, None, tr, 1, node0, nullid) - node2 = f.add(b'foo\n' * 32, None, tr, 2, node1, nullid) + node0 = f.add(b'foo\n' * 30, None, tr, 0, f.nullid, f.nullid) + node1 = f.add(b'foo\n' * 31, None, tr, 1, node0, f.nullid) + node2 = f.add(b'foo\n' * 32, None, tr, 2, node1, f.nullid) with self._maketransactionfn() as tr: f.censorrevision(tr, node1) @@ -1277,7 +1282,7 @@ with self._maketransactionfn() as tr: for rev in range(10): - f.add(b'%d' % rev, None, tr, rev, nullid, nullid) + f.add(b'%d' % rev, None, tr, rev, f.nullid, f.nullid) for rev in range(10): self.assertEqual(f.getstrippoint(rev), (rev, set())) @@ -1287,10 +1292,10 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - p1 = nullid + p1 = f.nullid for rev in range(10): - f.add(b'%d' % rev, None, tr, rev, p1, nullid) + f.add(b'%d' % rev, None, tr, rev, p1, f.nullid) for rev in range(10): self.assertEqual(f.getstrippoint(rev), (rev, set())) @@ -1299,11 +1304,11 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(b'0', None, tr, 0, nullid, nullid) - node1 = f.add(b'1', None, tr, 1, node0, nullid) - f.add(b'2', None, tr, 2, node1, nullid) - f.add(b'3', None, tr, 3, node0, nullid) - f.add(b'4', None, tr, 4, node0, nullid) + node0 = f.add(b'0', None, tr, 0, f.nullid, f.nullid) + node1 = f.add(b'1', None, tr, 1, node0, f.nullid) + f.add(b'2', None, tr, 2, node1, f.nullid) + f.add(b'3', None, tr, 3, node0, f.nullid) + f.add(b'4', None, tr, 4, node0, f.nullid) for rev in range(5): self.assertEqual(f.getstrippoint(rev), (rev, set())) @@ -1312,9 +1317,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - node0 = f.add(b'0', None, tr, 0, nullid, nullid) - f.add(b'1', None, tr, 10, node0, nullid) - f.add(b'2', None, tr, 5, node0, nullid) + node0 = f.add(b'0', None, tr, 0, f.nullid, f.nullid) + f.add(b'1', None, tr, 10, node0, f.nullid) + f.add(b'2', None, tr, 5, node0, f.nullid) self.assertEqual(f.getstrippoint(0), (0, set())) self.assertEqual(f.getstrippoint(1), (1, set())) @@ -1341,9 +1346,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - p1 = nullid + p1 = f.nullid for rev in range(10): - p1 = f.add(b'%d' % rev, None, tr, rev, p1, nullid) + p1 = f.add(b'%d' % rev, None, tr, rev, p1, f.nullid) self.assertEqual(len(f), 10) @@ -1356,9 +1361,9 @@ f = self._makefilefn() with self._maketransactionfn() as tr: - f.add(b'0', None, tr, 0, nullid, nullid) - node1 = f.add(b'1', None, tr, 5, nullid, nullid) - node2 = f.add(b'2', None, tr, 10, nullid, nullid) + f.add(b'0', None, tr, 0, f.nullid, f.nullid) + node1 = f.add(b'1', None, tr, 5, f.nullid, f.nullid) + node2 = f.add(b'2', None, tr, 10, f.nullid, f.nullid) self.assertEqual(len(f), 3) diff --git a/mercurial/thirdparty/selectors2.py b/mercurial/thirdparty/selectors2.py --- a/mercurial/thirdparty/selectors2.py +++ b/mercurial/thirdparty/selectors2.py @@ -48,14 +48,16 @@ __license__ = 'MIT' __url__ = 'https://www.github.com/SethMichaelLarson/selectors2' -__all__ = ['EVENT_READ', - 'EVENT_WRITE', - 'SelectorKey', - 'DefaultSelector', - 'BaseSelector'] +__all__ = [ + 'EVENT_READ', + 'EVENT_WRITE', + 'SelectorKey', + 'DefaultSelector', + 'BaseSelector', +] -EVENT_READ = (1 << 0) -EVENT_WRITE = (1 << 1) +EVENT_READ = 1 << 0 +EVENT_WRITE = 1 << 1 _DEFAULT_SELECTOR = None _SYSCALL_SENTINEL = object() # Sentinel in case a system call returns None. _ERROR_TYPES = (OSError, IOError, socket.error) @@ -114,6 +116,7 @@ and kqueue()) depending on the platform. The 'DefaultSelector' class uses the most efficient implementation for the current platform. """ + def __init__(self): # Maps file descriptors to keys. self._fd_to_key = {} @@ -149,8 +152,9 @@ key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) if key.fd in self._fd_to_key: - raise KeyError("{0!r} (FD {1}) is already registered" - .format(fileobj, key.fd)) + raise KeyError( + "{0!r} (FD {1}) is already registered".format(fileobj, key.fd) + ) self._fd_to_key[key.fd] = key return key @@ -236,8 +240,10 @@ # Almost all platforms have select.select() if hasattr(select, "select"): + class SelectSelector(BaseSelector): """ Select-based selector. """ + def __init__(self): super(SelectSelector, self).__init__() self._readers = set() @@ -264,8 +270,9 @@ timeout = None if timeout is None else max(timeout, 0.0) ready = [] - r, w, _ = _syscall_wrapper(self._wrap_select, True, self._readers, - self._writers, timeout) + r, w, _ = _syscall_wrapper( + self._wrap_select, True, self._readers, self._writers, timeout + ) r = set(r) w = set(w) for fd in r | w: @@ -288,6 +295,7 @@ # Jython has a different implementation of .fileno() for socket objects. if pycompat.isjython: + class _JythonSelectorMapping(object): """ This is an implementation of _SelectorMapping that is built for use specifically with Jython, which does not provide a hashable @@ -321,19 +329,24 @@ def __init__(self): super(JythonSelectSelector, self).__init__() - self._sockets = [] # Uses a list of tuples instead of dictionary. + self._sockets = ( + [] + ) # Uses a list of tuples instead of dictionary. self._map = _JythonSelectorMapping(self) self._readers = [] self._writers = [] # Jython has a select.cpython_compatible_select function in older versions. - self._select_func = getattr(select, 'cpython_compatible_select', select.select) + self._select_func = getattr( + select, 'cpython_compatible_select', select.select + ) def register(self, fileobj, events, data=None): for sock, _ in self._sockets: if sock is fileobj: - raise KeyError("{0!r} is already registered" - .format(fileobj, sock)) + raise KeyError( + "{0!r} is already registered".format(fileobj, sock) + ) key = SelectorKey(fileobj, -1, events, data) self._sockets.append((fileobj, key)) @@ -364,12 +377,16 @@ return self._select_func(r, w, [], timeout) __all__.append('JythonSelectSelector') - SelectSelector = JythonSelectSelector # Override so the wrong selector isn't used. + SelectSelector = ( + JythonSelectSelector # Override so the wrong selector isn't used. + ) if hasattr(select, "poll"): + class PollSelector(BaseSelector): """ Poll-based selector """ + def __init__(self): super(PollSelector, self).__init__() self._poll = select.poll() @@ -422,8 +439,10 @@ __all__.append('PollSelector') if hasattr(select, "epoll"): + class EpollSelector(BaseSelector): """ Epoll-based selector """ + def __init__(self): super(EpollSelector, self).__init__() self._epoll = select.epoll() @@ -468,9 +487,9 @@ max_events = max(len(self._fd_to_key), 1) ready = [] - fd_events = _syscall_wrapper(self._epoll.poll, True, - timeout=timeout, - maxevents=max_events) + fd_events = _syscall_wrapper( + self._epoll.poll, True, timeout=timeout, maxevents=max_events + ) for fd, event_mask in fd_events: events = 0 if event_mask & ~select.EPOLLIN: @@ -491,6 +510,7 @@ if hasattr(select, "devpoll"): + class DevpollSelector(BaseSelector): """Solaris /dev/poll selector.""" @@ -554,8 +574,10 @@ if hasattr(select, "kqueue"): + class KqueueSelector(BaseSelector): """ Kqueue / Kevent-based selector """ + def __init__(self): super(KqueueSelector, self).__init__() self._kqueue = select.kqueue() @@ -566,16 +588,16 @@ def register(self, fileobj, events, data=None): key = super(KqueueSelector, self).register(fileobj, events, data) if events & EVENT_READ: - kevent = select.kevent(key.fd, - select.KQ_FILTER_READ, - select.KQ_EV_ADD) + kevent = select.kevent( + key.fd, select.KQ_FILTER_READ, select.KQ_EV_ADD + ) _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) if events & EVENT_WRITE: - kevent = select.kevent(key.fd, - select.KQ_FILTER_WRITE, - select.KQ_EV_ADD) + kevent = select.kevent( + key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_ADD + ) _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) @@ -584,19 +606,23 @@ def unregister(self, fileobj): key = super(KqueueSelector, self).unregister(fileobj) if key.events & EVENT_READ: - kevent = select.kevent(key.fd, - select.KQ_FILTER_READ, - select.KQ_EV_DELETE) + kevent = select.kevent( + key.fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE + ) try: - _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) + _syscall_wrapper( + self._kqueue.control, False, [kevent], 0, 0 + ) except _ERROR_TYPES: pass if key.events & EVENT_WRITE: - kevent = select.kevent(key.fd, - select.KQ_FILTER_WRITE, - select.KQ_EV_DELETE) + kevent = select.kevent( + key.fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE + ) try: - _syscall_wrapper(self._kqueue.control, False, [kevent], 0, 0) + _syscall_wrapper( + self._kqueue.control, False, [kevent], 0, 0 + ) except _ERROR_TYPES: pass @@ -609,8 +635,9 @@ max_events = len(self._fd_to_key) * 2 ready_fds = {} - kevent_list = _syscall_wrapper(self._kqueue.control, True, - None, max_events, timeout) + kevent_list = _syscall_wrapper( + self._kqueue.control, True, None, max_events, timeout + ) for kevent in kevent_list: fd = kevent.ident @@ -627,7 +654,10 @@ ready_fds[key.fd] = (key, events & key.events) else: old_events = ready_fds[key.fd][1] - ready_fds[key.fd] = (key, (events | old_events) & key.events) + ready_fds[key.fd] = ( + key, + (events | old_events) & key.events, + ) return list(ready_fds.values()) @@ -659,11 +689,15 @@ # Python 3.5 uses a more direct route to wrap system calls to increase speed. if sys.version_info >= (3, 5): + def _syscall_wrapper(func, _, *args, **kwargs): """ This is the short-circuit version of the below logic because in Python 3.5+ all selectors restart system calls. """ return func(*args, **kwargs) + + else: + def _syscall_wrapper(func, recalc_timeout, *args, **kwargs): """ Wrapper function for syscalls that could fail due to EINTR. All functions should be retried if there is time left in the timeout @@ -682,7 +716,8 @@ args = list(args) if recalc_timeout and "timeout" not in kwargs: raise ValueError( - "Timeout must be in args or kwargs to be recalculated") + "Timeout must be in args or kwargs to be recalculated" + ) result = _SYSCALL_SENTINEL while result is _SYSCALL_SENTINEL: @@ -701,14 +736,17 @@ errcode = e.args[0] # Also test for the Windows equivalent of EINTR. - is_interrupt = (errcode == errno.EINTR or (hasattr(errno, "WSAEINTR") and - errcode == errno.WSAEINTR)) + is_interrupt = errcode == errno.EINTR or ( + hasattr(errno, "WSAEINTR") and errcode == errno.WSAEINTR + ) if is_interrupt: if expires is not None: current_time = monotonic() if current_time > expires: - raise OSError(errno.ETIMEDOUT, 'Connection timed out') + raise OSError( + errno.ETIMEDOUT, 'Connection timed out' + ) if recalc_timeout: if "timeout" in kwargs: kwargs["timeout"] = expires - current_time diff --git a/mercurial/treediscovery.py b/mercurial/treediscovery.py --- a/mercurial/treediscovery.py +++ b/mercurial/treediscovery.py @@ -10,10 +10,7 @@ import collections from .i18n import _ -from .node import ( - nullid, - short, -) +from .node import short from . import ( error, pycompat, @@ -41,11 +38,11 @@ with remote.commandexecutor() as e: heads = e.callcommand(b'heads', {}).result() - if repo.changelog.tip() == nullid: - base.add(nullid) - if heads != [nullid]: - return [nullid], [nullid], list(heads) - return [nullid], [], heads + if repo.changelog.tip() == repo.nullid: + base.add(repo.nullid) + if heads != [repo.nullid]: + return [repo.nullid], [repo.nullid], list(heads) + return [repo.nullid], [], heads # assume we're closer to the tip than the root # and start by examining the heads @@ -81,7 +78,7 @@ continue repo.ui.debug(b"examining %s:%s\n" % (short(n[0]), short(n[1]))) - if n[0] == nullid: # found the end of the branch + if n[0] == repo.nullid: # found the end of the branch pass elif n in seenbranch: repo.ui.debug(b"branch already found\n") @@ -164,7 +161,7 @@ raise error.RepoError(_(b"already have changeset ") + short(f[:4])) base = list(base) - if base == [nullid]: + if base == [repo.nullid]: if force: repo.ui.warn(_(b"warning: repository is unrelated\n")) else: diff --git a/mercurial/unionrepo.py b/mercurial/unionrepo.py --- a/mercurial/unionrepo.py +++ b/mercurial/unionrepo.py @@ -152,9 +152,9 @@ class unionmanifest(unionrevlog, manifest.manifestrevlog): - def __init__(self, opener, opener2, linkmapper): - manifest.manifestrevlog.__init__(self, opener) - manifest2 = manifest.manifestrevlog(opener2) + def __init__(self, nodeconstants, opener, opener2, linkmapper): + manifest.manifestrevlog.__init__(self, nodeconstants, opener) + manifest2 = manifest.manifestrevlog(nodeconstants, opener2) unionrevlog.__init__( self, opener, self.indexfile, manifest2, linkmapper ) @@ -204,7 +204,10 @@ @localrepo.unfilteredpropertycache def manifestlog(self): rootstore = unionmanifest( - self.svfs, self.repo2.svfs, self.unfiltered()._clrev + self.nodeconstants, + self.svfs, + self.repo2.svfs, + self.unfiltered()._clrev, ) return manifest.manifestlog( self.svfs, self, rootstore, self.narrowmatch() diff --git a/mercurial/upgrade.py b/mercurial/upgrade.py --- a/mercurial/upgrade.py +++ b/mercurial/upgrade.py @@ -673,7 +673,9 @@ return changelog.changelog(repo.svfs) elif path.endswith(b'00manifest.i'): mandir = path[: -len(b'00manifest.i')] - return manifest.manifestrevlog(repo.svfs, tree=mandir) + return manifest.manifestrevlog( + repo.nodeconstants, repo.svfs, tree=mandir + ) else: # reverse of "/".join(("data", path + ".i")) return filelog.filelog(repo.svfs, path[5:-2]) diff --git a/mercurial/util.py b/mercurial/util.py --- a/mercurial/util.py +++ b/mercurial/util.py @@ -35,6 +35,7 @@ import traceback import warnings +from .node import hex from .thirdparty import attr from .pycompat import ( delattr, @@ -47,7 +48,6 @@ encoding, error, i18n, - node as nodemod, policy, pycompat, urllibcompat, @@ -254,7 +254,7 @@ def __getitem__(self, key): if key not in DIGESTS: raise error.Abort(_(b'unknown digest type: %s') % k) - return nodemod.hex(self._hashes[key].digest()) + return hex(self._hashes[key].digest()) def __iter__(self): return iter(self._hashes) diff --git a/mercurial/utils/storageutil.py b/mercurial/utils/storageutil.py --- a/mercurial/utils/storageutil.py +++ b/mercurial/utils/storageutil.py @@ -13,8 +13,8 @@ from ..i18n import _ from ..node import ( bin, - nullid, nullrev, + sha1nodeconstants, ) from .. import ( dagop, @@ -25,7 +25,7 @@ from ..interfaces import repository from ..utils import hashutil -_nullhash = hashutil.sha1(nullid) +_nullhash = hashutil.sha1(sha1nodeconstants.nullid) def hashrevisionsha1(text, p1, p2): @@ -36,7 +36,7 @@ content in the revision graph. """ # As of now, if one of the parent node is null, p2 is null - if p2 == nullid: + if p2 == sha1nodeconstants.nullid: # deep copy of a hash is faster than creating one s = _nullhash.copy() s.update(p1) @@ -106,7 +106,7 @@ Returns ``False`` if the file has no copy metadata. Otherwise a 2-tuple of the source filename and node. """ - if store.parents(node)[0] != nullid: + if store.parents(node)[0] != sha1nodeconstants.nullid: return False meta = parsemeta(store.revision(node))[0] diff --git a/mercurial/verify.py b/mercurial/verify.py --- a/mercurial/verify.py +++ b/mercurial/verify.py @@ -10,10 +10,7 @@ import os from .i18n import _ -from .node import ( - nullid, - short, -) +from .node import short from . import ( error, @@ -156,13 +153,13 @@ try: p1, p2 = obj.parents(node) - if p1 not in seen and p1 != nullid: + if p1 not in seen and p1 != self.repo.nullid: self._err( lr, _(b"unknown parent 1 %s of %s") % (short(p1), short(node)), f, ) - if p2 not in seen and p2 != nullid: + if p2 not in seen and p2 != self.repo.nullid: self._err( lr, _(b"unknown parent 2 %s of %s") % (short(p2), short(node)), @@ -264,7 +261,7 @@ try: changes = cl.read(n) - if changes[0] != nullid: + if changes[0] != self.repo.nullid: mflinkrevs.setdefault(changes[0], []).append(i) self.refersmf = True for f in changes[3]: @@ -594,7 +591,7 @@ % (rp[0], short(rp[1])), f, ) - elif rp[1] == nullid: + elif rp[1] == self.repo.nullid: ui.note( _( b"warning: %s@%s: copy source" diff --git a/mercurial/wireprotov1server.py b/mercurial/wireprotov1server.py --- a/mercurial/wireprotov1server.py +++ b/mercurial/wireprotov1server.py @@ -11,10 +11,7 @@ import os from .i18n import _ -from .node import ( - hex, - nullid, -) +from .node import hex from .pycompat import getattr from . import ( @@ -469,7 +466,7 @@ clheads = set(repo.changelog.heads()) heads = set(opts.get(b'heads', set())) common = set(opts.get(b'common', set())) - common.discard(nullid) + common.discard(repo.nullid) if ( repo.ui.configbool(b'server', b'pullbundle') and b'partial-pull' in proto.getprotocaps() diff --git a/mercurial/wireprotov2server.py b/mercurial/wireprotov2server.py --- a/mercurial/wireprotov2server.py +++ b/mercurial/wireprotov2server.py @@ -10,10 +10,7 @@ import contextlib from .i18n import _ -from .node import ( - hex, - nullid, -) +from .node import hex from . import ( discovery, encoding, @@ -948,7 +945,7 @@ if spec[b'roots']: common = [n for n in spec[b'roots'] if clhasnode(n)] else: - common = [nullid] + common = [repo.nullid] for n in discovery.outgoing(repo, common, spec[b'heads']).missing: if n not in seen: diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -816,8 +816,7 @@ if sys.version_info[0] >= 3: fsdecode = os.fsdecode dest = os.path.join( - os.path.dirname(self.hgtarget), - fsdecode(dllbasename), + os.path.dirname(self.hgtarget), fsdecode(dllbasename), ) if not os.path.exists(dest): diff --git a/tests/drawdag.py b/tests/drawdag.py --- a/tests/drawdag.py +++ b/tests/drawdag.py @@ -299,7 +299,7 @@ self._added = added self._parents = parentctxs while len(self._parents) < 2: - self._parents.append(repo[node.nullid]) + self._parents.append(repo[repo.nullid]) def filectx(self, key): return simplefilectx(key, self._added[key]) @@ -388,7 +388,7 @@ content = content.replace(br'\n', b'\n').replace(br'\1', b'\1') files[name][path] = content - committed = {None: node.nullid} # {name: node} + committed = {None: repo.nullid} # {name: node} # for leaf nodes, try to find existing nodes in repo for name, parents in edges.items(): diff --git a/tests/simplestorerepo.py b/tests/simplestorerepo.py --- a/tests/simplestorerepo.py +++ b/tests/simplestorerepo.py @@ -18,7 +18,6 @@ from mercurial.node import ( bin, hex, - nullid, nullrev, ) from mercurial.thirdparty import attr @@ -106,7 +105,9 @@ _flagserrorclass = simplestoreerror - def __init__(self, svfs, path): + def __init__(self, repo, svfs, path): + self.nullid = repo.nullid + self._repo = repo self._svfs = svfs self._path = path @@ -134,18 +135,18 @@ self._indexbynode[entry[b'node']] = entry self._indexbyrev[i] = entry - self._indexbynode[nullid] = { - b'node': nullid, - b'p1': nullid, - b'p2': nullid, + self._indexbynode[self._repo.nullid] = { + b'node': self._repo.nullid, + b'p1': self._repo.nullid, + b'p2': self._repo.nullid, b'linkrev': nullrev, b'flags': 0, } self._indexbyrev[nullrev] = { - b'node': nullid, - b'p1': nullid, - b'p2': nullid, + b'node': self._repo.nullid, + b'p1': self._repo.nullid, + b'p2': self._repo.nullid, b'linkrev': nullrev, b'flags': 0, } @@ -158,7 +159,7 @@ (0, 0, 0, -1, entry[b'linkrev'], p1rev, p2rev, entry[b'node']) ) - self._index.append((0, 0, 0, -1, -1, -1, -1, nullid)) + self._index.append((0, 0, 0, -1, -1, -1, -1, self._repo.nullid)) def __len__(self): return len(self._indexdata) @@ -286,7 +287,7 @@ node = nodeorrev validatenode(node) - if node == nullid: + if node == self._repo.nullid: return b'' rev = self.rev(node) @@ -323,7 +324,7 @@ def renamed(self, node): validatenode(node) - if self.parents(node)[0] != nullid: + if self.parents(node)[0] != self._repo.nullid: return False fulltext = self.revision(node) @@ -448,7 +449,7 @@ deltamode=repository.CG_DELTAMODE_STD, ): # TODO this will probably break on some ordering options. - nodes = [n for n in nodes if n != nullid] + nodes = [n for n in nodes if n != self._repo.nullid] if not nodes: return for delta in storageutil.emitrevisions( @@ -555,7 +556,7 @@ continue # Need to resolve the fulltext from the delta base. - if deltabase == nullid: + if deltabase == self._repo.nullid: text = mdiff.patch(b'', delta) else: text = mdiff.patch(self.revision(deltabase), delta) @@ -584,11 +585,11 @@ # This is copied from revlog.py. if start is None and stop is None: if not len(self): - return [nullid] + return [self._repo.nullid] return [self.node(r) for r in self._headrevs()] if start is None: - start = nullid + start = self._repo.nullid if stop is None: stop = [] stoprevs = {self.rev(n) for n in stop} @@ -687,7 +688,7 @@ class simplestorerepo(repo.__class__): def file(self, f): - return filestorage(self.svfs, f) + return filestorage(repo, self.svfs, f) repo.__class__ = simplestorerepo diff --git a/tests/test-annotate.t b/tests/test-annotate.t --- a/tests/test-annotate.t +++ b/tests/test-annotate.t @@ -479,19 +479,19 @@ $ cat > ../legacyrepo.py < from __future__ import absolute_import - > from mercurial import commit, error, extensions, node + > from mercurial import commit, error, extensions > def _filecommit(orig, repo, fctx, manifest1, manifest2, > linkrev, tr, includecopymeta, ms): > fname = fctx.path() > text = fctx.data() > flog = repo.file(fname) - > fparent1 = manifest1.get(fname, node.nullid) - > fparent2 = manifest2.get(fname, node.nullid) + > fparent1 = manifest1.get(fname, repo.nullid) + > fparent2 = manifest2.get(fname, repo.nullid) > meta = {} > copy = fctx.copysource() > if copy and copy != fname: > raise error.Abort('copying is not supported') - > if fparent2 != node.nullid: + > if fparent2 != repo.nullid: > return flog.add(text, meta, tr, linkrev, > fparent1, fparent2), 'modified' > raise error.Abort('only merging is supported') diff --git a/tests/test-check-interfaces.py b/tests/test-check-interfaces.py --- a/tests/test-check-interfaces.py +++ b/tests/test-check-interfaces.py @@ -243,7 +243,10 @@ # Conforms to imanifestlog. ml = manifest.manifestlog( - vfs, repo, manifest.manifestrevlog(repo.svfs), repo.narrowmatch() + vfs, + repo, + manifest.manifestrevlog(repo.nodeconstants, repo.svfs), + repo.narrowmatch(), ) checkzobject(ml) checkzobject(repo.manifestlog) @@ -258,7 +261,7 @@ # Conforms to imanifestdict. checkzobject(mctx.read()) - mrl = manifest.manifestrevlog(vfs) + mrl = manifest.manifestrevlog(repo.nodeconstants, vfs) checkzobject(mrl) ziverify.verifyClass(repository.irevisiondelta, revlog.revlogrevisiondelta) diff --git a/tests/test-commit.t b/tests/test-commit.t --- a/tests/test-commit.t +++ b/tests/test-commit.t @@ -646,14 +646,14 @@ verify pathauditor blocks evil filepaths $ cat > evil-commit.py < from __future__ import absolute_import - > from mercurial import context, hg, node, ui as uimod + > from mercurial import context, hg, ui as uimod > notrc = u".h\u200cg".encode('utf-8') + b'/hgrc' > u = uimod.ui.load() > r = hg.repository(u, b'.') > def filectxfn(repo, memctx, path): > return context.memfilectx(repo, memctx, path, > b'[hooks]\nupdate = echo owned') - > c = context.memctx(r, [r.changelog.tip(), node.nullid], + > c = context.memctx(r, [r.changelog.tip(), r.nullid], > b'evil', [notrc], filectxfn, 0) > r.commitctx(c) > EOF @@ -672,14 +672,14 @@ repository tip rolled back to revision 2 (undo commit) $ cat > evil-commit.py < from __future__ import absolute_import - > from mercurial import context, hg, node, ui as uimod + > from mercurial import context, hg, ui as uimod > notrc = b"HG~1/hgrc" > u = uimod.ui.load() > r = hg.repository(u, b'.') > def filectxfn(repo, memctx, path): > return context.memfilectx(repo, memctx, path, > b'[hooks]\nupdate = echo owned') - > c = context.memctx(r, [r[b'tip'].node(), node.nullid], + > c = context.memctx(r, [r[b'tip'].node(), r.nullid], > b'evil', [notrc], filectxfn, 0) > r.commitctx(c) > EOF @@ -692,14 +692,14 @@ repository tip rolled back to revision 2 (undo commit) $ cat > evil-commit.py < from __future__ import absolute_import - > from mercurial import context, hg, node, ui as uimod + > from mercurial import context, hg, ui as uimod > notrc = b"HG8B6C~2/hgrc" > u = uimod.ui.load() > r = hg.repository(u, b'.') > def filectxfn(repo, memctx, path): > return context.memfilectx(repo, memctx, path, > b'[hooks]\nupdate = echo owned') - > c = context.memctx(r, [r[b'tip'].node(), node.nullid], + > c = context.memctx(r, [r[b'tip'].node(), r.nullid], > b'evil', [notrc], filectxfn, 0) > r.commitctx(c) > EOF diff --git a/tests/test-fastannotate-hg.t b/tests/test-fastannotate-hg.t --- a/tests/test-fastannotate-hg.t +++ b/tests/test-fastannotate-hg.t @@ -482,19 +482,19 @@ $ cat > ../legacyrepo.py < from __future__ import absolute_import - > from mercurial import commit, error, extensions, node + > from mercurial import commit, error, extensions > def _filecommit(orig, repo, fctx, manifest1, manifest2, > linkrev, tr, includecopymeta, ms): > fname = fctx.path() > text = fctx.data() > flog = repo.file(fname) - > fparent1 = manifest1.get(fname, node.nullid) - > fparent2 = manifest2.get(fname, node.nullid) + > fparent1 = manifest1.get(fname, repo.nullid) + > fparent2 = manifest2.get(fname, repo.nullid) > meta = {} > copy = fctx.copysource() > if copy and copy != fname: > raise error.Abort('copying is not supported') - > if fparent2 != node.nullid: + > if fparent2 != repo.nullid: > return flog.add(text, meta, tr, linkrev, > fparent1, fparent2), 'modified' > raise error.Abort('only merging is supported') diff --git a/tests/test-filelog.py b/tests/test-filelog.py --- a/tests/test-filelog.py +++ b/tests/test-filelog.py @@ -4,10 +4,7 @@ """ from __future__ import absolute_import, print_function -from mercurial.node import ( - hex, - nullid, -) +from mercurial.node import hex from mercurial import ( hg, ui as uimod, @@ -22,7 +19,7 @@ def addrev(text, renamed=False): if renamed: # data doesn't matter. Just make sure filelog.renamed() returns True - meta = {b'copyrev': hex(nullid), b'copy': b'bar'} + meta = {b'copyrev': hex(repo.nullid), b'copy': b'bar'} else: meta = {} @@ -30,7 +27,7 @@ try: lock = repo.lock() t = repo.transaction(b'commit') - node = fl.add(text, meta, t, 0, nullid, nullid) + node = fl.add(text, meta, t, 0, repo.nullid, repo.nullid) return node finally: if t: diff --git a/tests/test-manifest.py b/tests/test-manifest.py --- a/tests/test-manifest.py +++ b/tests/test-manifest.py @@ -6,6 +6,8 @@ import unittest import zlib +from mercurial.node import sha1nodeconstants + from mercurial import ( manifest as manifestmod, match as matchmod, @@ -432,7 +434,7 @@ class testtreemanifest(unittest.TestCase, basemanifesttests): def parsemanifest(self, text): - return manifestmod.treemanifest(b'', text) + return manifestmod.treemanifest(sha1nodeconstants, b'', text) def testWalkSubtrees(self): m = self.parsemanifest(A_DEEPER_MANIFEST) diff --git a/tests/test-parseindex2.py b/tests/test-parseindex2.py --- a/tests/test-parseindex2.py +++ b/tests/test-parseindex2.py @@ -12,8 +12,8 @@ import unittest from mercurial.node import ( - nullid, nullrev, + sha1nodeconstants, ) from mercurial import ( node as nodemod, @@ -39,7 +39,7 @@ s = 64 cache = None index = [] - nodemap = {nullid: nullrev} + nodemap = {sha1nodeconstants.nullid: nullrev} n = off = 0 l = len(data) - s @@ -226,7 +226,7 @@ ix = parsers.parse_index2(data_inlined, True)[0] for i, r in enumerate(ix): - if r[7] == nullid: + if r[7] == sha1nodeconstants.nullid: i = -1 try: self.assertEqual( @@ -239,7 +239,7 @@ break def testminusone(self): - want = (0, 0, 0, -1, -1, -1, -1, nullid) + want = (0, 0, 0, -1, -1, -1, -1, sha1nodeconstants.nullid) index, junk = parsers.parse_index2(data_inlined, True) got = index[-1] self.assertEqual(want, got) # inline data diff --git a/tests/test-remotefilelog-datapack.py b/tests/test-remotefilelog-datapack.py --- a/tests/test-remotefilelog-datapack.py +++ b/tests/test-remotefilelog-datapack.py @@ -16,7 +16,7 @@ # Load the local remotefilelog, not the system one sys.path[0:0] = [os.path.join(os.path.dirname(__file__), '..')] -from mercurial.node import nullid +from mercurial.node import sha1nodeconstants from mercurial import policy if not policy._packageprefs.get(policy.policy, (False, False))[1]: @@ -63,7 +63,14 @@ def createPack(self, revisions=None, packdir=None): if revisions is None: - revisions = [(b"filename", self.getFakeHash(), nullid, b"content")] + revisions = [ + ( + b"filename", + self.getFakeHash(), + sha1nodeconstants.nullid, + b"content", + ) + ] if packdir is None: packdir = self.makeTempDir() @@ -87,7 +94,7 @@ filename = b"foo" node = self.getHash(content) - revisions = [(filename, node, nullid, content)] + revisions = [(filename, node, sha1nodeconstants.nullid, content)] pack = self.createPack(revisions) if self.paramsavailable: self.assertEqual( @@ -128,7 +135,7 @@ """ revisions = [] filename = b"foo" - lastnode = nullid + lastnode = sha1nodeconstants.nullid for i in range(10): content = b"abcdef%d" % i node = self.getHash(content) @@ -160,7 +167,7 @@ for j in range(random.randint(1, 100)): content = b"content-%d" % j node = self.getHash(content) - lastnode = nullid + lastnode = sha1nodeconstants.nullid if len(filerevs) > 0: lastnode = filerevs[random.randint(0, len(filerevs) - 1)] filerevs.append(node) @@ -188,7 +195,9 @@ b'Z': b'random_string', b'_': b'\0' * i, } - revisions.append((filename, node, nullid, content, meta)) + revisions.append( + (filename, node, sha1nodeconstants.nullid, content, meta) + ) pack = self.createPack(revisions) for name, node, x, content, origmeta in revisions: parsedmeta = pack.getmeta(name, node) @@ -202,7 +211,7 @@ """ revisions = [] filename = b"foo" - lastnode = nullid + lastnode = sha1nodeconstants.nullid for i in range(10): content = b"abcdef%d" % i node = self.getHash(content) @@ -229,7 +238,7 @@ pack = self.createPack() try: - pack.add(b'filename', nullid, b'contents') + pack.add(b'filename', sha1nodeconstants.nullid, b'contents') self.assertTrue(False, "datapack.add should throw") except RuntimeError: pass @@ -268,7 +277,9 @@ content = filename node = self.getHash(content) blobs[(filename, node)] = content - revisions.append((filename, node, nullid, content)) + revisions.append( + (filename, node, sha1nodeconstants.nullid, content) + ) pack = self.createPack(revisions) if self.paramsavailable: @@ -292,7 +303,12 @@ for i in range(numpacks): chain = [] - revision = (b'%d' % i, self.getFakeHash(), nullid, b"content") + revision = ( + b'%d' % i, + self.getFakeHash(), + sha1nodeconstants.nullid, + b"content", + ) for _ in range(revisionsperpack): chain.append(revision) @@ -350,7 +366,9 @@ filename = b"filename-%d" % i content = b"content-%d" % i node = self.getHash(content) - revisions.append((filename, node, nullid, content)) + revisions.append( + (filename, node, sha1nodeconstants.nullid, content) + ) path = self.createPack(revisions).path diff --git a/tests/test-remotefilelog-histpack.py b/tests/test-remotefilelog-histpack.py --- a/tests/test-remotefilelog-histpack.py +++ b/tests/test-remotefilelog-histpack.py @@ -13,7 +13,7 @@ import silenttestrunner -from mercurial.node import nullid +from mercurial.node import sha1nodeconstants from mercurial import ( pycompat, ui as uimod, @@ -59,8 +59,8 @@ ( b"filename", self.getFakeHash(), - nullid, - nullid, + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, self.getFakeHash(), None, ) @@ -120,10 +120,19 @@ """ revisions = [] filename = b"foo" - lastnode = nullid + lastnode = sha1nodeconstants.nullid for i in range(10): node = self.getFakeHash() - revisions.append((filename, node, lastnode, nullid, nullid, None)) + revisions.append( + ( + filename, + node, + lastnode, + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, + None, + ) + ) lastnode = node # revisions must be added in topological order, newest first @@ -150,17 +159,17 @@ for i in range(100): filename = b"filename-%d" % i entries = [] - p2 = nullid - linknode = nullid + p2 = sha1nodeconstants.nullid + linknode = sha1nodeconstants.nullid for j in range(random.randint(1, 100)): node = self.getFakeHash() - p1 = nullid + p1 = sha1nodeconstants.nullid if len(entries) > 0: p1 = entries[random.randint(0, len(entries) - 1)] entries.append(node) revisions.append((filename, node, p1, p2, linknode, None)) allentries[(filename, node)] = (p1, p2, linknode) - if p1 == nullid: + if p1 == sha1nodeconstants.nullid: ancestorcounts[(filename, node)] = 1 else: newcount = ancestorcounts[(filename, p1)] + 1 @@ -184,10 +193,19 @@ def testGetNodeInfo(self): revisions = [] filename = b"foo" - lastnode = nullid + lastnode = sha1nodeconstants.nullid for i in range(10): node = self.getFakeHash() - revisions.append((filename, node, lastnode, nullid, nullid, None)) + revisions.append( + ( + filename, + node, + lastnode, + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, + None, + ) + ) lastnode = node pack = self.createPack(revisions) @@ -236,7 +254,14 @@ pack = self.createPack() try: - pack.add(b'filename', nullid, nullid, nullid, nullid, None) + pack.add( + b'filename', + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, + sha1nodeconstants.nullid, + None, + ) self.assertTrue(False, "historypack.add should throw") except RuntimeError: pass diff --git a/tests/test-revlog-raw.py b/tests/test-revlog-raw.py --- a/tests/test-revlog-raw.py +++ b/tests/test-revlog-raw.py @@ -8,7 +8,6 @@ from mercurial import ( encoding, - node, revlog, transaction, vfs, @@ -93,7 +92,7 @@ ''' nextrev = len(rlog) p1 = rlog.node(nextrev - 1) - p2 = node.nullid + p2 = rlog.nullid if isext: flags = revlog.REVIDX_EXTSTORED else: @@ -127,7 +126,7 @@ class dummychangegroup(object): @staticmethod def deltachunk(pnode): - pnode = pnode or node.nullid + pnode = pnode or rlog.nullid parentrev = rlog.rev(pnode) r = parentrev + 1 if r >= len(rlog): @@ -142,7 +141,7 @@ return { b'node': rlog.node(r), b'p1': pnode, - b'p2': node.nullid, + b'p2': rlog.nullid, b'cs': rlog.node(rlog.linkrev(r)), b'flags': rlog.flags(r), b'deltabase': rlog.node(deltaparent), @@ -181,7 +180,7 @@ dlog = newrevlog(destname, recreate=True) for r in rlog: p1 = rlog.node(r - 1) - p2 = node.nullid + p2 = rlog.nullid if r == 0 or (rlog.flags(r) & revlog.REVIDX_EXTSTORED): text = rlog.rawdata(r) cachedelta = None diff --git a/tests/testlib/ext-sidedata.py b/tests/testlib/ext-sidedata.py --- a/tests/testlib/ext-sidedata.py +++ b/tests/testlib/ext-sidedata.py @@ -10,9 +10,9 @@ import hashlib import struct +from mercurial.node import nullrev from mercurial import ( extensions, - node, requirements, revlog, upgrade, @@ -40,7 +40,7 @@ text = orig(self, nodeorrev, *args, **kwargs) if getattr(self, 'sidedatanocheck', False): return text - if nodeorrev != node.nullrev and nodeorrev != node.nullid: + if nodeorrev != nullrev and nodeorrev != self.nullid: sd = self.sidedata(nodeorrev) if len(text) != struct.unpack('>I', sd[sidedata.SD_TEST1])[0]: raise RuntimeError('text size mismatch')