2011-04-19 14:42:53 +04:00
|
|
|
# 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.
|
|
|
|
|
2015-12-22 08:23:43 +03:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
|
|
|
import errno
|
|
|
|
import glob
|
2016-06-10 07:12:33 +03:00
|
|
|
import hashlib
|
2015-12-22 08:23:43 +03:00
|
|
|
import os
|
|
|
|
import re
|
2016-11-24 03:48:40 +03:00
|
|
|
import socket
|
2017-06-28 04:54:19 +03:00
|
|
|
import weakref
|
2015-12-22 08:23:43 +03:00
|
|
|
|
|
|
|
from .i18n import _
|
2017-06-03 13:12:01 +03:00
|
|
|
from .node import (
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
hex,
|
|
|
|
nullid,
|
2017-06-03 13:12:01 +03:00
|
|
|
wdirid,
|
|
|
|
wdirrev,
|
|
|
|
)
|
|
|
|
|
2015-12-22 08:23:43 +03:00
|
|
|
from . import (
|
|
|
|
encoding,
|
|
|
|
error,
|
|
|
|
match as matchmod,
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
obsolete,
|
2017-06-28 04:54:19 +03:00
|
|
|
obsutil,
|
2015-12-22 08:23:43 +03:00
|
|
|
pathutil,
|
|
|
|
phases,
|
2016-11-06 01:47:19 +03:00
|
|
|
pycompat,
|
2017-02-19 12:19:33 +03:00
|
|
|
revsetlang,
|
2015-12-22 08:23:43 +03:00
|
|
|
similar,
|
|
|
|
util,
|
|
|
|
)
|
2013-02-12 21:36:21 +04:00
|
|
|
|
2016-12-18 21:46:52 +03:00
|
|
|
if pycompat.osname == 'nt':
|
2015-12-22 08:23:43 +03:00
|
|
|
from . import scmwindows as scmplatform
|
2013-02-12 21:36:21 +04:00
|
|
|
else:
|
2015-12-22 08:23:43 +03:00
|
|
|
from . import scmposix as scmplatform
|
2013-02-12 21:36:21 +04:00
|
|
|
|
2016-10-20 17:09:05 +03:00
|
|
|
termsize = scmplatform.termsize
|
2011-04-19 14:42:53 +04:00
|
|
|
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
class status(tuple):
|
|
|
|
'''Named tuple with a list of files per status. The 'deleted', 'unknown'
|
|
|
|
and 'ignored' properties are only relevant to the working copy.
|
|
|
|
'''
|
|
|
|
|
|
|
|
__slots__ = ()
|
|
|
|
|
|
|
|
def __new__(cls, modified, added, removed, deleted, unknown, ignored,
|
|
|
|
clean):
|
|
|
|
return tuple.__new__(cls, (modified, added, removed, deleted, unknown,
|
|
|
|
ignored, clean))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def modified(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files that have been modified'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[0]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def added(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files that have been added'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[1]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def removed(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files that have been removed'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[2]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def deleted(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files that are in the dirstate, but have been deleted from the
|
|
|
|
working copy (aka "missing")
|
|
|
|
'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[3]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def unknown(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files not in the dirstate that are not ignored'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[4]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def ignored(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files not in the dirstate that are ignored (by _dirignore())'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[5]
|
|
|
|
|
|
|
|
@property
|
|
|
|
def clean(self):
|
2014-10-10 21:14:35 +04:00
|
|
|
'''files that have not been modified'''
|
status: create class for status lists
Callers of various status() methods (on dirstate, context, repo) get a
tuple of 7 elements, where each element is a list of files. This
results in lots of uses of indexes where names would be much more
readable. For example, "status.ignored" seems clearer than "status[4]"
[1]. So, let's introduce a simple named tuple containing the 7 status
fields: modified, added, removed, deleted, unknown, ignored, clean.
This patch introduces the class and updates the status methods to
return instances of it. Later patches will update the callers.
[1] Did you even notice that it should have been "status[5]"?
(tweaked by mpm to introduce the class in scmutil and only change one user)
2014-10-11 01:32:36 +04:00
|
|
|
return self[6]
|
|
|
|
|
|
|
|
def __repr__(self, *args, **kwargs):
|
|
|
|
return (('<status modified=%r, added=%r, removed=%r, deleted=%r, '
|
|
|
|
'unknown=%r, ignored=%r, clean=%r>') % self)
|
|
|
|
|
2014-02-04 03:36:00 +04:00
|
|
|
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))
|
scmutil: consistently return subrepos relative to ctx1 from itersubrepos()
Previously, if a subrepo was added in ctx2 and then compared to another without
it (ctx1), the subrepo for ctx2 was returned amongst all of the ctx1 based
subrepos, since no subrepo exists in ctx1 to replace it in the 'subpaths' dict.
The two callers of this, basectx.status() and cmdutil.diffordiffstat(), both
compare the yielded subrepo against ctx2, and thus saw no changes when ctx2's
subrepo was returned. The tests here previously didn't mention 's/a' for the
'p1()' case.
This appears to have been a known issue, because some diffordiffstat() comments
mention that the subpath disappeared, and "the best we can do is ignore it". I
originally ran into the issue with some custom convert code to flatten a tree of
subrepos causing hg.putcommit() to abort, but this new behavior seems like the
correct status and diff behavior regardless. (The abort in convert isn't
something users will see, because convert doesn't currently support subrepos in
the official repo.)
2015-06-03 21:21:15 +03:00
|
|
|
|
|
|
|
missing = set()
|
|
|
|
|
|
|
|
for subpath in ctx2.substate:
|
|
|
|
if subpath not in ctx1.substate:
|
|
|
|
del subpaths[subpath]
|
|
|
|
missing.add(subpath)
|
|
|
|
|
2014-02-04 03:36:00 +04:00
|
|
|
for subpath, ctx in sorted(subpaths.iteritems()):
|
|
|
|
yield subpath, ctx.sub(subpath)
|
|
|
|
|
scmutil: consistently return subrepos relative to ctx1 from itersubrepos()
Previously, if a subrepo was added in ctx2 and then compared to another without
it (ctx1), the subrepo for ctx2 was returned amongst all of the ctx1 based
subrepos, since no subrepo exists in ctx1 to replace it in the 'subpaths' dict.
The two callers of this, basectx.status() and cmdutil.diffordiffstat(), both
compare the yielded subrepo against ctx2, and thus saw no changes when ctx2's
subrepo was returned. The tests here previously didn't mention 's/a' for the
'p1()' case.
This appears to have been a known issue, because some diffordiffstat() comments
mention that the subpath disappeared, and "the best we can do is ignore it". I
originally ran into the issue with some custom convert code to flatten a tree of
subrepos causing hg.putcommit() to abort, but this new behavior seems like the
correct status and diff behavior regardless. (The abort in convert isn't
something users will see, because convert doesn't currently support subrepos in
the official repo.)
2015-06-03 21:21:15 +03:00
|
|
|
# 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)
|
|
|
|
|
2012-07-25 21:34:31 +04:00
|
|
|
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)
|
|
|
|
|
2012-01-26 03:14:08 +04:00
|
|
|
if secretlist:
|
|
|
|
ui.status(_("no changes found (ignored %d secret changesets)\n")
|
|
|
|
% len(secretlist))
|
|
|
|
else:
|
|
|
|
ui.status(_("no changes found\n"))
|
|
|
|
|
2016-11-24 03:48:40 +03:00
|
|
|
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:
|
2017-04-15 07:02:34 +03:00
|
|
|
try:
|
|
|
|
return func()
|
|
|
|
except: # re-raises
|
|
|
|
ui.traceback()
|
|
|
|
raise
|
2016-11-24 03:48:40 +03:00
|
|
|
# Global exception handling, alphabetically
|
|
|
|
# Mercurial-specific first, followed by built-in and library exceptions
|
|
|
|
except error.LockHeld as inst:
|
|
|
|
if inst.errno == errno.ETIMEDOUT:
|
lock: avoid unintentional lock acquisition at failure of readlock
Acquiring lock by vfs.makelock() and getting lock holder (aka
"locker") information by vfs.readlock() aren't atomic action.
Therefore, failure of the former doesn't ensure success of the latter.
Before this patch, lock is unintentionally acquired, if ENOENT
causes failure of vfs.readlock() while 5 times retrying, because
lock._trylock() returns to caller silently after retrying, and
lock.lock() assumes that lock._trylock() returns successfully only if
lock is acquired.
In this case, lock symlink (or file) isn't created, even though lock
is treated as acquired in memory.
To avoid this issue, this patch makes lock._trylock() raise
LockHeld(EAGAIN) at the end of it, if lock isn't acquired while
retrying.
An empty "locker" meaning "busy for frequent lock/unlock by many
processes" might appear in an abortion message, if lock acquisition
fails. Therefore, this patch also does:
- use '%r' to increase visibility of "locker", even if it is empty
- show hint message to explain what empty "locker" means
2017-05-01 13:59:13 +03:00
|
|
|
reason = _('timed out waiting for lock held by %r') % inst.locker
|
2016-11-24 03:48:40 +03:00
|
|
|
else:
|
lock: avoid unintentional lock acquisition at failure of readlock
Acquiring lock by vfs.makelock() and getting lock holder (aka
"locker") information by vfs.readlock() aren't atomic action.
Therefore, failure of the former doesn't ensure success of the latter.
Before this patch, lock is unintentionally acquired, if ENOENT
causes failure of vfs.readlock() while 5 times retrying, because
lock._trylock() returns to caller silently after retrying, and
lock.lock() assumes that lock._trylock() returns successfully only if
lock is acquired.
In this case, lock symlink (or file) isn't created, even though lock
is treated as acquired in memory.
To avoid this issue, this patch makes lock._trylock() raise
LockHeld(EAGAIN) at the end of it, if lock isn't acquired while
retrying.
An empty "locker" meaning "busy for frequent lock/unlock by many
processes" might appear in an abortion message, if lock acquisition
fails. Therefore, this patch also does:
- use '%r' to increase visibility of "locker", even if it is empty
- show hint message to explain what empty "locker" means
2017-05-01 13:59:13 +03:00
|
|
|
reason = _('lock held by %r') % inst.locker
|
2016-11-24 03:48:40 +03:00
|
|
|
ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
|
lock: avoid unintentional lock acquisition at failure of readlock
Acquiring lock by vfs.makelock() and getting lock holder (aka
"locker") information by vfs.readlock() aren't atomic action.
Therefore, failure of the former doesn't ensure success of the latter.
Before this patch, lock is unintentionally acquired, if ENOENT
causes failure of vfs.readlock() while 5 times retrying, because
lock._trylock() returns to caller silently after retrying, and
lock.lock() assumes that lock._trylock() returns successfully only if
lock is acquired.
In this case, lock symlink (or file) isn't created, even though lock
is treated as acquired in memory.
To avoid this issue, this patch makes lock._trylock() raise
LockHeld(EAGAIN) at the end of it, if lock isn't acquired while
retrying.
An empty "locker" meaning "busy for frequent lock/unlock by many
processes" might appear in an abortion message, if lock acquisition
fails. Therefore, this patch also does:
- use '%r' to increase visibility of "locker", even if it is empty
- show hint message to explain what empty "locker" means
2017-05-01 13:59:13 +03:00
|
|
|
if not inst.locker:
|
|
|
|
ui.warn(_("(lock might be very busy)\n"))
|
2016-11-24 03:48:40 +03:00
|
|
|
except error.LockUnavailable as inst:
|
|
|
|
ui.warn(_("abort: could not lock %s: %s\n") %
|
|
|
|
(inst.desc or inst.filename, inst.strerror))
|
|
|
|
except error.OutOfBandError as inst:
|
|
|
|
if inst.args:
|
|
|
|
msg = _("abort: remote error:\n")
|
|
|
|
else:
|
|
|
|
msg = _("abort: remote error\n")
|
|
|
|
ui.warn(msg)
|
|
|
|
if inst.args:
|
|
|
|
ui.warn(''.join(inst.args))
|
|
|
|
if inst.hint:
|
|
|
|
ui.warn('(%s)\n' % inst.hint)
|
|
|
|
except error.RepoError as inst:
|
|
|
|
ui.warn(_("abort: %s!\n") % inst)
|
|
|
|
if inst.hint:
|
|
|
|
ui.warn(_("(%s)\n") % inst.hint)
|
|
|
|
except error.ResponseError as inst:
|
|
|
|
ui.warn(_("abort: %s") % inst.args[0])
|
|
|
|
if not isinstance(inst.args[1], basestring):
|
|
|
|
ui.warn(" %r\n" % (inst.args[1],))
|
|
|
|
elif not inst.args[1]:
|
|
|
|
ui.warn(_(" empty string\n"))
|
|
|
|
else:
|
|
|
|
ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
|
|
|
|
except error.CensoredNodeError as inst:
|
|
|
|
ui.warn(_("abort: file censored %s!\n") % inst)
|
|
|
|
except error.RevlogError as inst:
|
|
|
|
ui.warn(_("abort: %s!\n") % inst)
|
|
|
|
except error.InterventionRequired as inst:
|
|
|
|
ui.warn("%s\n" % inst)
|
|
|
|
if inst.hint:
|
|
|
|
ui.warn(_("(%s)\n") % inst.hint)
|
|
|
|
return 1
|
2016-08-20 16:37:58 +03:00
|
|
|
except error.WdirUnsupported:
|
|
|
|
ui.warn(_("abort: working directory revision cannot be specified\n"))
|
2016-11-24 03:48:40 +03:00
|
|
|
except error.Abort as inst:
|
|
|
|
ui.warn(_("abort: %s\n") % inst)
|
|
|
|
if inst.hint:
|
|
|
|
ui.warn(_("(%s)\n") % inst.hint)
|
|
|
|
except ImportError as inst:
|
|
|
|
ui.warn(_("abort: %s!\n") % inst)
|
|
|
|
m = str(inst).split()[-1]
|
|
|
|
if m in "mpatch bdiff".split():
|
|
|
|
ui.warn(_("(did you forget to compile extensions?)\n"))
|
|
|
|
elif m in "zlib".split():
|
|
|
|
ui.warn(_("(is your Python install correct?)\n"))
|
|
|
|
except IOError as inst:
|
|
|
|
if util.safehasattr(inst, "code"):
|
|
|
|
ui.warn(_("abort: %s\n") % inst)
|
|
|
|
elif util.safehasattr(inst, "reason"):
|
|
|
|
try: # usually it is in the form (errno, strerror)
|
|
|
|
reason = inst.reason.args[1]
|
|
|
|
except (AttributeError, IndexError):
|
|
|
|
# it might be anything, for example a string
|
|
|
|
reason = inst.reason
|
|
|
|
if isinstance(reason, unicode):
|
|
|
|
# SSLError of Python 2.7.9 contains a unicode
|
2017-04-08 08:32:37 +03:00
|
|
|
reason = encoding.unitolocal(reason)
|
2016-11-24 03:48:40 +03:00
|
|
|
ui.warn(_("abort: error: %s\n") % reason)
|
|
|
|
elif (util.safehasattr(inst, "args")
|
|
|
|
and inst.args and inst.args[0] == errno.EPIPE):
|
|
|
|
pass
|
|
|
|
elif getattr(inst, "strerror", None):
|
|
|
|
if getattr(inst, "filename", None):
|
|
|
|
ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
|
|
|
|
else:
|
|
|
|
ui.warn(_("abort: %s\n") % inst.strerror)
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
except OSError as inst:
|
|
|
|
if getattr(inst, "filename", None) is not None:
|
|
|
|
ui.warn(_("abort: %s: '%s'\n") % (inst.strerror, inst.filename))
|
|
|
|
else:
|
|
|
|
ui.warn(_("abort: %s\n") % inst.strerror)
|
|
|
|
except MemoryError:
|
|
|
|
ui.warn(_("abort: out of memory\n"))
|
|
|
|
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
|
|
|
|
except socket.error as inst:
|
|
|
|
ui.warn(_("abort: %s\n") % inst.args[-1])
|
|
|
|
|
|
|
|
return -1
|
|
|
|
|
2012-10-18 06:42:06 +04:00
|
|
|
def checknewlabel(repo, lbl, kind):
|
2013-04-19 21:55:11 +04:00
|
|
|
# Do not use the "kind" parameter in ui output.
|
|
|
|
# It makes strings difficult to translate.
|
2012-10-18 01:34:46 +04:00
|
|
|
if lbl in ['tip', '.', 'null']:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("the name '%s' is reserved") % lbl)
|
2012-10-18 06:42:06 +04:00
|
|
|
for c in (':', '\0', '\n', '\r'):
|
|
|
|
if c in lbl:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("%r cannot be used in a name") % c)
|
2013-02-06 04:22:53 +04:00
|
|
|
try:
|
|
|
|
int(lbl)
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("cannot use an integer as a name"))
|
2013-02-06 04:22:53 +04:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2012-10-18 01:34:46 +04:00
|
|
|
|
2011-04-21 15:18:52 +04:00
|
|
|
def checkfilename(f):
|
|
|
|
'''Check that the filename f is an acceptable filename for a tracked file'''
|
|
|
|
if '\r' in f or '\n' in f:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
|
2011-04-21 15:18:52 +04:00
|
|
|
|
2011-04-19 14:42:53 +04:00
|
|
|
def checkportable(ui, f):
|
|
|
|
'''Check if filename f is portable and warn or abort depending on config'''
|
2011-04-21 15:18:52 +04:00
|
|
|
checkfilename(f)
|
2011-05-01 01:27:00 +04:00
|
|
|
abort, warn = checkportabilityalert(ui)
|
|
|
|
if abort or warn:
|
2011-04-30 13:08:24 +04:00
|
|
|
msg = util.checkwinfilename(f)
|
|
|
|
if msg:
|
2017-07-27 06:47:54 +03:00
|
|
|
msg = "%s: %s" % (msg, util.shellquote(f))
|
2011-05-01 01:27:00 +04:00
|
|
|
if abort:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(msg)
|
2011-05-01 01:27:00 +04:00
|
|
|
ui.warn(_("warning: %s\n") % msg)
|
2011-04-30 14:39:46 +04:00
|
|
|
|
2011-04-30 13:08:24 +04:00
|
|
|
def checkportabilityalert(ui):
|
|
|
|
'''check if the user's config requests nothing, a warning, or abort for
|
|
|
|
non-portable filenames'''
|
codemod: register core configitems using a script
This is done by a script [2] using RedBaron [1], a tool designed for doing
code refactoring. All "default" values are decided by the script and are
strongly consistent with the existing code.
There are 2 changes done manually to fix tests:
[warn] mercurial/exchange.py: experimental.bundle2-output-capture: default needs manual removal
[warn] mercurial/localrepo.py: experimental.hook-track-tags: default needs manual removal
Since RedBaron is not confident about how to indent things [2].
[1]: https://github.com/PyCQA/redbaron
[2]: https://github.com/PyCQA/redbaron/issues/100
[3]:
#!/usr/bin/env python
# codemod_configitems.py - codemod tool to fill configitems
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function
import os
import sys
import redbaron
def readpath(path):
with open(path) as f:
return f.read()
def writepath(path, content):
with open(path, 'w') as f:
f.write(content)
_configmethods = {'config', 'configbool', 'configint', 'configbytes',
'configlist', 'configdate'}
def extractstring(rnode):
"""get the string from a RedBaron string or call_argument node"""
while rnode.type != 'string':
rnode = rnode.value
return rnode.value[1:-1] # unquote, "'str'" -> "str"
def uiconfigitems(red):
"""match *.ui.config* pattern, yield (node, method, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
obj = node[-3].value
method = node[-2].value
args = node[-1]
section = args[0].value
name = args[1].value
if (obj in ('ui', 'self') and method in _configmethods
and section.type == 'string' and name.type == 'string'):
entry = (node, method, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def coreconfigitems(red):
"""match coreconfigitem(...) pattern, yield (node, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
args = node[1]
section = args[0].value
name = args[1].value
if (node[0].value == 'coreconfigitem' and section.type == 'string'
and name.type == 'string'):
entry = (node, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def registercoreconfig(cfgred, section, name, defaultrepr):
"""insert coreconfigitem to cfgred AST
section and name are plain string, defaultrepr is a string
"""
# find a place to insert the "coreconfigitem" item
entries = list(coreconfigitems(cfgred))
for node, args, nodesection, nodename in reversed(entries):
if (nodesection, nodename) < (section, name):
# insert after this entry
node.insert_after(
'coreconfigitem(%r, %r,\n'
' default=%s,\n'
')' % (section, name, defaultrepr))
return
def main(argv):
if not argv:
print('Usage: codemod_configitems.py FILES\n'
'For example, FILES could be "{hgext,mercurial}/*/**.py"')
dirname = os.path.dirname
reporoot = dirname(dirname(dirname(os.path.abspath(__file__))))
# register configitems to this destination
cfgpath = os.path.join(reporoot, 'mercurial', 'configitems.py')
cfgred = redbaron.RedBaron(readpath(cfgpath))
# state about what to do
registered = set((s, n) for n, a, s, n in coreconfigitems(cfgred))
toregister = {} # {(section, name): defaultrepr}
coreconfigs = set() # {(section, name)}, whether it's used in core
# first loop: scan all files before taking any action
for i, path in enumerate(argv):
print('(%d/%d) scanning %s' % (i + 1, len(argv), path))
iscore = ('mercurial' in path) and ('hgext' not in path)
red = redbaron.RedBaron(readpath(path))
# find all repo.ui.config* and ui.config* calls, and collect their
# section, name and default value information.
for node, method, args, section, name in uiconfigitems(red):
if section == 'web':
# [web] section has some weirdness, ignore them for now
continue
defaultrepr = None
key = (section, name)
if len(args) == 2:
if key in registered:
continue
if method == 'configlist':
defaultrepr = 'list'
elif method == 'configbool':
defaultrepr = 'False'
else:
defaultrepr = 'None'
elif len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
# try to understand the "default" value
dnode = args[2].value
if dnode.type == 'name':
if dnode.value in {'None', 'True', 'False'}:
defaultrepr = dnode.value
elif dnode.type == 'string':
defaultrepr = repr(dnode.value[1:-1])
elif dnode.type in ('int', 'float'):
defaultrepr = dnode.value
# inconsistent default
if key in toregister and toregister[key] != defaultrepr:
defaultrepr = None
# interesting to rewrite
if key not in registered:
if defaultrepr is None:
print('[note] %s: %s.%s: unsupported default'
% (path, section, name))
registered.add(key) # skip checking it again
else:
toregister[key] = defaultrepr
if iscore:
coreconfigs.add(key)
# second loop: rewrite files given "toregister" result
for path in argv:
# reconstruct redbaron - trade CPU for memory
red = redbaron.RedBaron(readpath(path))
changed = False
for node, method, args, section, name in uiconfigitems(red):
key = (section, name)
defaultrepr = toregister.get(key)
if defaultrepr is None or key not in coreconfigs:
continue
if len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
try:
del args[2]
changed = True
except Exception:
# redbaron fails to do the rewrite due to indentation
# see https://github.com/PyCQA/redbaron/issues/100
print('[warn] %s: %s.%s: default needs manual removal'
% (path, section, name))
if key not in registered:
print('registering %s.%s' % (section, name))
registercoreconfig(cfgred, section, name, defaultrepr)
registered.add(key)
if changed:
print('updating %s' % path)
writepath(path, red.dumps())
if toregister:
print('updating configitems.py')
writepath(cfgpath, cfgred.dumps())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
2017-07-15 00:22:40 +03:00
|
|
|
val = ui.config('ui', 'portablefilenames')
|
2011-04-19 14:42:53 +04:00
|
|
|
lval = val.lower()
|
|
|
|
bval = util.parsebool(val)
|
2016-12-18 21:46:52 +03:00
|
|
|
abort = pycompat.osname == 'nt' or lval == 'abort'
|
2011-04-30 13:08:24 +04:00
|
|
|
warn = bval or lval == 'warn'
|
|
|
|
if bval is None and not (warn or abort or lval == 'ignore'):
|
2011-04-19 14:42:53 +04:00
|
|
|
raise error.ConfigError(
|
|
|
|
_("ui.portablefilenames value is invalid ('%s')") % val)
|
2011-04-30 13:08:24 +04:00
|
|
|
return abort, warn
|
|
|
|
|
2011-05-01 01:27:00 +04:00
|
|
|
class casecollisionauditor(object):
|
2012-07-07 00:56:40 +04:00
|
|
|
def __init__(self, ui, abort, dirstate):
|
2011-05-01 01:27:00 +04:00
|
|
|
self._ui = ui
|
|
|
|
self._abort = abort
|
2012-07-07 00:56:40 +04:00
|
|
|
allfiles = '\0'.join(dirstate._map)
|
|
|
|
self._loweredfiles = set(encoding.lower(allfiles).split('\0'))
|
|
|
|
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()
|
2011-05-01 01:27:00 +04:00
|
|
|
|
|
|
|
def __call__(self, f):
|
2013-11-11 19:07:23 +04:00
|
|
|
if f in self._newfiles:
|
|
|
|
return
|
2011-07-28 09:36:07 +04:00
|
|
|
fl = encoding.lower(f)
|
2013-11-11 19:07:23 +04:00
|
|
|
if fl in self._loweredfiles and f not in self._dirstate:
|
2011-05-01 01:27:00 +04:00
|
|
|
msg = _('possible case-folding collision for %s') % f
|
|
|
|
if self._abort:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(msg)
|
2011-05-01 01:27:00 +04:00
|
|
|
self._ui.warn(_("warning: %s\n") % msg)
|
2012-07-07 00:56:40 +04:00
|
|
|
self._loweredfiles.add(fl)
|
|
|
|
self._newfiles.add(f)
|
2011-04-20 21:54:57 +04:00
|
|
|
|
2015-04-02 04:43:29 +03:00
|
|
|
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:
|
2016-06-10 07:12:33 +03:00
|
|
|
s = hashlib.sha1()
|
2015-04-02 04:43:29 +03:00
|
|
|
for rev in revs:
|
2017-03-12 08:47:39 +03:00
|
|
|
s.update('%d;' % rev)
|
2015-04-02 04:43:29 +03:00
|
|
|
key = s.digest()
|
|
|
|
return key
|
|
|
|
|
2011-04-21 18:06:19 +04:00
|
|
|
def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
|
2012-06-21 14:50:15 +04:00
|
|
|
'''yield every hg repository under path, always recursively.
|
|
|
|
The recurse flag will only control recursion into repo working dirs'''
|
2011-04-21 18:06:19 +04:00
|
|
|
def errhandler(err):
|
|
|
|
if err.filename == path:
|
|
|
|
raise err
|
2011-07-26 00:45:11 +04:00
|
|
|
samestat = getattr(os.path, 'samestat', None)
|
|
|
|
if followsym and samestat is not None:
|
2011-05-06 17:02:53 +04:00
|
|
|
def adddir(dirlst, dirname):
|
2011-04-21 18:06:19 +04:00
|
|
|
match = False
|
|
|
|
dirstat = os.stat(dirname)
|
|
|
|
for lstdirstat in dirlst:
|
|
|
|
if samestat(dirstat, lstdirstat):
|
|
|
|
match = True
|
|
|
|
break
|
|
|
|
if not match:
|
|
|
|
dirlst.append(dirstat)
|
|
|
|
return not match
|
|
|
|
else:
|
|
|
|
followsym = False
|
|
|
|
|
|
|
|
if (seen_dirs is None) and followsym:
|
|
|
|
seen_dirs = []
|
2011-05-06 17:02:53 +04:00
|
|
|
adddir(seen_dirs, path)
|
2011-04-21 18:06:19 +04:00
|
|
|
for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
|
|
|
|
dirs.sort()
|
|
|
|
if '.hg' in dirs:
|
|
|
|
yield root # found a repository
|
|
|
|
qroot = os.path.join(root, '.hg', 'patches')
|
|
|
|
if os.path.isdir(os.path.join(qroot, '.hg')):
|
|
|
|
yield qroot # we have a patch queue repo here
|
|
|
|
if recurse:
|
|
|
|
# avoid recursing inside the .hg directory
|
|
|
|
dirs.remove('.hg')
|
|
|
|
else:
|
|
|
|
dirs[:] = [] # don't descend further
|
|
|
|
elif followsym:
|
|
|
|
newdirs = []
|
|
|
|
for d in dirs:
|
|
|
|
fname = os.path.join(root, d)
|
2011-05-06 17:02:53 +04:00
|
|
|
if adddir(seen_dirs, fname):
|
2011-04-21 18:06:19 +04:00
|
|
|
if os.path.islink(fname):
|
|
|
|
for hgname in walkrepos(fname, True, seen_dirs):
|
|
|
|
yield hgname
|
|
|
|
else:
|
|
|
|
newdirs.append(d)
|
|
|
|
dirs[:] = newdirs
|
2011-04-21 22:14:29 +04:00
|
|
|
|
2017-06-03 13:12:01 +03:00
|
|
|
def binnode(ctx):
|
|
|
|
"""Return binary node id for a given basectx"""
|
|
|
|
node = ctx.node()
|
|
|
|
if node is None:
|
|
|
|
return wdirid
|
|
|
|
return node
|
|
|
|
|
2017-06-03 12:57:28 +03:00
|
|
|
def intrev(ctx):
|
|
|
|
"""Return integer for a given basectx that can be used in comparison or
|
2015-03-14 13:38:59 +03:00
|
|
|
arithmetic operation"""
|
2017-06-03 12:57:28 +03:00
|
|
|
rev = ctx.rev()
|
2015-03-14 13:38:59 +03:00
|
|
|
if rev is None:
|
2015-07-02 16:03:06 +03:00
|
|
|
return wdirrev
|
2015-03-14 13:38:59 +03:00
|
|
|
return rev
|
|
|
|
|
2011-05-13 23:06:28 +04:00
|
|
|
def revsingle(repo, revspec, default='.'):
|
2013-07-27 00:42:10 +04:00
|
|
|
if not revspec and revspec != 0:
|
2011-05-13 23:06:28 +04:00
|
|
|
return repo[default]
|
|
|
|
|
|
|
|
l = revrange(repo, [revspec])
|
2014-10-06 22:43:32 +04:00
|
|
|
if not l:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_('empty revision set'))
|
2014-10-07 10:37:08 +04:00
|
|
|
return repo[l.last()]
|
2011-05-13 23:06:28 +04:00
|
|
|
|
2015-08-13 10:15:43 +03:00
|
|
|
def _pairspec(revspec):
|
2017-02-19 12:19:33 +03:00
|
|
|
tree = revsetlang.parse(revspec)
|
2015-08-13 10:15:43 +03:00
|
|
|
return tree and tree[0] in ('range', 'rangepre', 'rangepost', 'rangeall')
|
|
|
|
|
2011-05-13 23:06:28 +04:00
|
|
|
def revpair(repo, revs):
|
|
|
|
if not revs:
|
|
|
|
return repo.dirstate.p1(), None
|
|
|
|
|
|
|
|
l = revrange(repo, revs)
|
|
|
|
|
2014-03-21 05:44:25 +04:00
|
|
|
if not l:
|
|
|
|
first = second = None
|
|
|
|
elif l.isascending():
|
|
|
|
first = l.min()
|
|
|
|
second = l.max()
|
|
|
|
elif l.isdescending():
|
|
|
|
first = l.max()
|
|
|
|
second = l.min()
|
|
|
|
else:
|
2014-10-07 10:37:39 +04:00
|
|
|
first = l.first()
|
|
|
|
second = l.last()
|
2014-03-21 05:44:25 +04:00
|
|
|
|
|
|
|
if first is None:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_('empty revision range'))
|
2015-11-01 04:45:46 +03:00
|
|
|
if (first == second and len(revs) >= 2
|
|
|
|
and not all(revrange(repo, [r]) for r in revs)):
|
|
|
|
raise error.Abort(_('empty revision on one side of range'))
|
2011-05-13 23:06:28 +04:00
|
|
|
|
2015-08-13 10:15:43 +03:00
|
|
|
# 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]):
|
2014-03-21 05:44:25 +04:00
|
|
|
return repo.lookup(first), None
|
2011-05-13 23:06:28 +04:00
|
|
|
|
2014-03-21 05:44:25 +04:00
|
|
|
return repo.lookup(first), repo.lookup(second)
|
2011-05-13 23:06:28 +04:00
|
|
|
|
2016-06-26 05:12:20 +03:00
|
|
|
def revrange(repo, specs):
|
|
|
|
"""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
|
2017-02-19 12:19:33 +03:00
|
|
|
that need to be expanded in the revset, call ``revsetlang.formatspec()``
|
2016-06-26 05:12:20 +03:00
|
|
|
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.
|
|
|
|
"""
|
2015-07-05 06:35:42 +03:00
|
|
|
allspecs = []
|
2016-06-26 05:12:20 +03:00
|
|
|
for spec in specs:
|
2015-01-24 16:28:14 +03:00
|
|
|
if isinstance(spec, int):
|
2017-02-19 12:19:33 +03:00
|
|
|
spec = revsetlang.formatspec('rev(%d)', spec)
|
2015-07-05 06:35:42 +03:00
|
|
|
allspecs.append(spec)
|
2017-02-19 14:00:18 +03:00
|
|
|
return repo.anyrevs(allspecs, user=True)
|
2011-05-13 23:07:16 +04:00
|
|
|
|
2015-09-26 06:29:09 +03:00
|
|
|
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:
|
|
|
|
return [parents[0], repo['null']]
|
2017-06-03 12:57:28 +03:00
|
|
|
if parents[0].rev() >= intrev(ctx) - 1:
|
2015-09-26 06:29:09 +03:00
|
|
|
return []
|
|
|
|
return parents
|
|
|
|
|
2011-05-13 23:07:16 +04:00
|
|
|
def expandpats(pats):
|
2013-10-03 20:01:21 +04:00
|
|
|
'''Expand bare globs when running on windows.
|
|
|
|
On posix we assume it already has already been done by sh.'''
|
2011-05-13 23:07:16 +04:00
|
|
|
if not util.expandglobs:
|
|
|
|
return list(pats)
|
|
|
|
ret = []
|
2013-10-03 20:01:21 +04:00
|
|
|
for kindpat in pats:
|
|
|
|
kind, pat = matchmod._patsplit(kindpat, None)
|
2011-05-13 23:07:16 +04:00
|
|
|
if kind is None:
|
|
|
|
try:
|
2013-10-03 20:01:21 +04:00
|
|
|
globbed = glob.glob(pat)
|
2011-05-13 23:07:16 +04:00
|
|
|
except re.error:
|
2013-10-03 20:01:21 +04:00
|
|
|
globbed = [pat]
|
2011-05-13 23:07:16 +04:00
|
|
|
if globbed:
|
|
|
|
ret.extend(globbed)
|
|
|
|
continue
|
2013-10-03 20:01:21 +04:00
|
|
|
ret.append(kindpat)
|
2011-05-13 23:07:16 +04:00
|
|
|
return ret
|
|
|
|
|
2015-09-24 11:00:05 +03:00
|
|
|
def matchandpats(ctx, pats=(), opts=None, globbed=False, default='relpath',
|
2015-06-06 02:24:32 +03:00
|
|
|
badfn=None):
|
2013-10-03 20:01:21 +04:00
|
|
|
'''Return a matcher and the patterns that were used.
|
2015-06-06 02:24:32 +03:00
|
|
|
The matcher will warn about bad matches, unless an alternate badfn callback
|
|
|
|
is provided.'''
|
2011-05-13 23:07:16 +04:00
|
|
|
if pats == ("",):
|
|
|
|
pats = []
|
2015-09-24 11:00:05 +03:00
|
|
|
if opts is None:
|
|
|
|
opts = {}
|
2011-05-13 23:07:16 +04:00
|
|
|
if not globbed and default == 'relpath':
|
|
|
|
pats = expandpats(pats or [])
|
2011-06-19 01:52:51 +04:00
|
|
|
|
2015-06-06 02:24:32 +03:00
|
|
|
def bad(f, msg):
|
2015-03-13 06:16:26 +03:00
|
|
|
ctx.repo().ui.warn("%s: %s\n" % (m.rel(f), msg))
|
2015-06-06 02:07:54 +03:00
|
|
|
|
2015-06-06 02:24:32 +03:00
|
|
|
if badfn is None:
|
|
|
|
badfn = bad
|
|
|
|
|
2015-06-06 02:07:54 +03:00
|
|
|
m = ctx.match(pats, opts.get('include'), opts.get('exclude'),
|
|
|
|
default, listsubrepos=opts.get('subrepos'), badfn=badfn)
|
|
|
|
|
2014-11-20 02:56:58 +03:00
|
|
|
if m.always():
|
|
|
|
pats = []
|
2012-02-26 01:11:34 +04:00
|
|
|
return m, pats
|
|
|
|
|
2015-09-24 11:00:43 +03:00
|
|
|
def match(ctx, pats=(), opts=None, globbed=False, default='relpath',
|
|
|
|
badfn=None):
|
2013-10-03 20:01:21 +04:00
|
|
|
'''Return a matcher that will warn about bad matches.'''
|
2015-06-06 02:24:32 +03:00
|
|
|
return matchandpats(ctx, pats, opts, globbed, default, badfn=badfn)[0]
|
2011-05-13 23:07:16 +04:00
|
|
|
|
|
|
|
def matchall(repo):
|
2013-10-03 20:01:21 +04:00
|
|
|
'''Return a matcher that will efficiently match everything.'''
|
2011-05-13 23:07:16 +04:00
|
|
|
return matchmod.always(repo.root, repo.getcwd())
|
|
|
|
|
2015-06-06 02:24:32 +03:00
|
|
|
def matchfiles(repo, files, badfn=None):
|
2013-10-03 20:01:21 +04:00
|
|
|
'''Return a matcher that will efficiently match exactly these files.'''
|
2015-06-06 02:24:32 +03:00
|
|
|
return matchmod.exact(repo.root, repo.getcwd(), files, badfn=badfn)
|
2011-05-13 23:07:16 +04:00
|
|
|
|
2016-01-02 14:02:57 +03:00
|
|
|
def origpath(ui, repo, filepath):
|
|
|
|
'''customize where .orig files are created
|
|
|
|
|
|
|
|
Fetch user defined path from config file: [ui] origbackuppath = <path>
|
|
|
|
Fall back to default (filepath) if not specified
|
|
|
|
'''
|
codemod: register core configitems using a script
This is done by a script [2] using RedBaron [1], a tool designed for doing
code refactoring. All "default" values are decided by the script and are
strongly consistent with the existing code.
There are 2 changes done manually to fix tests:
[warn] mercurial/exchange.py: experimental.bundle2-output-capture: default needs manual removal
[warn] mercurial/localrepo.py: experimental.hook-track-tags: default needs manual removal
Since RedBaron is not confident about how to indent things [2].
[1]: https://github.com/PyCQA/redbaron
[2]: https://github.com/PyCQA/redbaron/issues/100
[3]:
#!/usr/bin/env python
# codemod_configitems.py - codemod tool to fill configitems
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function
import os
import sys
import redbaron
def readpath(path):
with open(path) as f:
return f.read()
def writepath(path, content):
with open(path, 'w') as f:
f.write(content)
_configmethods = {'config', 'configbool', 'configint', 'configbytes',
'configlist', 'configdate'}
def extractstring(rnode):
"""get the string from a RedBaron string or call_argument node"""
while rnode.type != 'string':
rnode = rnode.value
return rnode.value[1:-1] # unquote, "'str'" -> "str"
def uiconfigitems(red):
"""match *.ui.config* pattern, yield (node, method, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
obj = node[-3].value
method = node[-2].value
args = node[-1]
section = args[0].value
name = args[1].value
if (obj in ('ui', 'self') and method in _configmethods
and section.type == 'string' and name.type == 'string'):
entry = (node, method, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def coreconfigitems(red):
"""match coreconfigitem(...) pattern, yield (node, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
args = node[1]
section = args[0].value
name = args[1].value
if (node[0].value == 'coreconfigitem' and section.type == 'string'
and name.type == 'string'):
entry = (node, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def registercoreconfig(cfgred, section, name, defaultrepr):
"""insert coreconfigitem to cfgred AST
section and name are plain string, defaultrepr is a string
"""
# find a place to insert the "coreconfigitem" item
entries = list(coreconfigitems(cfgred))
for node, args, nodesection, nodename in reversed(entries):
if (nodesection, nodename) < (section, name):
# insert after this entry
node.insert_after(
'coreconfigitem(%r, %r,\n'
' default=%s,\n'
')' % (section, name, defaultrepr))
return
def main(argv):
if not argv:
print('Usage: codemod_configitems.py FILES\n'
'For example, FILES could be "{hgext,mercurial}/*/**.py"')
dirname = os.path.dirname
reporoot = dirname(dirname(dirname(os.path.abspath(__file__))))
# register configitems to this destination
cfgpath = os.path.join(reporoot, 'mercurial', 'configitems.py')
cfgred = redbaron.RedBaron(readpath(cfgpath))
# state about what to do
registered = set((s, n) for n, a, s, n in coreconfigitems(cfgred))
toregister = {} # {(section, name): defaultrepr}
coreconfigs = set() # {(section, name)}, whether it's used in core
# first loop: scan all files before taking any action
for i, path in enumerate(argv):
print('(%d/%d) scanning %s' % (i + 1, len(argv), path))
iscore = ('mercurial' in path) and ('hgext' not in path)
red = redbaron.RedBaron(readpath(path))
# find all repo.ui.config* and ui.config* calls, and collect their
# section, name and default value information.
for node, method, args, section, name in uiconfigitems(red):
if section == 'web':
# [web] section has some weirdness, ignore them for now
continue
defaultrepr = None
key = (section, name)
if len(args) == 2:
if key in registered:
continue
if method == 'configlist':
defaultrepr = 'list'
elif method == 'configbool':
defaultrepr = 'False'
else:
defaultrepr = 'None'
elif len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
# try to understand the "default" value
dnode = args[2].value
if dnode.type == 'name':
if dnode.value in {'None', 'True', 'False'}:
defaultrepr = dnode.value
elif dnode.type == 'string':
defaultrepr = repr(dnode.value[1:-1])
elif dnode.type in ('int', 'float'):
defaultrepr = dnode.value
# inconsistent default
if key in toregister and toregister[key] != defaultrepr:
defaultrepr = None
# interesting to rewrite
if key not in registered:
if defaultrepr is None:
print('[note] %s: %s.%s: unsupported default'
% (path, section, name))
registered.add(key) # skip checking it again
else:
toregister[key] = defaultrepr
if iscore:
coreconfigs.add(key)
# second loop: rewrite files given "toregister" result
for path in argv:
# reconstruct redbaron - trade CPU for memory
red = redbaron.RedBaron(readpath(path))
changed = False
for node, method, args, section, name in uiconfigitems(red):
key = (section, name)
defaultrepr = toregister.get(key)
if defaultrepr is None or key not in coreconfigs:
continue
if len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
try:
del args[2]
changed = True
except Exception:
# redbaron fails to do the rewrite due to indentation
# see https://github.com/PyCQA/redbaron/issues/100
print('[warn] %s: %s.%s: default needs manual removal'
% (path, section, name))
if key not in registered:
print('registering %s.%s' % (section, name))
registercoreconfig(cfgred, section, name, defaultrepr)
registered.add(key)
if changed:
print('updating %s' % path)
writepath(path, red.dumps())
if toregister:
print('updating configitems.py')
writepath(cfgpath, cfgred.dumps())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
2017-07-15 00:22:40 +03:00
|
|
|
origbackuppath = ui.config('ui', 'origbackuppath')
|
2016-01-02 14:02:57 +03:00
|
|
|
if origbackuppath is None:
|
|
|
|
return filepath + ".orig"
|
|
|
|
|
|
|
|
filepathfromroot = os.path.relpath(filepath, start=repo.root)
|
|
|
|
fullorigpath = repo.wjoin(origbackuppath, filepathfromroot)
|
|
|
|
|
|
|
|
origbackupdir = repo.vfs.dirname(fullorigpath)
|
|
|
|
if not repo.vfs.exists(origbackupdir):
|
|
|
|
ui.note(_('creating directory: %s\n') % origbackupdir)
|
|
|
|
util.makedirs(origbackupdir)
|
|
|
|
|
|
|
|
return fullorigpath + ".orig"
|
|
|
|
|
2017-06-26 23:13:51 +03:00
|
|
|
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))
|
|
|
|
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
def cleanupnodes(repo, mapping, operation):
|
|
|
|
"""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)
|
|
|
|
|
|
|
|
mapping is {oldnode: [newnode]} or a iterable of nodes if they do not have
|
|
|
|
replacements. operation is a string, like "rebase".
|
|
|
|
"""
|
|
|
|
if not util.safehasattr(mapping, 'items'):
|
|
|
|
mapping = {n: () for n in mapping}
|
|
|
|
|
|
|
|
with repo.transaction('cleanup') as tr:
|
|
|
|
# Move bookmarks
|
|
|
|
bmarks = repo._bookmarks
|
2017-07-10 20:10:13 +03:00
|
|
|
bmarkchanges = []
|
2017-06-26 23:13:51 +03:00
|
|
|
allnewnodes = [n for ns in mapping.values() for n in ns]
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
for oldnode, newnodes in mapping.items():
|
|
|
|
oldbmarks = repo.nodebookmarks(oldnode)
|
|
|
|
if not oldbmarks:
|
|
|
|
continue
|
2017-06-26 23:13:51 +03:00
|
|
|
from . import bookmarks # avoid import cycle
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
if len(newnodes) > 1:
|
2017-06-26 23:13:51 +03:00
|
|
|
# usually a split, take the one with biggest rev number
|
|
|
|
newnode = next(repo.set('max(%ln)', newnodes)).node()
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
elif len(newnodes) == 0:
|
|
|
|
# move bookmark backwards
|
|
|
|
roots = list(repo.set('max((::%n) - %ln)', oldnode,
|
|
|
|
list(mapping)))
|
|
|
|
if roots:
|
|
|
|
newnode = roots[0].node()
|
|
|
|
else:
|
|
|
|
newnode = nullid
|
|
|
|
else:
|
|
|
|
newnode = newnodes[0]
|
|
|
|
repo.ui.debug('moving bookmarks %r from %s to %s\n' %
|
|
|
|
(oldbmarks, hex(oldnode), hex(newnode)))
|
2017-06-26 23:13:51 +03:00
|
|
|
# Delete divergent bookmarks being parents of related newnodes
|
|
|
|
deleterevs = repo.revs('parents(roots(%ln & (::%n))) - parents(%n)',
|
|
|
|
allnewnodes, newnode, oldnode)
|
|
|
|
deletenodes = _containsnode(repo, deleterevs)
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
for name in oldbmarks:
|
2017-07-10 20:10:13 +03:00
|
|
|
bmarkchanges.append((name, newnode))
|
|
|
|
for b in bookmarks.divergent2delete(repo, deletenodes, name):
|
|
|
|
bmarkchanges.append((b, None))
|
|
|
|
|
|
|
|
if bmarkchanges:
|
|
|
|
bmarks.applychanges(repo, tr, bmarkchanges)
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
|
|
|
|
# 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.
|
|
|
|
# NOTE: the filtering and sorting might belong to createmarkers.
|
2017-06-27 01:08:37 +03:00
|
|
|
# Unfiltered repo is needed since nodes in mapping might be hidden.
|
|
|
|
unfi = repo.unfiltered()
|
|
|
|
isobs = unfi.obsstore.successors.__contains__
|
|
|
|
torev = unfi.changelog.rev
|
|
|
|
sortfunc = lambda ns: torev(ns[0])
|
2017-07-09 16:11:19 +03:00
|
|
|
rels = [(unfi[n], tuple(unfi[m] for m in s))
|
scmutil: add a cleanupnodes method for developers
It's now common that an old node gets replaced by zero or more new nodes,
that could happen with amend, rebase, histedit, etc. And it's a common
requirement to do bookmark movements, strip or obsolete nodes and even
moving working copy parent.
Previously, amend, rebase, history have their own logic doing the above.
This patch is an attempt to unify them and future code.
This enables new developers to be able to do "replace X with Y" thing
correctly, without any knowledge about bookmarks, strip or obsstore.
The next step will be migrating rebase to the new API, so it works inside a
transaction, and its code could be simplified.
2017-06-25 23:31:56 +03:00
|
|
|
for n, s in sorted(mapping.items(), key=sortfunc)
|
|
|
|
if s or not isobs(n)]
|
|
|
|
obsolete.createmarkers(repo, rels, operation=operation)
|
|
|
|
else:
|
|
|
|
from . import repair # avoid import cycle
|
|
|
|
repair.delayedstrip(repo.ui, repo, list(mapping), operation)
|
|
|
|
|
2015-09-24 11:04:10 +03:00
|
|
|
def addremove(repo, matcher, prefix, opts=None, dry_run=None, similarity=None):
|
|
|
|
if opts is None:
|
|
|
|
opts = {}
|
2014-11-10 03:57:02 +03:00
|
|
|
m = matcher
|
2011-05-13 23:07:16 +04:00
|
|
|
if dry_run is None:
|
|
|
|
dry_run = opts.get('dry_run')
|
|
|
|
if similarity is None:
|
|
|
|
similarity = float(opts.get('similarity') or 0)
|
2014-11-10 03:57:02 +03:00
|
|
|
|
2014-11-25 06:27:49 +03:00
|
|
|
ret = 0
|
|
|
|
join = lambda f: os.path.join(prefix, f)
|
|
|
|
|
|
|
|
wctx = repo[None]
|
|
|
|
for subpath in sorted(wctx.substate):
|
2016-08-16 11:15:12 +03:00
|
|
|
submatch = matchmod.subdirmatcher(subpath, m)
|
|
|
|
if opts.get('subrepos') or m.exact(subpath) or any(submatch.files()):
|
2014-11-25 06:27:49 +03:00
|
|
|
sub = wctx.sub(subpath)
|
|
|
|
try:
|
|
|
|
if sub.addremove(submatch, prefix, opts, dry_run, similarity):
|
|
|
|
ret = 1
|
|
|
|
except error.LookupError:
|
|
|
|
repo.ui.status(_("skipping missing subrepository: %s\n")
|
|
|
|
% join(subpath))
|
|
|
|
|
2012-02-25 02:52:32 +04:00
|
|
|
rejected = []
|
2014-11-26 22:27:36 +03:00
|
|
|
def badfn(f, msg):
|
|
|
|
if f in m.files():
|
2015-06-05 04:25:07 +03:00
|
|
|
m.bad(f, msg)
|
2014-11-26 22:27:36 +03:00
|
|
|
rejected.append(f)
|
2012-02-25 02:52:32 +04:00
|
|
|
|
2015-06-05 04:25:07 +03:00
|
|
|
badmatch = matchmod.badmatch(m, badfn)
|
|
|
|
added, unknown, deleted, removed, forgotten = _interestingfiles(repo,
|
|
|
|
badmatch)
|
2013-04-02 21:56:24 +04:00
|
|
|
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
unknownset = set(unknown + forgotten)
|
2013-04-02 21:56:24 +04:00
|
|
|
toprint = unknownset.copy()
|
|
|
|
toprint.update(deleted)
|
|
|
|
for abs in sorted(toprint):
|
|
|
|
if repo.ui.verbose or not m.exact(abs):
|
|
|
|
if abs in unknownset:
|
2014-11-27 18:16:56 +03:00
|
|
|
status = _('adding %s\n') % m.uipath(abs)
|
2013-04-02 21:56:24 +04:00
|
|
|
else:
|
2014-11-27 18:16:56 +03:00
|
|
|
status = _('removing %s\n') % m.uipath(abs)
|
2013-04-02 21:56:24 +04:00
|
|
|
repo.ui.status(status)
|
|
|
|
|
2013-04-04 03:32:41 +04:00
|
|
|
renames = _findrenames(repo, m, added + unknown, removed + deleted,
|
|
|
|
similarity)
|
2011-05-13 23:07:16 +04:00
|
|
|
|
|
|
|
if not dry_run:
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
_markchanges(repo, unknown + forgotten, deleted, renames)
|
2011-05-13 23:07:16 +04:00
|
|
|
|
2012-02-25 02:52:32 +04:00
|
|
|
for f in rejected:
|
|
|
|
if f in m.files():
|
|
|
|
return 1
|
2014-11-25 06:27:49 +03:00
|
|
|
return ret
|
2012-02-25 02:52:32 +04:00
|
|
|
|
2013-04-05 00:38:28 +04:00
|
|
|
def marktouched(repo, files, similarity=0.0):
|
|
|
|
'''Assert that files have somehow been operated upon. files are relative to
|
|
|
|
the repo root.'''
|
2015-06-06 02:24:32 +03:00
|
|
|
m = matchfiles(repo, files, badfn=lambda x, y: rejected.append(x))
|
2013-04-05 00:38:28 +04:00
|
|
|
rejected = []
|
|
|
|
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
added, unknown, deleted, removed, forgotten = _interestingfiles(repo, m)
|
2013-04-05 00:38:28 +04:00
|
|
|
|
|
|
|
if repo.ui.verbose:
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
unknownset = set(unknown + forgotten)
|
2013-04-05 00:38:28 +04:00
|
|
|
toprint = unknownset.copy()
|
|
|
|
toprint.update(deleted)
|
|
|
|
for abs in sorted(toprint):
|
|
|
|
if abs in unknownset:
|
|
|
|
status = _('adding %s\n') % abs
|
|
|
|
else:
|
|
|
|
status = _('removing %s\n') % abs
|
|
|
|
repo.ui.status(status)
|
|
|
|
|
|
|
|
renames = _findrenames(repo, m, added + unknown, removed + deleted,
|
|
|
|
similarity)
|
|
|
|
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
_markchanges(repo, unknown + forgotten, deleted, renames)
|
2013-04-05 00:38:28 +04:00
|
|
|
|
|
|
|
for f in rejected:
|
|
|
|
if f in m.files():
|
|
|
|
return 1
|
|
|
|
return 0
|
|
|
|
|
2013-04-03 04:19:36 +04:00
|
|
|
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.'''
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
added, unknown, deleted, removed, forgotten = [], [], [], [], []
|
2017-07-26 16:10:15 +03:00
|
|
|
audit_path = pathutil.pathauditor(repo.root, cached=True)
|
2013-04-03 04:19:36 +04:00
|
|
|
|
|
|
|
ctx = repo[None]
|
|
|
|
dirstate = repo.dirstate
|
2013-09-05 05:42:55 +04:00
|
|
|
walkresults = dirstate.walk(matcher, sorted(ctx.substate), True, False,
|
|
|
|
full=False)
|
2013-04-03 04:19:36 +04:00
|
|
|
for abs, st in walkresults.iteritems():
|
|
|
|
dstate = dirstate[abs]
|
|
|
|
if dstate == '?' and audit_path.check(abs):
|
|
|
|
unknown.append(abs)
|
|
|
|
elif dstate != 'r' and not st:
|
|
|
|
deleted.append(abs)
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
elif dstate == 'r' and st:
|
|
|
|
forgotten.append(abs)
|
2013-04-03 04:19:36 +04:00
|
|
|
# for finding renames
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
elif dstate == 'r' and not st:
|
2013-04-03 04:19:36 +04:00
|
|
|
removed.append(abs)
|
|
|
|
elif dstate == 'a':
|
|
|
|
added.append(abs)
|
|
|
|
|
addremove: add back forgotten files (BC)
After running "hg forget README && hg addremove", README will still be
reported as removed, while "hg forget README && hg add README" adds it
back so it gets reported as clean. It seems like they should behave
the same. Furthermore, it seems like no files should remain untracked
after 'hg addremove && hg commit' (or 'hg commit -A'). For these
reasons, change the behavior of addremove so it does add forgotten
files back.
The problem is with scmutil._interestingfiles(), which reports the
file as removed, so scmutil.addremove() does not add it. Fix by
teaching _interestingfiles() to report forgotten files separately from
removed files and make addremove() add forgotten files back. However,
do not treat forgotten files as sources for rename detection. Note
that since removed and forgotten files are treated the same before
this change, forgotten files were considered sources for rename
detection.
Also update the other caller, marktouched(), in the same way as
addremove().
2014-11-09 10:13:39 +03:00
|
|
|
return added, unknown, deleted, removed, forgotten
|
2013-04-03 04:19:36 +04:00
|
|
|
|
2013-04-04 03:32:41 +04:00
|
|
|
def _findrenames(repo, matcher, added, removed, similarity):
|
|
|
|
'''Find renames from removed files to added ones.'''
|
|
|
|
renames = {}
|
|
|
|
if similarity > 0:
|
|
|
|
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(_('recording removal of %s as rename to %s '
|
|
|
|
'(%d%% similar)\n') %
|
|
|
|
(matcher.rel(old), matcher.rel(new),
|
|
|
|
score * 100))
|
|
|
|
renames[new] = old
|
|
|
|
return renames
|
|
|
|
|
2013-04-04 02:53:59 +04:00
|
|
|
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]
|
2016-01-16 00:14:49 +03:00
|
|
|
with repo.wlock():
|
2013-04-04 02:53:59 +04:00
|
|
|
wctx.forget(deleted)
|
|
|
|
wctx.add(unknown)
|
|
|
|
for new, old in renames.iteritems():
|
|
|
|
wctx.copy(old, new)
|
|
|
|
|
2011-05-13 23:07:16 +04:00
|
|
|
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
|
|
|
|
if dst == origsrc: # copying back a copy?
|
|
|
|
if repo.dirstate[dst] not in 'mn' and not dryrun:
|
|
|
|
repo.dirstate.normallookup(dst)
|
|
|
|
else:
|
|
|
|
if repo.dirstate[origsrc] == 'a' and origsrc == src:
|
|
|
|
if not ui.quiet:
|
|
|
|
ui.warn(_("%s has not been committed yet, so no copy "
|
|
|
|
"data will be stored for %s.\n")
|
|
|
|
% (repo.pathto(origsrc, cwd), repo.pathto(dst, cwd)))
|
|
|
|
if repo.dirstate[dst] in '?r' and not dryrun:
|
|
|
|
wctx.add([dst])
|
|
|
|
elif not dryrun:
|
|
|
|
wctx.copy(origsrc, dst)
|
2011-05-31 21:16:18 +04:00
|
|
|
|
|
|
|
def readrequires(opener, supported):
|
|
|
|
'''Reads and parses .hg/requires and checks if all entries found
|
|
|
|
are in the list of supported features.'''
|
|
|
|
requirements = set(opener.read("requires").splitlines())
|
2011-06-25 04:30:24 +04:00
|
|
|
missings = []
|
2011-05-31 21:16:18 +04:00
|
|
|
for r in requirements:
|
|
|
|
if r not in supported:
|
2011-06-01 00:55:23 +04:00
|
|
|
if not r or not r[0].isalnum():
|
|
|
|
raise error.RequirementError(_(".hg/requires file is corrupt"))
|
2011-06-25 04:30:24 +04:00
|
|
|
missings.append(r)
|
|
|
|
missings.sort()
|
|
|
|
if missings:
|
2012-05-12 17:54:54 +04:00
|
|
|
raise error.RequirementError(
|
2014-03-19 03:18:30 +04:00
|
|
|
_("repository requires features unknown to this Mercurial: %s")
|
|
|
|
% " ".join(missings),
|
2015-09-30 23:43:49 +03:00
|
|
|
hint=_("see https://mercurial-scm.org/wiki/MissingRequirement"
|
2014-03-19 03:18:30 +04:00
|
|
|
" for more information"))
|
2011-05-31 21:16:18 +04:00
|
|
|
return requirements
|
2011-07-09 20:06:59 +04:00
|
|
|
|
2015-04-14 01:11:47 +03:00
|
|
|
def writerequires(opener, requirements):
|
2016-01-03 02:19:47 +03:00
|
|
|
with opener('requires', 'w') as fp:
|
|
|
|
for r in sorted(requirements):
|
|
|
|
fp.write("%s\n" % r)
|
2015-04-14 01:11:47 +03:00
|
|
|
|
2013-11-17 01:19:06 +04:00
|
|
|
class filecachesubentry(object):
|
2013-11-17 01:33:33 +04:00
|
|
|
def __init__(self, path, stat):
|
2011-07-09 20:06:59 +04:00
|
|
|
self.path = path
|
2013-01-11 01:54:53 +04:00
|
|
|
self.cachestat = None
|
|
|
|
self._cacheable = None
|
2011-07-09 20:06:59 +04:00
|
|
|
|
2013-01-11 01:54:53 +04:00
|
|
|
if stat:
|
2013-11-17 01:19:06 +04:00
|
|
|
self.cachestat = filecachesubentry.stat(self.path)
|
2013-01-11 01:54:53 +04:00
|
|
|
|
|
|
|
if self.cachestat:
|
|
|
|
self._cacheable = self.cachestat.cacheable()
|
|
|
|
else:
|
|
|
|
# None means we don't know yet
|
|
|
|
self._cacheable = None
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
def refresh(self):
|
|
|
|
if self.cacheable():
|
2013-11-17 01:19:06 +04:00
|
|
|
self.cachestat = filecachesubentry.stat(self.path)
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
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
|
|
|
|
|
2013-11-17 01:19:06 +04:00
|
|
|
newstat = filecachesubentry.stat(self.path)
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
# 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)
|
2015-06-24 08:20:08 +03:00
|
|
|
except OSError as e:
|
2011-07-09 20:06:59 +04:00
|
|
|
if e.errno != errno.ENOENT:
|
|
|
|
raise
|
|
|
|
|
2013-11-17 01:24:26 +04:00
|
|
|
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()
|
|
|
|
|
2011-07-09 20:06:59 +04:00
|
|
|
class filecache(object):
|
2013-11-17 01:29:39 +04:00
|
|
|
'''A property like decorator that tracks files under .hg/ for updates.
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
Records stat info when called in _filecache.
|
|
|
|
|
2013-11-17 01:29:39 +04:00
|
|
|
On subsequent calls, compares old stat info with new info, and recreates the
|
|
|
|
object when any of the files changes, updating the new stat info in
|
|
|
|
_filecache.
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
Mercurial either atomic renames or appends for files under .hg,
|
|
|
|
so to ensure the cache is reliable we need the filesystem to be able
|
|
|
|
to tell us if a file has been replaced. If it can't, we fallback to
|
2015-08-28 17:53:55 +03:00
|
|
|
recreating the object on every call (essentially the same behavior as
|
2013-11-17 01:29:39 +04:00
|
|
|
propertycache).
|
|
|
|
|
|
|
|
'''
|
|
|
|
def __init__(self, *paths):
|
|
|
|
self.paths = paths
|
2012-03-01 19:39:58 +04:00
|
|
|
|
|
|
|
def join(self, obj, fname):
|
2013-11-17 01:29:39 +04:00
|
|
|
"""Used to compute the runtime path of a cached file.
|
2012-03-01 19:39:58 +04:00
|
|
|
|
|
|
|
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).
|
|
|
|
"""
|
2016-08-05 15:24:53 +03:00
|
|
|
raise NotImplementedError
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
def __call__(self, func):
|
|
|
|
self.func = func
|
2017-03-16 04:02:33 +03:00
|
|
|
self.name = func.__name__.encode('ascii')
|
2011-07-09 20:06:59 +04:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __get__(self, obj, type=None):
|
2016-06-17 22:06:09 +03:00
|
|
|
# if accessed on the class, return the descriptor itself.
|
|
|
|
if obj is None:
|
|
|
|
return self
|
2012-02-15 22:02:35 +04:00
|
|
|
# do we need to check if the file changed?
|
|
|
|
if self.name in obj.__dict__:
|
2012-12-17 17:25:45 +04:00
|
|
|
assert self.name in obj._filecache, self.name
|
2012-02-15 22:02:35 +04:00
|
|
|
return obj.__dict__[self.name]
|
|
|
|
|
2011-07-09 20:06:59 +04:00
|
|
|
entry = obj._filecache.get(self.name)
|
|
|
|
|
|
|
|
if entry:
|
|
|
|
if entry.changed():
|
|
|
|
entry.obj = self.func(obj)
|
|
|
|
else:
|
2013-11-17 01:29:39 +04:00
|
|
|
paths = [self.join(obj, path) for path in self.paths]
|
2011-07-09 20:06:59 +04:00
|
|
|
|
|
|
|
# We stat -before- creating the object so our cache doesn't lie if
|
|
|
|
# a writer modified between the time we read and stat
|
2013-11-17 01:29:39 +04:00
|
|
|
entry = filecacheentry(paths, True)
|
2011-07-09 20:06:59 +04:00
|
|
|
entry.obj = self.func(obj)
|
|
|
|
|
|
|
|
obj._filecache[self.name] = entry
|
|
|
|
|
2012-02-15 22:02:35 +04:00
|
|
|
obj.__dict__[self.name] = entry.obj
|
2011-07-09 20:06:59 +04:00
|
|
|
return entry.obj
|
2012-02-15 22:02:35 +04:00
|
|
|
|
|
|
|
def __set__(self, obj, value):
|
2012-12-17 17:25:45 +04:00
|
|
|
if self.name not in obj._filecache:
|
|
|
|
# we add an entry for the missing value because X in __dict__
|
|
|
|
# implies X in _filecache
|
2013-11-17 01:29:39 +04:00
|
|
|
paths = [self.join(obj, path) for path in self.paths]
|
|
|
|
ce = filecacheentry(paths, False)
|
2012-12-17 17:25:45 +04:00
|
|
|
obj._filecache[self.name] = ce
|
|
|
|
else:
|
|
|
|
ce = obj._filecache[self.name]
|
|
|
|
|
|
|
|
ce.obj = value # update cached copy
|
2012-02-15 22:02:35 +04:00
|
|
|
obj.__dict__[self.name] = value # update copy returned by obj.x
|
|
|
|
|
|
|
|
def __delete__(self, obj):
|
|
|
|
try:
|
|
|
|
del obj.__dict__[self.name]
|
|
|
|
except KeyError:
|
2013-01-01 22:51:00 +04:00
|
|
|
raise AttributeError(self.name)
|
2015-10-06 00:34:52 +03:00
|
|
|
|
|
|
|
def _locksub(repo, lock, envvar, cmd, environ=None, *args, **kwargs):
|
|
|
|
if lock is None:
|
|
|
|
raise error.LockInheritanceContractViolation(
|
|
|
|
'lock can only be inherited while held')
|
|
|
|
if environ is None:
|
|
|
|
environ = {}
|
|
|
|
with lock.inherit() as locker:
|
|
|
|
environ[envvar] = locker
|
|
|
|
return repo.ui.system(cmd, environ=environ, *args, **kwargs)
|
2015-10-06 00:37:59 +03:00
|
|
|
|
|
|
|
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."""
|
|
|
|
return _locksub(repo, repo.currentwlock(), 'HG_WLOCK_LOCKER', cmd, *args,
|
|
|
|
**kwargs)
|
2015-11-02 19:52:34 +03:00
|
|
|
|
|
|
|
def gdinitconfig(ui):
|
|
|
|
"""helper function to know if a repo should be created as general delta
|
2015-11-02 18:59:12 +03:00
|
|
|
"""
|
|
|
|
# experimental config: format.generaldelta
|
2017-06-30 04:42:23 +03:00
|
|
|
return (ui.configbool('format', 'generaldelta')
|
2017-06-30 04:42:29 +03:00
|
|
|
or ui.configbool('format', 'usegeneraldelta'))
|
2015-11-02 19:52:34 +03:00
|
|
|
|
2015-11-02 18:59:12 +03:00
|
|
|
def gddeltaconfig(ui):
|
|
|
|
"""helper function to know if incoming delta should be optimised
|
|
|
|
"""
|
2015-11-02 19:52:34 +03:00
|
|
|
# experimental config: format.generaldelta
|
2017-06-30 04:42:23 +03:00
|
|
|
return ui.configbool('format', 'generaldelta')
|
2017-03-11 01:33:42 +03:00
|
|
|
|
|
|
|
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"""
|
2017-05-11 18:49:33 +03:00
|
|
|
firstlinekey = '__firstline'
|
2017-03-11 01:33:42 +03:00
|
|
|
|
|
|
|
def __init__(self, vfs, path, keys=None):
|
|
|
|
self.vfs = vfs
|
|
|
|
self.path = path
|
|
|
|
|
2017-05-11 18:49:33 +03:00
|
|
|
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."""
|
2017-03-11 01:33:42 +03:00
|
|
|
lines = self.vfs.readlines(self.path)
|
2017-05-11 18:49:33 +03:00
|
|
|
d = {}
|
|
|
|
if firstlinenonkeyval:
|
|
|
|
if not lines:
|
|
|
|
e = _("empty simplekeyvalue file")
|
|
|
|
raise error.CorruptedState(e)
|
|
|
|
# we don't want to include '\n' in the __firstline
|
|
|
|
d[self.firstlinekey] = lines[0][:-1]
|
|
|
|
del lines[0]
|
|
|
|
|
2017-03-11 01:33:42 +03:00
|
|
|
try:
|
2017-05-11 18:39:44 +03:00
|
|
|
# the 'if line.strip()' part prevents us from failing on empty
|
|
|
|
# lines which only contain '\n' therefore are not skipped
|
|
|
|
# by 'if line'
|
2017-05-11 18:49:33 +03:00
|
|
|
updatedict = dict(line[:-1].split('=', 1) for line in lines
|
|
|
|
if line.strip())
|
|
|
|
if self.firstlinekey in updatedict:
|
|
|
|
e = _("%r can't be used as a key")
|
|
|
|
raise error.CorruptedState(e % self.firstlinekey)
|
|
|
|
d.update(updatedict)
|
2017-03-11 01:33:42 +03:00
|
|
|
except ValueError as e:
|
|
|
|
raise error.CorruptedState(str(e))
|
|
|
|
return d
|
|
|
|
|
2017-05-11 18:49:33 +03:00
|
|
|
def write(self, data, firstline=None):
|
2017-03-11 01:33:42 +03:00
|
|
|
"""Write key=>value mapping to a file
|
|
|
|
data is a dict. Keys must be alphanumerical and start with a letter.
|
2017-05-11 18:49:33 +03:00
|
|
|
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"""
|
2017-03-11 01:33:42 +03:00
|
|
|
lines = []
|
2017-05-11 18:49:33 +03:00
|
|
|
if firstline is not None:
|
|
|
|
lines.append('%s\n' % firstline)
|
|
|
|
|
2017-03-11 01:33:42 +03:00
|
|
|
for k, v in data.items():
|
2017-05-11 18:49:33 +03:00
|
|
|
if k == self.firstlinekey:
|
|
|
|
e = "key name '%s' is reserved" % self.firstlinekey
|
|
|
|
raise error.ProgrammingError(e)
|
2017-03-11 01:33:42 +03:00
|
|
|
if not k[0].isalpha():
|
|
|
|
e = "keys must start with a letter in a key-value file"
|
|
|
|
raise error.ProgrammingError(e)
|
|
|
|
if not k.isalnum():
|
|
|
|
e = "invalid key name in a simple key-value file"
|
|
|
|
raise error.ProgrammingError(e)
|
|
|
|
if '\n' in v:
|
|
|
|
e = "invalid value in a simple key-value file"
|
|
|
|
raise error.ProgrammingError(e)
|
|
|
|
lines.append("%s=%s\n" % (k, v))
|
|
|
|
with self.vfs(self.path, mode='wb', atomictemp=True) as fp:
|
|
|
|
fp.write(''.join(lines))
|
2017-06-28 04:54:19 +03:00
|
|
|
|
2017-07-16 03:20:06 +03:00
|
|
|
_reportobsoletedsource = [
|
2017-07-16 03:33:14 +03:00
|
|
|
'debugobsolete',
|
2017-07-16 03:20:06 +03:00
|
|
|
'pull',
|
|
|
|
'push',
|
|
|
|
'serve',
|
|
|
|
'unbundle',
|
|
|
|
]
|
|
|
|
|
|
|
|
def registersummarycallback(repo, otr, txnname=''):
|
2017-06-28 04:54:19 +03:00
|
|
|
"""register a callback to issue a summary after the transaction is closed
|
|
|
|
"""
|
2017-07-16 03:20:06 +03:00
|
|
|
for source in _reportobsoletedsource:
|
|
|
|
if txnname.startswith(source):
|
|
|
|
reporef = weakref.ref(repo)
|
|
|
|
def reportsummary(tr):
|
|
|
|
"""the actual callback reporting the summary"""
|
|
|
|
repo = reporef()
|
|
|
|
obsoleted = obsutil.getobsoleted(repo, tr)
|
|
|
|
if obsoleted:
|
|
|
|
repo.ui.status(_('obsoleted %i changesets\n')
|
|
|
|
% len(obsoleted))
|
|
|
|
otr.addpostclose('00-txnreport', reportsummary)
|
|
|
|
break
|