scmutil.py
2201 lines
| 71.7 KiB
| text/x-python
|
PythonLexer
/ mercurial / scmutil.py
Adrian Buehlmann
|
r13962 | # scmutil.py - Mercurial core utility functions | ||
# | ||||
# Copyright Matt Mackall <mpm@selenic.com> | ||||
# | ||||
# This software may be used and distributed according to the terms of the | ||||
# GNU General Public License version 2 or any later version. | ||||
Gregory Szorc
|
r27482 | from __future__ import absolute_import | ||
import errno | ||||
import glob | ||||
import os | ||||
Martin von Zweigbergk
|
r41799 | import posixpath | ||
Gregory Szorc
|
r27482 | import re | ||
Yuya Nishihara
|
r34462 | import subprocess | ||
r33249 | import weakref | |||
Gregory Szorc
|
r27482 | |||
from .i18n import _ | ||||
Yuya Nishihara
|
r32656 | from .node import ( | ||
Martin von Zweigbergk
|
r37546 | bin, | ||
Jun Wu
|
r33088 | hex, | ||
nullid, | ||||
Martin von Zweigbergk
|
r39930 | nullrev, | ||
Yuya Nishihara
|
r34328 | short, | ||
Yuya Nishihara
|
r32656 | wdirid, | ||
wdirrev, | ||||
) | ||||
Gregory Szorc
|
r43359 | from .pycompat import getattr | ||
Augie Fackler
|
r44053 | from .thirdparty import attr | ||
Gregory Szorc
|
r27482 | from . import ( | ||
Martin von Zweigbergk
|
r42103 | copies as copiesmod, | ||
Gregory Szorc
|
r27482 | encoding, | ||
error, | ||||
match as matchmod, | ||||
Jun Wu
|
r33088 | obsolete, | ||
r33249 | obsutil, | |||
Gregory Szorc
|
r27482 | pathutil, | ||
phases, | ||||
Martin von Zweigbergk
|
r39262 | policy, | ||
Pulkit Goyal
|
r30305 | pycompat, | ||
Yuya Nishihara
|
r31024 | revsetlang, | ||
Gregory Szorc
|
r27482 | similar, | ||
Boris Feld
|
r39933 | smartset, | ||
Matt Mackall
|
r34457 | url, | ||
Gregory Szorc
|
r27482 | util, | ||
Mark Thomas
|
r34544 | vfs, | ||
Gregory Szorc
|
r27482 | ) | ||
Kevin Bullock
|
r18690 | |||
Yuya Nishihara
|
r37102 | from .utils import ( | ||
Augie Fackler
|
r44517 | hashutil, | ||
Yuya Nishihara
|
r37138 | procutil, | ||
Yuya Nishihara
|
r37102 | stringutil, | ||
) | ||||
Jun Wu
|
r34646 | if pycompat.iswindows: | ||
Gregory Szorc
|
r27482 | from . import scmwindows as scmplatform | ||
Kevin Bullock
|
r18690 | else: | ||
Gregory Szorc
|
r27482 | from . import scmposix as scmplatform | ||
Kevin Bullock
|
r18690 | |||
Augie Fackler
|
r43906 | parsers = policy.importmod('parsers') | ||
Georges Racinet
|
r44465 | rustrevlog = policy.importrust('revlog') | ||
Martin von Zweigbergk
|
r39262 | |||
Yuya Nishihara
|
r30314 | termsize = scmplatform.termsize | ||
Adrian Buehlmann
|
r13962 | |||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r44053 | @attr.s(slots=True, repr=False) | ||
class status(object): | ||||
'''Struct with a list of files per status. | ||||
The 'deleted', 'unknown' and 'ignored' properties are only | ||||
relevant to the working copy. | ||||
Martin von Zweigbergk
|
r22913 | ''' | ||
Yuya Nishihara
|
r44214 | modified = attr.ib(default=attr.Factory(list)) | ||
added = attr.ib(default=attr.Factory(list)) | ||||
removed = attr.ib(default=attr.Factory(list)) | ||||
deleted = attr.ib(default=attr.Factory(list)) | ||||
unknown = attr.ib(default=attr.Factory(list)) | ||||
ignored = attr.ib(default=attr.Factory(list)) | ||||
clean = attr.ib(default=attr.Factory(list)) | ||||
Martin von Zweigbergk
|
r22913 | |||
Augie Fackler
|
r44053 | def __iter__(self): | ||
yield self.modified | ||||
yield self.added | ||||
yield self.removed | ||||
yield self.deleted | ||||
yield self.unknown | ||||
yield self.ignored | ||||
yield self.clean | ||||
Martin von Zweigbergk
|
r22913 | |||
Augie Fackler
|
r44053 | def __repr__(self): | ||
Augie Fackler
|
r43346 | return ( | ||
r'<status modified=%s, added=%s, removed=%s, deleted=%s, ' | ||||
r'unknown=%s, ignored=%s, clean=%s>' | ||||
) % tuple(pycompat.sysstr(stringutil.pprint(v)) for v in self) | ||||
Martin von Zweigbergk
|
r22913 | |||
Augie Fackler
|
r20392 | def itersubrepos(ctx1, ctx2): | ||
"""find subrepos in ctx1 or ctx2""" | ||||
# Create a (subpath, ctx) mapping where we prefer subpaths from | ||||
# ctx1. The subpaths from ctx2 are important when the .hgsub file | ||||
# has been modified (in ctx2) but not yet committed (in ctx1). | ||||
subpaths = dict.fromkeys(ctx2.substate, ctx2) | ||||
subpaths.update(dict.fromkeys(ctx1.substate, ctx1)) | ||||
Matt Harbison
|
r25418 | |||
missing = set() | ||||
for subpath in ctx2.substate: | ||||
if subpath not in ctx1.substate: | ||||
del subpaths[subpath] | ||||
missing.add(subpath) | ||||
Gregory Szorc
|
r43376 | for subpath, ctx in sorted(pycompat.iteritems(subpaths)): | ||
Augie Fackler
|
r20392 | yield subpath, ctx.sub(subpath) | ||
Matt Harbison
|
r25418 | # Yield an empty subrepo based on ctx1 for anything only in ctx2. That way, | ||
# status and diff will have an accurate result when it does | ||||
# 'sub.{status|diff}(rev2)'. Otherwise, the ctx2 subrepo is compared | ||||
# against itself. | ||||
for subpath in missing: | ||||
yield subpath, ctx2.nullsub(subpath, ctx1) | ||||
Augie Fackler
|
r43346 | |||
Patrick Mezard
|
r17248 | def nochangesfound(ui, repo, excluded=None): | ||
'''Report no changes for push/pull, excluded is None or a list of | ||||
nodes excluded from the push/pull. | ||||
''' | ||||
secretlist = [] | ||||
if excluded: | ||||
for n in excluded: | ||||
ctx = repo[n] | ||||
if ctx.phase() >= phases.secret and not ctx.extinct(): | ||||
secretlist.append(n) | ||||
Matt Mackall
|
r15993 | if secretlist: | ||
Augie Fackler
|
r43346 | ui.status( | ||
Augie Fackler
|
r43347 | _(b"no changes found (ignored %d secret changesets)\n") | ||
Augie Fackler
|
r43346 | % len(secretlist) | ||
) | ||||
Matt Mackall
|
r15993 | else: | ||
Augie Fackler
|
r43347 | ui.status(_(b"no changes found\n")) | ||
Matt Mackall
|
r15993 | |||
Augie Fackler
|
r43346 | |||
Jun Wu
|
r30520 | def callcatch(ui, func): | ||
"""call func() with global exception handling | ||||
return func() if no exception happens. otherwise do some error handling | ||||
and return an exit code accordingly. does not handle all exceptions. | ||||
""" | ||||
try: | ||||
Yuya Nishihara
|
r32041 | try: | ||
return func() | ||||
Augie Fackler
|
r43346 | except: # re-raises | ||
Yuya Nishihara
|
r32041 | ui.traceback() | ||
raise | ||||
Jun Wu
|
r30520 | # Global exception handling, alphabetically | ||
# Mercurial-specific first, followed by built-in and library exceptions | ||||
except error.LockHeld as inst: | ||||
if inst.errno == errno.ETIMEDOUT: | ||||
Augie Fackler
|
r43347 | reason = _(b'timed out waiting for lock held by %r') % ( | ||
Augie Fackler
|
r43346 | pycompat.bytestr(inst.locker) | ||
) | ||||
Jun Wu
|
r30520 | else: | ||
Augie Fackler
|
r43347 | reason = _(b'lock held by %r') % inst.locker | ||
Augie Fackler
|
r43346 | ui.error( | ||
Augie Fackler
|
r43347 | _(b"abort: %s: %s\n") | ||
Augie Fackler
|
r43346 | % (inst.desc or stringutil.forcebytestr(inst.filename), reason) | ||
) | ||||
FUJIWARA Katsunori
|
r32089 | if not inst.locker: | ||
Augie Fackler
|
r43347 | ui.error(_(b"(lock might be very busy)\n")) | ||
Jun Wu
|
r30520 | except error.LockUnavailable as inst: | ||
Augie Fackler
|
r43346 | ui.error( | ||
Augie Fackler
|
r43347 | _(b"abort: could not lock %s: %s\n") | ||
Augie Fackler
|
r43346 | % ( | ||
inst.desc or stringutil.forcebytestr(inst.filename), | ||||
encoding.strtolocal(inst.strerror), | ||||
) | ||||
) | ||||
Jun Wu
|
r30520 | except error.OutOfBandError as inst: | ||
if inst.args: | ||||
Augie Fackler
|
r43347 | msg = _(b"abort: remote error:\n") | ||
Jun Wu
|
r30520 | else: | ||
Augie Fackler
|
r43347 | msg = _(b"abort: remote error\n") | ||
Rodrigo Damazio Bovendorp
|
r38791 | ui.error(msg) | ||
Jun Wu
|
r30520 | if inst.args: | ||
Augie Fackler
|
r43347 | ui.error(b''.join(inst.args)) | ||
Jun Wu
|
r30520 | if inst.hint: | ||
Augie Fackler
|
r43347 | ui.error(b'(%s)\n' % inst.hint) | ||
Jun Wu
|
r30520 | except error.RepoError as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s!\n") % inst) | ||
Jun Wu
|
r30520 | if inst.hint: | ||
Augie Fackler
|
r43347 | ui.error(_(b"(%s)\n") % inst.hint) | ||
Jun Wu
|
r30520 | except error.ResponseError as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s") % inst.args[0]) | ||
Augie Fackler
|
r36679 | msg = inst.args[1] | ||
if isinstance(msg, type(u'')): | ||||
msg = pycompat.sysbytes(msg) | ||||
Augie Fackler
|
r36713 | if not isinstance(msg, bytes): | ||
Augie Fackler
|
r43347 | ui.error(b" %r\n" % (msg,)) | ||
Augie Fackler
|
r36713 | elif not msg: | ||
Augie Fackler
|
r43347 | ui.error(_(b" empty string\n")) | ||
Jun Wu
|
r30520 | else: | ||
Augie Fackler
|
r43347 | ui.error(b"\n%r\n" % pycompat.bytestr(stringutil.ellipsis(msg))) | ||
Jun Wu
|
r30520 | except error.CensoredNodeError as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: file censored %s!\n") % inst) | ||
Gregory Szorc
|
r39813 | except error.StorageError as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s!\n") % inst) | ||
Matt Harbison
|
r40694 | if inst.hint: | ||
Augie Fackler
|
r43347 | ui.error(_(b"(%s)\n") % inst.hint) | ||
Jun Wu
|
r30520 | except error.InterventionRequired as inst: | ||
Augie Fackler
|
r43347 | ui.error(b"%s\n" % inst) | ||
Jun Wu
|
r30520 | if inst.hint: | ||
Augie Fackler
|
r43347 | ui.error(_(b"(%s)\n") % inst.hint) | ||
Jun Wu
|
r30520 | return 1 | ||
Yuya Nishihara
|
r32657 | except error.WdirUnsupported: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: working directory revision cannot be specified\n")) | ||
Jun Wu
|
r30520 | except error.Abort as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s\n") % inst) | ||
Jun Wu
|
r30520 | if inst.hint: | ||
Augie Fackler
|
r43347 | ui.error(_(b"(%s)\n") % inst.hint) | ||
Jun Wu
|
r30520 | except ImportError as inst: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s!\n") % stringutil.forcebytestr(inst)) | ||
Yuya Nishihara
|
r37102 | m = stringutil.forcebytestr(inst).split()[-1] | ||
Augie Fackler
|
r43347 | if m in b"mpatch bdiff".split(): | ||
ui.error(_(b"(did you forget to compile extensions?)\n")) | ||||
elif m in b"zlib".split(): | ||||
ui.error(_(b"(is your Python install correct?)\n")) | ||||
Yuya Nishihara
|
r41466 | except (IOError, OSError) as inst: | ||
Augie Fackler
|
r43347 | if util.safehasattr(inst, b"code"): # HTTPError | ||
ui.error(_(b"abort: %s\n") % stringutil.forcebytestr(inst)) | ||||
elif util.safehasattr(inst, b"reason"): # URLError or SSLError | ||||
Augie Fackler
|
r43346 | try: # usually it is in the form (errno, strerror) | ||
Jun Wu
|
r30520 | reason = inst.reason.args[1] | ||
except (AttributeError, IndexError): | ||||
# it might be anything, for example a string | ||||
reason = inst.reason | ||||
Pulkit Goyal
|
r38332 | if isinstance(reason, pycompat.unicode): | ||
Jun Wu
|
r30520 | # SSLError of Python 2.7.9 contains a unicode | ||
Pulkit Goyal
|
r32152 | reason = encoding.unitolocal(reason) | ||
Denis Laxalde
|
r44389 | ui.error(_(b"abort: error: %s\n") % stringutil.forcebytestr(reason)) | ||
Augie Fackler
|
r43346 | elif ( | ||
Augie Fackler
|
r43347 | util.safehasattr(inst, b"args") | ||
Augie Fackler
|
r43346 | and inst.args | ||
and inst.args[0] == errno.EPIPE | ||||
): | ||||
Jun Wu
|
r30520 | pass | ||
Augie Fackler
|
r43346 | elif getattr(inst, "strerror", None): # common IOError or OSError | ||
Yuya Nishihara
|
r41465 | if getattr(inst, "filename", None) is not None: | ||
Augie Fackler
|
r43346 | ui.error( | ||
Augie Fackler
|
r43347 | _(b"abort: %s: '%s'\n") | ||
Augie Fackler
|
r43346 | % ( | ||
encoding.strtolocal(inst.strerror), | ||||
stringutil.forcebytestr(inst.filename), | ||||
) | ||||
) | ||||
Jun Wu
|
r30520 | else: | ||
Augie Fackler
|
r43347 | ui.error(_(b"abort: %s\n") % encoding.strtolocal(inst.strerror)) | ||
Augie Fackler
|
r43346 | else: # suspicious IOError | ||
Jun Wu
|
r30520 | raise | ||
except MemoryError: | ||||
Augie Fackler
|
r43347 | ui.error(_(b"abort: out of memory\n")) | ||
Jun Wu
|
r30520 | except SystemExit as inst: | ||
# Commands shouldn't sys.exit directly, but give a return code. | ||||
# Just in case catch this and and pass exit code to caller. | ||||
return inst.code | ||||
return -1 | ||||
Augie Fackler
|
r43346 | |||
Kevin Bullock
|
r17821 | def checknewlabel(repo, lbl, kind): | ||
Durham Goode
|
r19070 | # Do not use the "kind" parameter in ui output. | ||
# It makes strings difficult to translate. | ||||
Augie Fackler
|
r43347 | if lbl in [b'tip', b'.', b'null']: | ||
raise error.Abort(_(b"the name '%s' is reserved") % lbl) | ||||
for c in (b':', b'\0', b'\n', b'\r'): | ||||
Kevin Bullock
|
r17821 | if c in lbl: | ||
Augie Fackler
|
r36587 | raise error.Abort( | ||
Augie Fackler
|
r43347 | _(b"%r cannot be used in a name") % pycompat.bytestr(c) | ||
Augie Fackler
|
r43346 | ) | ||
Durham Goode
|
r18566 | try: | ||
int(lbl) | ||||
Augie Fackler
|
r43347 | raise error.Abort(_(b"cannot use an integer as a name")) | ||
Durham Goode
|
r18566 | except ValueError: | ||
pass | ||||
Boris Feld
|
r36162 | if lbl.strip() != lbl: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b"leading or trailing whitespace in name %r") % lbl) | ||
Kevin Bullock
|
r17817 | |||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13974 | def checkfilename(f): | ||
'''Check that the filename f is an acceptable filename for a tracked file''' | ||||
Augie Fackler
|
r43347 | if b'\r' in f or b'\n' in f: | ||
Augie Fackler
|
r43346 | raise error.Abort( | ||
Augie Fackler
|
r43347 | _(b"'\\n' and '\\r' disallowed in filenames: %r") | ||
Augie Fackler
|
r43346 | % pycompat.bytestr(f) | ||
) | ||||
Adrian Buehlmann
|
r13974 | |||
Adrian Buehlmann
|
r13962 | def checkportable(ui, f): | ||
'''Check if filename f is portable and warn or abort depending on config''' | ||||
Adrian Buehlmann
|
r13974 | checkfilename(f) | ||
Adrian Buehlmann
|
r14138 | abort, warn = checkportabilityalert(ui) | ||
if abort or warn: | ||||
Adrian Buehlmann
|
r13962 | msg = util.checkwinfilename(f) | ||
if msg: | ||||
Augie Fackler
|
r43347 | msg = b"%s: %s" % (msg, procutil.shellquote(f)) | ||
Adrian Buehlmann
|
r14138 | if abort: | ||
Pierre-Yves David
|
r26587 | raise error.Abort(msg) | ||
Augie Fackler
|
r43347 | ui.warn(_(b"warning: %s\n") % msg) | ||
Kevin Gessner
|
r14068 | |||
Augie Fackler
|
r43346 | |||
Kevin Gessner
|
r14067 | def checkportabilityalert(ui): | ||
'''check if the user's config requests nothing, a warning, or abort for | ||||
non-portable filenames''' | ||||
Augie Fackler
|
r43347 | val = ui.config(b'ui', b'portablefilenames') | ||
Kevin Gessner
|
r14067 | lval = val.lower() | ||
Yuya Nishihara
|
r37102 | bval = stringutil.parsebool(val) | ||
Augie Fackler
|
r43347 | abort = pycompat.iswindows or lval == b'abort' | ||
warn = bval or lval == b'warn' | ||||
if bval is None and not (warn or abort or lval == b'ignore'): | ||||
Adrian Buehlmann
|
r13962 | raise error.ConfigError( | ||
Augie Fackler
|
r43347 | _(b"ui.portablefilenames value is invalid ('%s')") % val | ||
Augie Fackler
|
r43346 | ) | ||
Kevin Gessner
|
r14067 | return abort, warn | ||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14138 | class casecollisionauditor(object): | ||
Joshua Redstone
|
r17201 | def __init__(self, ui, abort, dirstate): | ||
Adrian Buehlmann
|
r14138 | self._ui = ui | ||
self._abort = abort | ||||
Augie Fackler
|
r43347 | allfiles = b'\0'.join(dirstate) | ||
self._loweredfiles = set(encoding.lower(allfiles).split(b'\0')) | ||||
Joshua Redstone
|
r17201 | self._dirstate = dirstate | ||
# The purpose of _newfiles is so that we don't complain about | ||||
# case collisions if someone were to call this object with the | ||||
# same filename twice. | ||||
self._newfiles = set() | ||||
Kevin Gessner
|
r14067 | |||
Adrian Buehlmann
|
r14138 | def __call__(self, f): | ||
FUJIWARA Katsunori
|
r20006 | if f in self._newfiles: | ||
return | ||||
FUJIWARA Katsunori
|
r14980 | fl = encoding.lower(f) | ||
FUJIWARA Katsunori
|
r20006 | if fl in self._loweredfiles and f not in self._dirstate: | ||
Augie Fackler
|
r43347 | msg = _(b'possible case-folding collision for %s') % f | ||
Adrian Buehlmann
|
r14138 | if self._abort: | ||
Pierre-Yves David
|
r26587 | raise error.Abort(msg) | ||
Augie Fackler
|
r43347 | self._ui.warn(_(b"warning: %s\n") % msg) | ||
Joshua Redstone
|
r17201 | self._loweredfiles.add(fl) | ||
self._newfiles.add(f) | ||||
Adrian Buehlmann
|
r13970 | |||
Augie Fackler
|
r43346 | |||
Gregory Szorc
|
r24723 | def filteredhash(repo, maxrev): | ||
"""build hash of filtered revisions in the current repoview. | ||||
Multiple caches perform up-to-date validation by checking that the | ||||
tiprev and tipnode stored in the cache file match the current repository. | ||||
However, this is not sufficient for validating repoviews because the set | ||||
of revisions in the view may change without the repository tiprev and | ||||
tipnode changing. | ||||
This function hashes all the revs filtered from the view and returns | ||||
that SHA-1 digest. | ||||
""" | ||||
cl = repo.changelog | ||||
if not cl.filteredrevs: | ||||
return None | ||||
key = None | ||||
revs = sorted(r for r in cl.filteredrevs if r <= maxrev) | ||||
if revs: | ||||
Augie Fackler
|
r44517 | s = hashutil.sha1() | ||
Gregory Szorc
|
r24723 | for rev in revs: | ||
Augie Fackler
|
r43347 | s.update(b'%d;' % rev) | ||
Gregory Szorc
|
r24723 | key = s.digest() | ||
return key | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13975 | def walkrepos(path, followsym=False, seen_dirs=None, recurse=False): | ||
Mads Kiilerich
|
r17104 | '''yield every hg repository under path, always recursively. | ||
The recurse flag will only control recursion into repo working dirs''' | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13975 | def errhandler(err): | ||
if err.filename == path: | ||||
raise err | ||||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r14961 | samestat = getattr(os.path, 'samestat', None) | ||
if followsym and samestat is not None: | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r14227 | def adddir(dirlst, dirname): | ||
Adrian Buehlmann
|
r13975 | dirstat = os.stat(dirname) | ||
Martin von Zweigbergk
|
r36356 | match = any(samestat(dirstat, lstdirstat) for lstdirstat in dirlst) | ||
Adrian Buehlmann
|
r13975 | if not match: | ||
dirlst.append(dirstat) | ||||
return not match | ||||
Augie Fackler
|
r43346 | |||
Adrian Buehlmann
|
r13975 | else: | ||
followsym = False | ||||
if (seen_dirs is None) and followsym: | ||||
seen_dirs = [] | ||||
Adrian Buehlmann
|
r14227 | adddir(seen_dirs, path) | ||
Adrian Buehlmann
|
r13975 | for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler): | ||
dirs.sort() | ||||
Augie Fackler
|
r43347 | if b'.hg' in dirs: | ||
Augie Fackler
|
r43346 | yield root # found a repository | ||
Augie Fackler
|
r43347 | qroot = os.path.join(root, b'.hg', b'patches') | ||
if os.path.isdir(os.path.join(qroot, b'.hg')): | ||||
Augie Fackler
|
r43346 | yield qroot # we have a patch queue repo here | ||
Adrian Buehlmann
|
r13975 | if recurse: | ||
# avoid recursing inside the .hg directory | ||||
Augie Fackler
|
r43347 | dirs.remove(b'.hg') | ||
Adrian Buehlmann
|
r13975 | else: | ||
Augie Fackler
|
r43346 | dirs[:] = [] # don't descend further | ||
Adrian Buehlmann
|
r13975 | elif followsym: | ||
newdirs = [] | ||||
for d in dirs: | ||||
fname = os.path.join(root, d) | ||||
Adrian Buehlmann
|
r14227 | if adddir(seen_dirs, fname): | ||
Adrian Buehlmann
|
r13975 | if os.path.islink(fname): | ||
for hgname in walkrepos(fname, True, seen_dirs): | ||||
yield hgname | ||||
else: | ||||
newdirs.append(d) | ||||
dirs[:] = newdirs | ||||
Adrian Buehlmann
|
r13984 | |||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r32656 | def binnode(ctx): | ||
"""Return binary node id for a given basectx""" | ||||
node = ctx.node() | ||||
if node is None: | ||||
return wdirid | ||||
return node | ||||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r32654 | def intrev(ctx): | ||
"""Return integer for a given basectx that can be used in comparison or | ||||
Yuya Nishihara
|
r24582 | arithmetic operation""" | ||
Yuya Nishihara
|
r32654 | rev = ctx.rev() | ||
Yuya Nishihara
|
r24582 | if rev is None: | ||
Yuya Nishihara
|
r25739 | return wdirrev | ||
Yuya Nishihara
|
r24582 | return rev | ||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r34328 | def formatchangeid(ctx): | ||
"""Format changectx as '{rev}:{node|formatnode}', which is the default | ||||
Yuya Nishihara
|
r35906 | template provided by logcmdutil.changesettemplater""" | ||
Yuya Nishihara
|
r34328 | repo = ctx.repo() | ||
return formatrevnode(repo.ui, intrev(ctx), binnode(ctx)) | ||||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r34328 | def formatrevnode(ui, rev, node): | ||
"""Format given revision and node depending on the current verbosity""" | ||||
if ui.debugflag: | ||||
hexfunc = hex | ||||
else: | ||||
hexfunc = short | ||||
Augie Fackler
|
r43347 | return b'%d:%s' % (rev, hexfunc(node)) | ||
Yuya Nishihara
|
r34328 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r37696 | def resolvehexnodeidprefix(repo, prefix): | ||
Augie Fackler
|
r43347 | if prefix.startswith(b'x') and repo.ui.configbool( | ||
b'experimental', b'revisions.prefixhexnode' | ||||
Augie Fackler
|
r43346 | ): | ||
Martin von Zweigbergk
|
r38891 | prefix = prefix[1:] | ||
Martin von Zweigbergk
|
r38878 | try: | ||
# Uses unfiltered repo because it's faster when prefix is ambiguous/ | ||||
# This matches the shortesthexnodeidprefix() function below. | ||||
node = repo.unfiltered().changelog._partialmatch(prefix) | ||||
except error.AmbiguousPrefixLookupError: | ||||
Augie Fackler
|
r43347 | revset = repo.ui.config( | ||
b'experimental', b'revisions.disambiguatewithin' | ||||
) | ||||
Martin von Zweigbergk
|
r38878 | if revset: | ||
# Clear config to avoid infinite recursion | ||||
Augie Fackler
|
r43346 | configoverrides = { | ||
Augie Fackler
|
r43347 | (b'experimental', b'revisions.disambiguatewithin'): None | ||
Augie Fackler
|
r43346 | } | ||
Martin von Zweigbergk
|
r38878 | with repo.ui.configoverride(configoverrides): | ||
revs = repo.anyrevs([revset], user=True) | ||||
matches = [] | ||||
for rev in revs: | ||||
node = repo.changelog.node(rev) | ||||
if hex(node).startswith(prefix): | ||||
matches.append(node) | ||||
if len(matches) == 1: | ||||
return matches[0] | ||||
raise | ||||
Martin von Zweigbergk
|
r37522 | if node is None: | ||
return | ||||
repo.changelog.rev(node) # make sure node isn't filtered | ||||
return node | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r38890 | def mayberevnum(repo, prefix): | ||
"""Checks if the given prefix may be mistaken for a revision number""" | ||||
try: | ||||
i = int(prefix) | ||||
# if we are a pure int, then starting with zero will not be | ||||
# confused as a rev; or, obviously, if the int is larger | ||||
Kyle Lippincott
|
r40377 | # than the value of the tip rev. We still need to disambiguate if | ||
# prefix == '0', since that *is* a valid revnum. | ||||
if (prefix != b'0' and prefix[0:1] == b'0') or i >= len(repo): | ||||
Martin von Zweigbergk
|
r38890 | return False | ||
return True | ||||
except ValueError: | ||||
return False | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r38889 | def shortesthexnodeidprefix(repo, node, minlength=1, cache=None): | ||
"""Find the shortest unambiguous prefix that matches hexnode. | ||||
If "cache" is not None, it must be a dictionary that can be used for | ||||
caching between calls to this method. | ||||
""" | ||||
Martin von Zweigbergk
|
r37726 | # _partialmatch() of filtered changelog could take O(len(repo)) time, | ||
# which would be unacceptably slow. so we look for hash collision in | ||||
# unfiltered space, which means some hashes may be slightly longer. | ||||
Martin von Zweigbergk
|
r37990 | |||
Augie Fackler
|
r43346 | minlength = max(minlength, 1) | ||
Martin von Zweigbergk
|
r40439 | |||
Martin von Zweigbergk
|
r37990 | def disambiguate(prefix): | ||
"""Disambiguate against revnums.""" | ||||
Augie Fackler
|
r43347 | if repo.ui.configbool(b'experimental', b'revisions.prefixhexnode'): | ||
Martin von Zweigbergk
|
r38892 | if mayberevnum(repo, prefix): | ||
Augie Fackler
|
r43347 | return b'x' + prefix | ||
Martin von Zweigbergk
|
r38892 | else: | ||
return prefix | ||||
Martin von Zweigbergk
|
r37990 | hexnode = hex(node) | ||
Martin von Zweigbergk
|
r38000 | for length in range(len(prefix), len(hexnode) + 1): | ||
Martin von Zweigbergk
|
r37990 | prefix = hexnode[:length] | ||
Martin von Zweigbergk
|
r38890 | if not mayberevnum(repo, prefix): | ||
Martin von Zweigbergk
|
r37990 | return prefix | ||
Martin von Zweigbergk
|
r38890 | cl = repo.unfiltered().changelog | ||
Augie Fackler
|
r43347 | revset = repo.ui.config(b'experimental', b'revisions.disambiguatewithin') | ||
Martin von Zweigbergk
|
r38879 | if revset: | ||
Martin von Zweigbergk
|
r38889 | revs = None | ||
if cache is not None: | ||||
Augie Fackler
|
r43347 | revs = cache.get(b'disambiguationrevset') | ||
Martin von Zweigbergk
|
r38889 | if revs is None: | ||
revs = repo.anyrevs([revset], user=True) | ||||
if cache is not None: | ||||
Augie Fackler
|
r43347 | cache[b'disambiguationrevset'] = revs | ||
Martin von Zweigbergk
|
r38879 | if cl.rev(node) in revs: | ||
hexnode = hex(node) | ||||
Martin von Zweigbergk
|
r39262 | nodetree = None | ||
if cache is not None: | ||||
Augie Fackler
|
r43347 | nodetree = cache.get(b'disambiguationnodetree') | ||
Martin von Zweigbergk
|
r39262 | if not nodetree: | ||
r44363 | if util.safehasattr(parsers, 'nodetree'): | |||
# The CExt is the only implementation to provide a nodetree | ||||
# class so far. | ||||
Georges Racinet
|
r44465 | index = cl.index | ||
if util.safehasattr(index, 'get_cindex'): | ||||
# the rust wrapped need to give access to its internal index | ||||
index = index.get_cindex() | ||||
nodetree = parsers.nodetree(index, len(revs)) | ||||
Martin von Zweigbergk
|
r39262 | for r in revs: | ||
nodetree.insert(r) | ||||
if cache is not None: | ||||
Augie Fackler
|
r43347 | cache[b'disambiguationnodetree'] = nodetree | ||
Martin von Zweigbergk
|
r39262 | if nodetree is not None: | ||
length = max(nodetree.shortest(node), minlength) | ||||
prefix = hexnode[:length] | ||||
return disambiguate(prefix) | ||||
Martin von Zweigbergk
|
r38879 | for length in range(minlength, len(hexnode) + 1): | ||
matches = [] | ||||
prefix = hexnode[:length] | ||||
for rev in revs: | ||||
otherhexnode = repo[rev].hex() | ||||
if prefix == otherhexnode[:length]: | ||||
matches.append(otherhexnode) | ||||
if len(matches) == 1: | ||||
return disambiguate(prefix) | ||||
Martin von Zweigbergk
|
r37882 | try: | ||
Martin von Zweigbergk
|
r37990 | return disambiguate(cl.shortest(node, minlength)) | ||
Martin von Zweigbergk
|
r37882 | except error.LookupError: | ||
raise error.RepoLookupError() | ||||
Martin von Zweigbergk
|
r37698 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r37368 | def isrevsymbol(repo, symbol): | ||
Martin von Zweigbergk
|
r37695 | """Checks if a symbol exists in the repo. | ||
Martin von Zweigbergk
|
r38877 | See revsymbol() for details. Raises error.AmbiguousPrefixLookupError if the | ||
symbol is an ambiguous nodeid prefix. | ||||
Martin von Zweigbergk
|
r37695 | """ | ||
Martin von Zweigbergk
|
r37368 | try: | ||
revsymbol(repo, symbol) | ||||
return True | ||||
except error.RepoLookupError: | ||||
return False | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r37289 | def revsymbol(repo, symbol): | ||
"""Returns a context given a single revision symbol (as string). | ||||
This is similar to revsingle(), but accepts only a single revision symbol, | ||||
i.e. things like ".", "tip", "1234", "deadbeef", "my-bookmark" work, but | ||||
not "max(public())". | ||||
""" | ||||
if not isinstance(symbol, bytes): | ||||
Augie Fackler
|
r43346 | msg = ( | ||
Augie Fackler
|
r43347 | b"symbol (%s of type %s) was not a string, did you mean " | ||
b"repo[symbol]?" % (symbol, type(symbol)) | ||||
Augie Fackler
|
r43346 | ) | ||
Martin von Zweigbergk
|
r37289 | raise error.ProgrammingError(msg) | ||
Martin von Zweigbergk
|
r37403 | try: | ||
Augie Fackler
|
r43347 | if symbol in (b'.', b'tip', b'null'): | ||
Martin von Zweigbergk
|
r37545 | return repo[symbol] | ||
try: | ||||
r = int(symbol) | ||||
Augie Fackler
|
r43347 | if b'%d' % r != symbol: | ||
Martin von Zweigbergk
|
r37545 | raise ValueError | ||
l = len(repo.changelog) | ||||
if r < 0: | ||||
r += l | ||||
if r < 0 or r >= l and r != wdirrev: | ||||
raise ValueError | ||||
return repo[r] | ||||
except error.FilteredIndexError: | ||||
raise | ||||
except (ValueError, OverflowError, IndexError): | ||||
pass | ||||
Martin von Zweigbergk
|
r37546 | if len(symbol) == 40: | ||
try: | ||||
node = bin(symbol) | ||||
rev = repo.changelog.rev(node) | ||||
return repo[rev] | ||||
except error.FilteredLookupError: | ||||
raise | ||||
except (TypeError, LookupError): | ||||
pass | ||||
Martin von Zweigbergk
|
r37547 | # look up bookmarks through the name interface | ||
try: | ||||
node = repo.names.singlenode(repo, symbol) | ||||
rev = repo.changelog.rev(node) | ||||
return repo[rev] | ||||
except KeyError: | ||||
pass | ||||
Martin von Zweigbergk
|
r37697 | node = resolvehexnodeidprefix(repo, symbol) | ||
Martin von Zweigbergk
|
r37548 | if node is not None: | ||
rev = repo.changelog.rev(node) | ||||
return repo[rev] | ||||
Augie Fackler
|
r43347 | raise error.RepoLookupError(_(b"unknown revision '%s'") % symbol) | ||
Martin von Zweigbergk
|
r37545 | |||
Martin von Zweigbergk
|
r37546 | except error.WdirUnsupported: | ||
return repo[None] | ||||
Augie Fackler
|
r43346 | except ( | ||
error.FilteredIndexError, | ||||
error.FilteredLookupError, | ||||
error.FilteredRepoLookupError, | ||||
): | ||||
Martin von Zweigbergk
|
r37403 | raise _filterederror(repo, symbol) | ||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r37403 | def _filterederror(repo, changeid): | ||
"""build an exception to be raised about a filtered changeid | ||||
This is extracted in a function to help extensions (eg: evolve) to | ||||
experiment with various message variants.""" | ||||
Augie Fackler
|
r43347 | if repo.filtername.startswith(b'visible'): | ||
Martin von Zweigbergk
|
r37403 | |||
# Check if the changeset is obsolete | ||||
unfilteredrepo = repo.unfiltered() | ||||
ctx = revsymbol(unfilteredrepo, changeid) | ||||
# If the changeset is obsolete, enrich the message with the reason | ||||
# that made this changeset not visible | ||||
if ctx.obsolete(): | ||||
msg = obsutil._getfilteredreason(repo, changeid, ctx) | ||||
else: | ||||
Augie Fackler
|
r43347 | msg = _(b"hidden revision '%s'") % changeid | ||
Martin von Zweigbergk
|
r37403 | |||
Augie Fackler
|
r43347 | hint = _(b'use --hidden to access hidden revisions') | ||
Martin von Zweigbergk
|
r37403 | |||
return error.FilteredRepoLookupError(msg, hint=hint) | ||||
Augie Fackler
|
r43347 | msg = _(b"filtered revision '%s' (not in '%s' subset)") | ||
Martin von Zweigbergk
|
r37403 | msg %= (changeid, repo.filtername) | ||
return error.FilteredRepoLookupError(msg) | ||||
Martin von Zweigbergk
|
r37289 | |||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r43347 | def revsingle(repo, revspec, default=b'.', localalias=None): | ||
Matt Mackall
|
r19509 | if not revspec and revspec != 0: | ||
Matt Mackall
|
r14319 | return repo[default] | ||
Jun Wu
|
r34007 | l = revrange(repo, [revspec], localalias=localalias) | ||
Pierre-Yves David
|
r22814 | if not l: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b'empty revision set')) | ||
Pierre-Yves David
|
r22815 | return repo[l.last()] | ||
Matt Mackall
|
r14319 | |||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r26020 | def _pairspec(revspec): | ||
Yuya Nishihara
|
r31024 | tree = revsetlang.parse(revspec) | ||
Augie Fackler
|
r43347 | return tree and tree[0] in ( | ||
b'range', | ||||
b'rangepre', | ||||
b'rangepost', | ||||
b'rangeall', | ||||
) | ||||
Yuya Nishihara
|
r26020 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r14319 | def revpair(repo, revs): | ||
if not revs: | ||||
Augie Fackler
|
r43347 | return repo[b'.'], repo[None] | ||
Matt Mackall
|
r14319 | |||
l = revrange(repo, revs) | ||||
Martin von Zweigbergk
|
r41415 | if not l: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b'empty revision range')) | ||
Martin von Zweigbergk
|
r41415 | |||
Martin von Zweigbergk
|
r41414 | first = l.first() | ||
second = l.last() | ||||
Pierre-Yves David
|
r20862 | |||
Augie Fackler
|
r43346 | if ( | ||
first == second | ||||
and len(revs) >= 2 | ||||
and not all(revrange(repo, [r]) for r in revs) | ||||
): | ||||
Augie Fackler
|
r43347 | raise error.Abort(_(b'empty revision on one side of range')) | ||
Matt Mackall
|
r14319 | |||
Yuya Nishihara
|
r26020 | # if top-level is range expression, the result must always be a pair | ||
if first == second and len(revs) == 1 and not _pairspec(revs[0]): | ||||
Martin von Zweigbergk
|
r37269 | return repo[first], repo[None] | ||
Matt Mackall
|
r14319 | |||
Martin von Zweigbergk
|
r37269 | return repo[first], repo[second] | ||
Matt Mackall
|
r14319 | |||
Augie Fackler
|
r43346 | |||
Jun Wu
|
r34007 | def revrange(repo, specs, localalias=None): | ||
Gregory Szorc
|
r29417 | """Execute 1 to many revsets and return the union. | ||
This is the preferred mechanism for executing revsets using user-specified | ||||
config options, such as revset aliases. | ||||
The revsets specified by ``specs`` will be executed via a chained ``OR`` | ||||
expression. If ``specs`` is empty, an empty result is returned. | ||||
``specs`` can contain integers, in which case they are assumed to be | ||||
revision numbers. | ||||
It is assumed the revsets are already formatted. If you have arguments | ||||
Yuya Nishihara
|
r31024 | that need to be expanded in the revset, call ``revsetlang.formatspec()`` | ||
Gregory Szorc
|
r29417 | and pass the result as an element of ``specs``. | ||
Specifying a single revset is allowed. | ||||
Returns a ``revset.abstractsmartset`` which is a list-like interface over | ||||
integer revisions. | ||||
""" | ||||
Yuya Nishihara
|
r25928 | allspecs = [] | ||
Gregory Szorc
|
r29417 | for spec in specs: | ||
Yuya Nishihara
|
r25904 | if isinstance(spec, int): | ||
Augie Fackler
|
r43347 | spec = revsetlang.formatspec(b'%d', spec) | ||
Yuya Nishihara
|
r25928 | allspecs.append(spec) | ||
Jun Wu
|
r34007 | return repo.anyrevs(allspecs, user=True, localalias=localalias) | ||
Matt Mackall
|
r14320 | |||
Augie Fackler
|
r43346 | |||
Yuya Nishihara
|
r26433 | def meaningfulparents(repo, ctx): | ||
"""Return list of meaningful (or all if debug) parentrevs for rev. | ||||
For merges (two non-nullrev revisions) both parents are meaningful. | ||||
Otherwise the first parent revision is considered meaningful if it | ||||
is not the preceding revision. | ||||
""" | ||||
parents = ctx.parents() | ||||
if len(parents) > 1: | ||||
return parents | ||||
if repo.ui.debugflag: | ||||
Martin von Zweigbergk
|
r39930 | return [parents[0], repo[nullrev]] | ||
Yuya Nishihara
|
r32654 | if parents[0].rev() >= intrev(ctx) - 1: | ||
Yuya Nishihara
|
r26433 | return [] | ||
return parents | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41716 | def getuipathfn(repo, legacyrelativevalue=False, forcerelativevalue=None): | ||
"""Return a function that produced paths for presenting to the user. | ||||
The returned function takes a repo-relative path and produces a path | ||||
that can be presented in the UI. | ||||
Depending on the value of ui.relative-paths, either a repo-relative or | ||||
cwd-relative path will be produced. | ||||
legacyrelativevalue is the value to use if ui.relative-paths=legacy | ||||
If forcerelativevalue is not None, then that value will be used regardless | ||||
of what ui.relative-paths is set to. | ||||
""" | ||||
if forcerelativevalue is not None: | ||||
relative = forcerelativevalue | ||||
else: | ||||
Augie Fackler
|
r43347 | config = repo.ui.config(b'ui', b'relative-paths') | ||
if config == b'legacy': | ||||
Martin von Zweigbergk
|
r41716 | relative = legacyrelativevalue | ||
else: | ||||
relative = stringutil.parsebool(config) | ||||
if relative is None: | ||||
raise error.ConfigError( | ||||
Augie Fackler
|
r43347 | _(b"ui.relative-paths is not a boolean ('%s')") % config | ||
Augie Fackler
|
r43346 | ) | ||
Martin von Zweigbergk
|
r41716 | |||
Martin von Zweigbergk
|
r41632 | if relative: | ||
cwd = repo.getcwd() | ||||
pathto = repo.pathto | ||||
return lambda f: pathto(f, cwd) | ||||
Augie Fackler
|
r43347 | elif repo.ui.configbool(b'ui', b'slash'): | ||
Martin von Zweigbergk
|
r41833 | return lambda f: f | ||
Martin von Zweigbergk
|
r41632 | else: | ||
Martin von Zweigbergk
|
r41833 | return util.localpath | ||
Martin von Zweigbergk
|
r41632 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41799 | def subdiruipathfn(subpath, uipathfn): | ||
'''Create a new uipathfn that treats the file as relative to subpath.''' | ||||
return lambda f: uipathfn(posixpath.join(subpath, f)) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41801 | def anypats(pats, opts): | ||
'''Checks if any patterns, including --include and --exclude were given. | ||||
Some commands (e.g. addremove) use this condition for deciding whether to | ||||
print absolute or relative paths. | ||||
''' | ||||
Augie Fackler
|
r43347 | return bool(pats or opts.get(b'include') or opts.get(b'exclude')) | ||
Martin von Zweigbergk
|
r41801 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r14320 | def expandpats(pats): | ||
Mads Kiilerich
|
r21111 | '''Expand bare globs when running on windows. | ||
On posix we assume it already has already been done by sh.''' | ||||
Matt Mackall
|
r14320 | if not util.expandglobs: | ||
return list(pats) | ||||
ret = [] | ||||
Mads Kiilerich
|
r21111 | for kindpat in pats: | ||
kind, pat = matchmod._patsplit(kindpat, None) | ||||
Matt Mackall
|
r14320 | if kind is None: | ||
try: | ||||
Mads Kiilerich
|
r21111 | globbed = glob.glob(pat) | ||
Matt Mackall
|
r14320 | except re.error: | ||
Mads Kiilerich
|
r21111 | globbed = [pat] | ||
Matt Mackall
|
r14320 | if globbed: | ||
ret.extend(globbed) | ||||
continue | ||||
Mads Kiilerich
|
r21111 | ret.append(kindpat) | ||
Matt Mackall
|
r14320 | return ret | ||
Augie Fackler
|
r43346 | |||
def matchandpats( | ||||
Augie Fackler
|
r43347 | ctx, pats=(), opts=None, globbed=False, default=b'relpath', badfn=None | ||
Augie Fackler
|
r43346 | ): | ||
Mads Kiilerich
|
r21111 | '''Return a matcher and the patterns that were used. | ||
Matt Harbison
|
r25467 | The matcher will warn about bad matches, unless an alternate badfn callback | ||
is provided.''' | ||||
Pierre-Yves David
|
r26326 | if opts is None: | ||
opts = {} | ||||
Augie Fackler
|
r43347 | if not globbed and default == b'relpath': | ||
Matt Mackall
|
r14320 | pats = expandpats(pats or []) | ||
Matt Mackall
|
r14670 | |||
Martin von Zweigbergk
|
r41814 | uipathfn = getuipathfn(ctx.repo(), legacyrelativevalue=True) | ||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r25467 | def bad(f, msg): | ||
Augie Fackler
|
r43347 | ctx.repo().ui.warn(b"%s: %s\n" % (uipathfn(f), msg)) | ||
Matt Harbison
|
r25466 | |||
Matt Harbison
|
r25467 | if badfn is None: | ||
badfn = bad | ||||
Augie Fackler
|
r43346 | m = ctx.match( | ||
pats, | ||||
Augie Fackler
|
r43347 | opts.get(b'include'), | ||
opts.get(b'exclude'), | ||||
Augie Fackler
|
r43346 | default, | ||
Augie Fackler
|
r43347 | listsubrepos=opts.get(b'subrepos'), | ||
Augie Fackler
|
r43346 | badfn=badfn, | ||
) | ||||
Matt Harbison
|
r25466 | |||
Martin von Zweigbergk
|
r24447 | if m.always(): | ||
pats = [] | ||||
Patrick Mezard
|
r16171 | return m, pats | ||
Augie Fackler
|
r43346 | |||
def match( | ||||
Augie Fackler
|
r43347 | ctx, pats=(), opts=None, globbed=False, default=b'relpath', badfn=None | ||
Augie Fackler
|
r43346 | ): | ||
Mads Kiilerich
|
r21111 | '''Return a matcher that will warn about bad matches.''' | ||
Matt Harbison
|
r25467 | return matchandpats(ctx, pats, opts, globbed, default, badfn=badfn)[0] | ||
Matt Mackall
|
r14320 | |||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r14320 | def matchall(repo): | ||
Mads Kiilerich
|
r21111 | '''Return a matcher that will efficiently match everything.''' | ||
Martin von Zweigbergk
|
r41825 | return matchmod.always() | ||
Matt Mackall
|
r14320 | |||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r25467 | def matchfiles(repo, files, badfn=None): | ||
Mads Kiilerich
|
r21111 | '''Return a matcher that will efficiently match exactly these files.''' | ||
Martin von Zweigbergk
|
r41825 | return matchmod.exact(files, badfn=badfn) | ||
Matt Mackall
|
r14320 | |||
Augie Fackler
|
r43346 | |||
Denis Laxalde
|
r34855 | def parsefollowlinespattern(repo, rev, pat, msg): | ||
"""Return a file name from `pat` pattern suitable for usage in followlines | ||||
logic. | ||||
""" | ||||
if not matchmod.patkind(pat): | ||||
return pathutil.canonpath(repo.root, repo.getcwd(), pat) | ||||
else: | ||||
ctx = repo[rev] | ||||
m = matchmod.match(repo.root, repo.getcwd(), [pat], ctx=ctx) | ||||
files = [f for f in ctx if m(f)] | ||||
if len(files) != 1: | ||||
raise error.ParseError(msg) | ||||
return files[0] | ||||
Augie Fackler
|
r43346 | |||
Boris Feld
|
r40783 | def getorigvfs(ui, repo): | ||
"""return a vfs suitable to save 'orig' file | ||||
return None if no special directory is configured""" | ||||
Augie Fackler
|
r43347 | origbackuppath = ui.config(b'ui', b'origbackuppath') | ||
Boris Feld
|
r40783 | if not origbackuppath: | ||
return None | ||||
return vfs.vfs(repo.wvfs.join(origbackuppath)) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41735 | def backuppath(ui, repo, filepath): | ||
'''customize where working copy backup files (.orig files) are created | ||||
Fetch user defined path from config file: [ui] origbackuppath = <path> | ||||
Fall back to default (filepath with .orig suffix) if not specified | ||||
filepath is repo-relative | ||||
Returns an absolute path | ||||
''' | ||||
origvfs = getorigvfs(ui, repo) | ||||
if origvfs is None: | ||||
Augie Fackler
|
r43347 | return repo.wjoin(filepath + b".orig") | ||
Martin von Zweigbergk
|
r41735 | |||
origbackupdir = origvfs.dirname(filepath) | ||||
if not origvfs.isdir(origbackupdir) or origvfs.islink(origbackupdir): | ||||
Augie Fackler
|
r43347 | ui.note(_(b'creating directory: %s\n') % origvfs.join(origbackupdir)) | ||
Martin von Zweigbergk
|
r41735 | |||
# Remove any files that conflict with the backup file's path | ||||
Martin von Zweigbergk
|
r44032 | for f in reversed(list(pathutil.finddirs(filepath))): | ||
Martin von Zweigbergk
|
r41735 | if origvfs.isfileorlink(f): | ||
Augie Fackler
|
r43347 | ui.note(_(b'removing conflicting file: %s\n') % origvfs.join(f)) | ||
Martin von Zweigbergk
|
r41735 | origvfs.unlink(f) | ||
break | ||||
origvfs.makedirs(origbackupdir) | ||||
if origvfs.isdir(filepath) and not origvfs.islink(filepath): | ||||
Augie Fackler
|
r43346 | ui.note( | ||
Augie Fackler
|
r43347 | _(b'removing conflicting directory: %s\n') % origvfs.join(filepath) | ||
Augie Fackler
|
r43346 | ) | ||
Martin von Zweigbergk
|
r41735 | origvfs.rmtree(filepath, forcibly=True) | ||
return origvfs.join(filepath) | ||||
Augie Fackler
|
r43346 | |||
Jun Wu
|
r33331 | class _containsnode(object): | ||
"""proxy __contains__(node) to container.__contains__ which accepts revs""" | ||||
def __init__(self, repo, revcontainer): | ||||
self._torev = repo.changelog.rev | ||||
self._revcontains = revcontainer.__contains__ | ||||
def __contains__(self, node): | ||||
return self._revcontains(self._torev(node)) | ||||
Augie Fackler
|
r43346 | |||
def cleanupnodes( | ||||
repo, | ||||
replacements, | ||||
operation, | ||||
moves=None, | ||||
metadata=None, | ||||
fixphase=False, | ||||
targetphase=None, | ||||
backup=True, | ||||
): | ||||
Jun Wu
|
r33088 | """do common cleanups when old nodes are replaced by new nodes | ||
That includes writing obsmarkers or stripping nodes, and moving bookmarks. | ||||
(we might also want to move working directory parent in the future) | ||||
Jun Wu
|
r34364 | By default, bookmark moves are calculated automatically from 'replacements', | ||
but 'moves' can be used to override that. Also, 'moves' may include | ||||
additional bookmark moves that should not have associated obsmarkers. | ||||
Martin von Zweigbergk
|
r34363 | replacements is {oldnode: [newnode]} or a iterable of nodes if they do not | ||
have replacements. operation is a string, like "rebase". | ||||
Pulkit Goyal
|
r34794 | |||
metadata is dictionary containing metadata to be stored in obsmarker if | ||||
obsolescence is enabled. | ||||
Jun Wu
|
r33088 | """ | ||
Martin von Zweigbergk
|
r38442 | assert fixphase or targetphase is None | ||
Jun Wu
|
r34364 | if not replacements and not moves: | ||
return | ||||
# translate mapping's other forms | ||||
Augie Fackler
|
r43347 | if not util.safehasattr(replacements, b'items'): | ||
Boris Feld
|
r39927 | replacements = {(n,): () for n in replacements} | ||
else: | ||||
# upgrading non tuple "source" to tuple ones for BC | ||||
repls = {} | ||||
for key, value in replacements.items(): | ||||
if not isinstance(key, tuple): | ||||
key = (key,) | ||||
repls[key] = value | ||||
replacements = repls | ||||
Jun Wu
|
r33088 | |||
Martin von Zweigbergk
|
r40890 | # Unfiltered repo is needed since nodes in replacements might be hidden. | ||
unfi = repo.unfiltered() | ||||
Martin von Zweigbergk
|
r34362 | # Calculate bookmark movements | ||
Jun Wu
|
r34364 | if moves is None: | ||
moves = {} | ||||
Martin von Zweigbergk
|
r40890 | for oldnodes, newnodes in replacements.items(): | ||
for oldnode in oldnodes: | ||||
if oldnode in moves: | ||||
continue | ||||
if len(newnodes) > 1: | ||||
# usually a split, take the one with biggest rev number | ||||
Augie Fackler
|
r43347 | newnode = next(unfi.set(b'max(%ln)', newnodes)).node() | ||
Martin von Zweigbergk
|
r40890 | elif len(newnodes) == 0: | ||
# move bookmark backwards | ||||
allreplaced = [] | ||||
for rep in replacements: | ||||
allreplaced.extend(rep) | ||||
Augie Fackler
|
r43346 | roots = list( | ||
Augie Fackler
|
r43347 | unfi.set(b'max((::%n) - %ln)', oldnode, allreplaced) | ||
Augie Fackler
|
r43346 | ) | ||
Martin von Zweigbergk
|
r40890 | if roots: | ||
newnode = roots[0].node() | ||||
else: | ||||
newnode = nullid | ||||
Boris Feld
|
r39927 | else: | ||
Martin von Zweigbergk
|
r40890 | newnode = newnodes[0] | ||
moves[oldnode] = newnode | ||||
Martin von Zweigbergk
|
r34362 | |||
Martin von Zweigbergk
|
r38442 | allnewnodes = [n for ns in replacements.values() for n in ns] | ||
toretract = {} | ||||
toadvance = {} | ||||
if fixphase: | ||||
precursors = {} | ||||
Boris Feld
|
r39927 | for oldnodes, newnodes in replacements.items(): | ||
for oldnode in oldnodes: | ||||
for newnode in newnodes: | ||||
precursors.setdefault(newnode, []).append(oldnode) | ||||
Martin von Zweigbergk
|
r38442 | |||
allnewnodes.sort(key=lambda n: unfi[n].rev()) | ||||
newphases = {} | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r38442 | def phase(ctx): | ||
return newphases.get(ctx.node(), ctx.phase()) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r38442 | for newnode in allnewnodes: | ||
ctx = unfi[newnode] | ||||
Martin von Zweigbergk
|
r38451 | parentphase = max(phase(p) for p in ctx.parents()) | ||
Martin von Zweigbergk
|
r38442 | if targetphase is None: | ||
Augie Fackler
|
r43346 | oldphase = max( | ||
unfi[oldnode].phase() for oldnode in precursors[newnode] | ||||
) | ||||
Martin von Zweigbergk
|
r38442 | newphase = max(oldphase, parentphase) | ||
else: | ||||
Martin von Zweigbergk
|
r38451 | newphase = max(targetphase, parentphase) | ||
Martin von Zweigbergk
|
r38442 | newphases[newnode] = newphase | ||
if newphase > ctx.phase(): | ||||
toretract.setdefault(newphase, []).append(newnode) | ||||
elif newphase < ctx.phase(): | ||||
toadvance.setdefault(newphase, []).append(newnode) | ||||
Augie Fackler
|
r43347 | with repo.transaction(b'cleanup') as tr: | ||
Jun Wu
|
r33088 | # Move bookmarks | ||
bmarks = repo._bookmarks | ||||
Boris Feld
|
r33511 | bmarkchanges = [] | ||
Martin von Zweigbergk
|
r34362 | for oldnode, newnode in moves.items(): | ||
Jun Wu
|
r33088 | oldbmarks = repo.nodebookmarks(oldnode) | ||
if not oldbmarks: | ||||
continue | ||||
Augie Fackler
|
r43346 | from . import bookmarks # avoid import cycle | ||
repo.ui.debug( | ||||
Augie Fackler
|
r43347 | b'moving bookmarks %r from %s to %s\n' | ||
Augie Fackler
|
r43346 | % ( | ||
pycompat.rapply(pycompat.maybebytestr, oldbmarks), | ||||
hex(oldnode), | ||||
hex(newnode), | ||||
) | ||||
) | ||||
Jun Wu
|
r33331 | # Delete divergent bookmarks being parents of related newnodes | ||
Augie Fackler
|
r43346 | deleterevs = repo.revs( | ||
Augie Fackler
|
r43347 | b'parents(roots(%ln & (::%n))) - parents(%n)', | ||
Augie Fackler
|
r43346 | allnewnodes, | ||
newnode, | ||||
oldnode, | ||||
) | ||||
Jun Wu
|
r33331 | deletenodes = _containsnode(repo, deleterevs) | ||
Jun Wu
|
r33088 | for name in oldbmarks: | ||
Boris Feld
|
r33511 | bmarkchanges.append((name, newnode)) | ||
for b in bookmarks.divergent2delete(repo, deletenodes, name): | ||||
bmarkchanges.append((b, None)) | ||||
if bmarkchanges: | ||||
bmarks.applychanges(repo, tr, bmarkchanges) | ||||
Jun Wu
|
r33088 | |||
Martin von Zweigbergk
|
r38442 | for phase, nodes in toretract.items(): | ||
phases.retractboundary(repo, tr, phase, nodes) | ||||
for phase, nodes in toadvance.items(): | ||||
phases.advanceboundary(repo, tr, phase, nodes) | ||||
Augie Fackler
|
r43347 | mayusearchived = repo.ui.config(b'experimental', b'cleanup-as-archived') | ||
Jun Wu
|
r33088 | # Obsolete or strip nodes | ||
if obsolete.isenabled(repo, obsolete.createmarkersopt): | ||||
# If a node is already obsoleted, and we want to obsolete it | ||||
# without a successor, skip that obssolete request since it's | ||||
# unnecessary. That's the "if s or not isobs(n)" check below. | ||||
# Also sort the node in topology order, that might be useful for | ||||
# some obsstore logic. | ||||
Boris Feld
|
r40077 | # NOTE: the sorting might belong to createmarkers. | ||
Jun Wu
|
r33330 | torev = unfi.changelog.rev | ||
Boris Feld
|
r39927 | sortfunc = lambda ns: torev(ns[0][0]) | ||
Boris Feld
|
r39926 | rels = [] | ||
Boris Feld
|
r39927 | for ns, s in sorted(replacements.items(), key=sortfunc): | ||
Boris Feld
|
r39959 | rel = (tuple(unfi[n] for n in ns), tuple(unfi[m] for m in s)) | ||
rels.append(rel) | ||||
Jun Wu
|
r34364 | if rels: | ||
Augie Fackler
|
r43346 | obsolete.createmarkers( | ||
repo, rels, operation=operation, metadata=metadata | ||||
) | ||||
Boris Feld
|
r41961 | elif phases.supportinternal(repo) and mayusearchived: | ||
# this assume we do not have "unstable" nodes above the cleaned ones | ||||
allreplaced = set() | ||||
for ns in replacements.keys(): | ||||
allreplaced.update(ns) | ||||
if backup: | ||||
Augie Fackler
|
r43346 | from . import repair # avoid import cycle | ||
Boris Feld
|
r41961 | node = min(allreplaced, key=repo.changelog.rev) | ||
Augie Fackler
|
r43346 | repair.backupbundle( | ||
repo, allreplaced, allreplaced, node, operation | ||||
) | ||||
Boris Feld
|
r41961 | phases.retractboundary(repo, tr, phases.archived, allreplaced) | ||
Jun Wu
|
r33088 | else: | ||
Augie Fackler
|
r43346 | from . import repair # avoid import cycle | ||
Boris Feld
|
r39927 | tostrip = list(n for ns in replacements for n in ns) | ||
Jun Wu
|
r34364 | if tostrip: | ||
Augie Fackler
|
r43346 | repair.delayedstrip( | ||
repo.ui, repo, tostrip, operation, backup=backup | ||||
) | ||||
Jun Wu
|
r33088 | |||
Martin von Zweigbergk
|
r41801 | def addremove(repo, matcher, prefix, uipathfn, opts=None): | ||
Pierre-Yves David
|
r26329 | if opts is None: | ||
opts = {} | ||||
Matt Harbison
|
r23533 | m = matcher | ||
Augie Fackler
|
r43347 | dry_run = opts.get(b'dry_run') | ||
Yuya Nishihara
|
r37322 | try: | ||
Augie Fackler
|
r43347 | similarity = float(opts.get(b'similarity') or 0) | ||
Yuya Nishihara
|
r37322 | except ValueError: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b'similarity must be a number')) | ||
Yuya Nishihara
|
r37322 | if similarity < 0 or similarity > 100: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b'similarity must be between 0 and 100')) | ||
Yuya Nishihara
|
r37322 | similarity /= 100.0 | ||
Matt Harbison
|
r23533 | |||
Matt Harbison
|
r23537 | ret = 0 | ||
wctx = repo[None] | ||||
for subpath in sorted(wctx.substate): | ||||
Hannes Oldenburg
|
r29802 | submatch = matchmod.subdirmatcher(subpath, m) | ||
Augie Fackler
|
r43347 | if opts.get(b'subrepos') or m.exact(subpath) or any(submatch.files()): | ||
Matt Harbison
|
r23537 | sub = wctx.sub(subpath) | ||
Martin von Zweigbergk
|
r41778 | subprefix = repo.wvfs.reljoin(prefix, subpath) | ||
Martin von Zweigbergk
|
r41801 | subuipathfn = subdiruipathfn(subpath, uipathfn) | ||
Matt Harbison
|
r23537 | try: | ||
Martin von Zweigbergk
|
r41801 | if sub.addremove(submatch, subprefix, subuipathfn, opts): | ||
Matt Harbison
|
r23537 | ret = 1 | ||
except error.LookupError: | ||||
Augie Fackler
|
r43346 | repo.ui.status( | ||
Augie Fackler
|
r43347 | _(b"skipping missing subrepository: %s\n") | ||
Augie Fackler
|
r43346 | % uipathfn(subpath) | ||
) | ||||
Matt Harbison
|
r23537 | |||
Matt Mackall
|
r16167 | rejected = [] | ||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r23534 | def badfn(f, msg): | ||
if f in m.files(): | ||||
Matt Harbison
|
r25434 | m.bad(f, msg) | ||
Matt Harbison
|
r23534 | rejected.append(f) | ||
Matt Mackall
|
r16167 | |||
Matt Harbison
|
r25434 | badmatch = matchmod.badmatch(m, badfn) | ||
Augie Fackler
|
r43346 | added, unknown, deleted, removed, forgotten = _interestingfiles( | ||
repo, badmatch | ||||
) | ||||
Siddharth Agarwal
|
r18863 | |||
Martin von Zweigbergk
|
r23259 | unknownset = set(unknown + forgotten) | ||
Siddharth Agarwal
|
r18863 | toprint = unknownset.copy() | ||
toprint.update(deleted) | ||||
for abs in sorted(toprint): | ||||
if repo.ui.verbose or not m.exact(abs): | ||||
if abs in unknownset: | ||||
Augie Fackler
|
r43347 | status = _(b'adding %s\n') % uipathfn(abs) | ||
label = b'ui.addremove.added' | ||||
Siddharth Agarwal
|
r18863 | else: | ||
Augie Fackler
|
r43347 | status = _(b'removing %s\n') % uipathfn(abs) | ||
label = b'ui.addremove.removed' | ||||
Boris Feld
|
r39123 | repo.ui.status(status, label=label) | ||
Siddharth Agarwal
|
r18863 | |||
Augie Fackler
|
r43346 | renames = _findrenames( | ||
repo, m, added + unknown, removed + deleted, similarity, uipathfn | ||||
) | ||||
Matt Mackall
|
r14320 | |||
if not dry_run: | ||||
Martin von Zweigbergk
|
r23259 | _markchanges(repo, unknown + forgotten, deleted, renames) | ||
Matt Mackall
|
r14320 | |||
Matt Mackall
|
r16167 | for f in rejected: | ||
if f in m.files(): | ||||
return 1 | ||||
Matt Harbison
|
r23537 | return ret | ||
Matt Mackall
|
r16167 | |||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r19154 | def marktouched(repo, files, similarity=0.0): | ||
'''Assert that files have somehow been operated upon. files are relative to | ||||
the repo root.''' | ||||
Matt Harbison
|
r25467 | m = matchfiles(repo, files, badfn=lambda x, y: rejected.append(x)) | ||
Siddharth Agarwal
|
r19154 | rejected = [] | ||
Martin von Zweigbergk
|
r23259 | added, unknown, deleted, removed, forgotten = _interestingfiles(repo, m) | ||
Siddharth Agarwal
|
r19154 | |||
if repo.ui.verbose: | ||||
Martin von Zweigbergk
|
r23259 | unknownset = set(unknown + forgotten) | ||
Siddharth Agarwal
|
r19154 | toprint = unknownset.copy() | ||
toprint.update(deleted) | ||||
for abs in sorted(toprint): | ||||
if abs in unknownset: | ||||
Augie Fackler
|
r43347 | status = _(b'adding %s\n') % abs | ||
Siddharth Agarwal
|
r19154 | else: | ||
Augie Fackler
|
r43347 | status = _(b'removing %s\n') % abs | ||
Siddharth Agarwal
|
r19154 | repo.ui.status(status) | ||
Martin von Zweigbergk
|
r41811 | # TODO: We should probably have the caller pass in uipathfn and apply it to | ||
Martin von Zweigbergk
|
r41846 | # the messages above too. legacyrelativevalue=True is consistent with how | ||
Martin von Zweigbergk
|
r41811 | # it used to work. | ||
Martin von Zweigbergk
|
r41834 | uipathfn = getuipathfn(repo, legacyrelativevalue=True) | ||
Augie Fackler
|
r43346 | renames = _findrenames( | ||
repo, m, added + unknown, removed + deleted, similarity, uipathfn | ||||
) | ||||
Siddharth Agarwal
|
r19154 | |||
Martin von Zweigbergk
|
r23259 | _markchanges(repo, unknown + forgotten, deleted, renames) | ||
Siddharth Agarwal
|
r19154 | |||
for f in rejected: | ||||
if f in m.files(): | ||||
return 1 | ||||
return 0 | ||||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r19150 | def _interestingfiles(repo, matcher): | ||
'''Walk dirstate with matcher, looking for files that addremove would care | ||||
about. | ||||
This is different from dirstate.status because it doesn't care about | ||||
whether files are modified or clean.''' | ||||
Martin von Zweigbergk
|
r23259 | added, unknown, deleted, removed, forgotten = [], [], [], [], [] | ||
Yuya Nishihara
|
r33722 | audit_path = pathutil.pathauditor(repo.root, cached=True) | ||
Siddharth Agarwal
|
r19150 | |||
ctx = repo[None] | ||||
dirstate = repo.dirstate | ||||
Martin von Zweigbergk
|
r40123 | matcher = repo.narrowmatch(matcher, includeexact=True) | ||
Augie Fackler
|
r43346 | walkresults = dirstate.walk( | ||
matcher, | ||||
subrepos=sorted(ctx.substate), | ||||
unknown=True, | ||||
ignored=False, | ||||
full=False, | ||||
) | ||||
Gregory Szorc
|
r43376 | for abs, st in pycompat.iteritems(walkresults): | ||
Siddharth Agarwal
|
r19150 | dstate = dirstate[abs] | ||
Augie Fackler
|
r43347 | if dstate == b'?' and audit_path.check(abs): | ||
Siddharth Agarwal
|
r19150 | unknown.append(abs) | ||
Augie Fackler
|
r43347 | elif dstate != b'r' and not st: | ||
Siddharth Agarwal
|
r19150 | deleted.append(abs) | ||
Augie Fackler
|
r43347 | elif dstate == b'r' and st: | ||
Martin von Zweigbergk
|
r23259 | forgotten.append(abs) | ||
Siddharth Agarwal
|
r19150 | # for finding renames | ||
Augie Fackler
|
r43347 | elif dstate == b'r' and not st: | ||
Siddharth Agarwal
|
r19150 | removed.append(abs) | ||
Augie Fackler
|
r43347 | elif dstate == b'a': | ||
Siddharth Agarwal
|
r19150 | added.append(abs) | ||
Martin von Zweigbergk
|
r23259 | return added, unknown, deleted, removed, forgotten | ||
Siddharth Agarwal
|
r19150 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41811 | def _findrenames(repo, matcher, added, removed, similarity, uipathfn): | ||
Siddharth Agarwal
|
r19152 | '''Find renames from removed files to added ones.''' | ||
renames = {} | ||||
if similarity > 0: | ||||
Augie Fackler
|
r43346 | for old, new, score in similar.findrenames( | ||
repo, added, removed, similarity | ||||
): | ||||
if ( | ||||
repo.ui.verbose | ||||
or not matcher.exact(old) | ||||
or not matcher.exact(new) | ||||
): | ||||
repo.ui.status( | ||||
_( | ||||
Augie Fackler
|
r43347 | b'recording removal of %s as rename to %s ' | ||
b'(%d%% similar)\n' | ||||
Augie Fackler
|
r43346 | ) | ||
% (uipathfn(old), uipathfn(new), score * 100) | ||||
) | ||||
Siddharth Agarwal
|
r19152 | renames[new] = old | ||
return renames | ||||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r19153 | def _markchanges(repo, unknown, deleted, renames): | ||
'''Marks the files in unknown as added, the files in deleted as removed, | ||||
and the files in renames as copied.''' | ||||
wctx = repo[None] | ||||
Bryan O'Sullivan
|
r27851 | with repo.wlock(): | ||
Siddharth Agarwal
|
r19153 | wctx.forget(deleted) | ||
wctx.add(unknown) | ||||
Gregory Szorc
|
r43376 | for new, old in pycompat.iteritems(renames): | ||
Siddharth Agarwal
|
r19153 | wctx.copy(old, new) | ||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r41947 | def getrenamedfn(repo, endrev=None): | ||
Martin von Zweigbergk
|
r42284 | if copiesmod.usechangesetcentricalgo(repo): | ||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42283 | def getrenamed(fn, rev): | ||
ctx = repo[rev] | ||||
p1copies = ctx.p1copies() | ||||
if fn in p1copies: | ||||
return p1copies[fn] | ||||
p2copies = ctx.p2copies() | ||||
if fn in p2copies: | ||||
return p2copies[fn] | ||||
return None | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42283 | return getrenamed | ||
Martin von Zweigbergk
|
r41947 | rcache = {} | ||
if endrev is None: | ||||
endrev = len(repo) | ||||
def getrenamed(fn, rev): | ||||
'''looks up all renames for a file (up to endrev) the first | ||||
time the file is given. It indexes on the changerev and only | ||||
parses the manifest if linkrev != changerev. | ||||
Returns rename info for fn at changerev rev.''' | ||||
if fn not in rcache: | ||||
rcache[fn] = {} | ||||
fl = repo.file(fn) | ||||
for i in fl: | ||||
lr = fl.linkrev(i) | ||||
renamed = fl.renamed(fl.node(i)) | ||||
rcache[fn][lr] = renamed and renamed[0] | ||||
if lr >= endrev: | ||||
break | ||||
if rev in rcache[fn]: | ||||
return rcache[fn][rev] | ||||
# If linkrev != rev (i.e. rev not found in rcache) fallback to | ||||
# filectx logic. | ||||
try: | ||||
return repo[rev][fn].copysource() | ||||
except error.LookupError: | ||||
return None | ||||
return getrenamed | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42703 | def getcopiesfn(repo, endrev=None): | ||
if copiesmod.usechangesetcentricalgo(repo): | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42703 | def copiesfn(ctx): | ||
if ctx.p2copies(): | ||||
allcopies = ctx.p1copies().copy() | ||||
# There should be no overlap | ||||
allcopies.update(ctx.p2copies()) | ||||
return sorted(allcopies.items()) | ||||
else: | ||||
return sorted(ctx.p1copies().items()) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42703 | else: | ||
getrenamed = getrenamedfn(repo, endrev) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42703 | def copiesfn(ctx): | ||
copies = [] | ||||
for fn in ctx.files(): | ||||
rename = getrenamed(fn, ctx.rev()) | ||||
if rename: | ||||
copies.append((fn, rename)) | ||||
return copies | ||||
return copiesfn | ||||
Augie Fackler
|
r43346 | |||
Matt Mackall
|
r14320 | def dirstatecopy(ui, repo, wctx, src, dst, dryrun=False, cwd=None): | ||
"""Update the dirstate to reflect the intent of copying src to dst. For | ||||
different reasons it might not end with dst being marked as copied from src. | ||||
""" | ||||
origsrc = repo.dirstate.copied(src) or src | ||||
Augie Fackler
|
r43346 | if dst == origsrc: # copying back a copy? | ||
Augie Fackler
|
r43347 | if repo.dirstate[dst] not in b'mn' and not dryrun: | ||
Matt Mackall
|
r14320 | repo.dirstate.normallookup(dst) | ||
else: | ||||
Augie Fackler
|
r43347 | if repo.dirstate[origsrc] == b'a' and origsrc == src: | ||
Matt Mackall
|
r14320 | if not ui.quiet: | ||
Augie Fackler
|
r43346 | ui.warn( | ||
_( | ||||
Augie Fackler
|
r43347 | b"%s has not been committed yet, so no copy " | ||
b"data will be stored for %s.\n" | ||||
Augie Fackler
|
r43346 | ) | ||
% (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)) | ||||
) | ||||
Augie Fackler
|
r43347 | if repo.dirstate[dst] in b'?r' and not dryrun: | ||
Matt Mackall
|
r14320 | wctx.add([dst]) | ||
elif not dryrun: | ||||
wctx.copy(origsrc, dst) | ||||
Adrian Buehlmann
|
r14482 | |||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r42103 | def movedirstate(repo, newctx, match=None): | ||
Martin von Zweigbergk
|
r42104 | """Move the dirstate to newctx and adjust it as necessary. | ||
A matcher can be provided as an optimization. It is probably a bug to pass | ||||
a matcher that doesn't match all the differences between the parent of the | ||||
working copy and newctx. | ||||
""" | ||||
Augie Fackler
|
r43347 | oldctx = repo[b'.'] | ||
Martin von Zweigbergk
|
r42103 | ds = repo.dirstate | ||
Martin von Zweigbergk
|
r44490 | copies = dict(ds.copies()) | ||
Martin von Zweigbergk
|
r42103 | ds.setparents(newctx.node(), nullid) | ||
s = newctx.status(oldctx, match=match) | ||||
for f in s.modified: | ||||
Augie Fackler
|
r43347 | if ds[f] == b'r': | ||
Martin von Zweigbergk
|
r42103 | # modified + removed -> removed | ||
continue | ||||
ds.normallookup(f) | ||||
for f in s.added: | ||||
Augie Fackler
|
r43347 | if ds[f] == b'r': | ||
Martin von Zweigbergk
|
r42103 | # added + removed -> unknown | ||
ds.drop(f) | ||||
Augie Fackler
|
r43347 | elif ds[f] != b'a': | ||
Martin von Zweigbergk
|
r42103 | ds.add(f) | ||
for f in s.removed: | ||||
Augie Fackler
|
r43347 | if ds[f] == b'a': | ||
Martin von Zweigbergk
|
r42103 | # removed + added -> normal | ||
ds.normallookup(f) | ||||
Augie Fackler
|
r43347 | elif ds[f] != b'r': | ||
Martin von Zweigbergk
|
r42103 | ds.remove(f) | ||
# Merge old parent and old working dir copies | ||||
oldcopies = copiesmod.pathcopies(newctx, oldctx, match) | ||||
oldcopies.update(copies) | ||||
Augie Fackler
|
r43346 | copies = dict( | ||
Gregory Szorc
|
r43376 | (dst, oldcopies.get(src, src)) | ||
for dst, src in pycompat.iteritems(oldcopies) | ||||
Augie Fackler
|
r43346 | ) | ||
Martin von Zweigbergk
|
r42103 | # Adjust the dirstate copies | ||
Gregory Szorc
|
r43376 | for dst, src in pycompat.iteritems(copies): | ||
Augie Fackler
|
r43347 | if src not in newctx or dst in newctx or ds[dst] != b'a': | ||
Martin von Zweigbergk
|
r42103 | src = None | ||
ds.copy(src, dst) | ||||
Augie Fackler
|
r43346 | |||
Drew Gottlieb
|
r24934 | def writerequires(opener, requirements): | ||
Augie Fackler
|
r43347 | with opener(b'requires', b'w', atomictemp=True) as fp: | ||
Gregory Szorc
|
r27706 | for r in sorted(requirements): | ||
Augie Fackler
|
r43347 | fp.write(b"%s\n" % r) | ||
Drew Gottlieb
|
r24934 | |||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r20043 | class filecachesubentry(object): | ||
Siddharth Agarwal
|
r20042 | def __init__(self, path, stat): | ||
Idan Kamara
|
r14928 | self.path = path | ||
Idan Kamara
|
r18315 | self.cachestat = None | ||
self._cacheable = None | ||||
Idan Kamara
|
r14928 | |||
Idan Kamara
|
r18315 | if stat: | ||
Siddharth Agarwal
|
r20043 | self.cachestat = filecachesubentry.stat(self.path) | ||
Idan Kamara
|
r18315 | |||
if self.cachestat: | ||||
self._cacheable = self.cachestat.cacheable() | ||||
else: | ||||
# None means we don't know yet | ||||
self._cacheable = None | ||||
Idan Kamara
|
r14928 | |||
def refresh(self): | ||||
if self.cacheable(): | ||||
Siddharth Agarwal
|
r20043 | self.cachestat = filecachesubentry.stat(self.path) | ||
Idan Kamara
|
r14928 | |||
def cacheable(self): | ||||
if self._cacheable is not None: | ||||
return self._cacheable | ||||
# we don't know yet, assume it is for now | ||||
return True | ||||
def changed(self): | ||||
# no point in going further if we can't cache it | ||||
if not self.cacheable(): | ||||
return True | ||||
Siddharth Agarwal
|
r20043 | newstat = filecachesubentry.stat(self.path) | ||
Idan Kamara
|
r14928 | |||
# we may not know if it's cacheable yet, check again now | ||||
if newstat and self._cacheable is None: | ||||
self._cacheable = newstat.cacheable() | ||||
# check again | ||||
if not self._cacheable: | ||||
return True | ||||
if self.cachestat != newstat: | ||||
self.cachestat = newstat | ||||
return True | ||||
else: | ||||
return False | ||||
@staticmethod | ||||
def stat(path): | ||||
try: | ||||
return util.cachestat(path) | ||||
Gregory Szorc
|
r25660 | except OSError as e: | ||
Idan Kamara
|
r14928 | if e.errno != errno.ENOENT: | ||
raise | ||||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r20044 | class filecacheentry(object): | ||
def __init__(self, paths, stat=True): | ||||
self._entries = [] | ||||
for path in paths: | ||||
self._entries.append(filecachesubentry(path, stat)) | ||||
def changed(self): | ||||
'''true if any entry has changed''' | ||||
for entry in self._entries: | ||||
if entry.changed(): | ||||
return True | ||||
return False | ||||
def refresh(self): | ||||
for entry in self._entries: | ||||
entry.refresh() | ||||
Augie Fackler
|
r43346 | |||
Idan Kamara
|
r14928 | class filecache(object): | ||
Gregory Szorc
|
r38698 | """A property like decorator that tracks files under .hg/ for updates. | ||
Idan Kamara
|
r14928 | |||
Gregory Szorc
|
r38698 | On first access, the files defined as arguments are stat()ed and the | ||
results cached. The decorated function is called. The results are stashed | ||||
away in a ``_filecache`` dict on the object whose method is decorated. | ||||
Idan Kamara
|
r14928 | |||
Yuya Nishihara
|
r40454 | On subsequent access, the cached result is used as it is set to the | ||
instance dictionary. | ||||
Gregory Szorc
|
r38698 | |||
Yuya Nishihara
|
r40454 | On external property set/delete operations, the caller must update the | ||
corresponding _filecache entry appropriately. Use __class__.<attr>.set() | ||||
instead of directly setting <attr>. | ||||
Idan Kamara
|
r14928 | |||
Yuya Nishihara
|
r40454 | When using the property API, the cached data is always used if available. | ||
No stat() is performed to check if the file has changed. | ||||
Siddharth Agarwal
|
r20045 | |||
Gregory Szorc
|
r38698 | Others can muck about with the state of the ``_filecache`` dict. e.g. they | ||
can populate an entry before the property's getter is called. In this case, | ||||
entries in ``_filecache`` will be used during property operations, | ||||
if available. If the underlying file changes, it is up to external callers | ||||
to reflect this by e.g. calling ``delattr(obj, attr)`` to remove the cached | ||||
method result as well as possibly calling ``del obj._filecache[attr]`` to | ||||
remove the ``filecacheentry``. | ||||
""" | ||||
Siddharth Agarwal
|
r20045 | def __init__(self, *paths): | ||
self.paths = paths | ||||
Idan Kamara
|
r16198 | |||
def join(self, obj, fname): | ||||
Siddharth Agarwal
|
r20045 | """Used to compute the runtime path of a cached file. | ||
Idan Kamara
|
r16198 | |||
Users should subclass filecache and provide their own version of this | ||||
function to call the appropriate join function on 'obj' (an instance | ||||
of the class that its member function was decorated). | ||||
""" | ||||
Pierre-Yves David
|
r31285 | raise NotImplementedError | ||
Idan Kamara
|
r14928 | |||
def __call__(self, func): | ||||
self.func = func | ||||
Augie Fackler
|
r37886 | self.sname = func.__name__ | ||
self.name = pycompat.sysbytes(self.sname) | ||||
Idan Kamara
|
r14928 | return self | ||
def __get__(self, obj, type=None): | ||||
Martijn Pieters
|
r29373 | # if accessed on the class, return the descriptor itself. | ||
if obj is None: | ||||
return self | ||||
Yuya Nishihara
|
r40454 | |||
assert self.sname not in obj.__dict__ | ||||
Idan Kamara
|
r16115 | |||
Idan Kamara
|
r14928 | entry = obj._filecache.get(self.name) | ||
if entry: | ||||
if entry.changed(): | ||||
entry.obj = self.func(obj) | ||||
else: | ||||
Siddharth Agarwal
|
r20045 | paths = [self.join(obj, path) for path in self.paths] | ||
Idan Kamara
|
r14928 | |||
# We stat -before- creating the object so our cache doesn't lie if | ||||
# a writer modified between the time we read and stat | ||||
Siddharth Agarwal
|
r20045 | entry = filecacheentry(paths, True) | ||
Idan Kamara
|
r14928 | entry.obj = self.func(obj) | ||
obj._filecache[self.name] = entry | ||||
Augie Fackler
|
r37886 | obj.__dict__[self.sname] = entry.obj | ||
Idan Kamara
|
r14928 | return entry.obj | ||
Idan Kamara
|
r16115 | |||
Yuya Nishihara
|
r40454 | # don't implement __set__(), which would make __dict__ lookup as slow as | ||
# function call. | ||||
def set(self, obj, value): | ||||
Idan Kamara
|
r18316 | if self.name not in obj._filecache: | ||
# we add an entry for the missing value because X in __dict__ | ||||
# implies X in _filecache | ||||
Siddharth Agarwal
|
r20045 | paths = [self.join(obj, path) for path in self.paths] | ||
ce = filecacheentry(paths, False) | ||||
Idan Kamara
|
r18316 | obj._filecache[self.name] = ce | ||
else: | ||||
ce = obj._filecache[self.name] | ||||
Augie Fackler
|
r43346 | ce.obj = value # update cached copy | ||
obj.__dict__[self.sname] = value # update copy returned by obj.x | ||||
Idan Kamara
|
r16115 | |||
Matt Mackall
|
r34457 | def extdatasource(repo, source): | ||
"""Gather a map of rev -> value dict from the specified source | ||||
A source spec is treated as a URL, with a special case shell: type | ||||
for parsing the output from a shell command. | ||||
The data is parsed as a series of newline-separated records where | ||||
each record is a revision specifier optionally followed by a space | ||||
and a freeform string value. If the revision is known locally, it | ||||
is converted to a rev, otherwise the record is skipped. | ||||
Note that both key and value are treated as UTF-8 and converted to | ||||
the local encoding. This allows uniformity between local and | ||||
remote data sources. | ||||
""" | ||||
Augie Fackler
|
r43347 | spec = repo.ui.config(b"extdata", source) | ||
Matt Mackall
|
r34457 | if not spec: | ||
Augie Fackler
|
r43347 | raise error.Abort(_(b"unknown extdata source '%s'") % source) | ||
Matt Mackall
|
r34457 | |||
data = {} | ||||
Yuya Nishihara
|
r34462 | src = proc = None | ||
Matt Mackall
|
r34457 | try: | ||
Augie Fackler
|
r43347 | if spec.startswith(b"shell:"): | ||
Yuya Nishihara
|
r34462 | # external commands should be run relative to the repo root | ||
cmd = spec[6:] | ||||
Augie Fackler
|
r43346 | proc = subprocess.Popen( | ||
procutil.tonativestr(cmd), | ||||
shell=True, | ||||
bufsize=-1, | ||||
close_fds=procutil.closefds, | ||||
stdout=subprocess.PIPE, | ||||
cwd=procutil.tonativestr(repo.root), | ||||
) | ||||
Yuya Nishihara
|
r34462 | src = proc.stdout | ||
else: | ||||
# treat as a URL or file | ||||
src = url.open(repo.ui, spec) | ||||
Yuya Nishihara
|
r34461 | for l in src: | ||
Augie Fackler
|
r43347 | if b" " in l: | ||
k, v = l.strip().split(b" ", 1) | ||||
Matt Mackall
|
r34457 | else: | ||
Augie Fackler
|
r43347 | k, v = l.strip(), b"" | ||
Matt Mackall
|
r34457 | |||
k = encoding.tolocal(k) | ||||
Yuya Nishihara
|
r34460 | try: | ||
Martin von Zweigbergk
|
r37378 | data[revsingle(repo, k).rev()] = encoding.tolocal(v) | ||
Yuya Nishihara
|
r34460 | except (error.LookupError, error.RepoLookupError): | ||
Augie Fackler
|
r43346 | pass # we ignore data for nodes that don't exist locally | ||
Matt Mackall
|
r34457 | finally: | ||
Yuya Nishihara
|
r34462 | if proc: | ||
Augie Fackler
|
r42776 | try: | ||
proc.communicate() | ||||
except ValueError: | ||||
# This happens if we started iterating src and then | ||||
# get a parse error on a line. It should be safe to ignore. | ||||
pass | ||||
Yuya Nishihara
|
r34462 | if src: | ||
src.close() | ||||
Yuya Nishihara
|
r35413 | if proc and proc.returncode != 0: | ||
Augie Fackler
|
r43346 | raise error.Abort( | ||
Augie Fackler
|
r43347 | _(b"extdata command '%s' failed: %s") | ||
Augie Fackler
|
r43346 | % (cmd, procutil.explainexit(proc.returncode)) | ||
) | ||||
Matt Mackall
|
r34457 | |||
return data | ||||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r26490 | def _locksub(repo, lock, envvar, cmd, environ=None, *args, **kwargs): | ||
if lock is None: | ||||
raise error.LockInheritanceContractViolation( | ||||
Augie Fackler
|
r43347 | b'lock can only be inherited while held' | ||
Augie Fackler
|
r43346 | ) | ||
Siddharth Agarwal
|
r26490 | if environ is None: | ||
environ = {} | ||||
with lock.inherit() as locker: | ||||
environ[envvar] = locker | ||||
return repo.ui.system(cmd, environ=environ, *args, **kwargs) | ||||
Siddharth Agarwal
|
r26491 | |||
Augie Fackler
|
r43346 | |||
Siddharth Agarwal
|
r26491 | def wlocksub(repo, cmd, *args, **kwargs): | ||
"""run cmd as a subprocess that allows inheriting repo's wlock | ||||
This can only be called while the wlock is held. This takes all the | ||||
arguments that ui.system does, and returns the exit code of the | ||||
subprocess.""" | ||||
Augie Fackler
|
r43346 | return _locksub( | ||
Augie Fackler
|
r43347 | repo, repo.currentwlock(), b'HG_WLOCK_LOCKER', cmd, *args, **kwargs | ||
Augie Fackler
|
r43346 | ) | ||
Pierre-Yves David
|
r26906 | |||
Martin von Zweigbergk
|
r38364 | class progress(object): | ||
Augie Fackler
|
r43347 | def __init__(self, ui, updatebar, topic, unit=b"", total=None): | ||
Martin von Zweigbergk
|
r38364 | self.ui = ui | ||
self.pos = 0 | ||||
self.topic = topic | ||||
self.unit = unit | ||||
self.total = total | ||||
Augie Fackler
|
r43347 | self.debug = ui.configbool(b'progress', b'debug') | ||
Martin von Zweigbergk
|
r41181 | self._updatebar = updatebar | ||
Martin von Zweigbergk
|
r38364 | |||
Martin von Zweigbergk
|
r38393 | def __enter__(self): | ||
Danny Hooper
|
r38522 | return self | ||
Martin von Zweigbergk
|
r38393 | |||
def __exit__(self, exc_type, exc_value, exc_tb): | ||||
self.complete() | ||||
Augie Fackler
|
r43347 | def update(self, pos, item=b"", total=None): | ||
Martin von Zweigbergk
|
r38438 | assert pos is not None | ||
Martin von Zweigbergk
|
r38364 | if total: | ||
self.total = total | ||||
self.pos = pos | ||||
Yuya Nishihara
|
r41245 | self._updatebar(self.topic, self.pos, item, self.unit, self.total) | ||
Martin von Zweigbergk
|
r41180 | if self.debug: | ||
self._printdebug(item) | ||||
Martin von Zweigbergk
|
r38364 | |||
Augie Fackler
|
r43347 | def increment(self, step=1, item=b"", total=None): | ||
Martin von Zweigbergk
|
r38364 | self.update(self.pos + step, item, total) | ||
Martin von Zweigbergk
|
r38392 | def complete(self): | ||
Martin von Zweigbergk
|
r41178 | self.pos = None | ||
Augie Fackler
|
r43347 | self.unit = b"" | ||
Martin von Zweigbergk
|
r41178 | self.total = None | ||
Augie Fackler
|
r43347 | self._updatebar(self.topic, self.pos, b"", self.unit, self.total) | ||
Martin von Zweigbergk
|
r38392 | |||
Martin von Zweigbergk
|
r41180 | def _printdebug(self, item): | ||
Matt Harbison
|
r44520 | unit = b'' | ||
Martin von Zweigbergk
|
r41178 | if self.unit: | ||
Augie Fackler
|
r43347 | unit = b' ' + self.unit | ||
Martin von Zweigbergk
|
r41178 | if item: | ||
Augie Fackler
|
r43347 | item = b' ' + item | ||
Martin von Zweigbergk
|
r41178 | |||
if self.total: | ||||
pct = 100.0 * self.pos / self.total | ||||
Augie Fackler
|
r43346 | self.ui.debug( | ||
Augie Fackler
|
r43347 | b'%s:%s %d/%d%s (%4.2f%%)\n' | ||
Augie Fackler
|
r43346 | % (self.topic, item, self.pos, self.total, unit, pct) | ||
) | ||||
Martin von Zweigbergk
|
r41178 | else: | ||
Augie Fackler
|
r43347 | self.ui.debug(b'%s:%s %d%s\n' % (self.topic, item, self.pos, unit)) | ||
Martin von Zweigbergk
|
r38364 | |||
Augie Fackler
|
r43346 | |||
Pierre-Yves David
|
r26906 | def gdinitconfig(ui): | ||
"""helper function to know if a repo should be created as general delta | ||||
Pierre-Yves David
|
r26907 | """ | ||
# experimental config: format.generaldelta | ||||
Augie Fackler
|
r43347 | return ui.configbool(b'format', b'generaldelta') or ui.configbool( | ||
b'format', b'usegeneraldelta' | ||||
Augie Fackler
|
r43346 | ) | ||
Pierre-Yves David
|
r26906 | |||
Pierre-Yves David
|
r26907 | def gddeltaconfig(ui): | ||
"""helper function to know if incoming delta should be optimised | ||||
""" | ||||
Pierre-Yves David
|
r26906 | # experimental config: format.generaldelta | ||
Augie Fackler
|
r43347 | return ui.configbool(b'format', b'generaldelta') | ||
Kostia Balytskyi
|
r31553 | |||
Augie Fackler
|
r43346 | |||
Kostia Balytskyi
|
r31553 | class simplekeyvaluefile(object): | ||
"""A simple file with key=value lines | ||||
Keys must be alphanumerics and start with a letter, values must not | ||||
contain '\n' characters""" | ||||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r43347 | firstlinekey = b'__firstline' | ||
Kostia Balytskyi
|
r31553 | |||
def __init__(self, vfs, path, keys=None): | ||||
self.vfs = vfs | ||||
self.path = path | ||||
Kostia Balytskyi
|
r32270 | def read(self, firstlinenonkeyval=False): | ||
"""Read the contents of a simple key-value file | ||||
'firstlinenonkeyval' indicates whether the first line of file should | ||||
be treated as a key-value pair or reuturned fully under the | ||||
__firstline key.""" | ||||
Kostia Balytskyi
|
r31553 | lines = self.vfs.readlines(self.path) | ||
Kostia Balytskyi
|
r32270 | d = {} | ||
if firstlinenonkeyval: | ||||
if not lines: | ||||
Augie Fackler
|
r43347 | e = _(b"empty simplekeyvalue file") | ||
Kostia Balytskyi
|
r32270 | raise error.CorruptedState(e) | ||
# we don't want to include '\n' in the __firstline | ||||
d[self.firstlinekey] = lines[0][:-1] | ||||
del lines[0] | ||||
Kostia Balytskyi
|
r31553 | try: | ||
Kostia Balytskyi
|
r32269 | # the 'if line.strip()' part prevents us from failing on empty | ||
# lines which only contain '\n' therefore are not skipped | ||||
# by 'if line' | ||||
Augie Fackler
|
r43346 | updatedict = dict( | ||
Augie Fackler
|
r43347 | line[:-1].split(b'=', 1) for line in lines if line.strip() | ||
Augie Fackler
|
r43346 | ) | ||
Kostia Balytskyi
|
r32270 | if self.firstlinekey in updatedict: | ||
Augie Fackler
|
r43347 | e = _(b"%r can't be used as a key") | ||
Kostia Balytskyi
|
r32270 | raise error.CorruptedState(e % self.firstlinekey) | ||
d.update(updatedict) | ||||
Kostia Balytskyi
|
r31553 | except ValueError as e: | ||
Emmanuel Leblond
|
r43682 | raise error.CorruptedState(stringutil.forcebytestr(e)) | ||
Kostia Balytskyi
|
r31553 | return d | ||
Kostia Balytskyi
|
r32270 | def write(self, data, firstline=None): | ||
Kostia Balytskyi
|
r31553 | """Write key=>value mapping to a file | ||
data is a dict. Keys must be alphanumerical and start with a letter. | ||||
Kostia Balytskyi
|
r32270 | Values must not contain newline characters. | ||
If 'firstline' is not None, it is written to file before | ||||
everything else, as it is, not in a key=value form""" | ||||
Kostia Balytskyi
|
r31553 | lines = [] | ||
Kostia Balytskyi
|
r32270 | if firstline is not None: | ||
Augie Fackler
|
r43347 | lines.append(b'%s\n' % firstline) | ||
Kostia Balytskyi
|
r32270 | |||
Kostia Balytskyi
|
r31553 | for k, v in data.items(): | ||
Kostia Balytskyi
|
r32270 | if k == self.firstlinekey: | ||
Augie Fackler
|
r43347 | e = b"key name '%s' is reserved" % self.firstlinekey | ||
Kostia Balytskyi
|
r32270 | raise error.ProgrammingError(e) | ||
Pulkit Goyal
|
r35931 | if not k[0:1].isalpha(): | ||
Augie Fackler
|
r43347 | e = b"keys must start with a letter in a key-value file" | ||
Kostia Balytskyi
|
r31553 | raise error.ProgrammingError(e) | ||
if not k.isalnum(): | ||||
Augie Fackler
|
r43347 | e = b"invalid key name in a simple key-value file" | ||
Kostia Balytskyi
|
r31553 | raise error.ProgrammingError(e) | ||
Augie Fackler
|
r43347 | if b'\n' in v: | ||
e = b"invalid value in a simple key-value file" | ||||
Kostia Balytskyi
|
r31553 | raise error.ProgrammingError(e) | ||
Augie Fackler
|
r43347 | lines.append(b"%s=%s\n" % (k, v)) | ||
with self.vfs(self.path, mode=b'wb', atomictemp=True) as fp: | ||||
fp.write(b''.join(lines)) | ||||
r33249 | ||||
Augie Fackler
|
r43346 | |||
Boris Feld
|
r33541 | _reportobsoletedsource = [ | ||
Augie Fackler
|
r43347 | b'debugobsolete', | ||
b'pull', | ||||
b'push', | ||||
b'serve', | ||||
b'unbundle', | ||||
Boris Feld
|
r33541 | ] | ||
Denis Laxalde
|
r34662 | _reportnewcssource = [ | ||
Augie Fackler
|
r43347 | b'pull', | ||
b'unbundle', | ||||
Denis Laxalde
|
r34662 | ] | ||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r37780 | def prefetchfiles(repo, revs, match): | ||
"""Invokes the registered file prefetch functions, allowing extensions to | ||||
ensure the corresponding files are available locally, before the command | ||||
uses them.""" | ||||
if match: | ||||
# The command itself will complain about files that don't exist, so | ||||
# don't duplicate the message. | ||||
match = matchmod.badmatch(match, lambda fn, msg: None) | ||||
else: | ||||
match = matchall(repo) | ||||
fileprefetchhooks(repo, revs, match) | ||||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r37780 | # a list of (repo, revs, match) prefetch functions | ||
Matt Harbison
|
r36154 | fileprefetchhooks = util.hooks() | ||
Martin von Zweigbergk
|
r35727 | # A marker that tells the evolve extension to suppress its own reporting | ||
_reportstroubledchangesets = True | ||||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r43347 | def registersummarycallback(repo, otr, txnname=b''): | ||
r33249 | """register a callback to issue a summary after the transaction is closed | |||
""" | ||||
Augie Fackler
|
r43346 | |||
Denis Laxalde
|
r34620 | def txmatch(sources): | ||
return any(txnname.startswith(source) for source in sources) | ||||
Denis Laxalde
|
r34621 | categories = [] | ||
def reportsummary(func): | ||||
"""decorator for report callbacks.""" | ||||
Boris Feld
|
r35140 | # The repoview life cycle is shorter than the one of the actual | ||
# underlying repository. So the filtered object can die before the | ||||
# weakref is used leading to troubles. We keep a reference to the | ||||
# unfiltered object and restore the filtering when retrieving the | ||||
# repository through the weakref. | ||||
filtername = repo.filtername | ||||
reporef = weakref.ref(repo.unfiltered()) | ||||
Augie Fackler
|
r43346 | |||
Denis Laxalde
|
r34621 | def wrapped(tr): | ||
Denis Laxalde
|
r34620 | repo = reporef() | ||
Boris Feld
|
r35140 | if filtername: | ||
Matt Harbison
|
r44120 | assert repo is not None # help pytype | ||
Boris Feld
|
r35140 | repo = repo.filtered(filtername) | ||
Denis Laxalde
|
r34621 | func(repo, tr) | ||
Augie Fackler
|
r43346 | |||
Augie Fackler
|
r43347 | newcat = b'%02i-txnreport' % len(categories) | ||
Denis Laxalde
|
r34621 | otr.addpostclose(newcat, wrapped) | ||
categories.append(newcat) | ||||
return wrapped | ||||
r43167 | @reportsummary | |||
def reportchangegroup(repo, tr): | ||||
Augie Fackler
|
r43347 | cgchangesets = tr.changes.get(b'changegroup-count-changesets', 0) | ||
cgrevisions = tr.changes.get(b'changegroup-count-revisions', 0) | ||||
cgfiles = tr.changes.get(b'changegroup-count-files', 0) | ||||
cgheads = tr.changes.get(b'changegroup-count-heads', 0) | ||||
r43167 | if cgchangesets or cgrevisions or cgfiles: | |||
Augie Fackler
|
r43347 | htext = b"" | ||
r43167 | if cgheads: | |||
Augie Fackler
|
r43347 | htext = _(b" (%+d heads)") % cgheads | ||
msg = _(b"added %d changesets with %d changes to %d files%s\n") | ||||
Matt Harbison
|
r44120 | assert repo is not None # help pytype | ||
r43167 | repo.ui.status(msg % (cgchangesets, cgrevisions, cgfiles, htext)) | |||
Denis Laxalde
|
r34621 | if txmatch(_reportobsoletedsource): | ||
Augie Fackler
|
r43346 | |||
Denis Laxalde
|
r34621 | @reportsummary | ||
def reportobsoleted(repo, tr): | ||||
Denis Laxalde
|
r34620 | obsoleted = obsutil.getobsoleted(repo, tr) | ||
Augie Fackler
|
r43347 | newmarkers = len(tr.changes.get(b'obsmarkers', ())) | ||
r43164 | if newmarkers: | |||
Augie Fackler
|
r43347 | repo.ui.status(_(b'%i new obsolescence markers\n') % newmarkers) | ||
Denis Laxalde
|
r34620 | if obsoleted: | ||
Augie Fackler
|
r43347 | repo.ui.status(_(b'obsoleted %i changesets\n') % len(obsoleted)) | ||
Denis Laxalde
|
r34662 | |||
Augie Fackler
|
r43346 | if obsolete.isenabled( | ||
repo, obsolete.createmarkersopt | ||||
Augie Fackler
|
r43347 | ) and repo.ui.configbool( | ||
b'experimental', b'evolution.report-instabilities' | ||||
): | ||||
Martin von Zweigbergk
|
r35727 | instabilitytypes = [ | ||
Augie Fackler
|
r43347 | (b'orphan', b'orphan'), | ||
(b'phase-divergent', b'phasedivergent'), | ||||
(b'content-divergent', b'contentdivergent'), | ||||
Martin von Zweigbergk
|
r35727 | ] | ||
def getinstabilitycounts(repo): | ||||
filtered = repo.changelog.filteredrevs | ||||
counts = {} | ||||
for instability, revset in instabilitytypes: | ||||
Augie Fackler
|
r43346 | counts[instability] = len( | ||
set(obsolete.getrevs(repo, revset)) - filtered | ||||
) | ||||
Martin von Zweigbergk
|
r35727 | return counts | ||
oldinstabilitycounts = getinstabilitycounts(repo) | ||||
Augie Fackler
|
r43346 | |||
Martin von Zweigbergk
|
r35727 | @reportsummary | ||
def reportnewinstabilities(repo, tr): | ||||
newinstabilitycounts = getinstabilitycounts(repo) | ||||
for instability, revset in instabilitytypes: | ||||
Augie Fackler
|
r43346 | delta = ( | ||
newinstabilitycounts[instability] | ||||
- oldinstabilitycounts[instability] | ||||
) | ||||
Pulkit Goyal
|
r38474 | msg = getinstabilitymessage(delta, instability) | ||
if msg: | ||||
repo.ui.warn(msg) | ||||
Martin von Zweigbergk
|
r35727 | |||
Denis Laxalde
|
r34662 | if txmatch(_reportnewcssource): | ||
Augie Fackler
|
r43346 | |||
Denis Laxalde
|
r34662 | @reportsummary | ||
def reportnewcs(repo, tr): | ||||
"""Report the range of new revisions pulled/unbundled.""" | ||||
Augie Fackler
|
r43347 | origrepolen = tr.changes.get(b'origrepolen', len(repo)) | ||
Boris Feld
|
r39934 | unfi = repo.unfiltered() | ||
if origrepolen >= len(unfi): | ||||
Denis Laxalde
|
r34662 | return | ||
Boris Feld
|
r39933 | # Compute the bounds of new visible revisions' range. | ||
revs = smartset.spanset(repo, start=origrepolen) | ||||
Boris Feld
|
r39934 | if revs: | ||
minrev, maxrev = repo[revs.min()], repo[revs.max()] | ||||
Denis Laxalde
|
r34662 | |||
Boris Feld
|
r39934 | if minrev == maxrev: | ||
revrange = minrev | ||||
else: | ||||
Augie Fackler
|
r43347 | revrange = b'%s:%s' % (minrev, maxrev) | ||
draft = len(repo.revs(b'%ld and draft()', revs)) | ||||
secret = len(repo.revs(b'%ld and secret()', revs)) | ||||
Boris Feld
|
r39934 | if not (draft or secret): | ||
Augie Fackler
|
r43347 | msg = _(b'new changesets %s\n') % revrange | ||
Boris Feld
|
r39934 | elif draft and secret: | ||
Augie Fackler
|
r43347 | msg = _(b'new changesets %s (%d drafts, %d secrets)\n') | ||
Boris Feld
|
r39934 | msg %= (revrange, draft, secret) | ||
elif draft: | ||||
Augie Fackler
|
r43347 | msg = _(b'new changesets %s (%d drafts)\n') | ||
Boris Feld
|
r39934 | msg %= (revrange, draft) | ||
elif secret: | ||||
Augie Fackler
|
r43347 | msg = _(b'new changesets %s (%d secrets)\n') | ||
Boris Feld
|
r39934 | msg %= (revrange, secret) | ||
else: | ||||
Augie Fackler
|
r43347 | errormsg = b'entered unreachable condition' | ||
Boris Feld
|
r39934 | raise error.ProgrammingError(errormsg) | ||
repo.ui.status(msg) | ||||
Matt Harbison
|
r35169 | |||
Boris Feld
|
r39935 | # search new changesets directly pulled as obsolete | ||
Augie Fackler
|
r43347 | duplicates = tr.changes.get(b'revduplicates', ()) | ||
Augie Fackler
|
r43346 | obsadded = unfi.revs( | ||
Augie Fackler
|
r43347 | b'(%d: + %ld) and obsolete()', origrepolen, duplicates | ||
Augie Fackler
|
r43346 | ) | ||
Boris Feld
|
r39935 | cl = repo.changelog | ||
extinctadded = [r for r in obsadded if r not in cl] | ||||
if extinctadded: | ||||
# They are not just obsolete, but obsolete and invisible | ||||
# we call them "extinct" internally but the terms have not been | ||||
# exposed to users. | ||||
Augie Fackler
|
r43347 | msg = b'(%d other changesets obsolete on arrival)\n' | ||
Boris Feld
|
r39935 | repo.ui.status(msg % len(extinctadded)) | ||
Denis Laxalde
|
r38189 | @reportsummary | ||
def reportphasechanges(repo, tr): | ||||
"""Report statistics of phase changes for changesets pre-existing | ||||
pull/unbundle. | ||||
""" | ||||
Augie Fackler
|
r43347 | origrepolen = tr.changes.get(b'origrepolen', len(repo)) | ||
phasetracking = tr.changes.get(b'phases', {}) | ||||
Denis Laxalde
|
r38189 | if not phasetracking: | ||
return | ||||
published = [ | ||||
Augie Fackler
|
r43346 | rev | ||
Gregory Szorc
|
r43376 | for rev, (old, new) in pycompat.iteritems(phasetracking) | ||
Yuya Nishihara
|
r39337 | if new == phases.public and rev < origrepolen | ||
Denis Laxalde
|
r38189 | ] | ||
if not published: | ||||
return | ||||
Augie Fackler
|
r43346 | repo.ui.status( | ||
Augie Fackler
|
r43347 | _(b'%d local changesets published\n') % len(published) | ||
Augie Fackler
|
r43346 | ) | ||
Denis Laxalde
|
r38189 | |||
Pulkit Goyal
|
r38474 | def getinstabilitymessage(delta, instability): | ||
"""function to return the message to show warning about new instabilities | ||||
exists as a separate function so that extension can wrap to show more | ||||
information like how to fix instabilities""" | ||||
if delta > 0: | ||||
Augie Fackler
|
r43347 | return _(b'%i new %s changesets\n') % (delta, instability) | ||
Pulkit Goyal
|
r38474 | |||
Augie Fackler
|
r43346 | |||
Boris Feld
|
r35185 | def nodesummaries(repo, nodes, maxnumnodes=4): | ||
if len(nodes) <= maxnumnodes or repo.ui.verbose: | ||||
Augie Fackler
|
r43347 | return b' '.join(short(h) for h in nodes) | ||
first = b' '.join(short(h) for h in nodes[:maxnumnodes]) | ||||
return _(b"%s and %d others") % (first, len(nodes) - maxnumnodes) | ||||
Boris Feld
|
r35185 | |||
Augie Fackler
|
r43346 | |||
r43239 | def enforcesinglehead(repo, tr, desc, accountclosed=False): | |||
Boris Feld
|
r35186 | """check that no named branch has multiple heads""" | ||
Augie Fackler
|
r43347 | if desc in (b'strip', b'repair'): | ||
Boris Feld
|
r35186 | # skip the logic during strip | ||
return | ||||
Augie Fackler
|
r43347 | visible = repo.filtered(b'visible') | ||
Boris Feld
|
r35186 | # possible improvement: we could restrict the check to affected branch | ||
r43239 | bm = visible.branchmap() | |||
for name in bm: | ||||
heads = bm.branchheads(name, closed=accountclosed) | ||||
Boris Feld
|
r35186 | if len(heads) > 1: | ||
Augie Fackler
|
r43347 | msg = _(b'rejecting multiple heads on branch "%s"') | ||
Boris Feld
|
r35186 | msg %= name | ||
Augie Fackler
|
r43347 | hint = _(b'%d heads: %s') | ||
Boris Feld
|
r35186 | hint %= (len(heads), nodesummaries(repo, heads)) | ||
raise error.Abort(msg, hint=hint) | ||||
Augie Fackler
|
r43346 | |||
Matt Harbison
|
r35169 | def wrapconvertsink(sink): | ||
"""Allow extensions to wrap the sink returned by convcmd.convertsink() | ||||
before it is used, whether or not the convert extension was formally loaded. | ||||
""" | ||||
return sink | ||||
Pulkit Goyal
|
r35512 | |||
Augie Fackler
|
r43346 | |||
Pulkit Goyal
|
r35512 | def unhidehashlikerevs(repo, specs, hiddentype): | ||
"""parse the user specs and unhide changesets whose hash or revision number | ||||
is passed. | ||||
hiddentype can be: 1) 'warn': warn while unhiding changesets | ||||
2) 'nowarn': don't warn while unhiding changesets | ||||
returns a repo object with the required changesets unhidden | ||||
""" | ||||
Augie Fackler
|
r43346 | if not repo.filtername or not repo.ui.configbool( | ||
Augie Fackler
|
r43347 | b'experimental', b'directaccess' | ||
Augie Fackler
|
r43346 | ): | ||
Pulkit Goyal
|
r35512 | return repo | ||
Augie Fackler
|
r43347 | if repo.filtername not in (b'visible', b'visible-hidden'): | ||
Pulkit Goyal
|
r35512 | return repo | ||
symbols = set() | ||||
for spec in specs: | ||||
try: | ||||
tree = revsetlang.parse(spec) | ||||
Augie Fackler
|
r43346 | except error.ParseError: # will be reported by scmutil.revrange() | ||
Pulkit Goyal
|
r35512 | continue | ||
symbols.update(revsetlang.gethashlikesymbols(tree)) | ||||
if not symbols: | ||||
return repo | ||||
revs = _getrevsfromsymbols(repo, symbols) | ||||
if not revs: | ||||
return repo | ||||
Augie Fackler
|
r43347 | if hiddentype == b'warn': | ||
Pulkit Goyal
|
r35512 | unfi = repo.unfiltered() | ||
Augie Fackler
|
r43347 | revstr = b", ".join([pycompat.bytestr(unfi[l]) for l in revs]) | ||
Augie Fackler
|
r43346 | repo.ui.warn( | ||
_( | ||||
Augie Fackler
|
r43347 | b"warning: accessing hidden changesets for write " | ||
b"operation: %s\n" | ||||
Augie Fackler
|
r43346 | ) | ||
% revstr | ||||
) | ||||
Pulkit Goyal
|
r35512 | |||
Pulkit Goyal
|
r35515 | # we have to use new filtername to separate branch/tags cache until we can | ||
# disbale these cache when revisions are dynamically pinned. | ||||
Augie Fackler
|
r43347 | return repo.filtered(b'visible-hidden', revs) | ||
Pulkit Goyal
|
r35512 | |||
Augie Fackler
|
r43346 | |||
Pulkit Goyal
|
r35512 | def _getrevsfromsymbols(repo, symbols): | ||
"""parse the list of symbols and returns a set of revision numbers of hidden | ||||
changesets present in symbols""" | ||||
revs = set() | ||||
unfi = repo.unfiltered() | ||||
unficl = unfi.changelog | ||||
cl = repo.changelog | ||||
tiprev = len(unficl) | ||||
Augie Fackler
|
r43347 | allowrevnums = repo.ui.configbool(b'experimental', b'directaccess.revnums') | ||
Pulkit Goyal
|
r35512 | for s in symbols: | ||
try: | ||||
n = int(s) | ||||
if n <= tiprev: | ||||
if not allowrevnums: | ||||
continue | ||||
else: | ||||
if n not in cl: | ||||
revs.add(n) | ||||
continue | ||||
except ValueError: | ||||
pass | ||||
try: | ||||
Martin von Zweigbergk
|
r37885 | s = resolvehexnodeidprefix(unfi, s) | ||
Yuya Nishihara
|
r37112 | except (error.LookupError, error.WdirUnsupported): | ||
Pulkit Goyal
|
r35512 | s = None | ||
if s is not None: | ||||
rev = unficl.rev(s) | ||||
if rev not in cl: | ||||
revs.add(rev) | ||||
return revs | ||||
David Demelier
|
r38146 | |||
Augie Fackler
|
r43346 | |||
David Demelier
|
r38146 | def bookmarkrevs(repo, mark): | ||
""" | ||||
Select revisions reachable by a given bookmark | ||||
""" | ||||
Augie Fackler
|
r43346 | return repo.revs( | ||
Augie Fackler
|
r43347 | b"ancestors(bookmark(%s)) - " | ||
b"ancestors(head() and not bookmark(%s)) - " | ||||
b"ancestors(bookmark() and not bookmark(%s))", | ||||
Augie Fackler
|
r43346 | mark, | ||
mark, | ||||
mark, | ||||
) | ||||