[PATCH 3 of 4] error: get Abort from 'error' instead of 'util'
Pierre-Yves David
pierre-yves.david at ens-lyon.org
Thu Oct 8 14:56:14 CDT 2015
# HG changeset patch
# User Pierre-Yves David <pierre-yves.david at fb.com>
# Date 1444334145 25200
# Thu Oct 08 12:55:45 2015 -0700
# Node ID e7caec61599aa3f169741ea98950b10c4808f6c9
# Parent 938ed1b297ac735888da73310d2821b3d4219fa5
error: get Abort from 'error' instead of 'util'
The home of 'Abort' is 'error' not 'util' however, a lot of code seems to be
confused about that and gives all the credit to 'util' instead of the
hardworking 'error'. In a spirit of equity, we break the cycle of injustice and
give back to 'error' the respect it deserves. And screw that 'util' poser.
For great justice.
diff --git a/contrib/simplemerge b/contrib/simplemerge
--- a/contrib/simplemerge
+++ b/contrib/simplemerge
@@ -3,11 +3,11 @@
from mercurial import demandimport
demandimport.enable()
import sys
from mercurial.i18n import _
-from mercurial import simplemerge, fancyopts, util, ui
+from mercurial import error, simplemerge, fancyopts, util, ui
options = [('L', 'label', [], _('labels to use on conflict markers')),
('a', 'text', None, _('treat all files as text')),
('p', 'print', None,
_('print results instead of overwriting LOCAL')),
@@ -57,10 +57,10 @@ try:
sys.exit(simplemerge.simplemerge(ui.ui(), *args, **opts))
except ParseError, e:
sys.stdout.write("%s: %s\n" % (sys.argv[0], e))
showhelp()
sys.exit(1)
-except util.Abort, e:
+except error.Abort, e:
sys.stderr.write("abort: %s\n" % e)
sys.exit(255)
except KeyboardInterrupt:
sys.exit(255)
diff --git a/contrib/synthrepo.py b/contrib/synthrepo.py
--- a/contrib/synthrepo.py
+++ b/contrib/synthrepo.py
@@ -35,11 +35,11 @@ A few obvious properties that are not cu
- Executability of files
- Symlinks and binary files are ignored
'''
import bisect, collections, itertools, json, os, random, time, sys
-from mercurial import cmdutil, context, patch, scmutil, util, hg
+from mercurial import cmdutil, context, patch, scmutil, util, hg, error
from mercurial.i18n import _
from mercurial.node import nullrev, nullid, short
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
@@ -252,11 +252,11 @@ def synthesize(ui, repo, descpath, **opt
path to an alternate dictionary to use.
'''
try:
fp = hg.openpath(ui, descpath)
except Exception as err:
- raise util.Abort('%s: %s' % (descpath, err[0].strerror))
+ raise error.Abort('%s: %s' % (descpath, err[0].strerror))
desc = json.load(fp)
fp.close()
def cdf(l):
if not l:
@@ -284,11 +284,11 @@ def synthesize(ui, repo, descpath, **opt
dictfile = opts.get('dict') or '/usr/share/dict/words'
try:
fp = open(dictfile, 'rU')
except IOError as err:
- raise util.Abort('%s: %s' % (dictfile, err.strerror))
+ raise error.Abort('%s: %s' % (dictfile, err.strerror))
words = fp.read().splitlines()
fp.close()
initdirs = {}
if desc['initdirs']:
diff --git a/hgext/acl.py b/hgext/acl.py
--- a/hgext/acl.py
+++ b/hgext/acl.py
@@ -190,11 +190,11 @@ 3) Deny access to a file to anyone but u
/misty/mountains/cave/ring = !gollum
'''
from mercurial.i18n import _
-from mercurial import util, match
+from mercurial import util, match, error
import getpass, urllib
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
@@ -211,11 +211,11 @@ def _getusers(ui, group):
ui.debug('acl: "%s" not defined in [acl.groups]\n' % group)
# If no users found in group definition, get users from OS-level group
try:
return util.groupmembers(group)
except KeyError:
- raise util.Abort(_("group '%s' is undefined") % group)
+ raise error.Abort(_("group '%s' is undefined") % group)
def _usermatch(ui, user, usersorgroups):
if usersorgroups == '*':
return True
@@ -266,11 +266,11 @@ def buildmatch(ui, repo, user, key):
return match.match(repo.root, '', pats)
return util.never
def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
if hooktype not in ['pretxnchangegroup', 'pretxncommit']:
- raise util.Abort(_('config error - hook type "%s" cannot stop '
+ raise error.Abort(_('config error - hook type "%s" cannot stop '
'incoming changesets nor commits') % hooktype)
if (hooktype == 'pretxnchangegroup' and
source not in ui.config('acl', 'sources', 'serve').split()):
ui.debug('acl: changes have source "%s" - skipping\n' % source)
return
@@ -299,23 +299,23 @@ def hook(ui, repo, hooktype, node=None,
for rev in xrange(repo[node], len(repo)):
ctx = repo[rev]
branch = ctx.branch()
if denybranches and denybranches(branch):
- raise util.Abort(_('acl: user "%s" denied on branch "%s"'
+ raise error.Abort(_('acl: user "%s" denied on branch "%s"'
' (changeset "%s")')
% (user, branch, ctx))
if allowbranches and not allowbranches(branch):
- raise util.Abort(_('acl: user "%s" not allowed on branch "%s"'
+ raise error.Abort(_('acl: user "%s" not allowed on branch "%s"'
' (changeset "%s")')
% (user, branch, ctx))
ui.debug('acl: branch access granted: "%s" on branch "%s"\n'
% (ctx, branch))
for f in ctx.files():
if deny and deny(f):
- raise util.Abort(_('acl: user "%s" denied on "%s"'
+ raise error.Abort(_('acl: user "%s" denied on "%s"'
' (changeset "%s")') % (user, f, ctx))
if allow and not allow(f):
- raise util.Abort(_('acl: user "%s" not allowed on "%s"'
+ raise error.Abort(_('acl: user "%s" not allowed on "%s"'
' (changeset "%s")') % (user, f, ctx))
ui.debug('acl: path access granted: "%s"\n' % ctx)
diff --git a/hgext/bugzilla.py b/hgext/bugzilla.py
--- a/hgext/bugzilla.py
+++ b/hgext/bugzilla.py
@@ -277,11 +277,11 @@ All the above add a comment to the Bugzi
Changeset commit comment. Bug 1234.
'''
from mercurial.i18n import _
from mercurial.node import short
-from mercurial import cmdutil, mail, util
+from mercurial import cmdutil, mail, util, error
import re, time, urlparse, xmlrpclib
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
@@ -356,11 +356,11 @@ class bzmysql(bzaccess):
def __init__(self, ui):
try:
import MySQLdb as mysql
bzmysql._MySQLdb = mysql
except ImportError as err:
- raise util.Abort(_('python mysql support not available: %s') % err)
+ raise error.Abort(_('python mysql support not available: %s') % err)
bzaccess.__init__(self, ui)
host = self.ui.config('bugzilla', 'host', 'localhost')
user = self.ui.config('bugzilla', 'user', 'bugs')
@@ -390,11 +390,11 @@ class bzmysql(bzaccess):
def get_longdesc_id(self):
'''get identity of longdesc field'''
self.run('select fieldid from fielddefs where name = "longdesc"')
ids = self.cursor.fetchall()
if len(ids) != 1:
- raise util.Abort(_('unknown database schema'))
+ raise error.Abort(_('unknown database schema'))
return ids[0][0]
def filter_real_bug_ids(self, bugs):
'''filter not-existing bugs from set.'''
self.run('select bug_id from bugs where bug_id in %s' %
@@ -435,11 +435,11 @@ class bzmysql(bzaccess):
fp = util.popen('(%s) 2>&1' % cmd)
out = fp.read()
ret = fp.close()
if ret:
self.ui.warn(out)
- raise util.Abort(_('bugzilla notify command %s') %
+ raise error.Abort(_('bugzilla notify command %s') %
util.explainexit(ret)[0])
self.ui.status(_('done\n'))
def get_user_id(self, user):
'''look up numeric bugzilla user id.'''
@@ -468,16 +468,16 @@ class bzmysql(bzaccess):
userid = self.get_user_id(user)
except KeyError:
try:
defaultuser = self.ui.config('bugzilla', 'bzuser')
if not defaultuser:
- raise util.Abort(_('cannot find bugzilla user id for %s') %
+ raise error.Abort(_('cannot find bugzilla user id for %s') %
user)
userid = self.get_user_id(defaultuser)
user = defaultuser
except KeyError:
- raise util.Abort(_('cannot find bugzilla user id for %s or %s')
+ raise error.Abort(_('cannot find bugzilla user id for %s or %s')
% (user, defaultuser))
return (user, userid)
def updatebug(self, bugid, newstate, text, committer):
'''update bug state with comment text.
@@ -515,11 +515,11 @@ class bzmysql_3_0(bzmysql_2_18):
def get_longdesc_id(self):
'''get identity of longdesc field'''
self.run('select id from fielddefs where name = "longdesc"')
ids = self.cursor.fetchall()
if len(ids) != 1:
- raise util.Abort(_('unknown database schema'))
+ raise error.Abort(_('unknown database schema'))
return ids[0][0]
# Bugzilla via XMLRPC interface.
class cookietransportrequest(object):
@@ -703,11 +703,11 @@ class bzxmlrpcemail(bzxmlrpc):
def __init__(self, ui):
bzxmlrpc.__init__(self, ui)
self.bzemail = self.ui.config('bugzilla', 'bzemail')
if not self.bzemail:
- raise util.Abort(_("configuration 'bzemail' missing"))
+ raise error.Abort(_("configuration 'bzemail' missing"))
mail.validateconfig(self.ui)
def makecommandline(self, fieldname, value):
if self.bzvermajor >= 4:
return "@%s %s" % (fieldname, str(value))
@@ -733,12 +733,12 @@ class bzxmlrpcemail(bzxmlrpc):
if not matches['users']:
user = self.ui.config('bugzilla', 'user', 'bugs')
matches = self.bzproxy.User.get({'match': [user],
'token': self.bztoken})
if not matches['users']:
- raise util.Abort(_("default bugzilla user %s email not found") %
- user)
+ raise error.Abort(_("default bugzilla user %s email not found")
+ % user)
user = matches['users'][0]['email']
commands.append(self.makecommandline("id", bugid))
text = "\n".join(commands) + "\n\n" + comment
@@ -787,11 +787,11 @@ class bugzilla(object):
bzversion = self.ui.config('bugzilla', 'version')
try:
bzclass = bugzilla._versions[bzversion]
except KeyError:
- raise util.Abort(_('bugzilla version %s not supported') %
+ raise error.Abort(_('bugzilla version %s not supported') %
bzversion)
self.bzdriver = bzclass(self.ui)
self.bug_re = re.compile(
self.ui.config('bugzilla', 'regexp',
@@ -898,17 +898,17 @@ class bugzilla(object):
def hook(ui, repo, hooktype, node=None, **kwargs):
'''add comment to bugzilla for each changeset that refers to a
bugzilla bug id. only add a comment once per bug, so same change
seen multiple times does not fill bug with duplicate data.'''
if node is None:
- raise util.Abort(_('hook type %s does not pass a changeset id') %
+ raise error.Abort(_('hook type %s does not pass a changeset id') %
hooktype)
try:
bz = bugzilla(ui, repo)
ctx = repo[node]
bugs = bz.find_bugs(ctx)
if bugs:
for bug in bugs:
bz.update(bug, bugs[bug], ctx)
bz.notify(bugs, util.email(ctx.user()))
except Exception as e:
- raise util.Abort(_('Bugzilla error: %s') % e)
+ raise error.Abort(_('Bugzilla error: %s') % e)
diff --git a/hgext/censor.py b/hgext/censor.py
--- a/hgext/censor.py
+++ b/hgext/censor.py
@@ -41,59 +41,59 @@ testedwith = 'internal'
[('r', 'rev', '', _('censor file from specified revision'), _('REV')),
('t', 'tombstone', '', _('replacement tombstone data'), _('TEXT'))],
_('-r REV [-t TEXT] [FILE]'))
def censor(ui, repo, path, rev='', tombstone='', **opts):
if not path:
- raise util.Abort(_('must specify file path to censor'))
+ raise error.Abort(_('must specify file path to censor'))
if not rev:
- raise util.Abort(_('must specify revision to censor'))
+ raise error.Abort(_('must specify revision to censor'))
wctx = repo[None]
m = scmutil.match(wctx, (path,))
if m.anypats() or len(m.files()) != 1:
- raise util.Abort(_('can only specify an explicit filename'))
+ raise error.Abort(_('can only specify an explicit filename'))
path = m.files()[0]
flog = repo.file(path)
if not len(flog):
- raise util.Abort(_('cannot censor file with no history'))
+ raise error.Abort(_('cannot censor file with no history'))
rev = scmutil.revsingle(repo, rev, rev).rev()
try:
ctx = repo[rev]
except KeyError:
- raise util.Abort(_('invalid revision identifier %s') % rev)
+ raise error.Abort(_('invalid revision identifier %s') % rev)
try:
fctx = ctx.filectx(path)
except error.LookupError:
- raise util.Abort(_('file does not exist at revision %s') % rev)
+ raise error.Abort(_('file does not exist at revision %s') % rev)
fnode = fctx.filenode()
headctxs = [repo[c] for c in repo.heads()]
heads = [c for c in headctxs if path in c and c.filenode(path) == fnode]
if heads:
headlist = ', '.join([short(c.node()) for c in heads])
- raise util.Abort(_('cannot censor file in heads (%s)') % headlist,
+ raise error.Abort(_('cannot censor file in heads (%s)') % headlist,
hint=_('clean/delete and commit first'))
wp = wctx.parents()
if ctx.node() in [p.node() for p in wp]:
- raise util.Abort(_('cannot censor working directory'),
+ raise error.Abort(_('cannot censor working directory'),
hint=_('clean/delete/update first'))
flogv = flog.version & 0xFFFF
if flogv != revlog.REVLOGNG:
- raise util.Abort(
+ raise error.Abort(
_('censor does not support revlog version %d') % (flogv,))
tombstone = filelog.packmeta({"censored": tombstone}, "")
crev = fctx.filerev()
if len(tombstone) > flog.rawsize(crev):
- raise util.Abort(_(
+ raise error.Abort(_(
'censor tombstone must be no longer than censored data'))
# Using two files instead of one makes it easy to rewrite entry-by-entry
idxread = repo.svfs(flog.indexfile, 'r')
idxwrite = repo.svfs(flog.indexfile, 'wb', atomictemp=True)
diff --git a/hgext/churn.py b/hgext/churn.py
--- a/hgext/churn.py
+++ b/hgext/churn.py
@@ -7,11 +7,11 @@
# GNU General Public License version 2 or any later version.
'''command to display statistics about repository history'''
from mercurial.i18n import _
-from mercurial import patch, cmdutil, scmutil, util, commands
+from mercurial import patch, cmdutil, scmutil, util, commands, error
from mercurial import encoding
import os
import time, datetime
cmdtable = {}
@@ -25,11 +25,11 @@ testedwith = 'internal'
def maketemplater(ui, repo, tmpl):
try:
t = cmdutil.changeset_templater(ui, repo, False, None, tmpl,
None, False)
except SyntaxError as inst:
- raise util.Abort(inst.args[0])
+ raise error.Abort(inst.args[0])
return t
def changedlines(ui, repo, ctx1, ctx2, fns):
added, removed = 0, 0
fmatch = scmutil.matchfiles(repo, fns)
diff --git a/hgext/convert/bzr.py b/hgext/convert/bzr.py
--- a/hgext/convert/bzr.py
+++ b/hgext/convert/bzr.py
@@ -7,20 +7,20 @@
# This module is for handling 'bzr', that was formerly known as Bazaar-NG;
# it cannot access 'bar' repositories, but they were never used very much
import os
-from mercurial import demandimport
+from mercurial import demandimport, error
# these do not work with demandimport, blacklist
demandimport.ignore.extend([
'bzrlib.transactions',
'bzrlib.urlutils',
'ElementPath',
])
from mercurial.i18n import _
-from mercurial import util
+from mercurial import error
from common import NoRepo, commit, converter_source
try:
# bazaar imports
from bzrlib import bzrdir, revision, errors
@@ -106,11 +106,12 @@ class bzr_source(converter_source):
info = r.in_history(branch)
except errors.BzrError:
pass
revid = info.rev_id
if revid is None:
- raise util.Abort(_('%s is not a valid revision') % self.revs[0])
+ raise error.Abort(_('%s is not a valid revision')
+ % self.revs[0])
heads = [revid]
# Empty repositories return 'null:', which cannot be retrieved
heads = [h for h in heads if h != 'null:']
return heads
@@ -125,20 +126,20 @@ class bzr_source(converter_source):
return None, None
mode = self._modecache[(name, rev)]
if kind == 'symlink':
target = revtree.get_symlink_target(fileid)
if target is None:
- raise util.Abort(_('%s.%s symlink has no target')
+ raise error.Abort(_('%s.%s symlink has no target')
% (name, rev))
return target, mode
else:
sio = revtree.get_file(fileid)
return sio.read(), mode
def getchanges(self, version, full):
if full:
- raise util.Abort(_("convert from cvs do not support --full"))
+ raise error.Abort(_("convert from cvs do not support --full"))
self._modecache = {}
self._revtree = self.sourcerepo.revision_tree(version)
# get the parentids from the cache
parentids = self._parentids.pop(version)
# only diff against first parent id
diff --git a/hgext/convert/common.py b/hgext/convert/common.py
--- a/hgext/convert/common.py
+++ b/hgext/convert/common.py
@@ -5,11 +5,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import base64, errno, subprocess, os, datetime, re
import cPickle as pickle
-from mercurial import phases, util
+from mercurial import phases, util, error
from mercurial.i18n import _
propertycache = util.propertycache
def encodeargs(args):
@@ -30,11 +30,11 @@ class MissingTool(Exception):
def checktool(exe, name=None, abort=True):
name = name or exe
if not util.findexe(exe):
if abort:
- exc = util.Abort
+ exc = error.Abort
else:
exc = MissingTool
raise exc(_('cannot find required "%s" tool') % name)
class NoRepo(Exception):
@@ -71,11 +71,11 @@ class converter_source(object):
def checkhexformat(self, revstr, mapname='splicemap'):
""" fails if revstr is not a 40 byte hex. mercurial and git both uses
such format for their revision numbering
"""
if not re.match(r'[0-9a-fA-F]{40,40}$', revstr):
- raise util.Abort(_('%s entry %s is not a valid revision'
+ raise error.Abort(_('%s entry %s is not a valid revision'
' identifier') % (mapname, revstr))
def before(self):
pass
@@ -367,11 +367,11 @@ class commandline(object):
if status:
if output:
self.ui.warn(_('%s error:\n') % self.command)
self.ui.warn(output)
msg = util.explainexit(status)[0]
- raise util.Abort('%s %s' % (self.command, msg))
+ raise error.Abort('%s %s' % (self.command, msg))
def run0(self, cmd, *args, **kwargs):
output, status = self.run(cmd, *args, **kwargs)
self.checkexit(status, output)
return output
@@ -444,11 +444,11 @@ class mapfile(dict):
# Ignore blank lines
continue
try:
key, value = line.rsplit(' ', 1)
except ValueError:
- raise util.Abort(
+ raise error.Abort(
_('syntax error in %s(%d): key/value pair expected')
% (self.path, i + 1))
if key not in self:
self.order.append(key)
super(mapfile, self).__setitem__(key, value)
@@ -457,11 +457,11 @@ class mapfile(dict):
def __setitem__(self, key, value):
if self.fp is None:
try:
self.fp = open(self.path, 'a')
except IOError as err:
- raise util.Abort(_('could not open map file %r: %s') %
+ raise error.Abort(_('could not open map file %r: %s') %
(self.path, err.strerror))
self.fp.write('%s %s\n' % (key, value))
self.fp.flush()
super(mapfile, self).__setitem__(key, value)
diff --git a/hgext/convert/convcmd.py b/hgext/convert/convcmd.py
--- a/hgext/convert/convcmd.py
+++ b/hgext/convert/convcmd.py
@@ -16,11 +16,11 @@ from gnuarch import gnuarch_source
from bzr import bzr_source
from p4 import p4_source
import filemap
import os, shutil, shlex
-from mercurial import hg, util, encoding
+from mercurial import hg, util, encoding, error
from mercurial.i18n import _
orig_encoding = 'ascii'
def recode(s):
@@ -80,34 +80,34 @@ sink_converters = [
]
def convertsource(ui, path, type, revs):
exceptions = []
if type and type not in [s[0] for s in source_converters]:
- raise util.Abort(_('%s: invalid source repository type') % type)
+ raise error.Abort(_('%s: invalid source repository type') % type)
for name, source, sortmode in source_converters:
try:
if not type or name == type:
return source(ui, path, revs), sortmode
except (NoRepo, MissingTool) as inst:
exceptions.append(inst)
if not ui.quiet:
for inst in exceptions:
ui.write("%s\n" % inst)
- raise util.Abort(_('%s: missing or unsupported repository') % path)
+ raise error.Abort(_('%s: missing or unsupported repository') % path)
def convertsink(ui, path, type):
if type and type not in [s[0] for s in sink_converters]:
- raise util.Abort(_('%s: invalid destination repository type') % type)
+ raise error.Abort(_('%s: invalid destination repository type') % type)
for name, sink in sink_converters:
try:
if not type or name == type:
return sink(ui, path)
except NoRepo as inst:
ui.note(_("convert: %s\n") % inst)
except MissingTool as inst:
- raise util.Abort('%s\n' % inst)
- raise util.Abort(_('%s: unknown repository type') % path)
+ raise error.Abort('%s\n' % inst)
+ raise error.Abort(_('%s: unknown repository type') % path)
class progresssource(object):
def __init__(self, ui, source, filecount):
self.ui = ui
self.source = source
@@ -183,22 +183,22 @@ class converter(object):
lex.whitespace_split = True
lex.whitespace += ','
line = list(lex)
# check number of parents
if not (2 <= len(line) <= 3):
- raise util.Abort(_('syntax error in %s(%d): child parent1'
+ raise error.Abort(_('syntax error in %s(%d): child parent1'
'[,parent2] expected') % (path, i + 1))
for part in line:
self.source.checkrevformat(part)
child, p1, p2 = line[0], line[1:2], line[2:]
if p1 == p2:
m[child] = p1
else:
m[child] = p1 + p2
# if file does not exist or error reading, exit
except IOError:
- raise util.Abort(_('splicemap file not found or error reading %s:')
+ raise error.Abort(_('splicemap file not found or error reading %s:')
% path)
return m
def walktree(self, heads):
@@ -245,11 +245,11 @@ class converter(object):
# We do not have to wait for nodes already in dest.
if self.dest.hascommitforsplicemap(self.map.get(p, p)):
continue
# Parent is not in dest and not being converted, not good
if p not in parents:
- raise util.Abort(_('unknown splice map parent: %s') % p)
+ raise error.Abort(_('unknown splice map parent: %s') % p)
pc.append(p)
parents[c] = pc
def toposort(self, parents, sortmode):
'''Return an ordering such that every uncommitted changeset is
@@ -341,11 +341,11 @@ class converter(object):
elif sortmode == 'sourcesort':
picknext = makesourcesorter()
elif sortmode == 'closesort':
picknext = makeclosesorter()
else:
- raise util.Abort(_('unknown sort mode: %s') % sortmode)
+ raise error.Abort(_('unknown sort mode: %s') % sortmode)
children, actives = mapchildren(parents)
s = []
pendings = {}
@@ -359,19 +359,19 @@ class converter(object):
if c not in pendings:
pendings[c] = [p for p in parents[c] if p not in self.map]
try:
pendings[c].remove(n)
except ValueError:
- raise util.Abort(_('cycle detected between %s and %s')
+ raise error.Abort(_('cycle detected between %s and %s')
% (recode(c), recode(n)))
if not pendings[c]:
# Parents are converted, node is eligible
actives.insert(0, c)
pendings[c] = None
if len(s) != len(parents):
- raise util.Abort(_("not all revisions were sorted"))
+ raise error.Abort(_("not all revisions were sorted"))
return s
def writeauthormap(self):
authorfile = self.authorfile
@@ -554,20 +554,21 @@ def convert(ui, src, dest=None, revmapfi
raise
sortmodes = ('branchsort', 'datesort', 'sourcesort', 'closesort')
sortmode = [m for m in sortmodes if opts.get(m)]
if len(sortmode) > 1:
- raise util.Abort(_('more than one sort mode specified'))
+ raise error.Abort(_('more than one sort mode specified'))
if sortmode:
sortmode = sortmode[0]
else:
sortmode = defaultsort
if sortmode == 'sourcesort' and not srcc.hasnativeorder():
- raise util.Abort(_('--sourcesort is not supported by this data source'))
+ raise error.Abort(_('--sourcesort is not supported by this data source')
+ )
if sortmode == 'closesort' and not srcc.hasnativeclose():
- raise util.Abort(_('--closesort is not supported by this data source'))
+ raise error.Abort(_('--closesort is not supported by this data source'))
fmap = opts.get('filemap')
if fmap:
srcc = filemap.filemap_source(ui, srcc, fmap)
destc.setfilemapmode(True)
diff --git a/hgext/convert/cvs.py b/hgext/convert/cvs.py
--- a/hgext/convert/cvs.py
+++ b/hgext/convert/cvs.py
@@ -5,11 +5,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import os, re, socket, errno
from cStringIO import StringIO
-from mercurial import encoding, util
+from mercurial import encoding, util, error
from mercurial.i18n import _
from common import NoRepo, commit, converter_source, checktool
from common import makedatetimestamp
import cvsps
@@ -41,18 +41,18 @@ class convert_cvs(converter_source):
self.changeset = {}
maxrev = 0
if self.revs:
if len(self.revs) > 1:
- raise util.Abort(_('cvs source does not support specifying '
+ raise error.Abort(_('cvs source does not support specifying '
'multiple revs'))
# TODO: handle tags
try:
# patchset number?
maxrev = int(self.revs[0])
except ValueError:
- raise util.Abort(_('revision %s is not a patchset number')
+ raise error.Abort(_('revision %s is not a patchset number')
% self.revs[0])
d = os.getcwd()
try:
os.chdir(self.path)
@@ -148,11 +148,11 @@ class convert_cvs(converter_source):
sck = socket.socket()
sck.connect((serv, port))
sck.send("\n".join(["BEGIN AUTH REQUEST", root, user, passw,
"END AUTH REQUEST", ""]))
if sck.recv(128) != "I LOVE YOU\n":
- raise util.Abort(_("CVS pserver authentication failed"))
+ raise error.Abort(_("CVS pserver authentication failed"))
self.writep = self.readp = sck.makefile('r+')
if not conntype and root.startswith(":local:"):
conntype = "local"
@@ -191,11 +191,11 @@ class convert_cvs(converter_source):
" Merged Removed\n")
self.writep.write("valid-requests\n")
self.writep.flush()
r = self.readp.readline()
if not r.startswith("Valid-requests"):
- raise util.Abort(_('unexpected response from CVS server '
+ raise error.Abort(_('unexpected response from CVS server '
'(expected "Valid-requests", but got %r)')
% r)
if "UseUnchanged" in r:
self.writep.write("UseUnchanged\n")
self.writep.flush()
@@ -213,11 +213,11 @@ class convert_cvs(converter_source):
chunksize = 65536
output = StringIO()
while count > 0:
data = fp.read(min(count, chunksize))
if not data:
- raise util.Abort(_("%d bytes missing from remote file")
+ raise error.Abort(_("%d bytes missing from remote file")
% count)
count -= len(data)
output.write(data)
return output.getvalue()
@@ -250,22 +250,22 @@ class convert_cvs(converter_source):
count = int(self.readp.readline()[:-1])
data = chunkedread(self.readp, count)
else:
if line == "ok\n":
if mode is None:
- raise util.Abort(_('malformed response from CVS'))
+ raise error.Abort(_('malformed response from CVS'))
return (data, "x" in mode and "x" or "")
elif line.startswith("E "):
self.ui.warn(_("cvs server: %s\n") % line[2:])
elif line.startswith("Remove"):
self.readp.readline()
else:
- raise util.Abort(_("unknown CVS response: %s") % line)
+ raise error.Abort(_("unknown CVS response: %s") % line)
def getchanges(self, rev, full):
if full:
- raise util.Abort(_("convert from cvs do not support --full"))
+ raise error.Abort(_("convert from cvs do not support --full"))
self._parse()
return sorted(self.files[rev].iteritems()), {}, set()
def getcommit(self, rev):
self._parse()
diff --git a/hgext/convert/darcs.py b/hgext/convert/darcs.py
--- a/hgext/convert/darcs.py
+++ b/hgext/convert/darcs.py
@@ -5,11 +5,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from common import NoRepo, checktool, commandline, commit, converter_source
from mercurial.i18n import _
-from mercurial import util
+from mercurial import util, error
import os, shutil, tempfile, re, errno
# The naming drift of ElementTree is fun!
try:
@@ -37,15 +37,15 @@ class darcs_source(converter_source, com
raise NoRepo(_("%s does not look like a darcs repository") % path)
checktool('darcs')
version = self.run0('--version').splitlines()[0].strip()
if version < '2.1':
- raise util.Abort(_('darcs version 2.1 or newer needed (found %r)') %
- version)
+ raise error.Abort(_('darcs version 2.1 or newer needed (found %r)')
+ % version)
if "ElementTree" not in globals():
- raise util.Abort(_("Python ElementTree module is not available"))
+ raise error.Abort(_("Python ElementTree module is not available"))
self.path = os.path.realpath(path)
self.lastrev = None
self.changes = {}
@@ -156,11 +156,11 @@ class darcs_source(converter_source, com
output, status = self.run('revert', all=True, repodir=self.tmppath)
self.checkexit(status, output)
def getchanges(self, rev, full):
if full:
- raise util.Abort(_("convert from darcs do not support --full"))
+ raise error.Abort(_("convert from darcs do not support --full"))
copies = {}
changes = []
man = None
for elt in self.changes[rev].find('summary').getchildren():
if elt.tag in ('add_directory', 'remove_directory'):
@@ -190,11 +190,11 @@ class darcs_source(converter_source, com
self.lastrev = rev
return sorted(changes), copies, set()
def getfile(self, name, rev):
if rev != self.lastrev:
- raise util.Abort(_('internal calling inconsistency'))
+ raise error.Abort(_('internal calling inconsistency'))
path = os.path.join(self.tmppath, name)
try:
data = util.readfile(path)
mode = os.lstat(path).st_mode
except IOError as inst:
diff --git a/hgext/convert/filemap.py b/hgext/convert/filemap.py
--- a/hgext/convert/filemap.py
+++ b/hgext/convert/filemap.py
@@ -5,11 +5,11 @@
# GNU General Public License version 2 or any later version.
import posixpath
import shlex
from mercurial.i18n import _
-from mercurial import util, error
+from mercurial import error
from common import SKIPREV, converter_source
def rpairs(path):
'''Yield tuples with path split at '/', starting with the full path.
No leading, trailing or double '/', please.
@@ -43,11 +43,11 @@ class filemapper(object):
self.exclude = {}
self.rename = {}
self.targetprefixes = None
if path:
if self.parse(path):
- raise util.Abort(_('errors in filemap'))
+ raise error.Abort(_('errors in filemap'))
def parse(self, path):
errs = 0
def check(name, mapping, listname):
if not name:
@@ -289,11 +289,11 @@ class filemap_source(converter_source):
# indicated by i. If we're interested in any of these files,
# we're interested in rev.
try:
files = self.base.getchangedfiles(rev, i)
except NotImplementedError:
- raise util.Abort(_("source repository doesn't support --filemap"))
+ raise error.Abort(_("source repository doesn't support --filemap"))
for f in files:
if self.filemapper(f):
return True
return False
diff --git a/hgext/convert/git.py b/hgext/convert/git.py
--- a/hgext/convert/git.py
+++ b/hgext/convert/git.py
@@ -95,11 +95,11 @@ class convert_git(converter_source):
raise NoRepo(_("%s does not look like a Git repository") % path)
# The default value (50) is based on the default for 'git diff'.
similarity = ui.configint('convert', 'git.similarity', default=50)
if similarity < 0 or similarity > 100:
- raise util.Abort(_('similarity must be between 0 and 100'))
+ raise error.Abort(_('similarity must be between 0 and 100'))
if similarity > 0:
self.simopt = '-C%d%%' % similarity
findcopiesharder = ui.configbool('convert', 'git.findcopiesharder',
False)
if findcopiesharder:
@@ -121,32 +121,32 @@ class convert_git(converter_source):
def getheads(self):
if not self.revs:
heads, ret = self.gitread('git rev-parse --branches --remotes')
heads = heads.splitlines()
if ret:
- raise util.Abort(_('cannot retrieve git heads'))
+ raise error.Abort(_('cannot retrieve git heads'))
else:
heads = []
for rev in self.revs:
rawhead, ret = self.gitread("git rev-parse --verify %s" % rev)
heads.append(rawhead[:-1])
if ret:
- raise util.Abort(_('cannot retrieve git head "%s"') % rev)
+ raise error.Abort(_('cannot retrieve git head "%s"') % rev)
return heads
def catfile(self, rev, type):
if rev == hex(nullid):
raise IOError
self.catfilepipe[0].write(rev+'\n')
self.catfilepipe[0].flush()
info = self.catfilepipe[1].readline().split()
if info[1] != type:
- raise util.Abort(_('cannot read %r object at %s') % (type, rev))
+ raise error.Abort(_('cannot read %r object at %s') % (type, rev))
size = int(info[2])
data = self.catfilepipe[1].read(size)
if len(data) < size:
- raise util.Abort(_('cannot read %r object at %s: unexpected size')
+ raise error.Abort(_('cannot read %r object at %s: unexpected size')
% (type, rev))
# read the trailing newline
self.catfilepipe[1].read(1)
return data
@@ -208,11 +208,11 @@ class convert_git(converter_source):
continue
m.node = node.strip()
def getchanges(self, version, full):
if full:
- raise util.Abort(_("convert from git do not support --full"))
+ raise error.Abort(_("convert from git do not support --full"))
self.modecache = {}
fh = self.gitopen("git diff-tree -z --root -m -r %s %s" % (
self.simopt, version))
changes = []
copies = {}
@@ -281,11 +281,11 @@ class convert_git(converter_source):
# and fro doesn't really make sense
if f != '.gitmodules' and fdest != '.gitmodules':
copies[fdest] = f
entry = None
if fh.close():
- raise util.Abort(_('cannot read changes in %s') % version)
+ raise error.Abort(_('cannot read changes in %s') % version)
if subexists[0]:
if subdeleted[0]:
changes.append(('.hgsubstate', hex(nullid)))
else:
@@ -340,17 +340,17 @@ class convert_git(converter_source):
# Build complete list of tags, both annotated and bare ones
for line in fh:
line = line.strip()
if line.startswith("error:") or line.startswith("fatal:"):
- raise util.Abort(_('cannot read tags from %s') % self.path)
+ raise error.Abort(_('cannot read tags from %s') % self.path)
node, tag = line.split(None, 1)
if not tag.startswith(prefix):
continue
alltags[tag[len(prefix):]] = node
if fh.close():
- raise util.Abort(_('cannot read tags from %s') % self.path)
+ raise error.Abort(_('cannot read tags from %s') % self.path)
# Filter out tag objects for annotated tag refs
for tag in alltags:
if tag.endswith('^{}'):
tags[tag[:-3]] = alltags[tag]
@@ -374,11 +374,11 @@ class convert_git(converter_source):
else:
fh = self.gitopen('git diff-tree --name-only --root -r %s '
'"%s^%s" --' % (version, version, i + 1))
changes = [f.rstrip('\n') for f in fh]
if fh.close():
- raise util.Abort(_('cannot read changes in %s') % version)
+ raise error.Abort(_('cannot read changes in %s') % version)
return changes
def getbookmarks(self):
bookmarks = {}
diff --git a/hgext/convert/gnuarch.py b/hgext/convert/gnuarch.py
--- a/hgext/convert/gnuarch.py
+++ b/hgext/convert/gnuarch.py
@@ -6,11 +6,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from common import NoRepo, commandline, commit, converter_source
from mercurial.i18n import _
-from mercurial import encoding, util
+from mercurial import encoding, util, error
import os, shutil, tempfile, stat
from email.Parser import Parser
class gnuarch_source(converter_source, commandline):
@@ -40,11 +40,11 @@ class gnuarch_source(converter_source, c
self.execmd = 'baz'
else:
if util.findexe('tla'):
self.execmd = 'tla'
else:
- raise util.Abort(_('cannot find a GNU Arch tool'))
+ raise error.Abort(_('cannot find a GNU Arch tool'))
commandline.__init__(self, ui, self.execmd)
self.path = os.path.realpath(path)
self.tmppath = None
@@ -133,20 +133,20 @@ class gnuarch_source(converter_source, c
def getheads(self):
return self.parents[None]
def getfile(self, name, rev):
if rev != self.lastrev:
- raise util.Abort(_('internal calling inconsistency'))
+ raise error.Abort(_('internal calling inconsistency'))
if not os.path.lexists(os.path.join(self.tmppath, name)):
return None, None
return self._getfile(name, rev)
def getchanges(self, rev, full):
if full:
- raise util.Abort(_("convert from arch do not support --full"))
+ raise error.Abort(_("convert from arch do not support --full"))
self._update(rev)
changes = []
copies = {}
for f in self.changes[rev].add_files:
@@ -285,11 +285,11 @@ class gnuarch_source(converter_source, c
# Commit revision origin when dealing with a branch or tag
if 'Continuation-of' in catlog:
self.changes[rev].continuationof = self.recode(
catlog['Continuation-of'])
except Exception:
- raise util.Abort(_('could not parse cat-log of %s') % rev)
+ raise error.Abort(_('could not parse cat-log of %s') % rev)
def _parsechangeset(self, data, rev):
for l in data:
l = l.strip()
# Added file (ignore added directory)
diff --git a/hgext/convert/hg.py b/hgext/convert/hg.py
--- a/hgext/convert/hg.py
+++ b/hgext/convert/hg.py
@@ -203,11 +203,11 @@ class mercurial_sink(converter_sink):
continue
# If the file requires actual merging, abort. We don't have enough
# context to resolve merges correctly.
if action in ['m', 'dm', 'cd', 'dc']:
- raise util.Abort(_("unable to convert merge commit "
+ raise error.Abort(_("unable to convert merge commit "
"since target parents do not merge cleanly (file "
"%s, parents %s and %s)") % (file, p1ctx,
p2ctx))
elif action == 'k':
# 'keep' means nothing changed from p1
@@ -421,11 +421,11 @@ class mercurial_sink(converter_sink):
# the exact semantics of clonebranches is unclear so we can't say no
return rev in self.repo or self.clonebranches
def hascommitforsplicemap(self, rev):
if rev not in self.repo and self.clonebranches:
- raise util.Abort(_('revision %s not found in destination '
+ raise error.Abort(_('revision %s not found in destination '
'repository (lookups with clonebranches=true '
'are not implemented)') % rev)
return rev in self.repo
class mercurial_source(converter_source):
@@ -453,11 +453,11 @@ class mercurial_source(converter_source)
if hgrevs is None:
if startnode is not None:
try:
startnode = self.repo.lookup(startnode)
except error.RepoError:
- raise util.Abort(_('%s is not a valid start revision')
+ raise error.Abort(_('%s is not a valid start revision')
% startnode)
startrev = self.repo.changelog.rev(startnode)
children = {startnode: 1}
for r in self.repo.changelog.descendants([startrev]):
children[self.repo.changelog.node(r)] = 1
@@ -468,11 +468,11 @@ class mercurial_source(converter_source)
self._heads = [self.repo[r].node() for r in revs]
else:
self._heads = self.repo.heads()
else:
if revs or startnode is not None:
- raise util.Abort(_('hg.revs cannot be combined with '
+ raise error.Abort(_('hg.revs cannot be combined with '
'hg.startrev or --rev'))
nodes = set()
parents = set()
for r in scmutil.revrange(self.repo, [hgrevs]):
ctx = self.repo[r]
diff --git a/hgext/convert/monotone.py b/hgext/convert/monotone.py
--- a/hgext/convert/monotone.py
+++ b/hgext/convert/monotone.py
@@ -5,20 +5,20 @@
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
import os, re
-from mercurial import util
+from mercurial import util, error
from common import NoRepo, commit, converter_source, checktool
from common import commandline
from mercurial.i18n import _
class monotone_source(converter_source, commandline):
def __init__(self, ui, path=None, revs=None):
converter_source.__init__(self, ui, path, revs)
if revs and len(revs) > 1:
- raise util.Abort(_('monotone source does not support specifying '
+ raise error.Abort(_('monotone source does not support specifying '
'multiple revs'))
commandline.__init__(self, ui, 'mtn')
self.ui = ui
self.path = path
@@ -108,38 +108,38 @@ class monotone_source(converter_source,
read = None
commandnbr = ''
while read != ':':
read = self.mtnreadfp.read(1)
if not read:
- raise util.Abort(_('bad mtn packet - no end of commandnbr'))
+ raise error.Abort(_('bad mtn packet - no end of commandnbr'))
commandnbr += read
commandnbr = commandnbr[:-1]
stream = self.mtnreadfp.read(1)
if stream not in 'mewptl':
- raise util.Abort(_('bad mtn packet - bad stream type %s') % stream)
+ raise error.Abort(_('bad mtn packet - bad stream type %s') % stream)
read = self.mtnreadfp.read(1)
if read != ':':
- raise util.Abort(_('bad mtn packet - no divider before size'))
+ raise error.Abort(_('bad mtn packet - no divider before size'))
read = None
lengthstr = ''
while read != ':':
read = self.mtnreadfp.read(1)
if not read:
- raise util.Abort(_('bad mtn packet - no end of packet size'))
+ raise error.Abort(_('bad mtn packet - no end of packet size'))
lengthstr += read
try:
length = long(lengthstr[:-1])
except TypeError:
- raise util.Abort(_('bad mtn packet - bad packet size %s')
+ raise error.Abort(_('bad mtn packet - bad packet size %s')
% lengthstr)
read = self.mtnreadfp.read(length)
if len(read) != length:
- raise util.Abort(_("bad mtn packet - unable to read full packet "
+ raise error.Abort(_("bad mtn packet - unable to read full packet "
"read %s of %s") % (len(read), length))
return (commandnbr, stream, length, read)
def mtnstdioreadcommandoutput(self, command):
@@ -150,11 +150,11 @@ class monotone_source(converter_source,
(commandnbr, stream, length))
if stream == 'l':
# End of command
if output != '0':
- raise util.Abort(_("mtn command '%s' returned %s") %
+ raise error.Abort(_("mtn command '%s' returned %s") %
(command, output))
break
elif stream in 'ew':
# Error, warning output
self.ui.warn(_('%s error:\n') % self.command)
@@ -227,11 +227,11 @@ class monotone_source(converter_source,
else:
return self.revs
def getchanges(self, rev, full):
if full:
- raise util.Abort(_("convert from monotone do not support --full"))
+ raise error.Abort(_("convert from monotone do not support --full"))
revision = self.mtnrun("get_revision", rev).split("\n\n")
files = {}
ignoremove = {}
renameddirs = []
copies = {}
@@ -328,11 +328,11 @@ class monotone_source(converter_source,
version = 0.0
try:
versionstr = self.mtnrunsingle("interface_version")
version = float(versionstr)
except Exception:
- raise util.Abort(_("unable to determine mtn automate interface "
+ raise error.Abort(_("unable to determine mtn automate interface "
"version"))
if version >= 12.0:
self.automatestdio = True
self.ui.debug("mtn automate version %s - using automate stdio\n" %
@@ -342,16 +342,16 @@ class monotone_source(converter_source,
self.mtnwritefp, self.mtnreadfp = self._run2('automate', 'stdio',
'-d', self.path)
# read the headers
read = self.mtnreadfp.readline()
if read != 'format-version: 2\n':
- raise util.Abort(_('mtn automate stdio header unexpected: %s')
+ raise error.Abort(_('mtn automate stdio header unexpected: %s')
% read)
while read != '\n':
read = self.mtnreadfp.readline()
if not read:
- raise util.Abort(_("failed to reach end of mtn automate "
+ raise error.Abort(_("failed to reach end of mtn automate "
"stdio headers"))
else:
self.ui.debug("mtn automate version %s - not using automate stdio "
"(automate >= 12.0 - mtn >= 0.46 is needed)\n" % version)
diff --git a/hgext/convert/p4.py b/hgext/convert/p4.py
--- a/hgext/convert/p4.py
+++ b/hgext/convert/p4.py
@@ -3,11 +3,11 @@
# Copyright 2009, Frank Kingswood <frank at kingswood-consulting.co.uk>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
-from mercurial import util
+from mercurial import util, error
from mercurial.i18n import _
from common import commit, converter_source, checktool, NoRepo
import marshal
import re
@@ -68,11 +68,11 @@ class p4_source(converter_source):
r"\$(Id|Header|Date|DateTime|Change|File|Revision|Author)"
r":[^$\n]*\$")
self.re_keywords_old = re.compile("\$(Id|Header):[^$\n]*\$")
if revs and len(revs) > 1:
- raise util.Abort(_("p4 source does not support specifying "
+ raise error.Abort(_("p4 source does not support specifying "
"multiple revisions"))
self._parse(ui, path)
def _parse_view(self, path):
"Read changes affecting the path"
@@ -275,11 +275,11 @@ class p4_source(converter_source):
return contents, mode
def getchanges(self, rev, full):
if full:
- raise util.Abort(_("convert from p4 do not support --full"))
+ raise error.Abort(_("convert from p4 do not support --full"))
return self.files[rev], self.copies[rev], set()
def getcommit(self, rev):
return self.changeset[rev]
diff --git a/hgext/convert/subversion.py b/hgext/convert/subversion.py
--- a/hgext/convert/subversion.py
+++ b/hgext/convert/subversion.py
@@ -4,11 +4,11 @@
import os, re, sys, tempfile, urllib, urllib2
import xml.dom.minidom
import cPickle as pickle
-from mercurial import strutil, scmutil, util, encoding
+from mercurial import strutil, scmutil, util, encoding, error
from mercurial.i18n import _
propertycache = util.propertycache
# Subversion stuff. Works best with very recent Python SVN bindings
@@ -139,11 +139,11 @@ def get_log_child(fp, url, paths, start,
def debugsvnlog(ui, **opts):
"""Fetch SVN log in a subprocess and channel them back to parent to
avoid memory collection issues.
"""
if svn is None:
- raise util.Abort(_('debugsvnlog could not load Subversion python '
+ raise error.Abort(_('debugsvnlog could not load Subversion python '
'bindings'))
util.setbinary(sys.stdin)
util.setbinary(sys.stdout)
args = decodeargs(sys.stdin.read())
@@ -157,18 +157,18 @@ class logstream(object):
def __iter__(self):
while True:
try:
entry = pickle.load(self._stdout)
except EOFError:
- raise util.Abort(_('Mercurial failed to run itself, check'
+ raise error.Abort(_('Mercurial failed to run itself, check'
' hg executable is in PATH'))
try:
orig_paths, revnum, author, date, message = entry
except (TypeError, ValueError):
if entry is None:
break
- raise util.Abort(_("log stream exception '%s'") % entry)
+ raise error.Abort(_("log stream exception '%s'") % entry)
yield entry
def close(self):
if self._stdout:
self._stdout.close()
@@ -325,35 +325,35 @@ class svn_source(converter_source):
"to libsvn version %s")
% (self.url, svnversion))
if revs:
if len(revs) > 1:
- raise util.Abort(_('subversion source does not support '
+ raise error.Abort(_('subversion source does not support '
'specifying multiple revisions'))
try:
latest = int(revs[0])
except ValueError:
- raise util.Abort(_('svn: revision %s is not an integer') %
+ raise error.Abort(_('svn: revision %s is not an integer') %
revs[0])
self.trunkname = self.ui.config('convert', 'svn.trunk',
'trunk').strip('/')
self.startrev = self.ui.config('convert', 'svn.startrev', default=0)
try:
self.startrev = int(self.startrev)
if self.startrev < 0:
self.startrev = 0
except ValueError:
- raise util.Abort(_('svn: start revision %s is not an integer')
+ raise error.Abort(_('svn: start revision %s is not an integer')
% self.startrev)
try:
self.head = self.latest(self.module, latest)
except SvnPathNotFound:
self.head = None
if not self.head:
- raise util.Abort(_('no revision found in module %s')
+ raise error.Abort(_('no revision found in module %s')
% self.module)
self.last_changed = self.revnum(self.head)
self._changescache = (None, None)
@@ -394,12 +394,12 @@ class svn_source(converter_source):
if not self.exists(path, rev):
if self.module.endswith(path) and name == 'trunk':
# we are converting from inside this directory
return None
if cfgpath:
- raise util.Abort(_('expected %s to be at %r, but not found')
- % (name, path))
+ raise error.Abort(_('expected %s to be at %r, but not found'
+ ) % (name, path))
return None
self.ui.note(_('found %s at %r\n') % (name, path))
return path
rev = optrev(self.last_changed)
@@ -413,11 +413,11 @@ class svn_source(converter_source):
if trunk:
oldmodule = self.module or ''
self.module += '/' + trunk
self.head = self.latest(self.module, self.last_changed)
if not self.head:
- raise util.Abort(_('no revision found in module %s')
+ raise error.Abort(_('no revision found in module %s')
% self.module)
# First head in the list is the module's head
self.heads = [self.head]
if self.tags is not None:
@@ -440,15 +440,15 @@ class svn_source(converter_source):
(branch, self.revnum(brevid)))
self.heads.append(brevid)
if self.startrev and self.heads:
if len(self.heads) > 1:
- raise util.Abort(_('svn: start revision is not supported '
+ raise error.Abort(_('svn: start revision is not supported '
'with more than one branch'))
revnum = self.revnum(self.heads[0])
if revnum < self.startrev:
- raise util.Abort(
+ raise error.Abort(
_('svn: no revision found after start revision %d')
% self.startrev)
return self.heads
@@ -500,22 +500,22 @@ class svn_source(converter_source):
stop = self.lastrevs.get(module, 0)
if revnum < stop:
stop = revnum + 1
self._fetch_revisions(revnum, stop)
if rev not in self.commits:
- raise util.Abort(_('svn: revision %s not found') % revnum)
+ raise error.Abort(_('svn: revision %s not found') % revnum)
revcommit = self.commits[rev]
# caller caches the result, so free it here to release memory
del self.commits[rev]
return revcommit
def checkrevformat(self, revstr, mapname='splicemap'):
""" fails if revision format does not match the correct format"""
if not re.match(r'svn:[0-9a-f]{8,8}-[0-9a-f]{4,4}-'
'[0-9a-f]{4,4}-[0-9a-f]{4,4}-[0-9a-f]'
'{12,12}(.*)\@[0-9]+$',revstr):
- raise util.Abort(_('%s entry %s is not a valid revision'
+ raise error.Abort(_('%s entry %s is not a valid revision'
' identifier') % (mapname, revstr))
def numcommits(self):
return int(self.head.rsplit('@', 1)[1]) - self.startrev
@@ -949,11 +949,11 @@ class svn_source(converter_source):
except SvnPathNotFound:
pass
except SubversionException as xxx_todo_changeme:
(inst, num) = xxx_todo_changeme.args
if num == svn.core.SVN_ERR_FS_NO_SUCH_REVISION:
- raise util.Abort(_('svn: branch has no revision %s')
+ raise error.Abort(_('svn: branch has no revision %s')
% to_revnum)
raise
def getfile(self, file, rev):
# TODO: ra.get_file transmits the whole file instead of diffs.
@@ -1050,11 +1050,11 @@ class svn_source(converter_source):
stdin, stdout = util.popen2(util.quotecommand(cmd))
stdin.write(arg)
try:
stdin.close()
except IOError:
- raise util.Abort(_('Mercurial failed to run itself, check'
+ raise error.Abort(_('Mercurial failed to run itself, check'
' hg executable is in PATH'))
return logstream(stdout)
pre_revprop_change = '''#!/bin/sh
@@ -1300,11 +1300,11 @@ class svn_sink(converter_sink, commandli
except AttributeError:
if parents and not files:
return parents[0]
self.ui.warn(_('unexpected svn output:\n'))
self.ui.warn(output)
- raise util.Abort(_('unable to cope with svn output'))
+ raise error.Abort(_('unable to cope with svn output'))
if commit.rev:
self.run('propset', 'hg:convert-rev', commit.rev,
revprop=True, revision=rev)
if commit.branch and commit.branch != 'default':
self.run('propset', 'hg:convert-branch', commit.branch,
@@ -1327,8 +1327,8 @@ class svn_sink(converter_sink, commandli
def hascommitforsplicemap(self, rev):
# This is not correct as one can convert to an existing subversion
# repository and childmap would not list all revisions. Too bad.
if rev in self.childmap:
return True
- raise util.Abort(_('splice map revision %s not found in subversion '
+ raise error.Abort(_('splice map revision %s not found in subversion '
'child map (revision lookups are not implemented)')
% rev)
diff --git a/hgext/eol.py b/hgext/eol.py
--- a/hgext/eol.py
+++ b/hgext/eol.py
@@ -245,11 +245,11 @@ def _checkhook(ui, repo, node, headsonly
eols = {'to-lf': 'CRLF', 'to-crlf': 'LF'}
msgs = []
for node, target, f in failed:
msgs.append(_(" %s in %s should not have %s line endings") %
(f, node, eols[target]))
- raise util.Abort(_("end-of-line check failed:\n") + "\n".join(msgs))
+ raise error.Abort(_("end-of-line check failed:\n") + "\n".join(msgs))
def checkallhook(ui, repo, node, hooktype, **kwargs):
"""verify that files have expected EOLs"""
_checkhook(ui, repo, node, False)
@@ -345,10 +345,10 @@ def reposetup(ui, repo):
# We should not abort here, since the user should
# be able to say "** = native" to automatically
# have all non-binary files taken care of.
continue
if inconsistenteol(data):
- raise util.Abort(_("inconsistent newline style "
+ raise error.Abort(_("inconsistent newline style "
"in %s\n") % f)
return super(eolrepo, self).commitctx(ctx, haserror)
repo.__class__ = eolrepo
repo._hgcleardirstate()
diff --git a/hgext/extdiff.py b/hgext/extdiff.py
--- a/hgext/extdiff.py
+++ b/hgext/extdiff.py
@@ -61,11 +61,11 @@ pretty fast (at least faster than having
'''
from mercurial.i18n import _
from mercurial.node import short, nullid
from mercurial import cmdutil, scmutil, util, commands, encoding, filemerge
-from mercurial import archival
+from mercurial import archival, error
import os, shlex, shutil, tempfile, re
cmdtable = {}
command = cmdutil.command(cmdtable)
# Note for extension authors: ONLY specify testedwith = 'internal' for
@@ -125,11 +125,11 @@ def dodiff(ui, repo, cmdline, pats, opts
change = opts.get('change')
do3way = '$parent2' in cmdline
if revs and change:
msg = _('cannot specify --rev and --change at the same time')
- raise util.Abort(msg)
+ raise error.Abort(msg)
elif change:
node2 = scmutil.revsingle(repo, change, None).node()
node1a, node1b = repo.changelog.parents(node2)
else:
node1a, node2 = scmutil.revpair(repo, revs)
@@ -147,13 +147,13 @@ def dodiff(ui, repo, cmdline, pats, opts
matcher = scmutil.match(repo[node2], pats, opts)
if opts.get('patch'):
if subrepos:
- raise util.Abort(_('--patch cannot be used with --subrepos'))
+ raise error.Abort(_('--patch cannot be used with --subrepos'))
if node2 is None:
- raise util.Abort(_('--patch requires two revisions'))
+ raise error.Abort(_('--patch requires two revisions'))
else:
mod_a, add_a, rem_a = map(set, repo.status(node1a, node2, matcher,
listsubrepos=subrepos)[:3])
if do3way:
mod_b, add_b, rem_b = map(set,
diff --git a/hgext/factotum.py b/hgext/factotum.py
--- a/hgext/factotum.py
+++ b/hgext/factotum.py
@@ -45,20 +45,20 @@ service entry controls the service name
'''
from mercurial.i18n import _
from mercurial.url import passwordmgr
-from mercurial import httpconnection, util
+from mercurial import httpconnection, error
import os, urllib2
ERRMAX = 128
_executable = _mountpoint = _service = None
def auth_getkey(self, params):
if not self.ui.interactive():
- raise util.Abort(_('factotum not interactive'))
+ raise error.Abort(_('factotum not interactive'))
if 'user=' not in params:
params = '%s user?' % params
params = '%s !password?' % params
os.system("%s -g '%s'" % (_executable, params))
@@ -75,14 +75,14 @@ def auth_getuserpasswd(self, getkey, par
if status == 'ok':
if passwd.startswith("'"):
if passwd.endswith("'"):
passwd = passwd[1:-1].replace("''", "'")
else:
- raise util.Abort(_('malformed password string'))
+ raise error.Abort(_('malformed password string'))
return (user, passwd)
except (OSError, IOError):
- raise util.Abort(_('factotum not responding'))
+ raise error.Abort(_('factotum not responding'))
finally:
os.close(fd)
getkey(self, params)
def monkeypatch_method(cls):
diff --git a/hgext/fetch.py b/hgext/fetch.py
--- a/hgext/fetch.py
+++ b/hgext/fetch.py
@@ -58,11 +58,11 @@ def fetch(ui, repo, source='default', **
try:
branchnode = repo.branchtip(branch)
except error.RepoLookupError:
branchnode = None
if parent != branchnode:
- raise util.Abort(_('working directory not at branch tip'),
+ raise error.Abort(_('working directory not at branch tip'),
hint=_('use "hg update" to check out branch tip'))
wlock = lock = None
try:
wlock = repo.wlock()
@@ -71,11 +71,11 @@ def fetch(ui, repo, source='default', **
cmdutil.bailifchanged(repo)
bheads = repo.branchheads(branch)
bheads = [head for head in bheads if len(repo[head].children()) == 0]
if len(bheads) > 1:
- raise util.Abort(_('multiple heads in this branch '
+ raise error.Abort(_('multiple heads in this branch '
'(use "hg heads ." and "hg merge" to merge)'))
other = hg.peer(repo, opts, ui.expandpath(source))
ui.status(_('pulling from %s\n') %
util.hidepassword(ui.expandpath(source)))
@@ -84,11 +84,11 @@ def fetch(ui, repo, source='default', **
try:
revs = [other.lookup(rev) for rev in opts['rev']]
except error.CapabilityError:
err = _("other repository doesn't support revision lookup, "
"so a rev cannot be specified.")
- raise util.Abort(err)
+ raise error.Abort(err)
# Are there any changes at all?
modheads = exchange.pull(repo, other, heads=revs).cgresult
if modheads == 0:
return 0
diff --git a/hgext/gpg.py b/hgext/gpg.py
--- a/hgext/gpg.py
+++ b/hgext/gpg.py
@@ -4,11 +4,11 @@
# GNU General Public License version 2 or any later version.
'''commands to sign and verify changesets'''
import os, tempfile, binascii
-from mercurial import util, commands, match, cmdutil
+from mercurial import util, commands, match, cmdutil, error
from mercurial import node as hgnode
from mercurial.i18n import _
cmdtable = {}
command = cmdutil.command(cmdtable)
@@ -235,11 +235,11 @@ def sign(ui, repo, *revs, **opts):
nodes = [repo.lookup(n) for n in revs]
else:
nodes = [node for node in repo.dirstate.parents()
if node != hgnode.nullid]
if len(nodes) > 1:
- raise util.Abort(_('uncommitted merge - please provide a '
+ raise error.Abort(_('uncommitted merge - please provide a '
'specific revision'))
if not nodes:
nodes = [repo.changelog.tip()]
for n in nodes:
@@ -248,11 +248,11 @@ def sign(ui, repo, *revs, **opts):
hgnode.short(n)))
# build data
data = node2txt(repo, n, sigver)
sig = mygpg.sign(data)
if not sig:
- raise util.Abort(_("error while signing"))
+ raise error.Abort(_("error while signing"))
sig = binascii.b2a_base64(sig)
sig = sig.replace("\n", "")
sigmessage += "%s %s %s\n" % (hexnode, sigver, sig)
# write it
@@ -261,11 +261,11 @@ def sign(ui, repo, *revs, **opts):
return
if not opts["force"]:
msigs = match.exact(repo.root, '', ['.hgsigs'])
if any(repo.status(match=msigs, unknown=True, ignored=True)):
- raise util.Abort(_("working copy of .hgsigs is changed "),
+ raise error.Abort(_("working copy of .hgsigs is changed "),
hint=_("please commit .hgsigs manually"))
sigsfile = repo.wfile(".hgsigs", "ab")
sigsfile.write(sigmessage)
sigsfile.close()
@@ -285,11 +285,11 @@ def sign(ui, repo, *revs, **opts):
try:
editor = cmdutil.getcommiteditor(editform='gpg.sign', **opts)
repo.commit(message, opts['user'], opts['date'], match=msigs,
editor=editor)
except ValueError as inst:
- raise util.Abort(str(inst))
+ raise error.Abort(str(inst))
def shortkey(ui, key):
if len(key) != 16:
ui.debug("key ID \"%s\" format error\n" % key)
return key
@@ -299,6 +299,6 @@ def shortkey(ui, key):
def node2txt(repo, node, ver):
"""map a manifest into some text"""
if ver == "0":
return "%s\n" % hgnode.hex(node)
else:
- raise util.Abort(_("unknown signature version"))
+ raise error.Abort(_("unknown signature version"))
diff --git a/hgext/hgcia.py b/hgext/hgcia.py
--- a/hgext/hgcia.py
+++ b/hgext/hgcia.py
@@ -41,11 +41,11 @@ configure it, set the following options
baseurl = http://server/path/to/repo
"""
from mercurial.i18n import _
from mercurial.node import bin, short
-from mercurial import cmdutil, patch, util, mail
+from mercurial import cmdutil, patch, util, mail, error
import email.Parser
import socket, xmlrpclib
from xml.sax import saxutils
# Note for extension authors: ONLY specify testedwith = 'internal' for
@@ -231,11 +231,11 @@ class hgcia(object):
def sendrpc(self, msg):
srv = xmlrpclib.Server(self.ciaurl)
res = srv.hub.deliver(msg)
if res is not True and res != 'queued.':
- raise util.Abort(_('%s returned an error: %s') %
+ raise error.Abort(_('%s returned an error: %s') %
(self.ciaurl, res))
def sendemail(self, address, data):
p = email.Parser.Parser()
msg = p.parsestr(data)
@@ -257,11 +257,11 @@ def hook(ui, repo, hooktype, node=None,
msg = ciamsg(cia, ctx).xml()
if cia.dryrun:
ui.write(msg)
elif cia.ciaurl.startswith('mailto:'):
if not cia.emailfrom:
- raise util.Abort(_('email.from must be defined when '
+ raise error.Abort(_('email.from must be defined when '
'sending by email'))
cia.sendemail(cia.ciaurl[7:], msg)
else:
cia.sendrpc(msg)
diff --git a/hgext/histedit.py b/hgext/histedit.py
--- a/hgext/histedit.py
+++ b/hgext/histedit.py
@@ -223,11 +223,11 @@ class histeditstate(object):
try:
fp = self.repo.vfs('histedit-state', 'r')
except IOError as err:
if err.errno != errno.ENOENT:
raise
- raise util.Abort(_('no histedit in progress'))
+ raise error.Abort(_('no histedit in progress'))
try:
data = pickle.load(fp)
parentctxnode, rules, keep, topmost, replacements = data
backupfile = None
@@ -325,11 +325,11 @@ class histeditaction(object):
repo = state.repo
rulehash = rule.strip().split(' ', 1)[0]
try:
node = repo[rulehash].node()
except error.RepoError:
- raise util.Abort(_('unknown changeset %s listed') % rulehash[:12])
+ raise error.Abort(_('unknown changeset %s listed') % rulehash[:12])
return cls(state, node)
def run(self):
"""Runs the action. The default behavior is simply apply the action's
rulectx onto the current parentctx."""
@@ -433,11 +433,11 @@ def collapse(repo, first, last, commitop
ctxs = list(repo.set('%d::%d', first, last))
if not ctxs:
return None
for c in ctxs:
if not c.mutable():
- raise util.Abort(
+ raise error.Abort(
_("cannot fold into public change %s") % node.short(c.node()))
base = first.parents()[0]
# commit a new version of the old changeset, including the update
# collect all files which might be affected
@@ -658,16 +658,16 @@ def findoutgoing(ui, repo, remote=None,
if revs:
revs = [repo.lookup(rev) for rev in revs]
outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
if not outgoing.missing:
- raise util.Abort(_('no outgoing ancestors'))
+ raise error.Abort(_('no outgoing ancestors'))
roots = list(repo.revs("roots(%ln)", outgoing.missing))
if 1 < len(roots):
msg = _('there are ambiguous outgoing revisions')
hint = _('see "hg help histedit" for more detail')
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
return repo.lookup(roots[0])
actiontable = {'p': pick,
'pick': pick,
'e': edit,
@@ -730,11 +730,11 @@ def histedit(ui, repo, *freeargs, **opts
def _histedit(ui, repo, state, *freeargs, **opts):
# TODO only abort if we try and histedit mq patches, not just
# blanket if mq patches are applied somewhere
mq = getattr(repo, 'mq', None)
if mq and mq.applied:
- raise util.Abort(_('source has mq patches applied'))
+ raise error.Abort(_('source has mq patches applied'))
# basic argument incompatibility processing
outg = opts.get('outgoing')
cont = opts.get('continue')
editplan = opts.get('edit_plan')
@@ -742,43 +742,43 @@ def _histedit(ui, repo, state, *freeargs
force = opts.get('force')
rules = opts.get('commands', '')
revs = opts.get('rev', [])
goal = 'new' # This invocation goal, in new, continue, abort
if force and not outg:
- raise util.Abort(_('--force only allowed with --outgoing'))
+ raise error.Abort(_('--force only allowed with --outgoing'))
if cont:
if any((outg, abort, revs, freeargs, rules, editplan)):
- raise util.Abort(_('no arguments allowed with --continue'))
+ raise error.Abort(_('no arguments allowed with --continue'))
goal = 'continue'
elif abort:
if any((outg, revs, freeargs, rules, editplan)):
- raise util.Abort(_('no arguments allowed with --abort'))
+ raise error.Abort(_('no arguments allowed with --abort'))
goal = 'abort'
elif editplan:
if any((outg, revs, freeargs)):
- raise util.Abort(_('only --commands argument allowed with '
+ raise error.Abort(_('only --commands argument allowed with '
'--edit-plan'))
goal = 'edit-plan'
else:
if os.path.exists(os.path.join(repo.path, 'histedit-state')):
- raise util.Abort(_('history edit already in progress, try '
+ raise error.Abort(_('history edit already in progress, try '
'--continue or --abort'))
if outg:
if revs:
- raise util.Abort(_('no revisions allowed with --outgoing'))
+ raise error.Abort(_('no revisions allowed with --outgoing'))
if len(freeargs) > 1:
- raise util.Abort(
+ raise error.Abort(
_('only one repo argument allowed with --outgoing'))
else:
revs.extend(freeargs)
if len(revs) == 0:
# experimental config: histedit.defaultrev
histeditdefault = ui.config('histedit', 'defaultrev')
if histeditdefault:
revs.append(histeditdefault)
if len(revs) != 1:
- raise util.Abort(
+ raise error.Abort(
_('histedit requires exactly one ancestor revision'))
replacements = []
state.keep = opts.get('keep', False)
@@ -841,17 +841,17 @@ def _histedit(ui, repo, state, *freeargs
remote = None
root = findoutgoing(ui, repo, remote, force, opts)
else:
rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
if len(rr) != 1:
- raise util.Abort(_('The specified revisions must have '
+ raise error.Abort(_('The specified revisions must have '
'exactly one common root'))
root = rr[0].node()
revs = between(repo, root, topmost, state.keep)
if not revs:
- raise util.Abort(_('%s is not an ancestor of working directory') %
+ raise error.Abort(_('%s is not an ancestor of working directory') %
node.short(root))
ctxs = [repo[r] for r in revs]
if not rules:
comment = editcomment % (node.short(root), node.short(topmost))
@@ -945,11 +945,11 @@ def bootstrapcontinue(ui, state, opts):
s = repo.status()
if s.modified or s.added or s.removed or s.deleted:
actobj.continuedirty()
s = repo.status()
if s.modified or s.added or s.removed or s.deleted:
- raise util.Abort(_("working copy still dirty"))
+ raise error.Abort(_("working copy still dirty"))
parentctx, replacements = actobj.continueclean()
state.parentctxnode = parentctx.node()
state.replacements.extend(replacements)
@@ -962,16 +962,16 @@ def between(repo, old, new, keep):
When keep is false, the specified set can't have children."""
ctxs = list(repo.set('%n::%n', old, new))
if ctxs and not keep:
if (not obsolete.isenabled(repo, obsolete.allowunstableopt) and
repo.revs('(%ld::) - (%ld)', ctxs, ctxs)):
- raise util.Abort(_('cannot edit history that would orphan nodes'))
+ raise error.Abort(_('cannot edit history that would orphan nodes'))
if repo.revs('(%ld) and merge()', ctxs):
- raise util.Abort(_('cannot edit history that contains merges'))
+ raise error.Abort(_('cannot edit history that contains merges'))
root = ctxs[0] # list is already sorted by repo.set
if not root.mutable():
- raise util.Abort(_('cannot edit public changeset: %s') % root,
+ raise error.Abort(_('cannot edit public changeset: %s') % root,
hint=_('see "hg help phases" for details'))
return [c.node() for c in ctxs]
def makedesc(repo, action, rev):
"""build a initial action line for a ctx
@@ -1018,30 +1018,30 @@ def verifyrules(rules, repo, ctxs):
parsed = []
expected = set(c.hex() for c in ctxs)
seen = set()
for r in rules:
if ' ' not in r:
- raise util.Abort(_('malformed line "%s"') % r)
+ raise error.Abort(_('malformed line "%s"') % r)
action, rest = r.split(' ', 1)
ha = rest.strip().split(' ', 1)[0]
try:
ha = repo[ha].hex()
except error.RepoError:
- raise util.Abort(_('unknown changeset %s listed') % ha[:12])
+ raise error.Abort(_('unknown changeset %s listed') % ha[:12])
if ha not in expected:
- raise util.Abort(
+ raise error.Abort(
_('may not use changesets other than the ones listed'))
if ha in seen:
- raise util.Abort(_('duplicated command for changeset %s') %
+ raise error.Abort(_('duplicated command for changeset %s') %
ha[:12])
seen.add(ha)
if action not in actiontable or action.startswith('_'):
- raise util.Abort(_('unknown action "%s"') % action)
+ raise error.Abort(_('unknown action "%s"') % action)
parsed.append([action, ha])
missing = sorted(expected - seen) # sort to stabilize output
if missing:
- raise util.Abort(_('missing rules for changeset %s') %
+ raise error.Abort(_('missing rules for changeset %s') %
missing[0][:12],
hint=_('do you want to use the drop action?'))
return parsed
def newnodestoabort(state):
@@ -1193,11 +1193,11 @@ def stripwrapper(orig, ui, repo, nodelis
histedit_nodes = set([repo[rulehash].node() for (action, rulehash)
in state.rules if rulehash in repo])
strip_nodes = set([repo[n].node() for n in nodelist])
common_nodes = histedit_nodes & strip_nodes
if common_nodes:
- raise util.Abort(_("histedit in progress, can't strip %s")
+ raise error.Abort(_("histedit in progress, can't strip %s")
% ', '.join(node.short(x) for x in common_nodes))
return orig(ui, repo, nodelist, *args, **kwargs)
extensions.wrapfunction(repair, 'strip', stripwrapper)
diff --git a/hgext/keyword.py b/hgext/keyword.py
--- a/hgext/keyword.py
+++ b/hgext/keyword.py
@@ -81,11 +81,11 @@ Expansions spanning more than one line a
like CVS' $Log$, are not supported. A keyword template map "Log =
{desc}" expands to the first line of the changeset description.
'''
from mercurial import commands, context, cmdutil, dispatch, filelog, extensions
-from mercurial import localrepo, match, patch, templatefilters, util
+from mercurial import localrepo, match, patch, templatefilters, util, error
from mercurial import scmutil, pathutil
from mercurial.hgweb import webcommands
from mercurial.i18n import _
import os, re, tempfile
@@ -346,24 +346,24 @@ def _status(ui, repo, wctx, kwt, *pats,
Returns status of working directory.'''
if kwt:
return repo.status(match=scmutil.match(wctx, pats, opts), clean=True,
unknown=opts.get('unknown') or opts.get('all'))
if ui.configitems('keyword'):
- raise util.Abort(_('[keyword] patterns cannot match'))
- raise util.Abort(_('no [keyword] patterns configured'))
+ raise error.Abort(_('[keyword] patterns cannot match'))
+ raise error.Abort(_('no [keyword] patterns configured'))
def _kwfwrite(ui, repo, expand, *pats, **opts):
'''Selects files and passes them to kwtemplater.overwrite.'''
wctx = repo[None]
if len(wctx.parents()) > 1:
- raise util.Abort(_('outstanding uncommitted merge'))
+ raise error.Abort(_('outstanding uncommitted merge'))
kwt = kwtools['templater']
wlock = repo.wlock()
try:
status = _status(ui, repo, wctx, kwt, *pats, **opts)
if status.modified or status.added or status.removed or status.deleted:
- raise util.Abort(_('outstanding uncommitted changes'))
+ raise error.Abort(_('outstanding uncommitted changes'))
kwt.overwrite(wctx, status.clean, True, expand)
finally:
wlock.release()
@command('kwdemo',
diff --git a/hgext/largefiles/basestore.py b/hgext/largefiles/basestore.py
--- a/hgext/largefiles/basestore.py
+++ b/hgext/largefiles/basestore.py
@@ -8,11 +8,11 @@
'''base class for store implementations and store-related utility code'''
import re
-from mercurial import util, node, hg
+from mercurial import util, node, hg, error
from mercurial.i18n import _
import lfutil
class StoreError(Exception):
@@ -207,15 +207,15 @@ def _openstore(repo, remote=None, put=Fa
scheme = match.group(1)
try:
storeproviders = _storeprovider[scheme]
except KeyError:
- raise util.Abort(_('unsupported URL scheme %r') % scheme)
+ raise error.Abort(_('unsupported URL scheme %r') % scheme)
for classobj in storeproviders:
try:
return classobj(ui, repo, remote)
except lfutil.storeprotonotcapable:
pass
- raise util.Abort(_('%s does not appear to be a largefile store') %
+ raise error.Abort(_('%s does not appear to be a largefile store') %
util.hidepassword(path))
diff --git a/hgext/largefiles/lfcommands.py b/hgext/largefiles/lfcommands.py
--- a/hgext/largefiles/lfcommands.py
+++ b/hgext/largefiles/lfcommands.py
@@ -60,13 +60,13 @@ def lfconvert(ui, src, dest, *pats, **op
else:
tolfile = True
size = lfutil.getminsize(ui, True, opts.get('size'), default=None)
if not hg.islocal(src):
- raise util.Abort(_('%s is not a local Mercurial repo') % src)
+ raise error.Abort(_('%s is not a local Mercurial repo') % src)
if not hg.islocal(dest):
- raise util.Abort(_('%s is not a local Mercurial repo') % dest)
+ raise error.Abort(_('%s is not a local Mercurial repo') % dest)
rsrc = hg.repository(ui, src)
ui.status(_('initializing destination %s\n') % dest)
rdst = hg.repository(ui, dest, create=True)
@@ -137,11 +137,11 @@ def lfconvert(ui, src, dest, *pats, **op
# Substitute in the largefile data for the hash
hash = f[0].strip()
path = lfutil.findfile(rsrc, hash)
if path is None:
- raise util.Abort(_("missing largefile for \'%s\' in %s")
+ raise error.Abort(_("missing largefile for '%s' in %s")
% (realname, realrev))
fp = open(path, 'rb')
try:
return (fp.read(), f[1])
@@ -155,11 +155,11 @@ def lfconvert(ui, src, dest, *pats, **op
super(converter, self).__init__(ui, src, dest, revmapfile,
opts)
found, missing = downloadlfiles(ui, rsrc)
if missing != 0:
- raise util.Abort(_("all largefiles must be present locally"))
+ raise error.Abort(_("all largefiles must be present locally"))
orig = convcmd.converter
convcmd.converter = converter
try:
@@ -194,11 +194,11 @@ def _lfconvert_addchangeset(rsrc, rdst,
renamed = fctx.renamed()
renamedlfile = renamed and renamed[0] in lfiles
islfile |= renamedlfile
if 'l' in fctx.flags():
if renamedlfile:
- raise util.Abort(
+ raise error.Abort(
_('renamed/copied largefile %s becomes symlink')
% f)
islfile = False
if islfile:
lfiles.add(f)
@@ -211,11 +211,11 @@ def _lfconvert_addchangeset(rsrc, rdst,
if f in ctx.manifest():
fctx = ctx.filectx(f)
if 'l' in fctx.flags():
renamed = fctx.renamed()
if renamed and renamed[0] in lfiles:
- raise util.Abort(_('largefile %s becomes symlink') % f)
+ raise error.Abort(_('largefile %s becomes symlink') % f)
# largefile was modified, update standins
m = util.sha1('')
m.update(ctx[f].data())
hash = m.hexdigest()
@@ -353,11 +353,11 @@ def uploadlfiles(ui, rsrc, rdst, files):
for hash in files:
ui.progress(_('uploading largefiles'), at, unit='largefile',
total=len(files))
source = lfutil.findfile(rsrc, hash)
if not source:
- raise util.Abort(_('largefile %s missing from store'
+ raise error.Abort(_('largefile %s missing from store'
' (needs to be uploaded)') % hash)
# XXX check for errors here
store.put(source, hash)
at += 1
ui.progress(_('uploading largefiles'), None)
@@ -537,11 +537,11 @@ def lfpull(ui, repo, source="default", *
"""
repo.lfpullsource = source
revs = opts.get('rev', [])
if not revs:
- raise util.Abort(_('no revisions specified'))
+ raise error.Abort(_('no revisions specified'))
revs = scmutil.revrange(repo, revs)
numcached = 0
for rev in revs:
ui.note(_('pulling largefiles for revision %s\n') % rev)
diff --git a/hgext/largefiles/lfutil.py b/hgext/largefiles/lfutil.py
--- a/hgext/largefiles/lfutil.py
+++ b/hgext/largefiles/lfutil.py
@@ -14,11 +14,11 @@ import shutil
import stat
import copy
from mercurial import dirstate, httpconnection, match as match_, util, scmutil
from mercurial.i18n import _
-from mercurial import node
+from mercurial import node, error
shortname = '.hglf'
shortnameslash = shortname + '/'
longname = 'largefiles'
@@ -31,14 +31,14 @@ def getminsize(ui, assumelfiles, opt, de
lfsize = ui.config(longname, 'minsize', default=default)
if lfsize:
try:
lfsize = float(lfsize)
except ValueError:
- raise util.Abort(_('largefiles: size must be number (not %s)\n')
+ raise error.Abort(_('largefiles: size must be number (not %s)\n')
% lfsize)
if lfsize is None:
- raise util.Abort(_('minimum size for largefiles must be specified'))
+ raise error.Abort(_('minimum size for largefiles must be specified'))
return lfsize
def link(src, dest):
util.makedirs(os.path.dirname(dest))
try:
@@ -72,11 +72,11 @@ def usercachepath(ui, hash):
else:
home = os.getenv('HOME')
if home:
path = os.path.join(home, '.cache', longname, hash)
else:
- raise util.Abort(_('unknown operating system: %s\n') % os.name)
+ raise error.Abort(_('unknown operating system: %s\n') % os.name)
return path
def inusercache(ui, hash):
path = usercachepath(ui, hash)
return path and os.path.exists(path)
diff --git a/hgext/largefiles/overrides.py b/hgext/largefiles/overrides.py
--- a/hgext/largefiles/overrides.py
+++ b/hgext/largefiles/overrides.py
@@ -10,11 +10,11 @@
import os
import copy
from mercurial import hg, util, cmdutil, scmutil, match as match_, \
- archival, pathutil, revset
+ archival, pathutil, revset, error
from mercurial.i18n import _
import lfutil
import lfcommands
import basestore
@@ -243,11 +243,11 @@ def decodepath(orig, path):
# -- Wrappers: modify existing commands --------------------------------
def overrideadd(orig, ui, repo, *pats, **opts):
if opts.get('normal') and opts.get('large'):
- raise util.Abort(_('--normal cannot be used with --large'))
+ raise error.Abort(_('--normal cannot be used with --large'))
return orig(ui, repo, *pats, **opts)
def cmdutiladd(orig, ui, repo, matcher, prefix, explicitonly, **opts):
# The --normal flag short circuits this override
if opts.get('normal'):
@@ -582,11 +582,11 @@ def overridecopy(orig, ui, repo, pats, o
nonormalfiles = False
nolfiles = False
installnormalfilesmatchfn(repo[None].manifest())
try:
result = orig(ui, repo, pats, opts, rename)
- except util.Abort as e:
+ except error.Abort as e:
if str(e) != _('no files to copy'):
raise e
else:
nonormalfiles = True
result = 0
@@ -686,21 +686,21 @@ def overridecopy(orig, ui, repo, pats, o
util.copyfile(repo.wjoin(srclfile),
repo.wjoin(destlfile))
lfdirstate.add(destlfile)
lfdirstate.write()
- except util.Abort as e:
+ except error.Abort as e:
if str(e) != _('no files to copy'):
raise e
else:
nolfiles = True
finally:
restorematchfn()
wlock.release()
if nolfiles and nonormalfiles:
- raise util.Abort(_('no files to copy'))
+ raise error.Abort(_('no files to copy'))
return result
# When the user calls revert, we have to be careful to not revert any
# changes to other largefiles accidentally. This means we have to keep
@@ -825,19 +825,19 @@ def pulledrevsetsymbol(repo, subset, x):
"""
try:
firstpulled = repo.firstpulled
except AttributeError:
- raise util.Abort(_("pulled() only available in --lfrev"))
+ raise error.Abort(_("pulled() only available in --lfrev"))
return revset.baseset([r for r in subset if r >= firstpulled])
def overrideclone(orig, ui, source, dest=None, **opts):
d = dest
if d is None:
d = hg.defaultdest(source)
if opts.get('all_largefiles') and not hg.islocal(d):
- raise util.Abort(_(
+ raise error.Abort(_(
'--all-largefiles is incompatible with non-local destination %s') %
d)
return orig(ui, source, dest, **opts)
@@ -914,17 +914,17 @@ def overridearchive(orig, repo, dest, no
# largefile caches, neither of which are modified.
if node is not None:
lfcommands.cachelfiles(repo.ui, repo, node)
if kind not in archival.archivers:
- raise util.Abort(_("unknown archive type '%s'") % kind)
+ raise error.Abort(_("unknown archive type '%s'") % kind)
ctx = repo[node]
if kind == 'files':
if prefix:
- raise util.Abort(
+ raise error.Abort(
_('cannot give prefix when archiving to files'))
else:
prefix = archival.tidyprefix(dest, kind, prefix)
def write(name, mode, islink, getdata):
@@ -947,11 +947,11 @@ def overridearchive(orig, repo, dest, no
if lfutil.isstandin(f):
if node is not None:
path = lfutil.findfile(repo, getdata().strip())
if path is None:
- raise util.Abort(
+ raise error.Abort(
_('largefile %s not found in repo store or system cache')
% lfutil.splitstandin(f))
else:
path = lfutil.splitstandin(f)
@@ -1004,11 +1004,11 @@ def hgsubrepoarchive(orig, repo, archive
if lfutil.isstandin(f):
if ctx.node() is not None:
path = lfutil.findfile(repo._repo, getdata().strip())
if path is None:
- raise util.Abort(
+ raise error.Abort(
_('largefile %s not found in repo store or system cache')
% lfutil.splitstandin(f))
else:
path = lfutil.splitstandin(f)
@@ -1041,11 +1041,11 @@ def overridebailifchanged(orig, repo, *a
orig(repo, *args, **kwargs)
repo.lfstatus = True
s = repo.status()
repo.lfstatus = False
if s.modified or s.added or s.removed or s.deleted:
- raise util.Abort(_('uncommitted changes'))
+ raise error.Abort(_('uncommitted changes'))
def cmdutilforget(orig, ui, repo, match, prefix, explicitonly):
normalmatcher = composenormalfilematcher(match, repo[None].manifest())
bad, forgot = orig(ui, repo, normalmatcher, prefix, explicitonly)
m = composelargefilematcher(match, repo[None].manifest())
@@ -1342,11 +1342,11 @@ def overridecat(orig, ui, repo, file1, *
hash = lfutil.readstandin(repo, lf, ctx.rev())
if not lfutil.inusercache(repo.ui, hash):
store = basestore._openstore(repo)
success, missing = store.get([(lf, hash)])
if len(success) != 1:
- raise util.Abort(
+ raise error.Abort(
_('largefile %s is not in cache and could not be '
'downloaded') % lf)
path = lfutil.usercachepath(repo.ui, hash)
fpin = open(path, "rb")
for chunk in util.filechunkiter(fpin, 128 * 1024):
diff --git a/hgext/largefiles/proto.py b/hgext/largefiles/proto.py
--- a/hgext/largefiles/proto.py
+++ b/hgext/largefiles/proto.py
@@ -49,11 +49,12 @@ def putlfile(repo, proto, sha):
def getlfile(repo, proto, sha):
'''Retrieve a largefile from the repository-local cache or system
cache.'''
filename = lfutil.findfile(repo, sha)
if not filename:
- raise util.Abort(_('requested largefile %s not present in cache') % sha)
+ raise error.Abort(_('requested largefile %s not present in cache')
+ % sha)
f = open(filename, 'rb')
length = os.fstat(f.fileno())[6]
# Since we can't set an HTTP content-length header here, and
# Mercurial core provides no way to give the length of a streamres
diff --git a/hgext/largefiles/remotestore.py b/hgext/largefiles/remotestore.py
--- a/hgext/largefiles/remotestore.py
+++ b/hgext/largefiles/remotestore.py
@@ -6,11 +6,11 @@
'''remote largefile store; the base class for wirestore'''
import urllib2
-from mercurial import util, wireproto
+from mercurial import util, wireproto, error
from mercurial.i18n import _
import lfutil
import basestore
@@ -19,11 +19,11 @@ class remotestore(basestore.basestore):
def __init__(self, ui, repo, url):
super(remotestore, self).__init__(ui, repo, url)
def put(self, source, hash):
if self.sendfile(source, hash):
- raise util.Abort(
+ raise error.Abort(
_('remotestore: could not put %s to remote store %s')
% (source, util.hidepassword(self.url)))
self.ui.debug(
_('remotestore: put %s to remote store %s\n')
% (source, util.hidepassword(self.url)))
@@ -37,29 +37,29 @@ class remotestore(basestore.basestore):
fd = None
try:
fd = lfutil.httpsendfile(self.ui, filename)
return self._put(hash, fd)
except IOError as e:
- raise util.Abort(
+ raise error.Abort(
_('remotestore: could not open file %s: %s')
% (filename, str(e)))
finally:
if fd:
fd.close()
def _getfile(self, tmpfile, filename, hash):
try:
chunks = self._get(hash)
except urllib2.HTTPError as e:
- # 401s get converted to util.Aborts; everything else is fine being
+ # 401s get converted to error.Aborts; everything else is fine being
# turned into a StoreError
raise basestore.StoreError(filename, hash, self.url, str(e))
except urllib2.URLError as e:
# This usually indicates a connection problem, so don't
# keep trying with the other files... they will probably
# all fail too.
- raise util.Abort('%s: %s' %
+ raise error.Abort('%s: %s' %
(util.hidepassword(self.url), e.reason))
except IOError as e:
raise basestore.StoreError(filename, hash, self.url, str(e))
return lfutil.copyandhash(chunks, tmpfile)
diff --git a/hgext/largefiles/reposetup.py b/hgext/largefiles/reposetup.py
--- a/hgext/largefiles/reposetup.py
+++ b/hgext/largefiles/reposetup.py
@@ -8,11 +8,11 @@
'''setup for largefiles repositories: reposetup'''
import copy
import os
-from mercurial import error, match as match_, util
+from mercurial import error, match as match_, error
from mercurial.i18n import _
from mercurial import scmutil, localrepo
import lfcommands
import lfutil
@@ -278,11 +278,11 @@ def reposetup(ui, repo):
missing = set(self.requirements) - remote.local().supported
if missing:
msg = _("required features are not"
" supported in the destination:"
" %s") % (', '.join(sorted(missing)))
- raise util.Abort(msg)
+ raise error.Abort(msg)
return super(lfilesrepo, self).push(remote, force=force, revs=revs,
newbranch=newbranch)
# TODO: _subdirlfs should be moved into "lfutil.py", because
# it is referred only from "lfutil.updatestandinsbymatch"
@@ -302,11 +302,11 @@ def reposetup(ui, repo):
dirs = []
regulars = []
for f in files:
if lfutil.isstandin(f + '/'):
- raise util.Abort(
+ raise error.Abort(
_('file "%s" is a largefile standin') % f,
hint=('commit the largefile itself instead'))
# Scan directories
if os.path.isdir(self.wjoin(f)):
dirs.append(f)
diff --git a/hgext/mq.py b/hgext/mq.py
--- a/hgext/mq.py
+++ b/hgext/mq.py
@@ -490,11 +490,11 @@ class queue(object):
elif self.gitmode == 'keep':
pass
elif self.gitmode in ('yes', 'no'):
diffopts.git = self.gitmode == 'yes'
else:
- raise util.Abort(_('mq.git option can be auto/keep/yes/no'
+ raise error.Abort(_('mq.git option can be auto/keep/yes/no'
' got %s') % self.gitmode)
if patchfn:
diffopts = self.patchopts(diffopts, patchfn)
return diffopts
@@ -542,11 +542,11 @@ class queue(object):
patch = l[:h]
comment = l[h:]
patch = patch.strip()
if patch:
if patch in self.series:
- raise util.Abort(_('%s appears more than once in %s') %
+ raise error.Abort(_('%s appears more than once in %s') %
(patch, self.join(self.seriespath)))
self.series.append(patch)
self.seriesguards.append(self.guard_re.findall(comment))
def checkguard(self, guard):
@@ -563,11 +563,11 @@ class queue(object):
def setactive(self, guards):
for guard in guards:
bad = self.checkguard(guard)
if bad:
- raise util.Abort(bad)
+ raise error.Abort(bad)
guards = sorted(set(guards))
self.ui.debug('active guards: %s\n' % ' '.join(guards))
self.activeguards = guards
self.guardsdirty = True
@@ -590,16 +590,16 @@ class queue(object):
return self.activeguards
def setguards(self, idx, guards):
for g in guards:
if len(g) < 2:
- raise util.Abort(_('guard %r too short') % g)
+ raise error.Abort(_('guard %r too short') % g)
if g[0] not in '-+':
- raise util.Abort(_('guard %r starts with invalid char') % g)
+ raise error.Abort(_('guard %r starts with invalid char') % g)
bad = self.checkguard(g[1:])
if bad:
- raise util.Abort(bad)
+ raise error.Abort(bad)
drop = self.guard_re.sub('', self.fullseries[idx])
self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
self.parseseries()
self.seriesdirty = True
@@ -706,29 +706,29 @@ class queue(object):
if err == 0:
return (err, n)
if n is None:
- raise util.Abort(_("apply failed for patch %s") % patch)
+ raise error.Abort(_("apply failed for patch %s") % patch)
self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
# apply failed, strip away that rev and merge.
hg.clean(repo, head)
strip(self.ui, repo, [n], update=False, backup=False)
ctx = repo[rev]
ret = hg.merge(repo, rev)
if ret:
- raise util.Abort(_("update returned %d") % ret)
+ raise error.Abort(_("update returned %d") % ret)
n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
if n is None:
- raise util.Abort(_("repo commit failed"))
+ raise error.Abort(_("repo commit failed"))
try:
ph = patchheader(mergeq.join(patch), self.plainmode)
except Exception:
- raise util.Abort(_("unable to read %s") % patch)
+ raise error.Abort(_("unable to read %s") % patch)
diffopts = self.patchopts(diffopts, patch)
patchf = self.opener(patch, "w")
comments = str(ph)
if comments:
@@ -932,13 +932,13 @@ class queue(object):
match = scmutil.matchfiles(repo, files or [])
oldtip = repo['tip']
n = newcommit(repo, None, message, ph.user, ph.date, match=match,
force=True)
if repo['tip'] == oldtip:
- raise util.Abort(_("qpush exactly duplicates child changeset"))
+ raise error.Abort(_("qpush exactly duplicates child changeset"))
if n is None:
- raise util.Abort(_("repository commit failed"))
+ raise error.Abort(_("repository commit failed"))
if update_status:
self.applied.append(statusentry(n, patchname))
if patcherr:
@@ -986,11 +986,11 @@ class queue(object):
for p in unknown:
msg = _('revision %s refers to unknown patches: %s\n')
self.ui.warn(msg % (short(rev[p]), p))
else:
msg = _('unknown patches: %s\n')
- raise util.Abort(''.join(msg % p for p in unknown))
+ raise error.Abort(''.join(msg % p for p in unknown))
self.parseseries()
self.seriesdirty = True
return [entry.node for entry in qfinished]
@@ -998,17 +998,17 @@ class queue(object):
firstrev = repo[self.applied[0].node].rev()
patches = []
for i, rev in enumerate(revs):
if rev < firstrev:
- raise util.Abort(_('revision %d is not managed') % rev)
+ raise error.Abort(_('revision %d is not managed') % rev)
ctx = repo[rev]
base = self.applied[i].node
if ctx.node() != base:
msg = _('cannot delete revision %d above applied patches')
- raise util.Abort(msg % rev)
+ raise error.Abort(msg % rev)
patch = self.applied[i].name
for fmt in ('[mq]: %s', 'imported patch %s'):
if ctx.description() == fmt % patch:
msg = _('patch %s finalized without changeset message\n')
@@ -1036,28 +1036,28 @@ class queue(object):
finally:
tr.release()
def delete(self, repo, patches, opts):
if not patches and not opts.get('rev'):
- raise util.Abort(_('qdelete requires at least one revision or '
+ raise error.Abort(_('qdelete requires at least one revision or '
'patch name'))
realpatches = []
for patch in patches:
patch = self.lookup(patch, strict=True)
info = self.isapplied(patch)
if info:
- raise util.Abort(_("cannot delete applied patch %s") % patch)
+ raise error.Abort(_("cannot delete applied patch %s") % patch)
if patch not in self.series:
- raise util.Abort(_("patch %s not in series file") % patch)
+ raise error.Abort(_("patch %s not in series file") % patch)
if patch not in realpatches:
realpatches.append(patch)
numrevs = 0
if opts.get('rev'):
if not self.applied:
- raise util.Abort(_('no patches applied'))
+ raise error.Abort(_('no patches applied'))
revs = scmutil.revrange(repo, opts.get('rev'))
revs.sort()
revpatches = self._revpatches(repo, revs)
realpatches += revpatches
numrevs = len(revpatches)
@@ -1068,11 +1068,11 @@ class queue(object):
'''check that working directory is at qtip'''
if self.applied:
top = self.applied[-1].node
patch = self.applied[-1].name
if repo.dirstate.p1() != top:
- raise util.Abort(_("working directory revision is not qtip"))
+ raise error.Abort(_("working directory revision is not qtip"))
return top, patch
return None, None
def putsubstate2changes(self, substatestate, changes):
for files in changes[:3]:
@@ -1096,33 +1096,33 @@ class queue(object):
return checklocalchanges(repo, force, excsuffix)
_reserved = ('series', 'status', 'guards', '.', '..')
def checkreservedname(self, name):
if name in self._reserved:
- raise util.Abort(_('"%s" cannot be used as the name of a patch')
+ raise error.Abort(_('"%s" cannot be used as the name of a patch')
% name)
for prefix in ('.hg', '.mq'):
if name.startswith(prefix):
- raise util.Abort(_('patch name cannot begin with "%s"')
+ raise error.Abort(_('patch name cannot begin with "%s"')
% prefix)
for c in ('#', ':', '\r', '\n'):
if c in name:
- raise util.Abort(_('%r cannot be used in the name of a patch')
+ raise error.Abort(_('%r cannot be used in the name of a patch')
% c)
def checkpatchname(self, name, force=False):
self.checkreservedname(name)
if not force and os.path.exists(self.join(name)):
if os.path.isdir(self.join(name)):
- raise util.Abort(_('"%s" already exists as a directory')
+ raise error.Abort(_('"%s" already exists as a directory')
% name)
else:
- raise util.Abort(_('patch "%s" already exists') % name)
+ raise error.Abort(_('patch "%s" already exists') % name)
def checkkeepchanges(self, keepchanges, force):
if force and keepchanges:
- raise util.Abort(_('cannot use both --force and --keep-changes'))
+ raise error.Abort(_('cannot use both --force and --keep-changes'))
def new(self, repo, patchfn, *pats, **opts):
"""options:
msg: a string or a no-argument function returning a string
"""
@@ -1141,30 +1141,30 @@ class queue(object):
substatestate = repo.dirstate['.hgsubstate']
if opts.get('include') or opts.get('exclude') or pats:
# detect missing files in pats
def badfn(f, msg):
if f != '.hgsubstate': # .hgsubstate is auto-created
- raise util.Abort('%s: %s' % (f, msg))
+ raise error.Abort('%s: %s' % (f, msg))
match = scmutil.match(repo[None], pats, opts, badfn=badfn)
changes = repo.status(match=match)
else:
changes = self.checklocalchanges(repo, force=True)
commitfiles = list(inclsubs)
for files in changes[:3]:
commitfiles.extend(files)
match = scmutil.matchfiles(repo, commitfiles)
if len(repo[None].parents()) > 1:
- raise util.Abort(_('cannot manage merge changesets'))
+ raise error.Abort(_('cannot manage merge changesets'))
self.checktoppatch(repo)
insert = self.fullseriesend()
wlock = repo.wlock()
try:
try:
# if patch file write fails, abort early
p = self.opener(patchfn, "w")
except IOError as e:
- raise util.Abort(_('cannot write patch "%s": %s')
+ raise error.Abort(_('cannot write patch "%s": %s')
% (patchfn, e.strerror))
try:
defaultmsg = "[mq]: %s" % patchfn
editor = cmdutil.getcommiteditor(editform=editform)
if edit:
@@ -1183,11 +1183,11 @@ class queue(object):
commitmsg = msg or defaultmsg
n = newcommit(repo, None, commitmsg, user, date, match=match,
force=True, editor=editor)
if n is None:
- raise util.Abort(_("repo commit failed"))
+ raise error.Abort(_("repo commit failed"))
try:
self.fullseries[insert:insert] = [patchfn]
self.applied.append(statusentry(n, patchfn))
self.parseseries()
self.seriesdirty = True
@@ -1300,11 +1300,11 @@ class queue(object):
except (ValueError, OverflowError):
pass
else:
if i + off < len(self.series):
return self.series[i + off]
- raise util.Abort(_("patch %s not in series") % patch)
+ raise error.Abort(_("patch %s not in series") % patch)
def push(self, repo, patch=None, force=False, list=False, mergeq=None,
all=False, move=False, exact=False, nobackup=False,
keepchanges=False):
self.checkkeepchanges(keepchanges, force)
@@ -1336,11 +1336,11 @@ class queue(object):
return 0
pushable, reason = self.pushable(patch)
if pushable:
if self.series.index(patch) < self.seriesend():
- raise util.Abort(
+ raise error.Abort(
_("cannot push to a previous patch: %s") % patch)
else:
if reason:
reason = _('guarded by %s') % reason
else:
@@ -1365,29 +1365,29 @@ class queue(object):
if not force and not keepchanges:
self.checklocalchanges(repo, refresh=self.applied)
if exact:
if keepchanges:
- raise util.Abort(
+ raise error.Abort(
_("cannot use --exact and --keep-changes together"))
if move:
- raise util.Abort(_('cannot use --exact and --move '
+ raise error.Abort(_('cannot use --exact and --move '
'together'))
if self.applied:
- raise util.Abort(_('cannot push --exact with applied '
+ raise error.Abort(_('cannot push --exact with applied '
'patches'))
root = self.series[start]
target = patchheader(self.join(root), self.plainmode).parent
if not target:
- raise util.Abort(
+ raise error.Abort(
_("%s does not have a parent recorded") % root)
if not repo[target] == repo['.']:
hg.update(repo, target)
if move:
if not patch:
- raise util.Abort(_("please specify the patch to move"))
+ raise error.Abort(_("please specify the patch to move"))
for fullstart, rpn in enumerate(self.fullseries):
# strip markers for patch guards
if self.guard_re.split(rpn, 1)[0] == self.series[start]:
break
for i, rpn in enumerate(self.fullseries[fullstart:]):
@@ -1465,11 +1465,11 @@ class queue(object):
info = self.isapplied(patch)
if not info:
patch = self.lookup(patch)
info = self.isapplied(patch)
if not info:
- raise util.Abort(_("patch %s is not applied") % patch)
+ raise error.Abort(_("patch %s is not applied") % patch)
if not self.applied:
# Allow qpop -a to work repeatedly,
# but not qpop without an argument
self.ui.warn(_("no patches applied\n"))
@@ -1518,32 +1518,32 @@ class queue(object):
try:
heads = repo.changelog.heads(rev)
except error.LookupError:
node = short(rev)
- raise util.Abort(_('trying to pop unknown node %s') % node)
+ raise error.Abort(_('trying to pop unknown node %s') % node)
if heads != [self.applied[-1].node]:
- raise util.Abort(_("popping would remove a revision not "
+ raise error.Abort(_("popping would remove a revision not "
"managed by this patch queue"))
if not repo[self.applied[-1].node].mutable():
- raise util.Abort(
+ raise error.Abort(
_("popping would remove a public revision"),
hint=_('see "hg help phases" for details'))
# we know there are no local changes, so we can make a simplified
# form of hg.update.
if update:
qp = self.qparents(repo, rev)
ctx = repo[qp]
m, a, r, d = repo.status(qp, '.')[:4]
if d:
- raise util.Abort(_("deletions found between repo revs"))
+ raise error.Abort(_("deletions found between repo revs"))
tobackup = set(a + m + r) & tobackup
if keepchanges and tobackup:
- raise util.Abort(_("local changes found, refresh first"))
+ raise error.Abort(_("local changes found, refresh first"))
self.backup(repo, tobackup)
repo.dirstate.beginparentchange()
for f in a:
util.unlinkpath(repo.wjoin(f), ignoremissing=True)
repo.dirstate.drop(f)
@@ -1594,13 +1594,13 @@ class queue(object):
try:
self.checktoppatch(repo)
(top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
if repo.changelog.heads(top) != [top]:
- raise util.Abort(_("cannot refresh a revision with children"))
+ raise error.Abort(_("cannot refresh a revision with children"))
if not repo[top].mutable():
- raise util.Abort(_("cannot refresh public revision"),
+ raise error.Abort(_("cannot refresh public revision"),
hint=_('see "hg help phases" for details'))
cparents = repo.changelog.parents(top)
patchparent = self.qparents(repo, top)
@@ -1813,22 +1813,22 @@ class queue(object):
wlock.release()
self.removeundo(repo)
def init(self, repo, create=False):
if not create and os.path.isdir(self.path):
- raise util.Abort(_("patch queue directory already exists"))
+ raise error.Abort(_("patch queue directory already exists"))
try:
os.mkdir(self.path)
except OSError as inst:
if inst.errno != errno.EEXIST or not create:
raise
if create:
return self.qrepo(create=True)
def unapplied(self, repo, patch=None):
if patch and patch not in self.series:
- raise util.Abort(_("patch %s is not in series file") % patch)
+ raise error.Abort(_("patch %s is not in series file") % patch)
if not patch:
start = self.seriesend()
else:
start = self.series.index(patch) + 1
unapplied = []
@@ -2032,64 +2032,64 @@ class queue(object):
def qimport(self, repo, files, patchname=None, rev=None, existing=None,
force=None, git=False):
def checkseries(patchname):
if patchname in self.series:
- raise util.Abort(_('patch %s is already in the series file')
+ raise error.Abort(_('patch %s is already in the series file')
% patchname)
if rev:
if files:
- raise util.Abort(_('option "-r" not valid when importing '
+ raise error.Abort(_('option "-r" not valid when importing '
'files'))
rev = scmutil.revrange(repo, rev)
rev.sort(reverse=True)
elif not files:
- raise util.Abort(_('no files or revisions specified'))
+ raise error.Abort(_('no files or revisions specified'))
if (len(files) > 1 or len(rev) > 1) and patchname:
- raise util.Abort(_('option "-n" not valid when importing multiple '
+ raise error.Abort(_('option "-n" not valid when importing multiple '
'patches'))
imported = []
if rev:
# If mq patches are applied, we can only import revisions
# that form a linear path to qbase.
# Otherwise, they should form a linear path to a head.
heads = repo.changelog.heads(repo.changelog.node(rev.first()))
if len(heads) > 1:
- raise util.Abort(_('revision %d is the root of more than one '
+ raise error.Abort(_('revision %d is the root of more than one '
'branch') % rev.last())
if self.applied:
base = repo.changelog.node(rev.first())
if base in [n.node for n in self.applied]:
- raise util.Abort(_('revision %d is already managed')
+ raise error.Abort(_('revision %d is already managed')
% rev.first())
if heads != [self.applied[-1].node]:
- raise util.Abort(_('revision %d is not the parent of '
+ raise error.Abort(_('revision %d is not the parent of '
'the queue') % rev.first())
base = repo.changelog.rev(self.applied[0].node)
lastparent = repo.changelog.parentrevs(base)[0]
else:
if heads != [repo.changelog.node(rev.first())]:
- raise util.Abort(_('revision %d has unmanaged children')
+ raise error.Abort(_('revision %d has unmanaged children')
% rev.first())
lastparent = None
diffopts = self.diffopts({'git': git})
tr = repo.transaction('qimport')
try:
for r in rev:
if not repo[r].mutable():
- raise util.Abort(_('revision %d is not mutable') % r,
+ raise error.Abort(_('revision %d is not mutable') % r,
hint=_('see "hg help phases" '
'for details'))
p1, p2 = repo.changelog.parentrevs(r)
n = repo.changelog.node(r)
if p2 != nullrev:
- raise util.Abort(_('cannot import merge revision %d')
+ raise error.Abort(_('cannot import merge revision %d')
% r)
if lastparent and lastparent != r:
- raise util.Abort(_('revision %d is not the parent of '
+ raise error.Abort(_('revision %d is not the parent of '
'%d')
% (r, lastparent))
lastparent = p1
if not patchname:
@@ -2119,17 +2119,18 @@ class queue(object):
tr.release()
for i, filename in enumerate(files):
if existing:
if filename == '-':
- raise util.Abort(_('-e is incompatible with import from -'))
+ raise error.Abort(_('-e is incompatible with import from -')
+ )
filename = normname(filename)
self.checkreservedname(filename)
if util.url(filename).islocal():
originpath = self.join(filename)
if not os.path.isfile(originpath):
- raise util.Abort(
+ raise error.Abort(
_("patch %s does not exist") % filename)
if patchname:
self.checkpatchname(patchname, force)
@@ -2139,11 +2140,11 @@ class queue(object):
else:
patchname = filename
else:
if filename == '-' and not patchname:
- raise util.Abort(_('need --name to import a patch from -'))
+ raise error.Abort(_('need --name to import a patch from -'))
elif not patchname:
patchname = normname(os.path.basename(filename.rstrip('/')))
self.checkpatchname(patchname, force)
try:
if filename == '-':
@@ -2151,11 +2152,11 @@ class queue(object):
else:
fp = hg.openpath(self.ui, filename)
text = fp.read()
fp.close()
except (OSError, IOError):
- raise util.Abort(_("unable to read file %s") % filename)
+ raise error.Abort(_("unable to read file %s") % filename)
patchf = self.opener(patchname, "w")
patchf.write(text)
patchf.close()
if not force:
checkseries(patchname)
@@ -2210,11 +2211,11 @@ def applied(ui, repo, patch=None, **opts
q = repo.mq
if patch:
if patch not in q.series:
- raise util.Abort(_("patch %s is not in series file") % patch)
+ raise error.Abort(_("patch %s is not in series file") % patch)
end = q.series.index(patch) + 1
else:
end = q.seriesend(True)
if opts.get('last') and not end:
@@ -2242,11 +2243,11 @@ def unapplied(ui, repo, patch=None, **op
Returns 0 on success."""
q = repo.mq
if patch:
if patch not in q.series:
- raise util.Abort(_("patch %s is not in series file") % patch)
+ raise error.Abort(_("patch %s is not in series file") % patch)
start = q.series.index(patch) + 1
else:
start = q.seriesend(True)
if start == len(q.series) and opts.get('first'):
@@ -2409,11 +2410,11 @@ def clone(ui, source, dest=None, **opts)
else:
patchespath = patchdir(sr)
try:
hg.peer(ui, opts, patchespath)
except error.RepoError:
- raise util.Abort(_('versioned patch repository not found'
+ raise error.Abort(_('versioned patch repository not found'
' (see init --mq)'))
qbase, destrev = None, None
if sr.local():
repo = sr.local()
if repo.mq.applied and repo[qbase].phase() != phases.secret:
@@ -2459,11 +2460,11 @@ def commit(ui, repo, *pats, **opts):
This command is deprecated; use :hg:`commit --mq` instead."""
q = repo.mq
r = q.qrepo()
if not r:
- raise util.Abort('no queue repository')
+ raise error.Abort('no queue repository')
commands.commit(r.ui, r, *pats, **opts)
@command("qseries",
[('m', 'missing', None, _('print patches not in series')),
] + seriesopts,
@@ -2664,13 +2665,13 @@ def fold(ui, repo, *files, **opts):
current patch header, separated by a line of ``* * *``.
Returns 0 on success."""
q = repo.mq
if not files:
- raise util.Abort(_('qfold requires at least one patch name'))
+ raise error.Abort(_('qfold requires at least one patch name'))
if not q.checktoppatch(repo)[0]:
- raise util.Abort(_('no patches applied'))
+ raise error.Abort(_('no patches applied'))
q.checklocalchanges(repo)
message = cmdutil.logmessage(ui, opts)
parent = q.lookup('qtip')
@@ -2679,11 +2680,11 @@ def fold(ui, repo, *files, **opts):
for f in files:
p = q.lookup(f)
if p in patches or p == parent:
ui.warn(_('skipping already folded patch %s\n') % p)
if q.isapplied(p):
- raise util.Abort(_('qfold cannot fold already applied patch %s')
+ raise error.Abort(_('qfold cannot fold already applied patch %s')
% p)
patches.append(p)
for p in patches:
if not message:
@@ -2691,11 +2692,11 @@ def fold(ui, repo, *files, **opts):
if ph.message:
messages.append(ph.message)
pf = q.join(p)
(patchsuccess, files, fuzz) = q.patch(repo, pf)
if not patchsuccess:
- raise util.Abort(_('error folding patch %s') % p)
+ raise error.Abort(_('error folding patch %s') % p)
if not message:
ph = patchheader(q.join(parent), q.plainmode)
message = ph.message
for msg in messages:
@@ -2790,27 +2791,27 @@ def guard(ui, repo, *args, **opts):
applied = set(p.name for p in q.applied)
patch = None
args = list(args)
if opts.get('list'):
if args or opts.get('none'):
- raise util.Abort(_('cannot mix -l/--list with options or '
+ raise error.Abort(_('cannot mix -l/--list with options or '
'arguments'))
for i in xrange(len(q.series)):
status(i)
return
if not args or args[0][0:1] in '-+':
if not q.applied:
- raise util.Abort(_('no patches applied'))
+ raise error.Abort(_('no patches applied'))
patch = q.applied[-1].name
if patch is None and args[0][0:1] not in '-+':
patch = args.pop(0)
if patch is None:
- raise util.Abort(_('no patch to work with'))
+ raise error.Abort(_('no patch to work with'))
if args or opts.get('none'):
idx = q.findseries(patch)
if idx is None:
- raise util.Abort(_('no patch named %s') % patch)
+ raise error.Abort(_('no patch named %s') % patch)
q.setguards(idx, args)
q.savedirty()
else:
status(q.series.index(q.lookup(patch)))
@@ -3032,14 +3033,14 @@ def save(ui, repo, **opts):
path = q.path
if opts.get('name'):
newpath = os.path.join(q.basepath, opts.get('name'))
if os.path.exists(newpath):
if not os.path.isdir(newpath):
- raise util.Abort(_('destination %s exists and is not '
+ raise error.Abort(_('destination %s exists and is not '
'a directory') % newpath)
if not opts.get('force'):
- raise util.Abort(_('destination %s exists, '
+ raise error.Abort(_('destination %s exists, '
'use -f to force') % newpath)
else:
newpath = savename(path)
ui.warn(_("copy %s to %s\n") % (path, newpath))
util.copyfiles(path, newpath)
@@ -3179,11 +3180,11 @@ def finish(ui, repo, *revrange, **opts):
to upstream.
Returns 0 on success.
"""
if not opts.get('applied') and not revrange:
- raise util.Abort(_('no revisions specified'))
+ raise error.Abort(_('no revisions specified'))
elif opts.get('applied'):
revrange = ('qbase::qtip',) + revrange
q = repo.mq
if not q.applied:
@@ -3268,11 +3269,11 @@ def qqueue(ui, repo, name=None, **opts):
return sorted(queues)
def _setactive(name):
if q.applied:
- raise util.Abort(_('new queue created, but cannot make active '
+ raise error.Abort(_('new queue created, but cannot make active '
'as patches are applied'))
_setactivenocheck(name)
def _setactivenocheck(name):
fh = repo.vfs(_activequeue, 'w')
@@ -3297,16 +3298,16 @@ def qqueue(ui, repo, name=None, **opts):
return False
return True
def _delete(name):
if name not in existing:
- raise util.Abort(_('cannot delete queue that does not exist'))
+ raise error.Abort(_('cannot delete queue that does not exist'))
current = _getcurrent()
if name == current:
- raise util.Abort(_('cannot delete currently active queue'))
+ raise error.Abort(_('cannot delete currently active queue'))
fh = repo.vfs('patches.queues.new', 'w')
for queue in existing:
if queue == name:
continue
@@ -3326,34 +3327,35 @@ def qqueue(ui, repo, name=None, **opts):
else:
ui.write('\n')
return
if not _validname(name):
- raise util.Abort(
+ raise error.Abort(
_('invalid queue name, may not contain the characters ":\\/."'))
existing = _getqueues()
if opts.get('create'):
if name in existing:
- raise util.Abort(_('queue "%s" already exists') % name)
+ raise error.Abort(_('queue "%s" already exists') % name)
if _noqueues():
_addqueue(_defaultqueue)
_addqueue(name)
_setactive(name)
elif opts.get('rename'):
current = _getcurrent()
if name == current:
- raise util.Abort(_('can\'t rename "%s" to its current name') % name)
+ raise error.Abort(_('can\'t rename "%s" to its current name')
+ % name)
if name in existing:
- raise util.Abort(_('queue "%s" already exists') % name)
+ raise error.Abort(_('queue "%s" already exists') % name)
olddir = _queuedir(current)
newdir = _queuedir(name)
if os.path.exists(newdir):
- raise util.Abort(_('non-queue directory "%s" already exists') %
+ raise error.Abort(_('non-queue directory "%s" already exists') %
newdir)
fh = repo.vfs('patches.queues.new', 'w')
for queue in existing:
if queue == current:
@@ -3373,11 +3375,11 @@ def qqueue(ui, repo, name=None, **opts):
qdir = _queuedir(name)
if os.path.exists(qdir):
shutil.rmtree(qdir)
else:
if name not in existing:
- raise util.Abort(_('use --create to create a new queue'))
+ raise error.Abort(_('use --create to create a new queue'))
_setactive(name)
def mqphasedefaults(repo, roots):
"""callback used to set mq changeset as secret when no phase data exists"""
if repo.mq.applied:
@@ -3404,11 +3406,11 @@ def reposetup(ui, repo):
def abortifwdirpatched(self, errmsg, force=False):
if self.mq.applied and self.mq.checkapplied and not force:
parents = self.dirstate.parents()
patches = [s.node for s in self.mq.applied]
if parents[0] in patches or parents[1] in patches:
- raise util.Abort(errmsg)
+ raise error.Abort(errmsg)
def commit(self, text="", user=None, date=None, match=None,
force=False, editor=False, extra={}):
self.abortifwdirpatched(
_('cannot commit over an applied mq patch'),
@@ -3431,11 +3433,11 @@ def reposetup(ui, repo):
else:
outapplied.pop()
# looking for pushed and shared changeset
for node in outapplied:
if self[node].phase() < phases.secret:
- raise util.Abort(_('source has mq patches applied'))
+ raise error.Abort(_('source has mq patches applied'))
# no non-secret patches pushed
super(mqrepo, self).checkpush(pushop)
def _findtags(self):
'''augment tags from base class with patch tags'''
@@ -3493,16 +3495,16 @@ def mqinit(orig, ui, *args, **kwargs):
return orig(ui, *args, **kwargs)
if args:
repopath = args[0]
if not hg.islocal(repopath):
- raise util.Abort(_('only a local queue repository '
+ raise error.Abort(_('only a local queue repository '
'may be initialized'))
else:
repopath = cmdutil.findrepo(os.getcwd())
if not repopath:
- raise util.Abort(_('there is no Mercurial repository here '
+ raise error.Abort(_('there is no Mercurial repository here '
'(.hg not found)'))
repo = hg.repository(ui, repopath)
return qinit(ui, repo, True)
def mqcommand(orig, ui, repo, *args, **kwargs):
@@ -3515,11 +3517,11 @@ def mqcommand(orig, ui, repo, *args, **k
return orig(ui, repo, *args, **kwargs)
q = repo.mq
r = q.qrepo()
if not r:
- raise util.Abort(_('no queue repository'))
+ raise error.Abort(_('no queue repository'))
return orig(r.ui, r, *args, **kwargs)
def summaryhook(ui, repo):
q = repo.mq
m = []
diff --git a/hgext/notify.py b/hgext/notify.py
--- a/hgext/notify.py
+++ b/hgext/notify.py
@@ -133,11 +133,11 @@ web.baseurl
'''
import email, socket, time
from mercurial.i18n import _
-from mercurial import patch, cmdutil, util, mail
+from mercurial import patch, cmdutil, util, mail, error
import fnmatch
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
@@ -275,11 +275,11 @@ class notifier(object):
p = email.Parser.Parser()
try:
msg = p.parsestr(data)
except email.Errors.MessageParseError as inst:
- raise util.Abort(inst)
+ raise error.Abort(inst)
# store sender and subject
sender, subject = msg['From'], msg['Subject']
del msg['From'], msg['Subject']
diff --git a/hgext/patchbomb.py b/hgext/patchbomb.py
--- a/hgext/patchbomb.py
+++ b/hgext/patchbomb.py
@@ -58,11 +58,11 @@ You can set patchbomb to always ask for
'''
import os, errno, socket, tempfile, cStringIO
import email
-from mercurial import cmdutil, commands, hg, mail, patch, util
+from mercurial import cmdutil, commands, hg, mail, patch, util, error
from mercurial import scmutil
from mercurial.i18n import _
from mercurial.node import bin
cmdtable = {}
@@ -499,28 +499,28 @@ def patchbomb(ui, repo, *revs, **opts):
if not (opts.get('test') or mbox):
# really sending
mail.validateconfig(ui)
if not (revs or rev or outgoing or bundle or patches):
- raise util.Abort(_('specify at least one changeset with -r or -o'))
+ raise error.Abort(_('specify at least one changeset with -r or -o'))
if outgoing and bundle:
- raise util.Abort(_("--outgoing mode always on with --bundle;"
+ raise error.Abort(_("--outgoing mode always on with --bundle;"
" do not re-specify --outgoing"))
if outgoing or bundle:
if len(revs) > 1:
- raise util.Abort(_("too many destinations"))
+ raise error.Abort(_("too many destinations"))
if revs:
dest = revs[0]
else:
dest = None
revs = []
if rev:
if revs:
- raise util.Abort(_('use only one form to specify the revision'))
+ raise error.Abort(_('use only one form to specify the revision'))
revs = rev
revs = scmutil.revrange(repo, revs)
if outgoing:
revs = _getoutgoing(repo, dest, revs)
@@ -576,11 +576,11 @@ def patchbomb(ui, repo, *revs, **opts):
return default
to = getaddrs('To', ask=True)
if not to:
# we can get here in non-interactive mode
- raise util.Abort(_('no recipient addresses provided'))
+ raise error.Abort(_('no recipient addresses provided'))
cc = getaddrs('Cc', ask=True, default='') or []
bcc = getaddrs('Bcc') or []
replyto = getaddrs('Reply-To')
confirm = ui.configbool('patchbomb', 'confirm')
@@ -596,11 +596,11 @@ def patchbomb(ui, repo, *revs, **opts):
if ds:
ui.write(ds, label='patchbomb.diffstats')
ui.write('\n')
if ui.promptchoice(_('are you sure you want to send (yn)?'
'$$ &Yes $$ &No')):
- raise util.Abort(_('patchbomb canceled'))
+ raise error.Abort(_('patchbomb canceled'))
ui.write('\n')
parent = opts.get('in_reply_to') or None
# angle brackets may be omitted, they're not semantically part of the msg-id
diff --git a/hgext/purge.py b/hgext/purge.py
--- a/hgext/purge.py
+++ b/hgext/purge.py
@@ -22,11 +22,11 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
'''command to delete untracked files from the working directory'''
-from mercurial import util, commands, cmdutil, scmutil
+from mercurial import util, commands, cmdutil, scmutil, error
from mercurial.i18n import _
import os
cmdtable = {}
command = cmdutil.command(cmdtable)
@@ -92,11 +92,11 @@ def purge(ui, repo, *dirs, **opts):
try:
remove_func(repo.wjoin(name))
except OSError:
m = _('%s cannot be removed') % name
if opts['abort_on_err']:
- raise util.Abort(m)
+ raise error.Abort(m)
ui.warn(_('warning: %s\n') % m)
else:
ui.write('%s%s' % (name, eol))
match = scmutil.match(repo[None], dirs, opts)
diff --git a/hgext/rebase.py b/hgext/rebase.py
--- a/hgext/rebase.py
+++ b/hgext/rebase.py
@@ -223,24 +223,24 @@ def rebase(ui, repo, **opts):
except KeyError:
enablehistedit = " --config extensions.histedit="
help = "hg%s help -e histedit" % enablehistedit
msg = _("interactive history editing is supported by the "
"'histedit' extension (see \"%s\")") % help
- raise util.Abort(msg)
+ raise error.Abort(msg)
if collapsemsg and not collapsef:
- raise util.Abort(
+ raise error.Abort(
_('message can only be specified with collapse'))
if contf or abortf:
if contf and abortf:
- raise util.Abort(_('cannot use both abort and continue'))
+ raise error.Abort(_('cannot use both abort and continue'))
if collapsef:
- raise util.Abort(
+ raise error.Abort(
_('cannot use collapse with continue or abort'))
if srcf or basef or destf:
- raise util.Abort(
+ raise error.Abort(
_('abort and continue do not allow specifying revisions'))
if abortf and opts.get('tool', False):
ui.warn(_('tool option will be ignored\n'))
try:
@@ -253,23 +253,23 @@ def rebase(ui, repo, **opts):
' only broken state is cleared)\n'))
return 0
else:
msg = _('cannot continue inconsistent rebase')
hint = _('use "hg rebase --abort" to clear broken state')
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
if abortf:
return abort(repo, originalwd, target, state,
activebookmark=activebookmark)
else:
if srcf and basef:
- raise util.Abort(_('cannot specify both a '
+ raise error.Abort(_('cannot specify both a '
'source and a base'))
if revf and basef:
- raise util.Abort(_('cannot specify both a '
+ raise error.Abort(_('cannot specify both a '
'revision and a base'))
if revf and srcf:
- raise util.Abort(_('cannot specify both a '
+ raise error.Abort(_('cannot specify both a '
'revision and a source'))
cmdutil.checkunfinished(repo)
cmdutil.bailifchanged(repo)
@@ -333,11 +333,11 @@ def rebase(ui, repo, **opts):
allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
if (not (keepf or allowunstable)
and repo.revs('first(children(%ld) - %ld)',
rebaseset, rebaseset)):
- raise util.Abort(
+ raise error.Abort(
_("can't remove original changesets with"
" unrebased descendants"),
hint=_('use --keep to keep original changesets'))
obsoletenotrebased = {}
@@ -359,11 +359,11 @@ def rebase(ui, repo, **opts):
ui.status(_('nothing to rebase\n'))
return 1
root = min(rebaseset)
if not keepf and not repo[root].mutable():
- raise util.Abort(_("can't rebase public changeset %s")
+ raise error.Abort(_("can't rebase public changeset %s")
% repo[root],
hint=_('see "hg help phases" for details'))
originalwd, target, state = result
if collapsef:
@@ -382,11 +382,11 @@ def rebase(ui, repo, **opts):
if collapsef:
branches = set()
for rev in state:
branches.add(repo[rev].branch())
if len(branches) > 1:
- raise util.Abort(_('cannot collapse multiple named '
+ raise error.Abort(_('cannot collapse multiple named '
'branches'))
# Rebase
if not targetancestors:
targetancestors = repo.changelog.ancestors([target], inclusive=True)
@@ -562,11 +562,11 @@ def externalparent(repo, state, targetan
parents.add(p.rev())
if not parents:
return nullrev
if len(parents) == 1:
return parents.pop()
- raise util.Abort(_('unable to collapse on top of %s, there is more '
+ raise error.Abort(_('unable to collapse on top of %s, there is more '
'than one external parent: %s') %
(max(targetancestors),
', '.join(str(p) for p in sorted(parents))))
def concludenode(repo, rev, p1, p2, commitmsg=None, editor=None, extrafn=None,
@@ -675,11 +675,11 @@ def defineparents(repo, rev, target, sta
p2 = target
else:
p2 = state[p2n]
else: # p2n external
if p2 != nullrev: # p1n external too => rev is a merged revision
- raise util.Abort(_('cannot use revision %d as base, result '
+ raise error.Abort(_('cannot use revision %d as base, result '
'would have 3 parents') % rev)
p2 = p2n
repo.ui.debug(" future parents are %d and %d\n" %
(repo[p1].rev(), repo[p2].rev()))
@@ -864,11 +864,11 @@ def restorestatus(repo):
# Legacy compat special case
else:
state[repo[oldrev].rev()] = repo[newrev].rev()
if keepbranches is None:
- raise util.Abort(_('.hg/rebasestate is incomplete'))
+ raise error.Abort(_('.hg/rebasestate is incomplete'))
skipped = set()
# recompute the set of skipped revs
if not collapse:
seen = set([target])
@@ -883,11 +883,11 @@ def restorestatus(repo):
return (originalwd, target, state, skipped,
collapse, keep, keepbranches, external, activebookmark)
except IOError as err:
if err.errno != errno.ENOENT:
raise
- raise util.Abort(_('no rebase in progress'))
+ raise error.Abort(_('no rebase in progress'))
def needupdate(repo, state):
'''check whether we should `update --clean` away from a merge, or if
somehow the working dir got forcibly updated, e.g. by older hg'''
parents = [p.rev() for p in repo.parents()]
@@ -957,22 +957,22 @@ def buildstate(repo, dest, rebaseset, co
# This check isn't strictly necessary, since mq detects commits over an
# applied patch. But it prevents messing up the working directory when
# a partially completed rebase is blocked by mq.
if 'qtip' in repo.tags() and (dest.node() in
[s.node for s in repo.mq.applied]):
- raise util.Abort(_('cannot rebase onto an applied mq patch'))
+ raise error.Abort(_('cannot rebase onto an applied mq patch'))
roots = list(repo.set('roots(%ld)', rebaseset))
if not roots:
- raise util.Abort(_('no matching revisions'))
+ raise error.Abort(_('no matching revisions'))
roots.sort()
state = {}
detachset = set()
for root in roots:
commonbase = root.ancestor(dest)
if commonbase == root:
- raise util.Abort(_('source is ancestor of destination'))
+ raise error.Abort(_('source is ancestor of destination'))
if commonbase == dest:
samebranch = root.branch() == dest.branch()
if not collapse and samebranch and root in dest.children():
repo.ui.debug('source is a child of destination\n')
return None
@@ -1112,11 +1112,11 @@ def pullrebase(orig, ui, repo, *args, **
% repo._activebookmark)
finally:
release(lock, wlock)
else:
if opts.get('tool'):
- raise util.Abort(_('--tool can only be used with --rebase'))
+ raise error.Abort(_('--tool can only be used with --rebase'))
orig(ui, repo, *args, **opts)
def _setrebasesetvisibility(repo, revs):
"""store the currently rebased set on the repo object
diff --git a/hgext/record.py b/hgext/record.py
--- a/hgext/record.py
+++ b/hgext/record.py
@@ -7,11 +7,11 @@
'''commands to interactively select changes for commit/qrefresh'''
from mercurial.i18n import _
from mercurial import cmdutil, commands, extensions
-from mercurial import util
+from mercurial import error
cmdtable = {}
command = cmdutil.command(cmdtable)
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
@@ -52,11 +52,11 @@ def record(ui, repo, *pats, **opts):
? - display help
This command is not available when committing a merge.'''
if not ui.interactive():
- raise util.Abort(_('running non-interactively, use %s instead') %
+ raise error.Abort(_('running non-interactively, use %s instead') %
'commit')
opts["interactive"] = True
backup = ui.backupconfig('experimental', 'crecord')
try:
@@ -97,11 +97,11 @@ def qrecord(ui, repo, patch, *pats, **op
def _qrecord(cmdsuggest, ui, repo, patch, *pats, **opts):
try:
mq = extensions.find('mq')
except KeyError:
- raise util.Abort(_("'mq' extension not loaded"))
+ raise error.Abort(_("'mq' extension not loaded"))
repo.mq.checkpatchname(patch)
def committomq(ui, repo, *pats, **opts):
opts['checkname'] = False
diff --git a/hgext/relink.py b/hgext/relink.py
--- a/hgext/relink.py
+++ b/hgext/relink.py
@@ -5,11 +5,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""recreates hardlinks between repository clones"""
-from mercurial import cmdutil, hg, util
+from mercurial import cmdutil, hg, util, error
from mercurial.i18n import _
import os, stat
cmdtable = {}
command = cmdutil.command(cmdtable)
@@ -45,21 +45,21 @@ def relink(ui, repo, origin=None, **opts
command is running. (Both repositories will be locked against
writes.)
"""
if (not util.safehasattr(util, 'samefile') or
not util.safehasattr(util, 'samedevice')):
- raise util.Abort(_('hardlinks are not supported on this system'))
+ raise error.Abort(_('hardlinks are not supported on this system'))
src = hg.repository(repo.baseui, ui.expandpath(origin or 'default-relink',
origin or 'default'))
ui.status(_('relinking %s to %s\n') % (src.store.path, repo.store.path))
if repo.root == src.root:
ui.status(_('there is nothing to relink\n'))
return
if not util.samedevice(src.store.path, repo.store.path):
# No point in continuing
- raise util.Abort(_('source and destination are on different devices'))
+ raise error.Abort(_('source and destination are on different devices'))
locallock = repo.lock()
try:
remotelock = src.lock()
try:
@@ -112,11 +112,11 @@ def prune(candidates, src, dst, ui):
return False
if util.samefile(src, dst):
return False
if not util.samedevice(src, dst):
# No point in continuing
- raise util.Abort(
+ raise error.Abort(
_('source and destination are on different devices'))
if st.st_size != ts.st_size:
return False
return st
diff --git a/hgext/schemes.py b/hgext/schemes.py
--- a/hgext/schemes.py
+++ b/hgext/schemes.py
@@ -39,11 +39,11 @@ For convenience, the extension adds thes
You can override a predefined scheme by defining a new scheme with the
same name.
"""
import os, re
-from mercurial import extensions, hg, templater, util
+from mercurial import extensions, hg, templater, util, error
from mercurial.i18n import _
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
@@ -67,11 +67,11 @@ class ShortRepository(object):
def instance(self, ui, url, create):
# Should this use the util.url class, or is manual parsing better?
try:
url = url.split('://', 1)[1]
except IndexError:
- raise util.Abort(_("no '://' in scheme url '%s'") % url)
+ raise error.Abort(_("no '://' in scheme url '%s'") % url)
parts = url.split('/', self.parts)
if len(parts) > self.parts:
tail = parts[-1]
parts = parts[:-1]
else:
@@ -99,10 +99,10 @@ def extsetup(ui):
schemes.update(dict(ui.configitems('schemes')))
t = templater.engine(lambda x: x)
for scheme, url in schemes.items():
if (os.name == 'nt' and len(scheme) == 1 and scheme.isalpha()
and os.path.exists('%s:\\' % scheme)):
- raise util.Abort(_('custom scheme %s:// conflicts with drive '
+ raise error.Abort(_('custom scheme %s:// conflicts with drive '
'letter %s:\\\n') % (scheme, scheme.upper()))
hg.schemes[scheme] = ShortRepository(url, scheme, t)
extensions.wrapfunction(util, 'hasdriveletter', hasdriveletter)
diff --git a/hgext/share.py b/hgext/share.py
--- a/hgext/share.py
+++ b/hgext/share.py
@@ -36,11 +36,11 @@ The following ``share.`` config options
The default naming mode is "identity."
'''
from mercurial.i18n import _
-from mercurial import cmdutil, commands, hg, util, extensions, bookmarks
+from mercurial import cmdutil, commands, hg, util, extensions, bookmarks, error
from mercurial.hg import repository, parseurl
import errno
cmdtable = {}
command = cmdutil.command(cmdtable)
@@ -81,11 +81,11 @@ def unshare(ui, repo):
Copy the store data to the repo and remove the sharedpath data.
"""
if not repo.shared():
- raise util.Abort(_("this is not a shared repo"))
+ raise error.Abort(_("this is not a shared repo"))
destlock = lock = None
lock = repo.lock()
try:
# we use locks here because if we race with commit, we
diff --git a/hgext/shelve.py b/hgext/shelve.py
--- a/hgext/shelve.py
+++ b/hgext/shelve.py
@@ -88,11 +88,11 @@ class shelvedfile(object):
try:
return self.vfs(self.fname, mode)
except IOError as err:
if err.errno != errno.ENOENT:
raise
- raise util.Abort(_("shelved change '%s' not found") % self.name)
+ raise error.Abort(_("shelved change '%s' not found") % self.name)
def applybundle(self):
fp = self.opener()
try:
gen = exchange.readbundle(self.repo.ui, fp, self.fname, self.vfs)
@@ -133,11 +133,11 @@ class shelvedstate(object):
fp = repo.vfs(cls._filename)
try:
version = int(fp.readline().strip())
if version != cls._version:
- raise util.Abort(_('this version of shelve is incompatible '
+ raise error.Abort(_('this version of shelve is incompatible '
'with the version used in this repo'))
name = fp.readline().strip()
wctx = fp.readline().strip()
pendingctx = fp.readline().strip()
parents = [bin(h) for h in fp.readline().split()]
@@ -240,11 +240,11 @@ def createcmd(ui, repo, pats, opts):
visit.append(parent)
wctx = repo[None]
parents = wctx.parents()
if len(parents) > 1:
- raise util.Abort(_('cannot shelve while merging'))
+ raise error.Abort(_('cannot shelve while merging'))
parent = parents[0]
# we never need the user, so we use a generic user for all shelve operations
user = 'shelve at localhost'
label = repo._activebookmark or parent.branch() or 'default'
@@ -291,26 +291,26 @@ def createcmd(ui, repo, pats, opts):
# pull races. ensure we don't print the abort message to stderr.
tr = repo.transaction('commit', report=lambda x: None)
if name:
if shelvedfile(repo, name, 'hg').exists():
- raise util.Abort(_("a shelved change named '%s' already exists")
- % name)
+ raise error.Abort(_("a shelved change named '%s' already exists"
+ ) % name)
else:
for n in gennames():
if not shelvedfile(repo, n, 'hg').exists():
name = n
break
else:
- raise util.Abort(_("too many shelved changes named '%s'") %
+ raise error.Abort(_("too many shelved changes named '%s'") %
label)
# ensure we are not creating a subdirectory or a hidden file
if '/' in name or '\\' in name:
- raise util.Abort(_('shelved change names may not contain slashes'))
+ raise error.Abort(_('shelved change names may not contain slashes'))
if name.startswith('.'):
- raise util.Abort(_("shelved change names may not start with '.'"))
+ raise error.Abort(_("shelved change names may not start with '.'"))
interactive = opts.get('interactive', False)
def interactivecommitfunc(ui, repo, *pats, **opts):
match = scmutil.match(repo['.'], pats, {})
message = opts['message']
@@ -360,21 +360,21 @@ def cleanupcmd(ui, repo):
lockmod.release(wlock)
def deletecmd(ui, repo, pats):
"""subcommand that deletes a specific shelve"""
if not pats:
- raise util.Abort(_('no shelved changes specified!'))
+ raise error.Abort(_('no shelved changes specified!'))
wlock = repo.wlock()
try:
for name in pats:
for suffix in 'hg patch'.split():
shelvedfile(repo, name, suffix).movetobackup()
cleanupoldbackups(repo)
except OSError as err:
if err.errno != errno.ENOENT:
raise
- raise util.Abort(_("shelved change '%s' not found") % name)
+ raise error.Abort(_("shelved change '%s' not found") % name)
finally:
lockmod.release(wlock)
def listshelves(repo):
"""return all shelves in repo as list of (time, filename)"""
@@ -442,22 +442,22 @@ def listcmd(ui, repo, pats, opts):
fp.close()
def singlepatchcmds(ui, repo, pats, opts, subcommand):
"""subcommand that displays a single shelf"""
if len(pats) != 1:
- raise util.Abort(_("--%s expects a single shelf") % subcommand)
+ raise error.Abort(_("--%s expects a single shelf") % subcommand)
shelfname = pats[0]
if not shelvedfile(repo, shelfname, 'patch').exists():
- raise util.Abort(_("cannot find shelf %s") % shelfname)
+ raise error.Abort(_("cannot find shelf %s") % shelfname)
listcmd(ui, repo, pats, opts)
def checkparents(repo, state):
"""check parent while resuming an unshelve"""
if state.parents != repo.dirstate.parents():
- raise util.Abort(_('working directory parents do not match unshelve '
+ raise error.Abort(_('working directory parents do not match unshelve '
'state'))
def pathtofiles(repo, files):
cwd = repo.getcwd()
return [repo.pathto(f, cwd) for f in files]
@@ -528,11 +528,11 @@ def unshelvecontinue(ui, repo, state, op
lock = None
try:
checkparents(repo, state)
ms = merge.mergestate(repo)
if [f for f in ms if ms[f] == 'u']:
- raise util.Abort(
+ raise error.Abort(
_("unresolved conflicts, can't continue"),
hint=_("see 'hg resolve', then 'hg unshelve --continue'"))
lock = repo.lock()
@@ -611,39 +611,39 @@ def unshelve(ui, repo, *shelved, **opts)
if not abortf and not continuef:
cmdutil.checkunfinished(repo)
if abortf or continuef:
if abortf and continuef:
- raise util.Abort(_('cannot use both abort and continue'))
+ raise error.Abort(_('cannot use both abort and continue'))
if shelved:
- raise util.Abort(_('cannot combine abort/continue with '
+ raise error.Abort(_('cannot combine abort/continue with '
'naming a shelved change'))
try:
state = shelvedstate.load(repo)
except IOError as err:
if err.errno != errno.ENOENT:
raise
- raise util.Abort(_('no unshelve operation underway'))
+ raise error.Abort(_('no unshelve operation underway'))
if abortf:
return unshelveabort(ui, repo, state, opts)
elif continuef:
return unshelvecontinue(ui, repo, state, opts)
elif len(shelved) > 1:
- raise util.Abort(_('can only unshelve one change at a time'))
+ raise error.Abort(_('can only unshelve one change at a time'))
elif not shelved:
shelved = listshelves(repo)
if not shelved:
- raise util.Abort(_('no shelved changes to apply!'))
+ raise error.Abort(_('no shelved changes to apply!'))
basename = util.split(shelved[0][1])[1]
ui.status(_("unshelving change '%s'\n") % basename)
else:
basename = shelved[0]
if not shelvedfile(repo, basename, 'patch').exists():
- raise util.Abort(_("shelved change '%s' not found") % basename)
+ raise error.Abort(_("shelved change '%s' not found") % basename)
oldquiet = ui.quiet
wlock = lock = tr = None
try:
wlock = repo.wlock()
@@ -809,16 +809,16 @@ def shelvecmd(ui, repo, *pats, **opts):
]
def checkopt(opt):
if opts[opt]:
for i, allowable in allowables:
if opts[i] and opt not in allowable:
- raise util.Abort(_("options '--%s' and '--%s' may not be "
+ raise error.Abort(_("options '--%s' and '--%s' may not be "
"used together") % (opt, i))
return True
if checkopt('cleanup'):
if pats:
- raise util.Abort(_("cannot specify names when using '--cleanup'"))
+ raise error.Abort(_("cannot specify names when using '--cleanup'"))
return cleanupcmd(ui, repo)
elif checkopt('delete'):
return deletecmd(ui, repo, pats)
elif checkopt('list'):
return listcmd(ui, repo, pats, opts)
diff --git a/hgext/strip.py b/hgext/strip.py
--- a/hgext/strip.py
+++ b/hgext/strip.py
@@ -4,11 +4,11 @@ This extension allows you to strip chang
repository. See the command help for details.
"""
from mercurial.i18n import _
from mercurial.node import nullid
from mercurial.lock import release
-from mercurial import cmdutil, hg, scmutil, util
+from mercurial import cmdutil, hg, scmutil, util, error
from mercurial import repair, bookmarks, merge
cmdtable = {}
command = cmdutil.command(cmdtable)
# Note for extension authors: ONLY specify testedwith = 'internal' for
@@ -36,14 +36,14 @@ def checklocalchanges(repo, force=False,
cmdutil.checkunfinished(repo)
s = repo.status()
if not force:
if s.modified or s.added or s.removed or s.deleted:
_("local changes found") # i18n tool detection
- raise util.Abort(_("local changes found" + excsuffix))
+ raise error.Abort(_("local changes found" + excsuffix))
if checksubstate(repo):
_("local changed subrepos found") # i18n tool detection
- raise util.Abort(_("local changed subrepos found" + excsuffix))
+ raise error.Abort(_("local changed subrepos found" + excsuffix))
return s
def strip(ui, repo, revs, update=True, backup=True, force=None, bookmark=None):
wlock = lock = None
try:
@@ -129,11 +129,11 @@ def stripcmd(ui, repo, *revs, **opts):
try:
if opts.get('bookmark'):
mark = opts.get('bookmark')
marks = repo._bookmarks
if mark not in marks:
- raise util.Abort(_("bookmark '%s' not found") % mark)
+ raise error.Abort(_("bookmark '%s' not found") % mark)
# If the requested bookmark is not the only one pointing to a
# a revision we have to only delete the bookmark and not strip
# anything. revsets cannot detect that case.
uniquebm = True
@@ -151,11 +151,11 @@ def stripcmd(ui, repo, *revs, **opts):
del marks[mark]
marks.write()
ui.write(_("bookmark '%s' deleted\n") % mark)
if not revs:
- raise util.Abort(_('empty revision set'))
+ raise error.Abort(_('empty revision set'))
descendants = set(cl.descendants(revs))
strippedrevs = revs.union(descendants)
roots = revs.difference(descendants)
diff --git a/hgext/transplant.py b/hgext/transplant.py
--- a/hgext/transplant.py
+++ b/hgext/transplant.py
@@ -173,11 +173,11 @@ class transplanter(object):
% (rev, short(node)))
skipmerge = True
else:
parent = source.lookup(opts['parent'])
if parent not in parents:
- raise util.Abort(_('%s is not a parent of %s') %
+ raise error.Abort(_('%s is not a parent of %s') %
(short(parent), short(node)))
else:
parent = parents[0]
if skipmerge:
@@ -248,11 +248,11 @@ class transplanter(object):
self.ui.system('%s %s %s' % (filter, util.shellquote(headerfile),
util.shellquote(patchfile)),
environ={'HGUSER': changelog[1],
'HGREVISION': revlog.hex(node),
},
- onerr=util.Abort, errprefix=_('filter failed'))
+ onerr=error.Abort, errprefix=_('filter failed'))
user, date, msg = self.parselog(file(headerfile))[1:4]
finally:
os.unlink(headerfile)
return (user, date, msg)
@@ -272,11 +272,11 @@ class transplanter(object):
self.ui.status(_('applying %s\n') % short(node))
self.ui.note('%s %s\n%s\n' % (user, date, message))
if not patchfile and not merge:
- raise util.Abort(_('can only omit patchfile if merging'))
+ raise error.Abort(_('can only omit patchfile if merging'))
if patchfile:
try:
files = set()
patch.patch(self.ui, repo, patchfile, files=files, eolmode=None)
files = list(files)
@@ -335,37 +335,37 @@ class transplanter(object):
'''commit working directory using journal metadata'''
node, user, date, message, parents = self.readlog()
merge = False
if not user or not date or not message or not parents[0]:
- raise util.Abort(_('transplant log file is corrupt'))
+ raise error.Abort(_('transplant log file is corrupt'))
parent = parents[0]
if len(parents) > 1:
if opts.get('parent'):
parent = source.lookup(opts['parent'])
if parent not in parents:
- raise util.Abort(_('%s is not a parent of %s') %
+ raise error.Abort(_('%s is not a parent of %s') %
(short(parent), short(node)))
else:
merge = True
extra = {'transplant_source': node}
wlock = repo.wlock()
try:
p1, p2 = repo.dirstate.parents()
if p1 != parent:
- raise util.Abort(_('working directory not at transplant '
+ raise error.Abort(_('working directory not at transplant '
'parent %s') % revlog.hex(parent))
if merge:
repo.setparents(p1, parents[1])
modified, added, removed, deleted = repo.status()[:4]
if merge or modified or added or removed or deleted:
n = repo.commit(message, user, date, extra=extra,
editor=self.getcommiteditor())
if not n:
- raise util.Abort(_('commit failed'))
+ raise error.Abort(_('commit failed'))
if not merge:
self.transplants.set(n, node)
else:
n = None
self.unlog()
@@ -421,11 +421,11 @@ class transplanter(object):
parents.append(revlog.bin(line[9:]))
elif not line.startswith('# '):
inmsg = True
message.append(line)
if None in (user, date):
- raise util.Abort(_("filter corrupted changeset (no user or date)"))
+ raise error.Abort(_("filter corrupted changeset (no user or date)"))
return (node, user, date, '\n'.join(message), parents)
def log(self, user, date, message, p1, p2, merge=False):
'''journal changelog metadata for later recover'''
@@ -597,22 +597,22 @@ def transplant(ui, repo, *revs, **opts):
yield node
def checkopts(opts, revs):
if opts.get('continue'):
if opts.get('branch') or opts.get('all') or opts.get('merge'):
- raise util.Abort(_('--continue is incompatible with '
+ raise error.Abort(_('--continue is incompatible with '
'--branch, --all and --merge'))
return
if not (opts.get('source') or revs or
opts.get('merge') or opts.get('branch')):
- raise util.Abort(_('no source URL, branch revision or revision '
+ raise error.Abort(_('no source URL, branch revision or revision '
'list provided'))
if opts.get('all'):
if not opts.get('branch'):
- raise util.Abort(_('--all requires a branch revision'))
+ raise error.Abort(_('--all requires a branch revision'))
if revs:
- raise util.Abort(_('--all is incompatible with a '
+ raise error.Abort(_('--all is incompatible with a '
'revision list'))
checkopts(opts, revs)
if not opts.get('log'):
@@ -625,17 +625,17 @@ def transplant(ui, repo, *revs, **opts):
tp = transplanter(ui, repo, opts)
cmdutil.checkunfinished(repo)
p1, p2 = repo.dirstate.parents()
if len(repo) > 0 and p1 == revlog.nullid:
- raise util.Abort(_('no revision checked out'))
+ raise error.Abort(_('no revision checked out'))
if not opts.get('continue'):
if p2 != revlog.nullid:
- raise util.Abort(_('outstanding uncommitted merges'))
+ raise error.Abort(_('outstanding uncommitted merges'))
m, a, r, d = repo.status()[:4]
if m or a or r or d:
- raise util.Abort(_('outstanding local changes'))
+ raise error.Abort(_('outstanding local changes'))
sourcerepo = opts.get('source')
if sourcerepo:
peer = hg.peer(repo, opts, ui.expandpath(sourcerepo))
heads = map(peer.lookup, opts.get('branch', ()))
diff --git a/hgext/win32mbcs.py b/hgext/win32mbcs.py
--- a/hgext/win32mbcs.py
+++ b/hgext/win32mbcs.py
@@ -45,11 +45,11 @@ You can specify the encoding by config o
It is useful for the users who want to commit with UTF-8 log message.
'''
import os, sys
from mercurial.i18n import _
-from mercurial import util, encoding
+from mercurial import error, encoding
# Note for extension authors: ONLY specify testedwith = 'internal' for
# extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
# be specifying the version(s) of Mercurial they are tested with, or
# leave the attribute unspecified.
testedwith = 'internal'
@@ -103,11 +103,11 @@ def basewrapper(func, argtype, enc, dec,
try:
# convert string arguments, call func, then convert back the
# return value.
return enc(func(*dec(args), **dec(kwds)))
except UnicodeError:
- raise util.Abort(_("[win32mbcs] filename conversion failed with"
+ raise error.Abort(_("[win32mbcs] filename conversion failed with"
" %s encoding\n") % (_encoding))
def wrapper(func, args, kwds):
return basewrapper(func, unicode, encode, decode, args, kwds)
diff --git a/mercurial/archival.py b/mercurial/archival.py
--- a/mercurial/archival.py
+++ b/mercurial/archival.py
@@ -53,11 +53,11 @@ def tidyprefix(dest, kind, prefix):
# Drop the leading '.' path component if present, so Windows can read the
# zip files (issue4634)
if prefix.startswith('./'):
prefix = prefix[2:]
if prefix.startswith('../') or os.path.isabs(lpfx) or '/../' in prefix:
- raise util.Abort(_('archive prefix contains illegal components'))
+ raise error.Abort(_('archive prefix contains illegal components'))
return prefix
exts = {
'tar': ['.tar'],
'tbz2': ['.tbz2', '.tar.bz2'],
@@ -290,22 +290,22 @@ def archive(repo, dest, node, kind, deco
prefix is name of path to put before every archive member.'''
if kind == 'files':
if prefix:
- raise util.Abort(_('cannot give prefix when archiving to files'))
+ raise error.Abort(_('cannot give prefix when archiving to files'))
else:
prefix = tidyprefix(dest, kind, prefix)
def write(name, mode, islink, getdata):
data = getdata()
if decode:
data = repo.wwritedata(name, data)
archiver.addfile(prefix + name, mode, islink, data)
if kind not in archivers:
- raise util.Abort(_("unknown archive type '%s'") % kind)
+ raise error.Abort(_("unknown archive type '%s'") % kind)
ctx = repo[node]
archiver = archivers[kind](dest, mtime or ctx.date()[0])
if repo.ui.configbool("ui", "archivemeta", True):
diff --git a/mercurial/branchmap.py b/mercurial/branchmap.py
--- a/mercurial/branchmap.py
+++ b/mercurial/branchmap.py
@@ -17,12 +17,12 @@ from .node import (
nullid,
nullrev,
)
from . import (
encoding,
+ error,
scmutil,
- util,
)
array = array.array
calcsize = struct.calcsize
pack = struct.pack
@@ -248,11 +248,11 @@ class branchcache(dict):
encoding.fromlocal(label)))
f.close()
repo.ui.log('branchcache',
'wrote %s branch cache with %d labels and %d nodes\n',
repo.filtername, len(self), nodecount)
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
repo.ui.debug("couldn't write branch cache: %s\n" % inst)
# Abort may be raise by read only opener
pass
def update(self, repo, revgen):
@@ -463,11 +463,11 @@ class revbranchcache(object):
f = repo.vfs.open(_rbcnames, 'wb')
f.write('\0'.join(encoding.fromlocal(b)
for b in self._names[self._rbcnamescount:]))
self._rbcsnameslen = f.tell()
f.close()
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
repo.ui.debug("couldn't write revision branch cache names: "
"%s\n" % inst)
return
self._rbcnamescount = len(self._names)
@@ -481,10 +481,10 @@ class revbranchcache(object):
f.seek(start)
f.truncate()
end = revs * _rbcrecsize
f.write(self._rbcrevs[start:end])
f.close()
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
repo.ui.debug("couldn't write revision branch cache: %s\n" %
inst)
return
self._rbcrevslen = revs
diff --git a/mercurial/bundle2.py b/mercurial/bundle2.py
--- a/mercurial/bundle2.py
+++ b/mercurial/bundle2.py
@@ -625,14 +625,14 @@ def getunbundler(ui, fp, magicstring=Non
"""return a valid unbundler object for a given magicstring"""
if magicstring is None:
magicstring = changegroup.readexactly(fp, 4)
magic, version = magicstring[0:2], magicstring[2:4]
if magic != 'HG':
- raise util.Abort(_('not a Mercurial bundle'))
+ raise error.Abort(_('not a Mercurial bundle'))
unbundlerclass = formatmap.get(version)
if unbundlerclass is None:
- raise util.Abort(_('unknown bundle version %s') % version)
+ raise error.Abort(_('unknown bundle version %s') % version)
unbundler = unbundlerclass(ui, fp)
indebug(ui, 'start processing of %s stream' % magicstring)
return unbundler
class unbundle20(unpackermixin):
@@ -1204,11 +1204,11 @@ class unbundlepart(unpackermixin):
if self._pos != newpos:
chunk, internaloffset = self._findchunk(newpos)
self._payloadstream = util.chunkbuffer(self._payloadchunks(chunk))
adjust = self.read(internaloffset)
if len(adjust) != internaloffset:
- raise util.Abort(_('Seek failed\n'))
+ raise error.Abort(_('Seek failed\n'))
self._pos = newpos
# These are only the static capabilities.
# Check the 'getrepocaps' function for the rest.
capabilities = {'HG20': (),
@@ -1302,31 +1302,31 @@ def handleremotechangegroup(op, inpart):
When multiple digest types are given, all of them are checked.
"""
try:
raw_url = inpart.params['url']
except KeyError:
- raise util.Abort(_('remote-changegroup: missing "%s" param') % 'url')
+ raise error.Abort(_('remote-changegroup: missing "%s" param') % 'url')
parsed_url = util.url(raw_url)
if parsed_url.scheme not in capabilities['remote-changegroup']:
- raise util.Abort(_('remote-changegroup does not support %s urls') %
+ raise error.Abort(_('remote-changegroup does not support %s urls') %
parsed_url.scheme)
try:
size = int(inpart.params['size'])
except ValueError:
- raise util.Abort(_('remote-changegroup: invalid value for param "%s"')
+ raise error.Abort(_('remote-changegroup: invalid value for param "%s"')
% 'size')
except KeyError:
- raise util.Abort(_('remote-changegroup: missing "%s" param') % 'size')
+ raise error.Abort(_('remote-changegroup: missing "%s" param') % 'size')
digests = {}
for typ in inpart.params.get('digests', '').split():
param = 'digest:%s' % typ
try:
value = inpart.params[param]
except KeyError:
- raise util.Abort(_('remote-changegroup: missing "%s" param') %
+ raise error.Abort(_('remote-changegroup: missing "%s" param') %
param)
digests[typ] = value
real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
@@ -1337,11 +1337,11 @@ def handleremotechangegroup(op, inpart):
# for the whole processing scope.
op.gettransaction()
from . import exchange
cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
if not isinstance(cg, changegroup.cg1unpacker):
- raise util.Abort(_('%s: not a bundle version 1.0') %
+ raise error.Abort(_('%s: not a bundle version 1.0') %
util.hidepassword(raw_url))
ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
op.records.add('changegroup', {'return': ret})
if op.reply is not None:
# This is definitely not the final form of this
@@ -1349,12 +1349,12 @@ def handleremotechangegroup(op, inpart):
part = op.reply.newpart('reply:changegroup')
part.addparam('in-reply-to', str(inpart.id), mandatory=False)
part.addparam('return', '%i' % ret, mandatory=False)
try:
real_part.validate()
- except util.Abort as e:
- raise util.Abort(_('bundle at %s is corrupted:\n%s') %
+ except error.Abort as e:
+ raise error.Abort(_('bundle at %s is corrupted:\n%s') %
(util.hidepassword(raw_url), str(e)))
assert not inpart.read()
@parthandler('reply:changegroup', ('return', 'in-reply-to'))
def handlereplychangegroup(op, inpart):
@@ -1394,11 +1394,11 @@ def handlereplycaps(op, inpart):
op.reply = bundle20(op.ui, caps)
@parthandler('error:abort', ('message', 'hint'))
def handleerrorabort(op, inpart):
"""Used to transmit abort error over the wire"""
- raise util.Abort(inpart.params['message'], hint=inpart.params.get('hint'))
+ raise error.Abort(inpart.params['message'], hint=inpart.params.get('hint'))
@parthandler('error:pushkey', ('namespace', 'key', 'new', 'old', 'ret',
'in-reply-to'))
def handleerrorpushkey(op, inpart):
"""Used to transmit failure of a mandatory pushkey over the wire"""
diff --git a/mercurial/bundlerepo.py b/mercurial/bundlerepo.py
--- a/mercurial/bundlerepo.py
+++ b/mercurial/bundlerepo.py
@@ -280,11 +280,11 @@ class bundlerepository(localrepo.localre
if (part.type == 'changegroup')
and (part.params.get('version', '01')
in changegroup.packermap)]
if not cgparts:
- raise util.Abort('No changegroups found')
+ raise error.Abort('No changegroups found')
version = cgparts[0].params.get('version', '01')
cgparts = [p for p in cgparts
if p.params.get('version', '01') == version]
if len(cgparts) > 1:
raise NotImplementedError("Can't process multiple changegroups")
@@ -372,11 +372,11 @@ class bundlerepository(localrepo.localre
return os.getcwd() # always outside the repo
def instance(ui, path, create):
if create:
- raise util.Abort(_('cannot create new bundle repository'))
+ raise error.Abort(_('cannot create new bundle repository'))
# internal config: bundle.mainreporoot
parentpath = ui.config("bundle", "mainreporoot", "")
if not parentpath:
# try to find the correct path to the working directory repo
parentpath = cmdutil.findrepo(os.getcwd())
diff --git a/mercurial/changegroup.py b/mercurial/changegroup.py
--- a/mercurial/changegroup.py
+++ b/mercurial/changegroup.py
@@ -35,22 +35,22 @@ from . import (
def readexactly(stream, n):
'''read n bytes from stream.read and abort if less was available'''
s = stream.read(n)
if len(s) < n:
- raise util.Abort(_("stream ended unexpectedly"
+ raise error.Abort(_("stream ended unexpectedly"
" (got %d bytes, expected %d)")
% (len(s), n))
return s
def getchunk(stream):
"""return the next chunk from stream as a string"""
d = readexactly(stream, 4)
l = struct.unpack(">l", d)[0]
if l <= 4:
if l:
- raise util.Abort(_("invalid chunk length %d") % l)
+ raise error.Abort(_("invalid chunk length %d") % l)
return ""
return readexactly(stream, l - 4)
def chunkheader(length):
"""return a changegroup chunk header (string)"""
@@ -142,16 +142,16 @@ def writebundle(ui, cg, filename, bundle
chunkiter = bundle.getchunks()
else:
# compression argument is only for the bundle2 case
assert compression is None
if cg.version != '01':
- raise util.Abort(_('old bundle types only supports v1 '
- 'changegroups'))
+ raise error.Abort(_('old bundle types only supports v1 '
+ 'changegroups'))
header, comp = bundletypes[bundletype]
if comp not in util.compressors:
- raise util.Abort(_('unknown stream compression type: %s')
- % comp)
+ raise error.Abort(_('unknown stream compression type: %s')
+ % comp)
z = util.compressors[comp]()
subchunkiter = cg.getchunks()
def chunkiter():
yield header
for chunk in subchunkiter:
@@ -173,11 +173,11 @@ class cg1unpacker(object):
version = '01'
def __init__(self, fh, alg):
if alg == 'UN':
alg = None # get more modern without breaking too much
if not alg in util.decompressors:
- raise util.Abort(_('unknown stream compression type: %s')
+ raise error.Abort(_('unknown stream compression type: %s')
% alg)
if alg == 'BZ':
alg = '_truncatedBZ'
self._stream = util.decompressors[alg](fh)
self._type = alg
@@ -196,11 +196,11 @@ class cg1unpacker(object):
def chunklength(self):
d = readexactly(self._stream, 4)
l = struct.unpack(">l", d)[0]
if l <= 4:
if l:
- raise util.Abort(_("invalid chunk length %d") % l)
+ raise error.Abort(_("invalid chunk length %d") % l)
return 0
if self.callback:
self.callback()
return l - 4
@@ -475,11 +475,11 @@ class cg1packer(object):
# for progress output
msgfiles = _('files')
for i, fname in enumerate(sorted(changedfiles)):
filerevlog = repo.file(fname)
if not filerevlog:
- raise util.Abort(_("empty or missing revlog for %s") % fname)
+ raise error.Abort(_("empty or missing revlog for %s") % fname)
linkrevnodes = linknodes(filerevlog, fname)
# Lookup for filenodes, we collected the linkrev nodes above in the
# fastpath case and with lookupmf in the slowpath case.
def lookupfilelog(x):
@@ -686,23 +686,23 @@ def addchangegroupfiles(repo, source, re
pr()
fl = repo.file(f)
o = len(fl)
try:
if not fl.addgroup(source, revmap, trp):
- raise util.Abort(_("received file revlog group is empty"))
+ raise error.Abort(_("received file revlog group is empty"))
except error.CensoredBaseError as e:
- raise util.Abort(_("received delta base is censored: %s") % e)
+ raise error.Abort(_("received delta base is censored: %s") % e)
revisions += len(fl) - o
files += 1
if f in needfiles:
needs = needfiles[f]
for new in xrange(o, len(fl)):
n = fl.node(new)
if n in needs:
needs.remove(n)
else:
- raise util.Abort(
+ raise error.Abort(
_("received spurious file revlog entry"))
if not needs:
del needfiles[f]
repo.ui.progress(_('files'), None)
@@ -710,11 +710,11 @@ def addchangegroupfiles(repo, source, re
fl = repo.file(f)
for n in needs:
try:
fl.rev(n)
except error.LookupError:
- raise util.Abort(
+ raise error.Abort(
_('missing file data for %s:%s - run hg verify') %
(f, hex(n)))
return revisions, files
@@ -782,11 +782,11 @@ def addchangegroup(repo, source, srctype
srccontent = cl.addgroup(source, csmap, trp,
addrevisioncb=onchangelog)
efiles = len(efiles)
if not (srccontent or emptyok):
- raise util.Abort(_("received changelog group is empty"))
+ raise error.Abort(_("received changelog group is empty"))
clend = len(cl)
changesets = clend - clstart
repo.ui.progress(_('changesets'), None)
# pull off the manifest group
diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py
--- a/mercurial/cmdutil.py
+++ b/mercurial/cmdutil.py
@@ -83,11 +83,11 @@ def dorecord(ui, repo, commitfunc, cmdsu
if not ui.interactive():
if cmdsuggest:
msg = _('running non-interactively, use %s instead') % cmdsuggest
else:
msg = _('running non-interactively')
- raise util.Abort(msg)
+ raise error.Abort(msg)
# make sure username is set before going interactive
if not opts.get('user'):
ui.username() # raise exception, username not provided
@@ -107,11 +107,11 @@ def dorecord(ui, repo, commitfunc, cmdsu
"""
checkunfinished(repo, commit=True)
merge = len(repo[None].parents()) > 1
if merge:
- raise util.Abort(_('cannot partially commit a merge '
+ raise error.Abort(_('cannot partially commit a merge '
'(use "hg commit" instead)'))
status = repo.status(match=match)
diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
diffopts.nodates = True
@@ -121,11 +121,11 @@ def dorecord(ui, repo, commitfunc, cmdsu
# 1. filter patch, so we have intending-to apply subset of it
try:
chunks = filterfn(ui, originalchunks)
except patch.PatchError as err:
- raise util.Abort(_('error parsing patch: %s') % err)
+ raise error.Abort(_('error parsing patch: %s') % err)
# We need to keep a backup of files that have been newly added and
# modified during the recording process because there is a previous
# version without the edit in the workdir
newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
@@ -191,11 +191,11 @@ def dorecord(ui, repo, commitfunc, cmdsu
try:
ui.debug('applying patch\n')
ui.debug(fp.getvalue())
patch.internalpatch(ui, repo, fp, 1, eolmode=None)
except patch.PatchError as err:
- raise util.Abort(str(err))
+ raise error.Abort(str(err))
del fp
# 4. We prepared working directory according to filtered
# patch. Now is the time to delegate the job to
# commit/qrefresh or the like!
@@ -303,34 +303,34 @@ def findrepo(p):
return p
def bailifchanged(repo, merge=True):
if merge and repo.dirstate.p2() != nullid:
- raise util.Abort(_('outstanding uncommitted merge'))
+ raise error.Abort(_('outstanding uncommitted merge'))
modified, added, removed, deleted = repo.status()[:4]
if modified or added or removed or deleted:
- raise util.Abort(_('uncommitted changes'))
+ raise error.Abort(_('uncommitted changes'))
ctx = repo[None]
for s in sorted(ctx.substate):
ctx.sub(s).bailifchanged()
def logmessage(ui, opts):
""" get the log message according to -m and -l option """
message = opts.get('message')
logfile = opts.get('logfile')
if message and logfile:
- raise util.Abort(_('options --message and --logfile are mutually '
+ raise error.Abort(_('options --message and --logfile are mutually '
'exclusive'))
if not message and logfile:
try:
if logfile == '-':
message = ui.fin.read()
else:
message = '\n'.join(util.readfile(logfile).splitlines())
except IOError as inst:
- raise util.Abort(_("can't read commit message '%s': %s") %
+ raise error.Abort(_("can't read commit message '%s': %s") %
(logfile, inst.strerror))
return message
def mergeeditform(ctxorbool, baseformname):
"""return appropriate editform name (referencing a committemplate)
@@ -385,13 +385,13 @@ def loglimit(opts):
limit = opts.get('limit')
if limit:
try:
limit = int(limit)
except ValueError:
- raise util.Abort(_('limit must be a positive integer'))
+ raise error.Abort(_('limit must be a positive integer'))
if limit <= 0:
- raise util.Abort(_('limit must be positive'))
+ raise error.Abort(_('limit must be positive'))
else:
limit = None
return limit
def makefilename(repo, pat, node, desc=None,
@@ -435,11 +435,11 @@ def makefilename(repo, pat, node, desc=N
c = expander[c]()
newname.append(c)
i += 1
return ''.join(newname)
except KeyError as inst:
- raise util.Abort(_("invalid format spec '%%%s' in output filename") %
+ raise error.Abort(_("invalid format spec '%%%s' in output filename") %
inst.args[0])
def makefileobj(repo, pat, node=None, desc=None, total=None,
seqno=None, revwidth=None, mode='wb', modemap=None,
pathname=None):
@@ -493,19 +493,19 @@ def openrevlog(repo, cmd, file_, opts):
msg = _('cannot specify filename with --changelog or --manifest')
elif not repo:
msg = _('cannot specify --changelog or --manifest or --dir '
'without a repository')
if msg:
- raise util.Abort(msg)
+ raise error.Abort(msg)
r = None
if repo:
if cl:
r = repo.unfiltered().changelog
elif dir:
if 'treemanifest' not in repo.requirements:
- raise util.Abort(_("--dir can only be used on repos with "
+ raise error.Abort(_("--dir can only be used on repos with "
"treemanifest enabled"))
dirlog = repo.dirlog(file_)
if len(dirlog):
r = dirlog
elif mf:
@@ -516,11 +516,11 @@ def openrevlog(repo, cmd, file_, opts):
r = filelog
if not r:
if not file_:
raise error.CommandError(cmd, _('invalid arguments'))
if not os.path.isfile(file_):
- raise util.Abort(_("revlog '%s' not found") % file_)
+ raise error.Abort(_("revlog '%s' not found") % file_)
r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
file_[:-2] + ".i")
return r
def copy(ui, repo, pats, opts, rename=False):
@@ -714,21 +714,21 @@ def copy(ui, repo, pats, opts, rename=Fa
res = lambda p: dest
return res
pats = scmutil.expandpats(pats)
if not pats:
- raise util.Abort(_('no source or destination specified'))
+ raise error.Abort(_('no source or destination specified'))
if len(pats) == 1:
- raise util.Abort(_('no destination specified'))
+ raise error.Abort(_('no destination specified'))
dest = pats.pop()
destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
if not destdirexists:
if len(pats) > 1 or matchmod.patkind(pats[0]):
- raise util.Abort(_('with multiple sources, destination must be an '
+ raise error.Abort(_('with multiple sources, destination must be an '
'existing directory'))
if util.endswithsep(dest):
- raise util.Abort(_('destination %s is not a directory') % dest)
+ raise error.Abort(_('destination %s is not a directory') % dest)
tfn = targetpathfn
if after:
tfn = targetpathafterfn
copylist = []
@@ -736,11 +736,11 @@ def copy(ui, repo, pats, opts, rename=Fa
srcs = walkpat(pat)
if not srcs:
continue
copylist.append((tfn(pat, dest, srcs), srcs))
if not copylist:
- raise util.Abort(_('no files to copy'))
+ raise error.Abort(_('no files to copy'))
errors = 0
for targetpath, srcs in copylist:
for abssrc, relsrc, exact in srcs:
if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
@@ -784,11 +784,11 @@ def service(opts, parentfn=None, initfn=
break
def condfn():
return not os.path.exists(lockpath)
pid = util.rundetached(runargs, condfn)
if pid < 0:
- raise util.Abort(_('child process failed to start'))
+ raise error.Abort(_('child process failed to start'))
writepid(pid)
finally:
try:
os.unlink(lockpath)
except OSError as e:
@@ -907,11 +907,11 @@ def tryimportone(ui, repo, hunk, parents
if len(parents) == 1:
parents.append(repo[nullid])
if opts.get('exact'):
if not nodeid or not p1:
- raise util.Abort(_('not a Mercurial patch'))
+ raise error.Abort(_('not a Mercurial patch'))
p1 = repo[p1]
p2 = repo[p2 or nullid]
elif p2:
try:
p1 = repo[p1]
@@ -946,11 +946,11 @@ def tryimportone(ui, repo, hunk, parents
try:
patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
files=files, eolmode=None, similarity=sim / 100.0)
except patch.PatchError as e:
if not partial:
- raise util.Abort(str(e))
+ raise error.Abort(str(e))
if partial:
rejects = True
files = list(files)
if opts.get('no_commit'):
@@ -994,11 +994,11 @@ def tryimportone(ui, repo, hunk, parents
files = set()
try:
patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
files, eolmode=None)
except patch.PatchError as e:
- raise util.Abort(str(e))
+ raise error.Abort(str(e))
if opts.get('exact'):
editor = None
else:
editor = getcommiteditor(editform='import.bypass')
memctx = context.makememctx(repo, (p1.node(), p2.node()),
@@ -1013,11 +1013,11 @@ def tryimportone(ui, repo, hunk, parents
if opts.get('exact') and opts.get('no_commit'):
# --exact with --no-commit is still useful in that it does merge
# and branch bits
ui.warn(_("warning: can't check exact import with --no-commit\n"))
elif opts.get('exact') and hex(n) != nodeid:
- raise util.Abort(_('patch is damaged or loses information'))
+ raise error.Abort(_('patch is damaged or loses information'))
if n:
# i18n: refers to a short changeset id
msg = _('created %s') % short(n)
return (msg, n, rejects)
finally:
@@ -1502,13 +1502,13 @@ class changeset_templater(changeset_prin
if not self.footer:
self.footer = templater.stringify(
self.t(self._parts['footer'], **props))
except KeyError as inst:
msg = _("%s: no key named '%s'")
- raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
+ raise error.Abort(msg % (self.t.mapfile, inst.args[0]))
except SyntaxError as inst:
- raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
+ raise error.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
def gettemplate(ui, tmpl, style):
"""
Find the template matching the given template spec or style.
"""
@@ -1565,11 +1565,11 @@ def show_changeset(ui, repo, opts, buffe
try:
t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
buffered)
except SyntaxError as inst:
- raise util.Abort(inst.args[0])
+ raise error.Abort(inst.args[0])
return t
def showmarker(ui, marker):
"""utility function to display obsolescence marker in a readable way
@@ -1605,11 +1605,11 @@ def finddate(ui, repo, date):
if rev in results:
ui.status(_("found revision %s from %s\n") %
(rev, util.datestr(results[rev])))
return str(rev)
- raise util.Abort(_("revision matching date not found"))
+ raise error.Abort(_("revision matching date not found"))
def increasingwindows(windowsize=8, sizelimit=512):
while True:
yield windowsize
if windowsize < sizelimit:
@@ -1660,11 +1660,11 @@ def walkfilerevs(repo, match, follow, re
def iterfiles():
pctx = repo['.']
for filename in match.files():
if follow:
if filename not in pctx:
- raise util.Abort(_('cannot follow file not in parent '
+ raise error.Abort(_('cannot follow file not in parent '
'revision: "%s"') % filename)
yield filename, pctx[filename].filenode()
else:
yield filename, None
for filename_node in copies:
@@ -1675,11 +1675,11 @@ def walkfilerevs(repo, match, follow, re
if not len(filelog):
if node is None:
# A zero count may be a directory or deleted file, so
# try to find matching entries on the slow path.
if follow:
- raise util.Abort(
+ raise error.Abort(
_('cannot follow nonexistent file: "%s"') % file_)
raise FileWalkError("Cannot walk via filelog")
else:
continue
@@ -1806,11 +1806,11 @@ def walkchangerevs(repo, match, opts, pr
if slowpath:
# We have to read the changelog to match filenames against
# changed files
if follow:
- raise util.Abort(_('can only follow copies/renames for explicit '
+ raise error.Abort(_('can only follow copies/renames for explicit '
'filenames'))
# The slow path checks files modified in every changeset.
# This is really slow on large repos, so compute the set lazily.
class lazywantedset(object):
@@ -1978,18 +1978,18 @@ def _makelogrevset(repo, pats, opts, rev
# take the slow path.
if os.path.exists(repo.wjoin(f)):
slowpath = True
continue
else:
- raise util.Abort(_('cannot follow file not in parent '
+ raise error.Abort(_('cannot follow file not in parent '
'revision: "%s"') % f)
filelog = repo.file(f)
if not filelog:
# A zero count may be a directory or deleted file, so
# try to find matching entries on the slow path.
if follow:
- raise util.Abort(
+ raise error.Abort(
_('cannot follow nonexistent file: "%s"') % f)
slowpath = True
# We decided to fall back to the slowpath because at least one
# of the paths was not a file. Check to see if at least one of them
@@ -2209,11 +2209,11 @@ def graphlog(ui, repo, *pats, **opts):
graphmod.asciiedges, getrenamed, filematcher)
def checkunsupportedgraphflags(pats, opts):
for op in ["newest_first"]:
if op in opts and opts[op]:
- raise util.Abort(_("-G/--graph option is incompatible with --%s")
+ raise error.Abort(_("-G/--graph option is incompatible with --%s")
% op.replace("_", "-"))
def graphrevs(repo, nodes, opts):
limit = loglimit(opts)
nodes.reverse()
@@ -2487,11 +2487,11 @@ def commit(ui, repo, commitfunc, pats, o
# extract addremove carefully -- this function can be called from a command
# that doesn't support addremove
if opts.get('addremove'):
if scmutil.addremove(repo, matcher, "", opts) != 0:
- raise util.Abort(
+ raise error.Abort(
_("failed to mark all new/missing files as added/removed"))
return commitfunc(ui, repo, message, matcher, opts)
def amend(ui, repo, commitfunc, old, extra, pats, opts):
@@ -2723,22 +2723,22 @@ def commitforceeditor(repo, ctx, subs, f
os.chdir(olddir)
if finishdesc:
text = finishdesc(text)
if not text.strip():
- raise util.Abort(_("empty commit message"))
+ raise error.Abort(_("empty commit message"))
return text
def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
ui = repo.ui
tmpl, mapfile = gettemplate(ui, tmpl, None)
try:
t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
except SyntaxError as inst:
- raise util.Abort(inst.args[0])
+ raise error.Abort(inst.args[0])
for k, v in repo.ui.configitems('committemplate'):
if k != 'changeset':
t.t.cache[k] = v
@@ -3101,11 +3101,11 @@ def revert(ui, repo, ctx, parents, *pats
# Revert the subrepos on the revert list
for sub in targetsubs:
try:
wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
except KeyError:
- raise util.Abort("subrepository '%s' does not exist in %s!"
+ raise error.Abort("subrepository '%s' does not exist in %s!"
% (sub, short(ctx.node())))
finally:
wlock.release()
def _revertprefetch(repo, ctx, *files):
@@ -3172,11 +3172,11 @@ def _performrevert(repo, parents, ctx, a
chunks = recordfilter(repo.ui, originalchunks)
if reversehunks:
chunks = patch.reversehunks(chunks)
except patch.PatchError as err:
- raise util.Abort(_('error parsing patch: %s') % err)
+ raise error.Abort(_('error parsing patch: %s') % err)
newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
# Apply changes
fp = cStringIO.StringIO()
for c in chunks:
@@ -3185,11 +3185,11 @@ def _performrevert(repo, parents, ctx, a
fp.seek(0)
if dopatch:
try:
patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
except patch.PatchError as err:
- raise util.Abort(str(err))
+ raise error.Abort(str(err))
del fp
else:
for f in actions['revert'][0]:
checkout(f)
if normal:
@@ -3306,19 +3306,19 @@ def checkunfinished(repo, commit=False):
'''
for f, clearable, allowcommit, msg, hint in unfinishedstates:
if commit and allowcommit:
continue
if repo.vfs.exists(f):
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
def clearunfinished(repo):
'''Check for unfinished operations (as above), and clear the ones
that are clearable.
'''
for f, clearable, allowcommit, msg, hint in unfinishedstates:
if not clearable and repo.vfs.exists(f):
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
for f, clearable, allowcommit, msg, hint in unfinishedstates:
if clearable and repo.vfs.exists(f):
util.unlink(repo.join(f))
class dirstateguard(object):
@@ -3353,11 +3353,11 @@ class dirstateguard(object):
def close(self):
if not self._active: # already inactivated
msg = (_("can't close already inactivated backup: %s")
% self._filename)
- raise util.Abort(msg)
+ raise error.Abort(msg)
self._repo.vfs.unlink(self._filename)
self._active = False
self._closed = True
@@ -3372,11 +3372,11 @@ class dirstateguard(object):
def release(self):
if not self._closed:
if not self._active: # already inactivated
msg = (_("can't release already inactivated backup: %s")
% self._filename)
- raise util.Abort(msg)
+ raise error.Abort(msg)
self._abort()
_bundlecompspecs = {'none': None,
'bzip2': 'BZ',
'gzip': 'GZ',
@@ -3406,26 +3406,26 @@ def parsebundletype(repo, spec):
elif spec in _bundlecompspecs:
comp = spec
elif spec in _bundleversionspecs:
version = spec
else:
- raise util.Abort(_('unknown bundle type specified with --type'))
+ raise error.Abort(_('unknown bundle type specified with --type'))
if comp is None:
comp = 'BZ'
else:
try:
comp = _bundlecompspecs[comp]
except KeyError:
- raise util.Abort(_('unknown bundle type specified with --type'))
+ raise error.Abort(_('unknown bundle type specified with --type'))
if version is None:
version = '01'
if 'generaldelta' in repo.requirements:
version = '02'
else:
try:
version = _bundleversionspecs[version]
except KeyError:
- raise util.Abort(_('unknown bundle type specified with --type'))
+ raise error.Abort(_('unknown bundle type specified with --type'))
return version, comp
diff --git a/mercurial/commands.py b/mercurial/commands.py
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -236,13 +236,13 @@ def addremove(ui, repo, *pats, **opts):
Returns 0 if all files are successfully added.
"""
try:
sim = float(opts.get('similarity') or 100)
except ValueError:
- raise util.Abort(_('similarity must be a number'))
+ raise error.Abort(_('similarity must be a number'))
if sim < 0 or sim > 100:
- raise util.Abort(_('similarity must be between 0 and 100'))
+ raise error.Abort(_('similarity must be between 0 and 100'))
matcher = scmutil.match(repo[None], pats, opts)
return scmutil.addremove(repo, matcher, "", opts, similarity=sim / 100.0)
@command('^annotate|blame',
[('r', 'rev', '', _('annotate the specified revision'), _('REV')),
@@ -274,11 +274,11 @@ def annotate(ui, repo, *pats, **opts):
nor desirable.
Returns 0 on success.
"""
if not pats:
- raise util.Abort(_('at least one filename or pattern is required'))
+ raise error.Abort(_('at least one filename or pattern is required'))
if opts.get('follow'):
# --follow is deprecated and now just an alias for -f/--file
# to mimic the behavior of Mercurial before version 1.5
opts['file'] = True
@@ -331,11 +331,11 @@ def annotate(ui, repo, *pats, **opts):
and not opts.get('date') and not opts.get('file')):
opts['number'] = True
linenumber = opts.get('line_number') is not None
if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
- raise util.Abort(_('at least one of -n/-c is required for -l'))
+ raise error.Abort(_('at least one of -n/-c is required for -l'))
if fm:
def makefunc(get, fmt):
return get
else:
@@ -346,11 +346,11 @@ def annotate(ui, repo, *pats, **opts):
funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
if opts.get(op))
def bad(x, y):
- raise util.Abort("%s: %s" % (x, y))
+ raise error.Abort("%s: %s" % (x, y))
m = scmutil.match(ctx, pats, opts, badfn=bad)
follow = not opts.get('no_follow')
diffopts = patch.difffeatureopts(ui, opts, section='annotate',
@@ -436,22 +436,22 @@ def archive(ui, repo, dest, **opts):
Returns 0 on success.
'''
ctx = scmutil.revsingle(repo, opts.get('rev'))
if not ctx:
- raise util.Abort(_('no working directory: please specify a revision'))
+ raise error.Abort(_('no working directory: please specify a revision'))
node = ctx.node()
dest = cmdutil.makefilename(repo, dest, node)
if os.path.realpath(dest) == repo.root:
- raise util.Abort(_('repository root cannot be destination'))
+ raise error.Abort(_('repository root cannot be destination'))
kind = opts.get('type') or archival.guesskind(dest) or 'files'
prefix = opts.get('prefix')
if dest == '-':
if kind == 'files':
- raise util.Abort(_('cannot archive plain files to stdout'))
+ raise error.Abort(_('cannot archive plain files to stdout'))
dest = cmdutil.makefileobj(repo, dest)
if not prefix:
prefix = os.path.basename(repo.root) + '-%h'
prefix = cmdutil.makefilename(repo, prefix, node)
@@ -502,17 +502,17 @@ def backout(ui, repo, node=None, rev=Non
Returns 0 on success, 1 if nothing to backout or there are unresolved
files.
'''
if rev and node:
- raise util.Abort(_("please specify just one revision"))
+ raise error.Abort(_("please specify just one revision"))
if not rev:
rev = node
if not rev:
- raise util.Abort(_("please specify a revision to backout"))
+ raise error.Abort(_("please specify a revision to backout"))
date = opts.get('date')
if date:
opts['date'] = util.parsedate(date)
@@ -520,26 +520,26 @@ def backout(ui, repo, node=None, rev=Non
cmdutil.bailifchanged(repo)
node = scmutil.revsingle(repo, rev).node()
op1, op2 = repo.dirstate.parents()
if not repo.changelog.isancestor(node, op1):
- raise util.Abort(_('cannot backout change that is not an ancestor'))
+ raise error.Abort(_('cannot backout change that is not an ancestor'))
p1, p2 = repo.changelog.parents(node)
if p1 == nullid:
- raise util.Abort(_('cannot backout a change with no parents'))
+ raise error.Abort(_('cannot backout a change with no parents'))
if p2 != nullid:
if not opts.get('parent'):
- raise util.Abort(_('cannot backout a merge changeset'))
+ raise error.Abort(_('cannot backout a merge changeset'))
p = repo.lookup(opts['parent'])
if p not in (p1, p2):
- raise util.Abort(_('%s is not a parent of %s') %
+ raise error.Abort(_('%s is not a parent of %s') %
(short(p), short(node)))
parent = p
else:
if opts.get('parent'):
- raise util.Abort(_('cannot use --parent on non-merge changeset'))
+ raise error.Abort(_('cannot use --parent on non-merge changeset'))
parent = p1
# the backout should appear on the same branch
wlock = repo.wlock()
try:
@@ -743,13 +743,13 @@ def bisect(ui, repo, rev=None, extra=Non
def check_state(state, interactive=True):
if not state['good'] or not state['bad']:
if (good or bad or skip or reset) and interactive:
return
if not state['good']:
- raise util.Abort(_('cannot bisect (no known good revisions)'))
+ raise error.Abort(_('cannot bisect (no known good revisions)'))
else:
- raise util.Abort(_('cannot bisect (no known bad revisions)'))
+ raise error.Abort(_('cannot bisect (no known bad revisions)'))
return True
# backward compatibility
if rev in "good bad reset init".split():
ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
@@ -759,11 +759,11 @@ def bisect(ui, repo, rev=None, extra=Non
elif cmd == "bad":
bad = True
else:
reset = True
elif extra or good + bad + skip + reset + extend + bool(command) > 1:
- raise util.Abort(_('incompatible arguments'))
+ raise error.Abort(_('incompatible arguments'))
cmdutil.checkunfinished(repo)
if reset:
p = repo.join("bisect.state")
@@ -777,16 +777,16 @@ def bisect(ui, repo, rev=None, extra=Non
changesets = 1
if noupdate:
try:
node = state['current'][0]
except LookupError:
- raise util.Abort(_('current bisect revision is unknown - '
+ raise error.Abort(_('current bisect revision is unknown - '
'start a new bisect to fix'))
else:
node, p2 = repo.dirstate.parents()
if p2 != nullid:
- raise util.Abort(_('current bisect revision is a merge'))
+ raise error.Abort(_('current bisect revision is a merge'))
try:
while changesets:
# update state
state['current'] = [node]
hbisect.save_state(repo, state)
@@ -795,13 +795,13 @@ def bisect(ui, repo, rev=None, extra=Non
transition = "skip"
elif status == 0:
transition = "good"
# status < 0 means process was killed
elif status == 127:
- raise util.Abort(_("failed to execute %s") % command)
+ raise error.Abort(_("failed to execute %s") % command)
elif status < 0:
- raise util.Abort(_("%s killed") % command)
+ raise error.Abort(_("%s killed") % command)
else:
transition = "bad"
ctx = scmutil.revsingle(repo, rev, node)
rev = None # clear for future iterations
state[transition].append(ctx.node())
@@ -851,11 +851,11 @@ def bisect(ui, repo, rev=None, extra=Non
hbisect.save_state(repo, state)
if noupdate:
return
cmdutil.bailifchanged(repo)
return hg.clean(repo, extendnode.node())
- raise util.Abort(_("nothing to extend"))
+ raise error.Abort(_("nothing to extend"))
if changesets == 0:
print_result(nodes, good)
else:
assert len(nodes) == 1 # only a single node can be tested next
@@ -934,11 +934,11 @@ def bookmark(ui, repo, *names, **opts):
inactive = opts.get('inactive')
def checkformat(mark):
mark = mark.strip()
if not mark:
- raise util.Abort(_("bookmark names cannot consist entirely of "
+ raise error.Abort(_("bookmark names cannot consist entirely of "
"whitespace"))
scmutil.checknewlabel(repo, mark, 'bookmark')
return mark
def checkconflict(repo, mark, cur, force=False, target=None):
@@ -964,25 +964,25 @@ def bookmark(ui, repo, *names, **opts):
bookmarks.deletedivergent(repo, deletefrom, mark)
if bookmarks.validdest(repo, bmctx, repo[target]):
ui.status(_("moving bookmark '%s' forward from %s\n") %
(mark, short(bmctx.node())))
return
- raise util.Abort(_("bookmark '%s' already exists "
+ raise error.Abort(_("bookmark '%s' already exists "
"(use -f to force)") % mark)
if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
and not force):
- raise util.Abort(
+ raise error.Abort(
_("a bookmark cannot have the name of an existing branch"))
if delete and rename:
- raise util.Abort(_("--delete and --rename are incompatible"))
+ raise error.Abort(_("--delete and --rename are incompatible"))
if delete and rev:
- raise util.Abort(_("--rev is incompatible with --delete"))
+ raise error.Abort(_("--rev is incompatible with --delete"))
if rename and rev:
- raise util.Abort(_("--rev is incompatible with --rename"))
+ raise error.Abort(_("--rev is incompatible with --rename"))
if not names and (delete or rev):
- raise util.Abort(_("bookmark name required"))
+ raise error.Abort(_("bookmark name required"))
if delete or rename or names or inactive:
wlock = lock = tr = None
try:
wlock = repo.wlock()
@@ -991,25 +991,26 @@ def bookmark(ui, repo, *names, **opts):
marks = repo._bookmarks
if delete:
tr = repo.transaction('bookmark')
for mark in names:
if mark not in marks:
- raise util.Abort(_("bookmark '%s' does not exist") %
+ raise error.Abort(_("bookmark '%s' does not exist") %
mark)
if mark == repo._activebookmark:
bookmarks.deactivate(repo)
del marks[mark]
elif rename:
tr = repo.transaction('bookmark')
if not names:
- raise util.Abort(_("new bookmark name required"))
+ raise error.Abort(_("new bookmark name required"))
elif len(names) > 1:
- raise util.Abort(_("only one new bookmark name allowed"))
+ raise error.Abort(_("only one new bookmark name allowed"))
mark = checkformat(names[0])
if rename not in marks:
- raise util.Abort(_("bookmark '%s' does not exist") % rename)
+ raise error.Abort(_("bookmark '%s' does not exist")
+ % rename)
checkconflict(repo, mark, cur, force)
marks[mark] = marks[rename]
if repo._activebookmark == rename and not inactive:
bookmarks.activate(repo, mark)
del marks[rename]
@@ -1116,11 +1117,11 @@ def branch(ui, repo, label=None, **opts)
repo.dirstate.setbranch(label)
ui.status(_('reset working directory to branch %s\n') % label)
elif label:
if not opts.get('force') and label in repo.branchmap():
if label not in [p.branch() for p in repo.parents()]:
- raise util.Abort(_('a branch of the same name already'
+ raise error.Abort(_('a branch of the same name already'
' exists'),
# i18n: "it" refers to an existing branch
hint=_("use 'hg update' to switch to it"))
scmutil.checknewlabel(repo, label, 'branch')
repo.dirstate.setbranch(label)
@@ -1248,11 +1249,11 @@ def bundle(ui, repo, fname, dest=None, *
base = scmutil.revrange(repo, opts.get('base'))
# TODO: get desired bundlecaps from command line.
bundlecaps = None
if base:
if dest:
- raise util.Abort(_("--base is incompatible with specifying "
+ raise error.Abort(_("--base is incompatible with specifying "
"a destination"))
common = [repo.lookup(rev) for rev in base]
heads = revs and map(repo.lookup, revs) or revs
cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
common=common, bundlecaps=bundlecaps,
@@ -1426,11 +1427,11 @@ def clone(ui, source, dest=None, **opts)
See :hg:`help urls` for details on specifying URLs.
Returns 0 on success.
"""
if opts.get('noupdate') and opts.get('updaterev'):
- raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
+ raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
r = hg.clone(ui, opts, source, dest,
pull=opts.get('pull'),
stream=opts.get('uncompressed'),
rev=opts.get('rev'),
@@ -1498,11 +1499,11 @@ def commit(ui, repo, *pats, **opts):
cmdutil.recordfilter, *pats, **opts)
return
if opts.get('subrepos'):
if opts.get('amend'):
- raise util.Abort(_('cannot amend with --subrepos'))
+ raise error.Abort(_('cannot amend with --subrepos'))
# Let --subrepos on the command line override config setting.
ui.setconfig('ui', 'commitsubrepos', True, 'commit')
cmdutil.checkunfinished(repo, commit=True)
@@ -1512,28 +1513,28 @@ def commit(ui, repo, *pats, **opts):
extra = {}
if opts.get('close_branch'):
extra['close'] = 1
if not bheads:
- raise util.Abort(_('can only close branch heads'))
+ raise error.Abort(_('can only close branch heads'))
elif opts.get('amend'):
if repo.parents()[0].p1().branch() != branch and \
repo.parents()[0].p2().branch() != branch:
- raise util.Abort(_('can only close branch heads'))
+ raise error.Abort(_('can only close branch heads'))
if opts.get('amend'):
if ui.configbool('ui', 'commitsubrepos'):
- raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
+ raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
old = repo['.']
if not old.mutable():
- raise util.Abort(_('cannot amend public changesets'))
+ raise error.Abort(_('cannot amend public changesets'))
if len(repo[None].parents()) > 1:
- raise util.Abort(_('cannot amend while merging'))
+ raise error.Abort(_('cannot amend while merging'))
allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
if not allowunstable and old.children():
- raise util.Abort(_('cannot amend changeset with children'))
+ raise error.Abort(_('cannot amend changeset with children'))
# commitfunc is used only for temporary amend commit by cmdutil.amend
def commitfunc(ui, repo, message, match, opts):
return repo.commit(message,
opts.get('user') or old.user(),
@@ -1611,15 +1612,15 @@ def config(ui, repo, *values, **opts):
"""
if opts.get('edit') or opts.get('local') or opts.get('global'):
if opts.get('local') and opts.get('global'):
- raise util.Abort(_("can't use --local and --global together"))
+ raise error.Abort(_("can't use --local and --global together"))
if opts.get('local'):
if not repo:
- raise util.Abort(_("can't use --local outside a repository"))
+ raise error.Abort(_("can't use --local outside a repository"))
paths = [repo.join('hgrc')]
elif opts.get('global'):
paths = scmutil.systemrcpath()
else:
paths = scmutil.userrcpath()
@@ -1640,21 +1641,21 @@ def config(ui, repo, *values, **opts):
fp.write(samplehgrc)
fp.close()
editor = ui.geteditor()
ui.system("%s \"%s\"" % (editor, f),
- onerr=util.Abort, errprefix=_("edit failed"))
+ onerr=error.Abort, errprefix=_("edit failed"))
return
for f in scmutil.rcpath():
ui.debug('read config from: %s\n' % f)
untrusted = bool(opts.get('untrusted'))
if values:
sections = [v for v in values if '.' not in v]
items = [v for v in values if '.' in v]
if len(items) > 1 or items and sections:
- raise util.Abort(_('only one config item permitted'))
+ raise error.Abort(_('only one config item permitted'))
matched = False
for section, name, value in ui.walkconfig(untrusted=untrusted):
value = str(value).replace('\n', '\\n')
sectname = section + '.' + name
if values:
@@ -1712,17 +1713,17 @@ def debugancestor(ui, repo, *args):
index, rev1, rev2 = args
r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
lookup = r.lookup
elif len(args) == 2:
if not repo:
- raise util.Abort(_("there is no Mercurial repository here "
+ raise error.Abort(_("there is no Mercurial repository here "
"(.hg not found)"))
rev1, rev2 = args
r = repo.changelog
lookup = repo.lookup
else:
- raise util.Abort(_('either two or three arguments required'))
+ raise error.Abort(_('either two or three arguments required'))
a = r.ancestor(lookup(rev1), lookup(rev2))
ui.write("%d:%s\n" % (r.rev(a), hex(a)))
@command('debugbuilddag',
[('m', 'mergeable-file', None, _('add single file mergeable changes')),
@@ -1769,11 +1770,11 @@ def debugbuilddag(ui, repo, text=None,
ui.status(_("reading DAG from stdin\n"))
text = ui.fin.read()
cl = repo.changelog
if len(cl) > 0:
- raise util.Abort(_('repository is not empty'))
+ raise error.Abort(_('repository is not empty'))
# determine number of revs in DAG
total = 0
for type, data in dagparser.parsedag(text):
if type == 'n':
@@ -1917,11 +1918,11 @@ def debugbundle(ui, bundlepath, all=None
break
fname = chunkdata['filename']
showchunks(fname)
else:
if isinstance(gen, bundle2.unbundle20):
- raise util.Abort(_('use debugbundle2 for this file'))
+ raise error.Abort(_('use debugbundle2 for this file'))
chunkdata = gen.changelogheader()
chain = None
while True:
chunkdata = gen.deltachunk(chain)
if not chunkdata:
@@ -1933,11 +1934,11 @@ def debugbundle(ui, bundlepath, all=None
f.close()
def _debugbundle2(ui, gen, **opts):
"""lists the contents of a bundle2"""
if not isinstance(gen, bundle2.unbundle20):
- raise util.Abort(_('not a bundle2 file'))
+ raise error.Abort(_('not a bundle2 file'))
ui.write(('Stream params: %s\n' % repr(gen.params)))
for part in gen.iterparts():
ui.write('%s -- %r\n' % (part.type, repr(part.params)))
if part.type == 'changegroup':
version = part.params.get('version', '01')
@@ -1976,11 +1977,11 @@ def debugcheckstate(ui, repo):
if state not in "nrm":
ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
errors += 1
if errors:
error = _(".hg/dirstate inconsistent with current parent's manifest")
- raise util.Abort(error)
+ raise error.Abort(error)
@command('debugcommands', [], _('[COMMAND]'), norepo=True)
def debugcommands(ui, cmd='', *args):
"""list all available commands and options"""
for cmd, vals in sorted(table.iteritems()):
@@ -2064,11 +2065,11 @@ def debugdag(ui, repo, file_=None, *revs
ls = labels.get(r)
if ls:
for l in ls:
yield 'l', (r, l)
else:
- raise util.Abort(_('need repo for changelog dag'))
+ raise error.Abort(_('need repo for changelog dag'))
for line in dagparser.dagtextlines(events(),
addspaces=spaces,
wraplabels=True,
wrapannotations=True,
@@ -2091,11 +2092,11 @@ def debugdata(ui, repo, file_, rev=None,
raise error.CommandError('debugdata', _('invalid arguments'))
r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
try:
ui.write(r.revision(r.lookup(rev)))
except KeyError:
- raise util.Abort(_('invalid revision identifier %s') % rev)
+ raise error.Abort(_('invalid revision identifier %s') % rev)
@command('debugdate',
[('e', 'extended', None, _('try extended date formats'))],
_('[-e] DATE [RANGE]'),
norepo=True, optionalrepo=True)
@@ -2128,11 +2129,11 @@ def debugdiscovery(ui, repo, remoteurl="
random.seed(12323)
def doit(localheads, remoteheads, remote=remote):
if opts.get('old'):
if localheads:
- raise util.Abort('cannot use localheads with old style '
+ raise error.Abort('cannot use localheads with old style '
'discovery')
if not util.safehasattr(remote, 'branches'):
# enable in-client legacy support
remote = localrepo.locallegacypeer(remote.local())
common, _in, hds = treediscovery.findcommonincoming(repo, remote,
@@ -2256,11 +2257,11 @@ def debuggetbundle(ui, repopath, bundlep
Every ID must be a full-length hex node id string. Saves the bundle to the
given file.
"""
repo = hg.peer(ui, opts, repopath)
if not repo.capable('getbundle'):
- raise util.Abort("getbundle() not supported by target repository")
+ raise error.Abort("getbundle() not supported by target repository")
args = {}
if common:
args['common'] = [bin(s) for s in common]
if head:
args['heads'] = [bin(s) for s in head]
@@ -2273,22 +2274,22 @@ def debuggetbundle(ui, repopath, bundlep
'bzip2': 'HG10BZ',
'gzip': 'HG10GZ',
'bundle2': 'HG20'}
bundletype = btypes.get(bundletype)
if bundletype not in changegroup.bundletypes:
- raise util.Abort(_('unknown bundle type specified with --type'))
+ raise error.Abort(_('unknown bundle type specified with --type'))
changegroup.writebundle(ui, bundle, bundlepath, bundletype)
@command('debugignore', [], '')
def debugignore(ui, repo, *values, **opts):
"""display the combined ignore pattern"""
ignore = repo.dirstate._ignore
includepat = getattr(ignore, 'includepat', None)
if includepat is not None:
ui.write("%s\n" % includepat)
else:
- raise util.Abort(_("no ignore patterns found"))
+ raise error.Abort(_("no ignore patterns found"))
@command('debugindex',
[('c', 'changelog', False, _('open changelog')),
('m', 'manifest', False, _('open manifest')),
('', 'dir', False, _('open directory manifest')),
@@ -2298,11 +2299,11 @@ def debugignore(ui, repo, *values, **opt
def debugindex(ui, repo, file_=None, **opts):
"""dump the contents of an index file"""
r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
format = opts.get('format', 0)
if format not in (0, 1):
- raise util.Abort(_("unknown format %d") % format)
+ raise error.Abort(_("unknown format %d") % format)
generaldelta = r.version & revlog.REVLOGGENERALDELTA
if generaldelta:
basehdr = ' delta'
else:
@@ -2384,11 +2385,11 @@ def debuginstall(ui):
# encoding
ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
try:
encoding.fromlocal("test")
- except util.Abort as inst:
+ except error.Abort as inst:
ui.write(" %s\n" % inst)
ui.write(_(" (check that your locale is properly set)\n"))
problems += 1
# Python
@@ -2450,11 +2451,11 @@ def debuginstall(ui):
# check username
ui.status(_("checking username...\n"))
try:
ui.username()
- except util.Abort as e:
+ except error.Abort as e:
ui.write(" %s\n" % e)
ui.write(_(" (specify a username in your configuration file)\n"))
problems += 1
if not problems:
@@ -2472,11 +2473,11 @@ def debugknown(ui, repopath, *ids, **opt
Every ID must be a full-length hex node id string. Returns a list of 0s
and 1s indicating unknown/known.
"""
repo = hg.peer(ui, opts, repopath)
if not repo.capable('known'):
- raise util.Abort("known() not supported by target repository")
+ raise error.Abort("known() not supported by target repository")
flags = repo.known([bin(s) for s in ids])
ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
@command('debuglabelcomplete', [], _('LABEL...'))
def debuglabelcomplete(ui, repo, *args):
@@ -2660,16 +2661,16 @@ def debugobsolete(ui, repo, precursor=No
n = bin(s)
if len(n) != len(nullid):
raise TypeError()
return n
except TypeError:
- raise util.Abort('changeset references must be full hexadecimal '
+ raise error.Abort('changeset references must be full hexadecimal '
'node identifiers')
if precursor is not None:
if opts['rev']:
- raise util.Abort('cannot select revision when creating marker')
+ raise error.Abort('cannot select revision when creating marker')
metadata = {}
metadata['user'] = opts['user'] or ui.username()
succs = tuple(parsenodeid(succ) for succ in successors)
l = repo.lock()
try:
@@ -2682,20 +2683,20 @@ def debugobsolete(ui, repo, precursor=No
date = None
prec = parsenodeid(precursor)
parents = None
if opts['record_parents']:
if prec not in repo.unfiltered():
- raise util.Abort('cannot used --record-parents on '
+ raise error.Abort('cannot used --record-parents on '
'unknown changesets')
parents = repo.unfiltered()[prec].parents()
parents = tuple(p.node() for p in parents)
repo.obsstore.create(tr, prec, succs, opts['flags'],
parents=parents, date=date,
metadata=metadata)
tr.close()
except ValueError as exc:
- raise util.Abort(_('bad obsmarker input: %s') % exc)
+ raise error.Abort(_('bad obsmarker input: %s') % exc)
finally:
tr.release()
finally:
l.release()
else:
@@ -3316,11 +3317,11 @@ def diff(ui, repo, *pats, **opts):
stat = opts.get('stat')
reverse = opts.get('reverse')
if revs and change:
msg = _('cannot specify --rev and --change at the same time')
- raise util.Abort(msg)
+ raise error.Abort(msg)
elif change:
node2 = scmutil.revsingle(repo, change, None).node()
node1 = repo[node2].p1().node()
else:
node1, node2 = scmutil.revpair(repo, revs)
@@ -3404,11 +3405,11 @@ def export(ui, repo, *changesets, **opts
changesets += tuple(opts.get('rev', []))
if not changesets:
changesets = ['.']
revs = scmutil.revrange(repo, changesets)
if not revs:
- raise util.Abort(_("export requires at least one changeset"))
+ raise error.Abort(_("export requires at least one changeset"))
if len(revs) > 1:
ui.note(_('exporting patches:\n'))
else:
ui.note(_('exporting patch:\n'))
cmdutil.export(repo, revs, template=opts.get('output'),
@@ -3508,11 +3509,11 @@ def forget(ui, repo, *pats, **opts):
Returns 0 on success.
"""
if not pats:
- raise util.Abort(_('no files specified'))
+ raise error.Abort(_('no files specified'))
m = scmutil.match(repo[None], pats, opts)
rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
return rejected and 1 or 0
@@ -3599,24 +3600,24 @@ def graft(ui, repo, *revs, **opts):
cont = False
if opts['continue']:
cont = True
if revs:
- raise util.Abort(_("can't specify --continue and revisions"))
+ raise error.Abort(_("can't specify --continue and revisions"))
# read in unfinished revisions
try:
nodes = repo.vfs.read('graftstate').splitlines()
revs = [repo[node].rev() for node in nodes]
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
- raise util.Abort(_("no graft state found, can't continue"))
+ raise error.Abort(_("no graft state found, can't continue"))
else:
cmdutil.checkunfinished(repo)
cmdutil.bailifchanged(repo)
if not revs:
- raise util.Abort(_('no revisions specified'))
+ raise error.Abort(_('no revisions specified'))
revs = scmutil.revrange(repo, revs)
skipped = set()
# check for merges
for rev in repo.revs('%ld and merge()', revs):
@@ -3735,11 +3736,11 @@ def graft(ui, repo, *revs, **opts):
# report any conflicts
if stats and stats[3] > 0:
# write out state for --continue
nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
repo.vfs.write('graftstate', ''.join(nodelines))
- raise util.Abort(
+ raise error.Abort(
_("unresolved conflicts, can't continue"),
hint=_('use hg resolve and hg graft --continue'))
else:
cont = False
@@ -4098,11 +4099,11 @@ def help_(ui, name=None, **opts):
# We could have been given a weird ".foo" section without a name
# to look for, or we could have simply failed to found "foo.bar"
# because bar isn't a section of foo
if section and not (formatted and name):
- raise util.Abort(_("help section not found"))
+ raise error.Abort(_("help section not found"))
if 'verbose' in pruned:
keep.append('omitted')
else:
keep.append('notomitted')
@@ -4155,11 +4156,11 @@ def identify(ui, repo, source=None, rev=
Returns 0 if successful.
"""
if not repo and not source:
- raise util.Abort(_("there is no Mercurial repository here "
+ raise error.Abort(_("there is no Mercurial repository here "
"(.hg not found)"))
if ui.debugflag:
hexfunc = hex
else:
@@ -4174,11 +4175,11 @@ def identify(ui, repo, source=None, rev=
repo = peer.local()
revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
if not repo:
if num or branch or tags:
- raise util.Abort(
+ raise error.Abort(
_("can't query remote revision number, branch, or tags"))
if not rev and revs:
rev = revs[0]
if not rev:
rev = "tip"
@@ -4367,33 +4368,33 @@ def import_(ui, repo, patch1=None, *patc
Returns 0 on success, 1 on partial success (see --partial).
"""
if not patch1:
- raise util.Abort(_('need at least one patch to import'))
+ raise error.Abort(_('need at least one patch to import'))
patches = (patch1,) + patches
date = opts.get('date')
if date:
opts['date'] = util.parsedate(date)
update = not opts.get('bypass')
if not update and opts.get('no_commit'):
- raise util.Abort(_('cannot use --no-commit with --bypass'))
+ raise error.Abort(_('cannot use --no-commit with --bypass'))
try:
sim = float(opts.get('similarity') or 0)
except ValueError:
- raise util.Abort(_('similarity must be a number'))
+ raise error.Abort(_('similarity must be a number'))
if sim < 0 or sim > 100:
- raise util.Abort(_('similarity must be between 0 and 100'))
+ raise error.Abort(_('similarity must be between 0 and 100'))
if sim and not update:
- raise util.Abort(_('cannot use --similarity with --bypass'))
+ raise error.Abort(_('cannot use --similarity with --bypass'))
if opts.get('exact') and opts.get('edit'):
- raise util.Abort(_('cannot use --exact with --edit'))
+ raise error.Abort(_('cannot use --exact with --edit'))
if opts.get('exact') and opts.get('prefix'):
- raise util.Abort(_('cannot use --exact with --prefix'))
+ raise error.Abort(_('cannot use --exact with --prefix'))
if update:
cmdutil.checkunfinished(repo)
if (opts.get('exact') or not opts.get('force')) and update:
cmdutil.bailifchanged(repo)
@@ -4440,11 +4441,11 @@ def import_(ui, repo, patch1=None, *patc
"`hg commit --amend`)\n"))
ret = 1
break
if not haspatch:
- raise util.Abort(_('%s: no diffs found') % patchurl)
+ raise error.Abort(_('%s: no diffs found') % patchurl)
if tr:
tr.close()
if msgs:
repo.savecommitmessage('\n* * *\n'.join(msgs))
@@ -4535,11 +4536,11 @@ def incoming(ui, repo, source="default",
hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
return 0
if opts.get('bundle') and opts.get('subrepos'):
- raise util.Abort(_('cannot combine --bundle and --subrepos'))
+ raise error.Abort(_('cannot combine --bundle and --subrepos'))
if opts.get('bookmarks'):
source, branches = hg.parseurl(ui.expandpath(source),
opts.get('branch'))
other = hg.peer(repo, opts, source)
@@ -4801,11 +4802,11 @@ def manifest(ui, repo, node=None, rev=No
fm = ui.formatter('manifest', opts)
if opts.get('all'):
if rev or node:
- raise util.Abort(_("can't specify a revision with --all"))
+ raise error.Abort(_("can't specify a revision with --all"))
res = []
prefix = "data/"
suffix = ".i"
plen = len(prefix)
@@ -4822,11 +4823,11 @@ def manifest(ui, repo, node=None, rev=No
fm.write("path", '%s\n', f)
fm.end()
return
if rev and node:
- raise util.Abort(_("please specify just one revision"))
+ raise error.Abort(_("please specify just one revision"))
if not node:
node = rev
char = {'l': '@', 'x': '*', '': ''}
@@ -4877,11 +4878,11 @@ def merge(ui, repo, node=None, **opts):
Returns 0 on success, 1 if there are unresolved files.
"""
if opts.get('rev') and node:
- raise util.Abort(_("please specify just one revision"))
+ raise error.Abort(_("please specify just one revision"))
if not node:
node = opts.get('rev')
if node:
node = scmutil.revsingle(repo, node).node()
@@ -5007,22 +5008,22 @@ def parents(ui, repo, file_=None, **opts
ctx = scmutil.revsingle(repo, opts.get('rev'), None)
if file_:
m = scmutil.match(ctx, (file_,), opts)
if m.anypats() or len(m.files()) != 1:
- raise util.Abort(_('can only specify an explicit filename'))
+ raise error.Abort(_('can only specify an explicit filename'))
file_ = m.files()[0]
filenodes = []
for cp in ctx.parents():
if not cp:
continue
try:
filenodes.append(cp.filenode(file_))
except error.LookupError:
pass
if not filenodes:
- raise util.Abort(_("'%s' not found in manifest!") % file_)
+ raise error.Abort(_("'%s' not found in manifest!") % file_)
p = []
for fn in filenodes:
fctx = repo.filectx(file_, fileid=fn)
p.append(fctx.node())
else:
@@ -5107,11 +5108,11 @@ def phase(ui, repo, *revs, **opts):
# search for a unique phase argument
targetphase = None
for idx, name in enumerate(phases.phasenames):
if opts[name]:
if targetphase is not None:
- raise util.Abort(_('only one phase can be specified'))
+ raise error.Abort(_('only one phase can be specified'))
targetphase = idx
# look for specified revision
revs = list(revs)
revs.extend(opts['rev'])
@@ -5134,11 +5135,11 @@ def phase(ui, repo, *revs, **opts):
lock = repo.lock()
try:
tr = repo.transaction("phase")
# set phase
if not revs:
- raise util.Abort(_('empty revision set'))
+ raise error.Abort(_('empty revision set'))
nodes = [repo[r].node() for r in revs]
# moving revision from public to draft may hide them
# We have to check result on an unfiltered repository
unfi = repo.unfiltered()
getphase = unfi._phasecache.phase
@@ -5176,11 +5177,11 @@ def postincoming(ui, repo, modheads, opt
return
if optupdate:
checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
try:
ret = hg.update(repo, checkout)
- except util.Abort as inst:
+ except error.Abort as inst:
ui.warn(_("not updating: %s\n") % str(inst))
if inst.hint:
ui.warn(_("(%s)\n") % inst.hint)
return 0
if not ret and not checkout:
@@ -5247,11 +5248,11 @@ def pull(ui, repo, source="default", **o
# condition on the server. (See issue 4689 for details)
remotebookmarks = other.listkeys('bookmarks')
pullopargs['remotebookmarks'] = remotebookmarks
for b in opts['bookmark']:
if b not in remotebookmarks:
- raise util.Abort(_('remote bookmark %s not found!') % b)
+ raise error.Abort(_('remote bookmark %s not found!') % b)
revs.append(remotebookmarks[b])
if revs:
try:
# When 'rev' is a bookmark name, we cannot guarantee that it
@@ -5265,11 +5266,11 @@ def pull(ui, repo, source="default", **o
if r == checkout:
checkout = node
except error.CapabilityError:
err = _("other repository doesn't support revision lookup, "
"so a rev cannot be specified.")
- raise util.Abort(err)
+ raise error.Abort(err)
modheads = exchange.pull(repo, other, heads=revs,
force=opts.get('force'),
bookmarks=opts.get('bookmark', ()),
opargs=pullopargs).cgresult
@@ -5345,21 +5346,21 @@ def push(ui, repo, dest=None, **opts):
# this lets simultaneous -r, -b options continue working
opts.setdefault('rev', []).append("null")
path = ui.paths.getpath(dest, default='default')
if not path:
- raise util.Abort(_('default repository not configured!'),
+ raise error.Abort(_('default repository not configured!'),
hint=_('see the "path" section in "hg help config"'))
dest, branches = path.pushloc, (path.branch, opts.get('branch') or [])
ui.status(_('pushing to %s\n') % util.hidepassword(dest))
revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
other = hg.peer(repo, opts, dest)
if revs:
revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
if not revs:
- raise util.Abort(_("specified revisions evaluate to an empty set"),
+ raise error.Abort(_("specified revisions evaluate to an empty set"),
hint=_("use different revision arguments"))
repo._subtoppath = dest
try:
# push subrepos depth-first for coherent ordering
@@ -5445,11 +5446,11 @@ def remove(ui, repo, *pats, **opts):
Returns 0 on success, 1 if any warnings encountered.
"""
after, force = opts.get('after'), opts.get('force')
if not pats and not after:
- raise util.Abort(_('no files specified'))
+ raise error.Abort(_('no files specified'))
m = scmutil.match(repo[None], pats, opts)
subrepos = opts.get('subrepos')
return cmdutil.remove(ui, repo, m, "", after, force, subrepos)
@@ -5529,15 +5530,15 @@ def resolve(ui, repo, *pats, **opts):
all, mark, unmark, show, nostatus = \
[opts.get(o) for o in 'all mark unmark list no_status'.split()]
if (show and (mark or unmark)) or (mark and unmark):
- raise util.Abort(_("too many options specified"))
+ raise error.Abort(_("too many options specified"))
if pats and all:
- raise util.Abort(_("can't specify --all and patterns"))
+ raise error.Abort(_("can't specify --all and patterns"))
if not (all or pats or show or mark or unmark):
- raise util.Abort(_('no files or directories specified'),
+ raise error.Abort(_('no files or directories specified'),
hint=('use --all to re-merge all unresolved files'))
if show:
fm = ui.formatter('resolve', opts)
ms = mergemod.mergestate(repo)
@@ -5555,11 +5556,11 @@ def resolve(ui, repo, *pats, **opts):
wlock = repo.wlock()
try:
ms = mergemod.mergestate(repo)
if not (ms.active() or repo.dirstate.p2() != nullid):
- raise util.Abort(
+ raise error.Abort(
_('resolve command not applicable when not merging'))
m = scmutil.match(repo[None], pats, opts)
ret = 0
didwork = False
@@ -5651,28 +5652,28 @@ def revert(ui, repo, *pats, **opts):
Returns 0 on success.
"""
if opts.get("date"):
if opts.get("rev"):
- raise util.Abort(_("you can't specify a revision and a date"))
+ raise error.Abort(_("you can't specify a revision and a date"))
opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
parent, p2 = repo.dirstate.parents()
if not opts.get('rev') and p2 != nullid:
# revert after merge is a trap for new users (issue2915)
- raise util.Abort(_('uncommitted merge with no revision specified'),
+ raise error.Abort(_('uncommitted merge with no revision specified'),
hint=_('use "hg update" or see "hg help revert"'))
ctx = scmutil.revsingle(repo, opts.get('rev'))
if (not (pats or opts.get('include') or opts.get('exclude') or
opts.get('all') or opts.get('interactive'))):
msg = _("no files or directories specified")
if p2 != nullid:
hint = _("uncommitted merge, use --all to discard all changes,"
" or 'hg update -C .' to abort the merge")
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
dirty = any(repo.status())
node = ctx.node()
if node != parent:
if dirty:
hint = _("uncommitted changes, use --all to discard all"
@@ -5682,11 +5683,11 @@ def revert(ui, repo, *pats, **opts):
" or 'hg update %s' to update") % ctx.rev()
elif dirty:
hint = _("uncommitted changes, use --all to discard all changes")
else:
hint = _("use --all to revert all files")
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
@command('rollback', dryrunopts +
[('f', 'force', False, _('ignore safety measures'))])
@@ -5794,11 +5795,11 @@ def serve(ui, repo, **opts):
Returns 0 on success.
"""
if opts["stdio"] and opts["cmdserver"]:
- raise util.Abort(_("cannot use --stdio with --cmdserver"))
+ raise error.Abort(_("cannot use --stdio with --cmdserver"))
if opts["stdio"]:
if repo is None:
raise error.RepoError(_("there is no Mercurial repository here"
" (.hg not found)"))
@@ -5963,11 +5964,11 @@ def status(ui, repo, *pats, **opts):
revs = opts.get('rev')
change = opts.get('change')
if revs and change:
msg = _('cannot specify --rev and --change at the same time')
- raise util.Abort(msg)
+ raise error.Abort(msg)
elif change:
node2 = scmutil.revsingle(repo, change, None).node()
node1 = repo[node2].p1().node()
else:
node1, node2 = scmutil.revpair(repo, revs)
@@ -6315,18 +6316,18 @@ def tag(ui, repo, name1, *names, **opts)
wlock = repo.wlock()
lock = repo.lock()
rev_ = "."
names = [t.strip() for t in (name1,) + names]
if len(names) != len(set(names)):
- raise util.Abort(_('tag names must be unique'))
+ raise error.Abort(_('tag names must be unique'))
for n in names:
scmutil.checknewlabel(repo, n, 'tag')
if not n:
- raise util.Abort(_('tag names cannot consist entirely of '
+ raise error.Abort(_('tag names cannot consist entirely of '
'whitespace'))
if opts.get('rev') and opts.get('remove'):
- raise util.Abort(_("--rev and --remove are incompatible"))
+ raise error.Abort(_("--rev and --remove are incompatible"))
if opts.get('rev'):
rev_ = opts['rev']
message = opts.get('message')
if opts.get('remove'):
if opts.get('local'):
@@ -6334,32 +6335,32 @@ def tag(ui, repo, name1, *names, **opts)
else:
expectedtype = 'global'
for n in names:
if not repo.tagtype(n):
- raise util.Abort(_("tag '%s' does not exist") % n)
+ raise error.Abort(_("tag '%s' does not exist") % n)
if repo.tagtype(n) != expectedtype:
if expectedtype == 'global':
- raise util.Abort(_("tag '%s' is not a global tag") % n)
+ raise error.Abort(_("tag '%s' is not a global tag") % n)
else:
- raise util.Abort(_("tag '%s' is not a local tag") % n)
+ raise error.Abort(_("tag '%s' is not a local tag") % n)
rev_ = 'null'
if not message:
# we don't translate commit messages
message = 'Removed tag %s' % ', '.join(names)
elif not opts.get('force'):
for n in names:
if n in repo.tags():
- raise util.Abort(_("tag '%s' already exists "
+ raise error.Abort(_("tag '%s' already exists "
"(use -f to force)") % n)
if not opts.get('local'):
p1, p2 = repo.dirstate.parents()
if p2 != nullid:
- raise util.Abort(_('uncommitted merge'))
+ raise error.Abort(_('uncommitted merge'))
bheads = repo.branchheads()
if not opts.get('force') and bheads and p1 not in bheads:
- raise util.Abort(_('not at a branch head (use -f to force)'))
+ raise error.Abort(_('not at a branch head (use -f to force)'))
r = scmutil.revsingle(repo, rev_).node()
if not message:
# we don't translate commit messages
message = ('Added tag %s for changeset %s' %
@@ -6376,11 +6377,11 @@ def tag(ui, repo, name1, *names, **opts)
editor = cmdutil.getcommiteditor(editform=editform, **opts)
# don't allow tagging the null rev
if (not opts.get('remove') and
scmutil.revsingle(repo, rev_).rev() == nullrev):
- raise util.Abort(_("cannot tag null revision"))
+ raise error.Abort(_("cannot tag null revision"))
repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
editor=editor)
finally:
release(lock, wlock)
@@ -6465,11 +6466,11 @@ def unbundle(ui, repo, fname1, *fnames,
tr = repo.transaction('unbundle')
try:
op = bundle2.processbundle(repo, gen, lambda: tr)
tr.close()
except error.BundleUnknownFeatureError as exc:
- raise util.Abort(_('%s: unknown bundle feature, %s')
+ raise error.Abort(_('%s: unknown bundle feature, %s')
% (fname, exc),
hint=_("see https://mercurial-scm.org/"
"wiki/BundleFeature for more "
"information"))
finally:
@@ -6544,33 +6545,34 @@ def update(ui, repo, node=None, rev=None
See :hg:`help dates` for a list of formats valid for -d/--date.
Returns 0 on success, 1 if there are unresolved files.
"""
if rev and node:
- raise util.Abort(_("please specify just one revision"))
+ raise error.Abort(_("please specify just one revision"))
if rev is None or rev == '':
rev = node
wlock = repo.wlock()
try:
cmdutil.clearunfinished(repo)
if date:
if rev is not None:
- raise util.Abort(_("you can't specify a revision and a date"))
+ raise error.Abort(_("you can't specify a revision and a date"))
rev = cmdutil.finddate(ui, repo, date)
# with no argument, we also move the active bookmark, if any
rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
# if we defined a bookmark, we have to remember the original name
brev = rev
rev = scmutil.revsingle(repo, rev, rev).rev()
if check and clean:
- raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
+ raise error.Abort(_("cannot specify both -c/--check and -C/--clean")
+ )
if check:
cmdutil.bailifchanged(repo, merge=False)
if rev is None:
rev = repo[repo[None].branch()].rev()
diff --git a/mercurial/commandserver.py b/mercurial/commandserver.py
--- a/mercurial/commandserver.py
+++ b/mercurial/commandserver.py
@@ -6,11 +6,11 @@
# GNU General Public License version 2 or any later version.
from i18n import _
import struct
import sys, os, errno, traceback, SocketServer
-import dispatch, encoding, util
+import dispatch, encoding, util, error
logfile = None
def log(*args):
if not logfile:
@@ -220,11 +220,11 @@ class server(object):
if handler:
handler(self)
else:
# clients are expected to check what commands are supported by
# looking at the servers capabilities
- raise util.Abort(_('unknown command %s') % cmd)
+ raise error.Abort(_('unknown command %s') % cmd)
return cmd != ''
capabilities = {'runcommand' : runcommand,
'getencoding' : getencoding}
@@ -299,11 +299,11 @@ class _requesthandler(SocketServer.Strea
try:
try:
sv.serve()
# handle exceptions that may be raised by command server. most of
# known exceptions are caught by dispatch.
- except util.Abort as inst:
+ except error.Abort as inst:
ui.warn(_('abort: %s\n') % inst)
except IOError as inst:
if inst.errno != errno.EPIPE:
raise
except KeyboardInterrupt:
@@ -321,13 +321,13 @@ class unixservice(object):
def __init__(self, ui, repo, opts):
self.ui = ui
self.repo = repo
self.address = opts['address']
if not util.safehasattr(SocketServer, 'UnixStreamServer'):
- raise util.Abort(_('unsupported platform'))
+ raise error.Abort(_('unsupported platform'))
if not self.address:
- raise util.Abort(_('no socket path specified with --address'))
+ raise error.Abort(_('no socket path specified with --address'))
def init(self):
class cls(SocketServer.ForkingMixIn, SocketServer.UnixStreamServer):
ui = self.ui
repo = self.repo
@@ -349,6 +349,6 @@ class unixservice(object):
def createservice(ui, repo, opts):
mode = opts['cmdserver']
try:
return _servicemap[mode](ui, repo, opts)
except KeyError:
- raise util.Abort(_('unknown mode %s') % mode)
+ raise error.Abort(_('unknown mode %s') % mode)
diff --git a/mercurial/context.py b/mercurial/context.py
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -1058,11 +1058,11 @@ class filectx(basefilectx):
try:
return self._filelog.read(self._filenode)
except error.CensoredNodeError:
if self._repo.ui.config("censor", "policy", "abort") == "ignore":
return ""
- raise util.Abort(_("censored node: %s") % short(self._filenode),
+ raise error.Abort(_("censored node: %s") % short(self._filenode),
hint=_("set censor.policy to ignore errors"))
def size(self):
return self._filelog.size(self._filerev)
@@ -1118,11 +1118,11 @@ class committablectx(basectx):
self._extra = extra.copy()
if 'branch' not in self._extra:
try:
branch = encoding.fromlocal(self._repo.dirstate.branch())
except UnicodeDecodeError:
- raise util.Abort(_('branch name not in UTF-8!'))
+ raise error.Abort(_('branch name not in UTF-8!'))
self._extra['branch'] = branch
if self._extra['branch'] == '':
self._extra['branch'] = 'default'
def __str__(self):
diff --git a/mercurial/crecord.py b/mercurial/crecord.py
--- a/mercurial/crecord.py
+++ b/mercurial/crecord.py
@@ -20,12 +20,12 @@ import sys
import tempfile
from .i18n import _
from . import (
encoding,
+ error,
patch as patchmod,
- util,
)
# This is required for ncurses to display non-ASCII characters in default user
# locale encoding correctly. --immerrr
locale.setlocale(locale.LC_ALL, '')
@@ -45,11 +45,11 @@ else:
try:
curses
except NameError:
if os.name != 'nt': # Temporary hack to get running on Windows again
- raise util.Abort(
+ raise error.Abort(
_('the python curses/wcurses module is not available/installed'))
_origstdout = sys.__stdout__ # used by gethw()
class patchnode(object):
@@ -496,11 +496,11 @@ def chunkselector(ui, headerlist):
ui.write(_('starting interactive selection\n'))
chunkselector = curseschunkselector(headerlist, ui)
f = signal.getsignal(signal.SIGTSTP)
curses.wrapper(chunkselector.main)
if chunkselector.initerr is not None:
- raise util.Abort(chunkselector.initerr)
+ raise error.Abort(chunkselector.initerr)
# ncurses does not restore signal handler for SIGTSTP
signal.signal(signal.SIGTSTP, f)
def testdecorator(testfn, f):
def u(*args, **kwargs):
@@ -1564,11 +1564,11 @@ are you sure you want to review/edit and
elif keypressed in ["h", "KEY_LEFT"]:
self.leftarrowevent()
elif keypressed in ["H", "KEY_SLEFT"]:
self.leftarrowshiftevent()
elif keypressed in ["q"]:
- raise util.Abort(_('user quit'))
+ raise error.Abort(_('user quit'))
elif keypressed in ["c"]:
if self.confirmcommit():
return True
elif keypressed in ["r"]:
if self.confirmcommit(review=True):
diff --git a/mercurial/dagparser.py b/mercurial/dagparser.py
--- a/mercurial/dagparser.py
+++ b/mercurial/dagparser.py
@@ -9,11 +9,11 @@ from __future__ import absolute_import
import re
import string
from .i18n import _
-from . import util
+from . import error
def parsedag(desc):
'''parses a DAG from a concise textual description; generates events
"+n" is a linear run of n nodes based on the current default parent
@@ -267,11 +267,11 @@ def parsedag(desc):
i = 0
while c != '\0' and i < 10:
s += c
i += 1
c = nextch()
- raise util.Abort(_('invalid character in dag description: '
+ raise error.Abort(_('invalid character in dag description: '
'%s...') % s)
def dagtextlines(events,
addspaces=True,
wraplabels=False,
@@ -296,17 +296,17 @@ def dagtextlines(events,
if kind == 'n':
r, ps = data
# sanity check
if r != wantr:
- raise util.Abort(_("expected id %i, got %i") % (wantr, r))
+ raise error.Abort(_("expected id %i, got %i") % (wantr, r))
if not ps:
ps = [-1]
else:
for p in ps:
if p >= r:
- raise util.Abort(_("parent id %i is larger than "
+ raise error.Abort(_("parent id %i is larger than "
"current id %i") % (p, r))
wantr += 1
# new root?
p1 = r - 1
@@ -364,11 +364,11 @@ def dagtextlines(events,
yield '@' + wrapstring(data)
elif kind == '#':
yield '#' + data
yield '\n'
else:
- raise util.Abort(_("invalid event type in dag: %s")
+ raise error.Abort(_("invalid event type in dag: %s")
% str((type, data)))
if run:
yield '+' + str(run)
line = ''
diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py
--- a/mercurial/dirstate.py
+++ b/mercurial/dirstate.py
@@ -5,11 +5,11 @@
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from node import nullid
from i18n import _
-import scmutil, util, osutil, parsers, encoding, pathutil
+import scmutil, util, osutil, parsers, encoding, pathutil, error
import os, stat, errno
import match as matchmod
propertycache = util.propertycache
filecache = scmutil.filecache
@@ -132,11 +132,11 @@ class dirstate(object):
fp.close()
l = len(st)
if l == 40:
return st[:20], st[20:40]
elif l > 0 and l < 40:
- raise util.Abort(_('working directory state appears damaged!'))
+ raise error.Abort(_('working directory state appears damaged!'))
except IOError as err:
if err.errno != errno.ENOENT:
raise
return [nullid, nullid]
@@ -410,17 +410,17 @@ class dirstate(object):
def _addpath(self, f, state, mode, size, mtime):
oldstate = self[f]
if state == 'a' or oldstate == 'r':
scmutil.checkfilename(f)
if f in self._dirs:
- raise util.Abort(_('directory %r already in dirstate') % f)
+ raise error.Abort(_('directory %r already in dirstate') % f)
# shadows
for d in util.finddirs(f):
if d in self._dirs:
break
if d in self._map and self[d] != 'r':
- raise util.Abort(
+ raise error.Abort(
_('file %r in dirstate clashes with %r') % (d, f))
if oldstate in "?r" and "_dirs" in self.__dict__:
self._dirs.addpath(f)
self._dirty = True
self._map[f] = dirstatetuple(state, mode, size, mtime)
@@ -462,11 +462,11 @@ class dirstate(object):
del self._copymap[f]
def otherparent(self, f):
'''Mark as coming from the other parent, always dirty.'''
if self._pl[1] == nullid:
- raise util.Abort(_("setting %r to other parent "
+ raise error.Abort(_("setting %r to other parent "
"only allowed in merges") % f)
if f in self and self[f] == 'n':
# merge-like
self._addpath(f, 'm', 0, -2, -1)
else:
diff --git a/mercurial/discovery.py b/mercurial/discovery.py
--- a/mercurial/discovery.py
+++ b/mercurial/discovery.py
@@ -14,10 +14,11 @@ from .node import (
)
from . import (
bookmarks,
branchmap,
+ error,
obsolete,
phases,
setdiscovery,
treediscovery,
util,
@@ -260,11 +261,11 @@ def checkheads(repo, remote, outgoing, r
newbranches = [branch for branch, heads in headssum.iteritems()
if heads[0] is None]
# 1. Check for new branches on the remote.
if newbranches and not newbranch: # new branch requires --new-branch
branchnames = ', '.join(sorted(newbranches))
- raise util.Abort(_("push creates new remote branches: %s!")
+ raise error.Abort(_("push creates new remote branches: %s!")
% branchnames,
hint=_("use 'hg push --new-branch' to create"
" new remote branches"))
# 2. Compute newly pushed bookmarks. We don't warn about bookmarked heads.
@@ -388,6 +389,6 @@ def checkheads(repo, remote, outgoing, r
else:
repo.ui.note(_("new remote heads on branch '%s':\n") % branch)
for h in dhs:
repo.ui.note((" %s\n") % short(h))
if errormsg:
- raise util.Abort(errormsg, hint=hint)
+ raise error.Abort(errormsg, hint=hint)
diff --git a/mercurial/dispatch.py b/mercurial/dispatch.py
--- a/mercurial/dispatch.py
+++ b/mercurial/dispatch.py
@@ -98,11 +98,11 @@ def dispatch(req):
req.ui.fin = req.fin
if req.fout:
req.ui.fout = req.fout
if req.ferr:
req.ui.ferr = req.ferr
- except util.Abort as inst:
+ except error.Abort as inst:
ferr.write(_("abort: %s\n") % inst)
if inst.hint:
ferr.write(_("(%s)\n") % inst.hint)
return -1
except error.ParseError as inst:
@@ -251,11 +251,11 @@ def _runcatch(req):
ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
try:
# check if the command is in a disabled extension
# (but don't check for extensions themselves)
commands.help_(ui, inst.args[0], unknowncmd=True)
- except (error.UnknownCommand, util.Abort):
+ except (error.UnknownCommand, error.Abort):
suggested = False
if len(inst.args) == 2:
sim = _getsimilar(inst.args[1], inst.args[0])
if sim:
ui.warn(_('(did you mean one of %s?)\n') %
@@ -264,11 +264,11 @@ def _runcatch(req):
if not suggested:
commands.help_(ui, 'shortlist')
except error.InterventionRequired as inst:
ui.warn("%s\n" % inst)
return 1
- except util.Abort as inst:
+ 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)
@@ -396,11 +396,11 @@ def aliasargs(fn, givenargs):
def replacer(m):
num = int(m.group(1)) - 1
nums.append(num)
if num < len(givenargs):
return givenargs[num]
- raise util.Abort(_('too few arguments for command alias'))
+ raise error.Abort(_('too few arguments for command alias'))
cmd = re.sub(r'\$(\d+|\$)', replacer, cmd)
givenargs = [x for i, x in enumerate(givenargs)
if i not in nums]
args = shlex.split(cmd)
return args + givenargs
@@ -523,11 +523,11 @@ class cmdalias(object):
# check if the command is in a disabled extension
cmd, ext = extensions.disabledcmd(ui, self.cmdname)[:2]
hint = _("'%s' is provided by '%s' extension") % (cmd, ext)
except error.UnknownCommand:
pass
- raise util.Abort(self.badalias, hint=hint)
+ raise error.Abort(self.badalias, hint=hint)
if self.shadows:
ui.debug("alias '%s' shadows command '%s'\n" %
(self.name, self.cmdname))
if util.safehasattr(self, 'shell'):
@@ -612,11 +612,11 @@ def _parseconfig(ui, config):
if not section or not name:
raise IndexError
ui.setconfig(section, name, value, '--config')
configs.append((section, name, value))
except (IndexError, ValueError):
- raise util.Abort(_('malformed --config option: %r '
+ raise error.Abort(_('malformed --config option: %r '
'(use --config section.name=value)') % cfg)
return configs
def _earlygetopt(aliases, args):
@@ -688,11 +688,11 @@ def _getlocal(ui, rpath):
Takes paths in [cwd]/.hg/hgrc into account."
"""
try:
wd = os.getcwd()
except OSError as e:
- raise util.Abort(_("error getting current working directory: %s") %
+ raise error.Abort(_("error getting current working directory: %s") %
e.strerror)
path = cmdutil.findrepo(wd) or ""
if not path:
lui = ui
else:
@@ -811,15 +811,15 @@ def _dispatch(req):
fullargs = args
cmd, func, args, options, cmdoptions = _parse(lui, args)
if options["config"]:
- raise util.Abort(_("option --config may not be abbreviated!"))
+ raise error.Abort(_("option --config may not be abbreviated!"))
if options["cwd"]:
- raise util.Abort(_("option --cwd may not be abbreviated!"))
+ raise error.Abort(_("option --cwd may not be abbreviated!"))
if options["repository"]:
- raise util.Abort(_(
+ raise error.Abort(_(
"option -R has to be separated from other options (e.g. not -qR) "
"and --repository may only be abbreviated as --repo!"))
if options["encoding"]:
encoding.encoding = options["encoding"]
@@ -882,11 +882,11 @@ def _dispatch(req):
repo.ui.ferr = ui.ferr
else:
try:
repo = hg.repository(ui, path=path)
if not repo.local():
- raise util.Abort(_("repository '%s' is not local") % path)
+ raise error.Abort(_("repository '%s' is not local") % path)
repo.ui.setconfig("bundle", "mainreporoot", repo.root, 'repo')
except error.RequirementError:
raise
except error.RepoError:
if rpath and rpath[-1]: # invalid -R path
@@ -934,11 +934,11 @@ def lsprofile(ui, func, fp):
format = 'text'
try:
from . import lsprof
except ImportError:
- raise util.Abort(_(
+ raise error.Abort(_(
'lsprof not available - install from '
'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
p = lsprof.Profiler()
p.enable(subcalls=True)
try:
@@ -958,11 +958,11 @@ def lsprofile(ui, func, fp):
def flameprofile(ui, func, fp):
try:
from flamegraph import flamegraph
except ImportError:
- raise util.Abort(_(
+ raise error.Abort(_(
'flamegraph not available - install from '
'https://github.com/evanhempel/python-flamegraph'))
# developer config: profiling.freq
freq = ui.configint('profiling', 'freq', default=1000)
filter_ = None
@@ -983,11 +983,11 @@ def flameprofile(ui, func, fp):
def statprofile(ui, func, fp):
try:
import statprof
except ImportError:
- raise util.Abort(_(
+ raise error.Abort(_(
'statprof not available - install using "easy_install statprof"'))
freq = ui.configint('profiling', 'freq', default=1000)
if freq > 0:
statprof.reset(freq)
diff --git a/mercurial/exchange.py b/mercurial/exchange.py
--- a/mercurial/exchange.py
+++ b/mercurial/exchange.py
@@ -28,19 +28,19 @@ def readbundle(ui, fh, fname, vfs=None):
fname = vfs.join(fname)
magic, version = header[0:2], header[2:4]
if magic != 'HG':
- raise util.Abort(_('%s: not a Mercurial bundle') % fname)
+ raise error.Abort(_('%s: not a Mercurial bundle') % fname)
if version == '10':
if alg is None:
alg = changegroup.readexactly(fh, 2)
return changegroup.cg1unpacker(fh, alg)
elif version.startswith('2'):
return bundle2.getunbundler(ui, fh, magicstring=magic + version)
else:
- raise util.Abort(_('%s: unknown bundle version %s') % (fname, version))
+ raise error.Abort(_('%s: unknown bundle version %s') % (fname, version))
def buildobsmarkerspart(bundler, markers):
"""add an obsmarker part to the bundler with <markers>
No part is created if markers is empty.
@@ -191,22 +191,22 @@ def push(repo, remote, force=False, revs
- pushop.remote.local().supported)
if missing:
msg = _("required features are not"
" supported in the destination:"
" %s") % (', '.join(sorted(missing)))
- raise util.Abort(msg)
+ raise error.Abort(msg)
# there are two ways to push to remote repo:
#
# addchangegroup assumes local user can lock remote
# repo (local filesystem, old ssh servers).
#
# unbundle assumes local user cannot lock remote repo (new ssh
# servers, http servers).
if not pushop.remote.canpush():
- raise util.Abort(_("destination does not support push"))
+ raise error.Abort(_("destination does not support push"))
# get local lock as we might write phase data
localwlock = locallock = None
try:
# bundle2 push may receive a reply bundle touching bookmarks or other
# things requiring the wlock. Take it now to ensure proper ordering.
@@ -433,13 +433,13 @@ def _pushcheckoutgoing(pushop):
# least one of the missinghead will be obsolete or
# unstable. So checking heads only is ok
for node in outgoing.missingheads:
ctx = unfi[node]
if ctx.obsolete():
- raise util.Abort(mso % ctx)
+ raise error.Abort(mso % ctx)
elif ctx.troubled():
- raise util.Abort(mst[ctx.troubles()[0]] % ctx)
+ raise error.Abort(mst[ctx.troubles()[0]] % ctx)
# internal config: bookmarks.pushing
newbm = pushop.ui.configlist('bookmarks', 'pushing')
discovery.checkheads(unfi, pushop.remote, outgoing,
pushop.remoteheads,
@@ -656,18 +656,18 @@ def _pushbundle2(pushop):
stream = util.chunkbuffer(bundler.getchunks())
try:
try:
reply = pushop.remote.unbundle(stream, ['force'], 'push')
except error.BundleValueError as exc:
- raise util.Abort('missing support for %s' % exc)
+ raise error.Abort('missing support for %s' % exc)
try:
trgetter = None
if pushback:
trgetter = pushop.trmanager.transaction
op = bundle2.processbundle(pushop.repo, reply, trgetter)
except error.BundleValueError as exc:
- raise util.Abort('missing support for %s' % exc)
+ raise error.Abort('missing support for %s' % exc)
except error.PushkeyFailed as exc:
partid = int(exc.partid)
if partid not in pushop.pkfailcb:
raise
pushop.pkfailcb[partid](pushop, exc)
@@ -965,11 +965,11 @@ def pull(repo, remote, heads=None, force
missing = set(pullop.remote.requirements) - pullop.repo.supported
if missing:
msg = _("required features are not"
" supported in the destination:"
" %s") % (', '.join(sorted(missing)))
- raise util.Abort(msg)
+ raise error.Abort(msg)
lock = pullop.repo.lock()
try:
pullop.trmanager = transactionmanager(repo, 'pull', remote.url())
streamclone.maybeperformlegacystreamclone(pullop)
@@ -1106,11 +1106,11 @@ def _pullbundle2(pullop):
_pullbundle2extraprepare(pullop, kwargs)
bundle = pullop.remote.getbundle('pull', **kwargs)
try:
op = bundle2.processbundle(pullop.repo, bundle, pullop.gettransaction)
except error.BundleValueError as exc:
- raise util.Abort('missing support for %s' % exc)
+ raise error.Abort('missing support for %s' % exc)
if pullop.fetch:
results = [cg['return'] for cg in op.records['changegroup']]
pullop.cgresult = changegroup.combineresults(results)
@@ -1156,11 +1156,11 @@ def _pullchangeset(pullop):
cg = pullop.remote.getbundle('pull', common=pullop.common,
heads=pullop.heads or pullop.rheads)
elif pullop.heads is None:
cg = pullop.remote.changegroup(pullop.fetch, 'pull')
elif not pullop.remote.capable('changegroupsubset'):
- raise util.Abort(_("partial pull cannot be done because "
+ raise error.Abort(_("partial pull cannot be done because "
"other repository doesn't support "
"changegroupsubset."))
else:
cg = pullop.remote.changegroupsubset(pullop.fetch, pullop.heads, 'pull')
pullop.cgresult = changegroup.addchangegroup(pullop.repo, cg, 'pull',
diff --git a/mercurial/fancyopts.py b/mercurial/fancyopts.py
--- a/mercurial/fancyopts.py
+++ b/mercurial/fancyopts.py
@@ -8,11 +8,11 @@
from __future__ import absolute_import
import getopt
from .i18n import _
-from . import util
+from . import error
def gnugetopt(args, options, longoptions):
"""Parse options mostly like getopt.gnu_getopt.
This is different from getopt.gnu_getopt in that an argument of - will
@@ -112,11 +112,11 @@ def fancyopts(args, options, state, gnu=
state[name] = defmap[name](val)
elif t is type(1):
try:
state[name] = int(val)
except ValueError:
- raise util.Abort(_('invalid value %r for option %s, '
+ raise error.Abort(_('invalid value %r for option %s, '
'expected int') % (val, opt))
elif t is type(''):
state[name] = val
elif t is type([]):
state[name].append(val)
diff --git a/mercurial/fileset.py b/mercurial/fileset.py
--- a/mercurial/fileset.py
+++ b/mercurial/fileset.py
@@ -361,11 +361,11 @@ def encoding(mctx, x):
for f in mctx.existing():
d = mctx.ctx[f].data()
try:
d.decode(enc)
except LookupError:
- raise util.Abort(_("unknown encoding '%s'") % enc)
+ raise error.Abort(_("unknown encoding '%s'") % enc)
except UnicodeDecodeError:
continue
s.append(f)
return s
diff --git a/mercurial/formatter.py b/mercurial/formatter.py
--- a/mercurial/formatter.py
+++ b/mercurial/formatter.py
@@ -16,12 +16,12 @@ from .node import (
short,
)
from . import (
encoding,
+ error,
templater,
- util,
)
class baseformatter(object):
def __init__(self, ui, topic, opts):
self._ui = ui
@@ -177,11 +177,11 @@ def lookuptemplate(ui, topic, tmpl):
tmpl = t
return tmpl, None
if tmpl == 'list':
ui.write(_("available styles: %s\n") % templater.stylelist())
- raise util.Abort(_("specify a template"))
+ raise error.Abort(_("specify a template"))
# perhaps it's a path to a map or a template
if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
# is it a mapfile for a style?
if os.path.basename(tmpl).startswith("map-"):
diff --git a/mercurial/hbisect.py b/mercurial/hbisect.py
--- a/mercurial/hbisect.py
+++ b/mercurial/hbisect.py
@@ -18,11 +18,10 @@ from .node import (
hex,
short,
)
from . import (
error,
- util,
)
def bisect(changelog, state):
"""find the next node (if any) for testing during a bisect search.
returns a (nodes, number, good) tuple.
@@ -72,12 +71,12 @@ def bisect(changelog, state):
badrev, ancestors = buildancestors(state['good'], state['bad'])
bad = changelog.node(badrev)
if not ancestors: # now we're confused
if (len(state['bad']) == 1 and len(state['good']) == 1 and
state['bad'] != state['good']):
- raise util.Abort(_("starting revisions are not directly related"))
- raise util.Abort(_("inconsistent state, %s:%s is good and bad")
+ raise error.Abort(_("starting revisions are not directly related"))
+ raise error.Abort(_("inconsistent state, %s:%s is good and bad")
% (badrev, short(bad)))
# build children dict
children = {}
visit = collections.deque([badrev])
@@ -147,11 +146,11 @@ def load_state(repo):
if os.path.exists(repo.join("bisect.state")):
for l in repo.vfs("bisect.state"):
kind, node = l[:-1].split()
node = repo.lookup(node)
if kind not in state:
- raise util.Abort(_("unknown bisect kind %s") % kind)
+ raise error.Abort(_("unknown bisect kind %s") % kind)
state[kind].append(node)
return state
def save_state(repo, state):
diff --git a/mercurial/help.py b/mercurial/help.py
--- a/mercurial/help.py
+++ b/mercurial/help.py
@@ -500,11 +500,11 @@ def help_(ui, name, unknowncmd=False, fu
rst.extend(minirst.maketable(sorted(matches[t]), 1))
rst.append('\n')
if not rst:
msg = _('no matches')
hint = _('try "hg help" for a list of topics')
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
elif name and name != 'shortlist':
queries = []
if unknowncmd:
queries += [helpextcmd]
if opts.get('extension'):
@@ -523,11 +523,11 @@ def help_(ui, name, unknowncmd=False, fu
if unknowncmd:
raise error.UnknownCommand(name)
else:
msg = _('no such help topic: %s') % name
hint = _('try "hg help --keyword %s"') % name
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
else:
# program name
if not ui.quiet:
rst = [_("Mercurial Distributed SCM\n"), '\n']
rst.extend(helplist())
diff --git a/mercurial/hg.py b/mercurial/hg.py
--- a/mercurial/hg.py
+++ b/mercurial/hg.py
@@ -63,19 +63,19 @@ def addbranchrevs(lrepo, other, branches
else:
revs = []
if not peer.capable('branchmap'):
if branches:
- raise util.Abort(_("remote branch lookup not supported"))
+ raise error.Abort(_("remote branch lookup not supported"))
revs.append(hashbranch)
return revs, revs[0]
branchmap = peer.branchmap()
def primary(branch):
if branch == '.':
if not lrepo:
- raise util.Abort(_("dirstate branch not accessible"))
+ raise error.Abort(_("dirstate branch not accessible"))
branch = lrepo.dirstate.branch()
if branch in branchmap:
revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
return True
else:
@@ -158,11 +158,11 @@ def _peerorrepo(ui, path, create=False):
def repository(ui, path='', create=False):
"""return a repository object for the specified path"""
peer = _peerorrepo(ui, path, create)
repo = peer.local()
if not repo:
- raise util.Abort(_("repository '%s' is not local") %
+ raise error.Abort(_("repository '%s' is not local") %
(path or peer.url()))
return repo.filtered('visible')
def peer(uiorrepo, opts, path, create=False):
'''return a repository peer for the specified path'''
@@ -192,11 +192,11 @@ def defaultdest(source):
def share(ui, source, dest=None, update=True, bookmarks=True):
'''create a shared repository'''
if not islocal(source):
- raise util.Abort(_('can only share local repositories'))
+ raise error.Abort(_('can only share local repositories'))
if not dest:
dest = defaultdest(source)
else:
dest = ui.expandpath(dest)
@@ -215,11 +215,11 @@ def share(ui, source, dest=None, update=
destwvfs = scmutil.vfs(dest, realpath=True)
destvfs = scmutil.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
if destvfs.lexists():
- raise util.Abort(_('destination already exists'))
+ raise error.Abort(_('destination already exists'))
if not destwvfs.isdir():
destwvfs.mkdir()
destvfs.makedir()
@@ -318,11 +318,11 @@ def clonewithshare(ui, peeropts, sharepa
True.
"""
revs = None
if rev:
if not srcpeer.capable('lookup'):
- raise util.Abort(_("src repository does not support "
+ raise error.Abort(_("src repository does not support "
"revision lookup and so doesn't "
"support clone by revision"))
revs = [srcpeer.lookup(r) for r in rev]
basename = os.path.basename(sharepath)
@@ -414,18 +414,18 @@ def clone(ui, peeropts, source, dest=Non
dest = util.urllocalpath(dest)
source = util.urllocalpath(source)
if not dest:
- raise util.Abort(_("empty destination path is not valid"))
+ raise error.Abort(_("empty destination path is not valid"))
destvfs = scmutil.vfs(dest, expandpath=True)
if destvfs.lexists():
if not destvfs.isdir():
- raise util.Abort(_("destination '%s' already exists") % dest)
+ raise error.Abort(_("destination '%s' already exists") % dest)
elif destvfs.listdir():
- raise util.Abort(_("destination '%s' is not empty") % dest)
+ raise error.Abort(_("destination '%s' is not empty") % dest)
shareopts = shareopts or {}
sharepool = shareopts.get('pool')
sharenamemode = shareopts.get('mode')
if sharepool and islocal(dest):
@@ -446,11 +446,11 @@ def clone(ui, peeropts, source, dest=Non
ui.status(_('(not using pooled storage: '
'unable to resolve identity of remote)\n'))
elif sharenamemode == 'remote':
sharepath = os.path.join(sharepool, util.sha1(source).hexdigest())
else:
- raise util.Abort('unknown share naming mode: %s' % sharenamemode)
+ raise error.Abort('unknown share naming mode: %s' % sharenamemode)
if sharepath:
return clonewithshare(ui, peeropts, sharepath, source, srcpeer,
dest, pull=pull, rev=rev, update=update,
stream=stream)
@@ -492,11 +492,11 @@ def clone(ui, peeropts, source, dest=Non
destpath = hgdir
util.makedir(destpath, notindexed=True)
except OSError as inst:
if inst.errno == errno.EEXIST:
cleandir = None
- raise util.Abort(_("destination '%s' already exists")
+ raise error.Abort(_("destination '%s' already exists")
% dest)
raise
destlock = copystore(ui, srcrepo, destpath)
# copy bookmarks over
@@ -532,18 +532,18 @@ def clone(ui, peeropts, source, dest=Non
destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
# only pass ui when no srcrepo
except OSError as inst:
if inst.errno == errno.EEXIST:
cleandir = None
- raise util.Abort(_("destination '%s' already exists")
+ raise error.Abort(_("destination '%s' already exists")
% dest)
raise
revs = None
if rev:
if not srcpeer.capable('lookup'):
- raise util.Abort(_("src repository does not support "
+ raise error.Abort(_("src repository does not support "
"revision lookup and so doesn't "
"support clone by revision"))
revs = [srcpeer.lookup(r) for r in rev]
checkout = revs[0]
if destpeer.local():
@@ -555,11 +555,12 @@ def clone(ui, peeropts, source, dest=Non
destpeer.local().clone(srcpeer, heads=revs, stream=stream)
elif srcrepo:
exchange.push(srcrepo, destpeer, revs=revs,
bookmarks=srcrepo._bookmarks.keys())
else:
- raise util.Abort(_("clone from remote to remote not supported"))
+ raise error.Abort(_("clone from remote to remote not supported")
+ )
cleandir = None
destrepo = destpeer.local()
if destrepo:
diff --git a/mercurial/hgweb/hgwebdir_mod.py b/mercurial/hgweb/hgwebdir_mod.py
--- a/mercurial/hgweb/hgwebdir_mod.py
+++ b/mercurial/hgweb/hgwebdir_mod.py
@@ -116,11 +116,11 @@ class hgwebdir(object):
u.setconfig('progress', 'disable', 'true', 'hgweb')
if not isinstance(self.conf, (dict, list, tuple)):
map = {'paths': 'hgweb-paths'}
if not os.path.exists(self.conf):
- raise util.Abort(_('config file %s not found!') % self.conf)
+ raise error.Abort(_('config file %s not found!') % self.conf)
u.readconfig(self.conf, remap=map, trust=True)
paths = []
for name, ignored in u.configitems('hgweb-paths'):
for path in u.configlist('hgweb-paths', name):
paths.append((name, path))
diff --git a/mercurial/hgweb/server.py b/mercurial/hgweb/server.py
--- a/mercurial/hgweb/server.py
+++ b/mercurial/hgweb/server.py
@@ -206,11 +206,11 @@ class _httprequesthandleropenssl(_httpre
def preparehttpserver(httpserver, ssl_cert):
try:
import OpenSSL
OpenSSL.SSL.Context
except ImportError:
- raise util.Abort(_("SSL support is unavailable"))
+ raise error.Abort(_("SSL support is unavailable"))
ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
ctx.use_privatekey_file(ssl_cert)
ctx.use_certificate_file(ssl_cert)
sock = socket.socket(httpserver.address_family, httpserver.socket_type)
httpserver.socket = OpenSSL.SSL.Connection(ctx, sock)
@@ -247,11 +247,11 @@ class _httprequesthandlerssl(_httpreques
def preparehttpserver(httpserver, ssl_cert):
try:
import ssl
ssl.wrap_socket
except ImportError:
- raise util.Abort(_("SSL support is unavailable"))
+ raise error.Abort(_("SSL support is unavailable"))
httpserver.socket = ssl.wrap_socket(
httpserver.socket, server_side=True,
certfile=ssl_cert, ssl_version=ssl.PROTOCOL_TLSv1)
def setup(self):
@@ -343,7 +343,7 @@ def create_server(ui, app):
address = ui.config('web', 'address', '')
port = util.getport(ui.config('web', 'port', 8000))
try:
return cls(ui, app, (address, port), handler)
except socket.error as inst:
- raise util.Abort(_("cannot start server at '%s:%d': %s")
+ raise error.Abort(_("cannot start server at '%s:%d': %s")
% (address, port, inst.args[1]))
diff --git a/mercurial/hook.py b/mercurial/hook.py
--- a/mercurial/hook.py
+++ b/mercurial/hook.py
@@ -33,11 +33,11 @@ def _pythonhook(ui, repo, name, hname, f
obj = funcname
funcname = obj.__module__ + "." + obj.__name__
else:
d = funcname.rfind('.')
if d == -1:
- raise util.Abort(_('%s hook is invalid ("%s" not in '
+ raise error.Abort(_('%s hook is invalid ("%s" not in '
'a module)') % (hname, funcname))
modname = funcname[:d]
oldpaths = sys.path
if util.mainfrozen():
# binary installs require sys.path manipulation
@@ -61,23 +61,23 @@ def _pythonhook(ui, repo, name, hname, f
ui.traceback(e1)
if ui.tracebackflag:
ui.warn(_('exception from second failed import '
'attempt:\n'))
ui.traceback(e2)
- raise util.Abort(_('%s hook is invalid '
+ raise error.Abort(_('%s hook is invalid '
'(import of "%s" failed)') %
(hname, modname))
sys.path = oldpaths
try:
for p in funcname.split('.')[1:]:
obj = getattr(obj, p)
except AttributeError:
- raise util.Abort(_('%s hook is invalid '
+ raise error.Abort(_('%s hook is invalid '
'("%s" is not defined)') %
(hname, funcname))
if not callable(obj):
- raise util.Abort(_('%s hook is invalid '
+ raise error.Abort(_('%s hook is invalid '
'("%s" is not callable)') %
(hname, funcname))
ui.note(_("calling hook %s: %s\n") % (hname, funcname))
starttime = time.time()
@@ -89,11 +89,11 @@ def _pythonhook(ui, repo, name, hname, f
old = sys.stdout, sys.stderr, sys.stdin
sys.stdout, sys.stderr, sys.stdin = ui.fout, ui.ferr, ui.fin
r = obj(ui=ui, repo=repo, hooktype=name, **args)
except Exception as exc:
- if isinstance(exc, util.Abort):
+ if isinstance(exc, error.Abort):
ui.warn(_('error: %s hook failed: %s\n') %
(hname, exc.args[0]))
else:
ui.warn(_('error: %s hook raised an exception: '
'%s\n') % (hname, exc))
diff --git a/mercurial/httppeer.py b/mercurial/httppeer.py
--- a/mercurial/httppeer.py
+++ b/mercurial/httppeer.py
@@ -47,11 +47,11 @@ class httppeer(wireproto.wirepeer):
self.handler = None
self.urlopener = None
self.requestbuilder = None
u = util.url(path)
if u.query or u.fragment:
- raise util.Abort(_('unsupported URL component: "%s"') %
+ raise error.Abort(_('unsupported URL component: "%s"') %
(u.query or u.fragment))
# urllib cannot handle URLs with embedded user or passwd
self._url, authinfo = u.authinfo()
@@ -84,11 +84,11 @@ class httppeer(wireproto.wirepeer):
self.ui.debug('capabilities: %s\n' %
(' '.join(self.caps or ['none'])))
return self.caps
def lock(self):
- raise util.Abort(_('operation not supported over http'))
+ raise error.Abort(_('operation not supported over http'))
def _callstream(self, cmd, **args):
if cmd == 'pushkey':
args['data'] = ''
data = args.pop('data', None)
@@ -135,19 +135,19 @@ class httppeer(wireproto.wirepeer):
req.add_unredirected_header('Content-Length', '%d' % size)
try:
resp = self.urlopener.open(req)
except urllib2.HTTPError as inst:
if inst.code == 401:
- raise util.Abort(_('authorization failed'))
+ raise error.Abort(_('authorization failed'))
raise
except httplib.HTTPException as inst:
self.ui.debug('http error while sending %s command\n' % cmd)
self.ui.traceback()
raise IOError(None, inst)
except IndexError:
# this only happens with Python 2.3, later versions raise URLError
- raise util.Abort(_('http error, possibly caused by proxy setting'))
+ raise error.Abort(_('http error, possibly caused by proxy setting'))
# record the url we got redirected to
resp_url = resp.geturl()
if resp_url.endswith(qs):
resp_url = resp_url[:-len(qs)]
if self._url.rstrip('/') != resp_url.rstrip('/'):
@@ -221,12 +221,12 @@ class httppeer(wireproto.wirepeer):
if len(vals) < 2:
raise error.ResponseError(_("unexpected response:"), r)
return vals
except socket.error as err:
if err.args[0] in (errno.ECONNRESET, errno.EPIPE):
- raise util.Abort(_('push failed: %s') % err.args[1])
- raise util.Abort(err.args[1])
+ raise error.Abort(_('push failed: %s') % err.args[1])
+ raise error.Abort(err.args[1])
finally:
fp.close()
os.unlink(tempname)
def _calltwowaystream(self, cmd, fp, **args):
@@ -261,17 +261,17 @@ class httppeer(wireproto.wirepeer):
raise exception
class httpspeer(httppeer):
def __init__(self, ui, path):
if not url.has_https:
- raise util.Abort(_('Python support for SSL and HTTPS '
+ raise error.Abort(_('Python support for SSL and HTTPS '
'is not installed'))
httppeer.__init__(self, ui, path)
def instance(ui, path, create):
if create:
- raise util.Abort(_('cannot create new http repository'))
+ raise error.Abort(_('cannot create new http repository'))
try:
if path.startswith('https:'):
inst = httpspeer(ui, path)
else:
inst = httppeer(ui, path)
diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py
--- a/mercurial/localrepo.py
+++ b/mercurial/localrepo.py
@@ -638,11 +638,11 @@ class localrepository(object):
date: date tuple to use if committing'''
if not local:
m = matchmod.exact(self.root, '', ['.hgtags'])
if any(self.status(match=m, unknown=True, ignored=True)):
- raise util.Abort(_('working copy of .hgtags is changed'),
+ raise error.Abort(_('working copy of .hgtags is changed'),
hint=_('please commit .hgtags manually'))
self.tags() # instantiate the cache
self._tag(names, node, message, local, user, date, editor=editor)
@@ -1104,11 +1104,11 @@ class localrepository(object):
except IOError:
msg = _('rolling back unknown transaction\n')
desc = None
if not force and self['.'] != self['tip'] and desc == 'commit':
- raise util.Abort(
+ raise error.Abort(
_('rollback of last commit while not checked out '
'may lose data'), hint=_('use -f to force'))
ui.status(msg)
if dryrun:
@@ -1418,11 +1418,11 @@ class localrepository(object):
"""
if extra is None:
extra = {}
def fail(f, msg):
- raise util.Abort('%s: %s' % (f, msg))
+ raise error.Abort('%s: %s' % (f, msg))
if not match:
match = matchmod.always(self.root, '')
if not force:
@@ -1434,11 +1434,11 @@ class localrepository(object):
try:
wctx = self[None]
merge = len(wctx.parents()) > 1
if not force and merge and match.ispartial():
- raise util.Abort(_('cannot partially commit a merge '
+ raise error.Abort(_('cannot partially commit a merge '
'(do not specify files or patterns)'))
status = self.status(match=match, clean=force)
if force:
status.modified.extend(status.clean) # mq may commit clean files
@@ -1462,16 +1462,16 @@ class localrepository(object):
# ignore working copy, use old state if present
if s in oldstate:
newstate[s] = oldstate[s]
continue
if not force:
- raise util.Abort(
+ raise error.Abort(
_("commit with new subrepo %s excluded") % s)
dirtyreason = wctx.sub(s).dirtyreason(True)
if dirtyreason:
if not self.ui.configbool('ui', 'commitsubrepos'):
- raise util.Abort(dirtyreason,
+ raise error.Abort(dirtyreason,
hint=_("use --subrepos for recursive commit"))
subs.append(s)
commitsubs.add(s)
else:
bs = wctx.sub(s).basestate()
@@ -1484,11 +1484,11 @@ class localrepository(object):
r = [s for s in p.substate if s not in newstate]
subs += [s for s in r if match(s)]
if subs:
if (not match('.hgsub') and
'.hgsub' in (wctx.modified() + wctx.added())):
- raise util.Abort(
+ raise error.Abort(
_("can't commit subrepos without .hgsub"))
status.modified.insert(0, '.hgsubstate')
elif '.hgsub' in status.removed:
# clean up .hgsubstate when .hgsub is removed
@@ -1526,16 +1526,16 @@ class localrepository(object):
or self.ui.configbool('ui', 'allowemptycommit'))
if not allowemptycommit:
return None
if merge and cctx.deleted():
- raise util.Abort(_("cannot commit merge with missing files"))
+ raise error.Abort(_("cannot commit merge with missing files"))
ms = mergemod.mergestate(self)
for f in status.modified:
if f in ms and ms[f] == 'u':
- raise util.Abort(_('unresolved merge conflicts '
+ raise error.Abort(_('unresolved merge conflicts '
'(see "hg help resolve")'))
if editor:
cctx._text = editor(self, cctx, subs)
edited = (text != cctx._text)
diff --git a/mercurial/mail.py b/mercurial/mail.py
--- a/mercurial/mail.py
+++ b/mercurial/mail.py
@@ -16,10 +16,11 @@ import sys
import time
from .i18n import _
from . import (
encoding,
+ error,
sslutil,
util,
)
_oldheaderinit = email.Header.Header.__init__
@@ -91,28 +92,28 @@ if util.safehasattr(smtplib.SMTP, '_get_
**self._sslkwargs)
self.file = smtplib.SSLFakeFile(new_socket)
return new_socket
else:
def SMTPS(sslkwargs, keyfile=None, certfile=None, **kwargs):
- raise util.Abort(_('SMTPS requires Python 2.6 or later'))
+ raise error.Abort(_('SMTPS requires Python 2.6 or later'))
def _smtp(ui):
'''build an smtp connection and return a function to send mail'''
local_hostname = ui.config('smtp', 'local_hostname')
tls = ui.config('smtp', 'tls', 'none')
# backward compatible: when tls = true, we use starttls.
starttls = tls == 'starttls' or util.parsebool(tls)
smtps = tls == 'smtps'
if (starttls or smtps) and not util.safehasattr(socket, 'ssl'):
- raise util.Abort(_("can't use TLS: Python SSL support not installed"))
+ raise error.Abort(_("can't use TLS: Python SSL support not installed"))
mailhost = ui.config('smtp', 'host')
if not mailhost:
- raise util.Abort(_('smtp.host not configured - cannot send mail'))
+ raise error.Abort(_('smtp.host not configured - cannot send mail'))
verifycert = ui.config('smtp', 'verifycert', 'strict')
if verifycert not in ['strict', 'loose']:
if util.parsebool(verifycert) is not False:
- raise util.Abort(_('invalid smtp.verifycert configuration: %s')
+ raise error.Abort(_('invalid smtp.verifycert configuration: %s')
% (verifycert))
verifycert = False
if (starttls or smtps) and verifycert:
sslkwargs = sslutil.sslkwargs(ui, mailhost)
else:
@@ -149,20 +150,20 @@ def _smtp(ui):
ui.note(_('(authenticating to mail server as %s)\n') %
(username))
try:
s.login(username, password)
except smtplib.SMTPException as inst:
- raise util.Abort(inst)
+ raise error.Abort(inst)
def send(sender, recipients, msg):
try:
return s.sendmail(sender, recipients, msg)
except smtplib.SMTPRecipientsRefused as inst:
recipients = [r[1] for r in inst.recipients.values()]
- raise util.Abort('\n' + '\n'.join(recipients))
+ raise error.Abort('\n' + '\n'.join(recipients))
except smtplib.SMTPException as inst:
- raise util.Abort(inst)
+ raise error.Abort(inst)
return send
def _sendmail(ui, sender, recipients, msg):
'''send mail using sendmail.'''
@@ -172,11 +173,11 @@ def _sendmail(ui, sender, recipients, ms
ui.note(_('sending mail: %s\n') % cmdline)
fp = util.popen(cmdline, 'w')
fp.write(msg)
ret = fp.close()
if ret:
- raise util.Abort('%s %s' % (
+ raise error.Abort('%s %s' % (
os.path.basename(program.split(None, 1)[0]),
util.explainexit(ret)[0]))
def _mbox(mbox, sender, recipients, msg):
'''write mails to mbox'''
@@ -206,15 +207,15 @@ def sendmail(ui, sender, recipients, msg
def validateconfig(ui):
'''determine if we have enough config data to try sending email.'''
method = ui.config('email', 'method', 'smtp')
if method == 'smtp':
if not ui.config('smtp', 'host'):
- raise util.Abort(_('smtp specified as email transport, '
+ raise error.Abort(_('smtp specified as email transport, '
'but no smtp host configured'))
else:
if not util.findexe(method):
- raise util.Abort(_('%r specified as email transport, '
+ raise error.Abort(_('%r specified as email transport, '
'but not in PATH') % method)
def mimetextpatch(s, subtype='plain', display=False):
'''Return MIME message suitable for a patch.
Charset will be detected as utf-8 or (possibly fake) us-ascii.
@@ -300,17 +301,17 @@ def _addressencode(ui, name, addr, chars
acc, dom = addr.split('@')
acc = acc.encode('ascii')
dom = dom.decode(encoding.encoding).encode('idna')
addr = '%s@%s' % (acc, dom)
except UnicodeDecodeError:
- raise util.Abort(_('invalid email address: %s') % addr)
+ raise error.Abort(_('invalid email address: %s') % addr)
except ValueError:
try:
# too strict?
addr = addr.encode('ascii')
except UnicodeDecodeError:
- raise util.Abort(_('invalid local address: %s') % addr)
+ raise error.Abort(_('invalid local address: %s') % addr)
return email.Utils.formataddr((name, addr))
def addressencode(ui, address, charsets=None, display=False):
'''Turns address into RFC-2047 compliant header.'''
if display or not address:
diff --git a/mercurial/match.py b/mercurial/match.py
--- a/mercurial/match.py
+++ b/mercurial/match.py
@@ -11,10 +11,11 @@ import copy
import os
import re
from .i18n import _
from . import (
+ error,
pathutil,
util,
)
propertycache = util.propertycache
@@ -35,11 +36,11 @@ def _expandsets(kindpats, ctx, listsubre
other = []
for kind, pat, source in kindpats:
if kind == 'set':
if not ctx:
- raise util.Abort("fileset expression with no context")
+ raise error.Abort("fileset expression with no context")
s = ctx.getfileset(pat)
fset.update(s)
if listsubrepos:
for subpath in ctx.substate:
@@ -288,11 +289,11 @@ class match(object):
files = files.split('\0')
else:
files = files.splitlines()
files = [f for f in files if f]
except EnvironmentError:
- raise util.Abort(_("unable to read file list (%s)") % pat)
+ raise error.Abort(_("unable to read file list (%s)") % pat)
for k, p, source in self._normalize(files, default, root, cwd,
auditor):
kindpats.append((k, p, pat))
continue
elif kind == 'include':
@@ -300,12 +301,12 @@ class match(object):
fullpath = os.path.join(root, util.localpath(pat))
includepats = readpatternfile(fullpath, self._warn)
for k, p, source in self._normalize(includepats, default,
root, cwd, auditor):
kindpats.append((k, p, source or pat))
- except util.Abort as inst:
- raise util.Abort('%s: %s' % (pat, inst[0]))
+ except error.Abort as inst:
+ raise error.Abort('%s: %s' % (pat, inst[0]))
except IOError as inst:
if self._warn:
self._warn(_("skipping unreadable pattern file "
"'%s': %s\n") % (pat, inst.strerror))
continue
@@ -585,15 +586,15 @@ def _buildregexmatch(kindpats, globsuffi
for k, p, s in kindpats:
try:
_rematcher('(?:%s)' % _regex(k, p, globsuffix))
except re.error:
if s:
- raise util.Abort(_("%s: invalid pattern (%s): %s") %
+ raise error.Abort(_("%s: invalid pattern (%s): %s") %
(s, k, p))
else:
- raise util.Abort(_("invalid pattern (%s): %s") % (k, p))
- raise util.Abort(_("invalid pattern"))
+ raise error.Abort(_("invalid pattern (%s): %s") % (k, p))
+ raise error.Abort(_("invalid pattern"))
def _roots(kindpats):
'''return roots and exact explicitly listed files from patterns
>>> _roots([('glob', 'g/*', ''), ('glob', 'g', ''), ('glob', 'g*', '')])
diff --git a/mercurial/mdiff.py b/mercurial/mdiff.py
--- a/mercurial/mdiff.py
+++ b/mercurial/mdiff.py
@@ -4,11 +4,11 @@
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from i18n import _
-import bdiff, mpatch, util, base85
+import bdiff, mpatch, util, base85, error
import re, struct, zlib
def splitnewlines(text):
'''like str.splitlines, but only split on newlines.'''
lines = [l + '\n' for l in text.split('\n')]
@@ -57,11 +57,11 @@ class diffopts(object):
setattr(self, k, v)
try:
self.context = int(self.context)
except ValueError:
- raise util.Abort(_('diff context lines count must be '
+ raise error.Abort(_('diff context lines count must be '
'an integer, not %r') % self.context)
def copy(self, **kwargs):
opts = dict((k, getattr(self, k)) for k in self.defaults)
opts.update(kwargs)
diff --git a/mercurial/merge.py b/mercurial/merge.py
--- a/mercurial/merge.py
+++ b/mercurial/merge.py
@@ -19,10 +19,11 @@ from .node import (
nullid,
nullrev,
)
from . import (
copies,
+ error,
filemerge,
obsolete,
subrepo,
util,
worker,
@@ -95,11 +96,11 @@ class mergestate(object):
self._other = bin(record)
elif rtype == 'F':
bits = record.split('\0')
self._state[bits[0]] = bits[1:]
elif not rtype.islower():
- raise util.Abort(_('unsupported merge state record: %s')
+ raise error.Abort(_('unsupported merge state record: %s')
% rtype)
self._dirty = False
def _readrecords(self):
"""Read merge state from disk and return a list of record (TYPE, data)
@@ -343,11 +344,11 @@ def _checkunknownfiles(repo, wctx, mctx,
aborts.append(f)
for f in sorted(aborts):
repo.ui.warn(_("%s: untracked file differs\n") % f)
if aborts:
- raise util.Abort(_("untracked files in working directory differ "
+ raise error.Abort(_("untracked files in working directory differ "
"from files in requested revision"))
for f, (m, args, msg) in actions.iteritems():
if m == 'c':
actions[f] = ('g', args, msg)
@@ -416,11 +417,11 @@ def _checkcollision(repo, wmf, actions):
# check case-folding collision in provisional merged manifest
foldmap = {}
for f in sorted(pmmf):
fold = util.normcase(f)
if fold in foldmap:
- raise util.Abort(_("case-folding collision between %s and %s")
+ raise error.Abort(_("case-folding collision between %s and %s")
% (f, foldmap[fold]))
foldmap[fold] = f
def manifestmerge(repo, wctx, p2, pa, branchmerge, force, partial,
acceptremote, followcopies):
@@ -1010,22 +1011,22 @@ def update(repo, node, branchmerge, forc
fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
### check phase
if not overwrite and len(pl) > 1:
- raise util.Abort(_("outstanding uncommitted merge"))
+ raise error.Abort(_("outstanding uncommitted merge"))
if branchmerge:
if pas == [p2]:
- raise util.Abort(_("merging with a working directory ancestor"
+ raise error.Abort(_("merging with a working directory ancestor"
" has no effect"))
elif pas == [p1]:
if not mergeancestor and p1.branch() == p2.branch():
- raise util.Abort(_("nothing to merge"),
+ raise error.Abort(_("nothing to merge"),
hint=_("use 'hg update' "
"or check 'hg heads'"))
if not force and (wc.files() or wc.deleted()):
- raise util.Abort(_("uncommitted changes"),
+ raise error.Abort(_("uncommitted changes"),
hint=_("use 'hg status' to list changes"))
for s in sorted(wc.substate):
wc.sub(s).bailifchanged()
elif not overwrite:
@@ -1050,15 +1051,15 @@ def update(repo, node, branchmerge, forc
hint = _("commit and merge, or update --clean to"
" discard changes")
else:
hint = _("commit or update --clean to discard"
" changes")
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
else: # node is none
msg = _("not a linear update")
hint = _("merge or update --check to force update")
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
else:
# Allow jumping branches if clean and specific rev given
pas = [p1]
# deprecated config: merge.followcopies
diff --git a/mercurial/obsolete.py b/mercurial/obsolete.py
--- a/mercurial/obsolete.py
+++ b/mercurial/obsolete.py
@@ -66,11 +66,11 @@ The file starts with a version header:
The header is followed by the markers. Marker format depend of the version. See
comment associated with each format for details.
"""
import errno, struct
-import util, base85, node, parsers
+import util, base85, node, parsers, error
import phases
from i18n import _
_pack = struct.pack
_unpack = struct.unpack
@@ -162,11 +162,11 @@ def _fm0readmarkers(data, off):
off += s
# read metadata
# (metadata will be decoded on demand)
metadata = data[off:off + mdsize]
if len(metadata) != mdsize:
- raise util.Abort(_('parsing obsolete marker: metadata is too '
+ raise error.Abort(_('parsing obsolete marker: metadata is too '
'short, %d bytes expected, got %d')
% (mdsize, len(metadata)))
off += mdsize
metadata = _fm0decodemeta(metadata)
try:
@@ -198,11 +198,11 @@ def _fm0readmarkers(data, off):
yield (pre, sucs, flags, metadata, date, parents)
def _fm0encodeonemarker(marker):
pre, sucs, flags, metadata, date, parents = marker
if flags & usingsha256:
- raise util.Abort(_('cannot handle sha256 with old obsstore format'))
+ raise error.Abort(_('cannot handle sha256 with old obsstore format'))
metadata = dict(metadata)
time, tz = date
metadata['date'] = '%r %i' % (time, tz)
if parents is not None:
if not parents:
@@ -412,11 +412,11 @@ def _readmarkers(data):
"""Read and enumerate markers from raw data"""
off = 0
diskversion = _unpack('>B', data[off:off + 1])[0]
off += 1
if diskversion not in formats:
- raise util.Abort(_('parsing obsolete marker: unknown version %r')
+ raise error.Abort(_('parsing obsolete marker: unknown version %r')
% diskversion)
return diskversion, formats[diskversion][0](data, off)
def encodemarkers(markers, addheader=False, version=_fm0version):
# Kept separate from flushmarkers(), it will be reused for
@@ -494,11 +494,11 @@ def _checkinvalidmarkers(markers):
Exist as a separated function to allow the evolve extension for a more
subtle handling.
"""
for mark in markers:
if node.nullid in mark[1]:
- raise util.Abort(_('bad obsolescence marker detected: '
+ raise error.Abort(_('bad obsolescence marker detected: '
'invalid successors nullid'))
class obsstore(object):
"""Store obsolete markers
@@ -581,12 +581,12 @@ class obsstore(object):
"""Add new markers to the store
Take care of filtering duplicate.
Return the number of new marker."""
if self._readonly:
- raise util.Abort('creating obsolete markers is not enabled on this '
- 'repo')
+ raise error.Abort('creating obsolete markers is not enabled on '
+ 'this repo')
known = set(self._all)
new = []
for m in markers:
if m not in known:
known.add(m)
@@ -1215,20 +1215,20 @@ def createmarkers(repo, relations, flag=
localmetadata = metadata.copy()
if 2 < len(rel):
localmetadata.update(rel[2])
if not prec.mutable():
- raise util.Abort("cannot obsolete public changeset: %s"
+ raise error.Abort("cannot obsolete public changeset: %s"
% prec,
hint='see "hg help phases" for details')
nprec = prec.node()
nsucs = tuple(s.node() for s in sucs)
npare = None
if not nsucs:
npare = tuple(p.node() for p in prec.parents())
if nprec in nsucs:
- raise util.Abort("changeset %s cannot obsolete itself" % prec)
+ raise error.Abort("changeset %s cannot obsolete itself" % prec)
repo.obsstore.create(tr, nprec, nsucs, flag, parents=npare,
date=date, metadata=localmetadata)
repo.filteredrevcache.clear()
tr.close()
finally:
@@ -1248,9 +1248,9 @@ def isenabled(repo, option):
return True
# createmarkers must be enabled if other options are enabled
if ((allowunstableopt in result or exchangeopt in result) and
not createmarkersopt in result):
- raise util.Abort(_("'createmarkers' obsolete option must be enabled "
+ raise error.Abort(_("'createmarkers' obsolete option must be enabled "
"if other obsolete options are enabled"))
return option in result
diff --git a/mercurial/patch.py b/mercurial/patch.py
--- a/mercurial/patch.py
+++ b/mercurial/patch.py
@@ -1054,11 +1054,11 @@ the hunk is left unchanged.
elif r == 5: # done, skip remaining
ret = skipall = False
elif r == 6: # all
ret = skipall = True
elif r == 7: # quit
- raise util.Abort(_('user quit'))
+ raise error.Abort(_('user quit'))
return ret, skipfile, skipall, newpatches
seen = set()
applied = {} # 'filename' -> [] of chunks
skipfile, skipall = None, None
@@ -1962,11 +1962,11 @@ def _applydiff(ui, fp, patcher, backend,
# process.
pass
else:
store.setfile(path, data, mode)
else:
- raise util.Abort(_('unsupported parser state: %s') % state)
+ raise error.Abort(_('unsupported parser state: %s') % state)
if current_file:
rejects += current_file.close()
if rejects:
@@ -2020,11 +2020,11 @@ def patchbackend(ui, backend, patchobj,
if files is None:
files = set()
if eolmode is None:
eolmode = ui.config('patch', 'eol', 'strict')
if eolmode.lower() not in eolmodes:
- raise util.Abort(_('unsupported line endings type: %s') % eolmode)
+ raise error.Abort(_('unsupported line endings type: %s') % eolmode)
eolmode = eolmode.lower()
store = filestore()
try:
fp = open(patchobj, 'rb')
@@ -2093,11 +2093,11 @@ def changedfiles(ui, repo, patchpath, st
'')
changed.add(gp.path)
if gp.op == 'RENAME':
changed.add(gp.oldpath)
elif state not in ('hunk', 'git'):
- raise util.Abort(_('unsupported parser state: %s') % state)
+ raise error.Abort(_('unsupported parser state: %s') % state)
return changed
finally:
fp.close()
class GitDiffRequired(Exception):
diff --git a/mercurial/pathutil.py b/mercurial/pathutil.py
--- a/mercurial/pathutil.py
+++ b/mercurial/pathutil.py
@@ -6,10 +6,11 @@ import posixpath
import stat
from .i18n import _
from . import (
encoding,
+ error,
util,
)
def _lowerclean(s):
return encoding.hfsignoreclean(s.lower())
@@ -45,30 +46,30 @@ class pathauditor(object):
normpath = self.normcase(path)
if normpath in self.audited:
return
# AIX ignores "/" at end of path, others raise EISDIR.
if util.endswithsep(path):
- raise util.Abort(_("path ends in directory separator: %s") % path)
+ raise error.Abort(_("path ends in directory separator: %s") % path)
parts = util.splitpath(path)
if (os.path.splitdrive(path)[0]
or _lowerclean(parts[0]) in ('.hg', '.hg.', '')
or os.pardir in parts):
- raise util.Abort(_("path contains illegal component: %s") % path)
+ raise error.Abort(_("path contains illegal component: %s") % path)
# Windows shortname aliases
for p in parts:
if "~" in p:
first, last = p.split("~", 1)
if last.isdigit() and first.upper() in ["HG", "HG8B6C"]:
- raise util.Abort(_("path contains illegal component: %s")
+ raise error.Abort(_("path contains illegal component: %s")
% path)
if '.hg' in _lowerclean(path):
lparts = [_lowerclean(p.lower()) for p in parts]
for p in '.hg', '.hg.':
if p in lparts[1:]:
pos = lparts.index(p)
base = os.path.join(*parts[:pos])
- raise util.Abort(_("path '%s' is inside nested repo %r")
+ raise error.Abort(_("path '%s' is inside nested repo %r")
% (path, base))
normparts = util.splitpath(normpath)
assert len(parts) == len(normparts)
@@ -88,17 +89,17 @@ class pathauditor(object):
# They must be ignored for patterns can be checked too.
if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
raise
else:
if stat.S_ISLNK(st.st_mode):
- raise util.Abort(
+ raise error.Abort(
_('path %r traverses symbolic link %r')
% (path, prefix))
elif (stat.S_ISDIR(st.st_mode) and
os.path.isdir(os.path.join(curpath, '.hg'))):
if not self.callback or not self.callback(curpath):
- raise util.Abort(_("path '%s' is inside nested "
+ raise error.Abort(_("path '%s' is inside nested "
"repo %r")
% (path, prefix))
prefixes.append(normprefix)
parts.pop()
normparts.pop()
@@ -110,11 +111,11 @@ class pathauditor(object):
def check(self, path):
try:
self(path)
return True
- except (OSError, util.Abort):
+ except (OSError, error.Abort):
return False
def canonpath(root, cwd, myname, auditor=None):
'''return the canonical path of myname, given cwd and root'''
if util.endswithsep(root):
@@ -165,14 +166,14 @@ def canonpath(root, cwd, myname, auditor
try:
if cwd != root:
canonpath(root, root, myname, auditor)
hint = (_("consider using '--cwd %s'")
% os.path.relpath(root, cwd))
- except util.Abort:
+ except error.Abort:
pass
- raise util.Abort(_("%s not under root '%s'") % (myname, root),
+ raise error.Abort(_("%s not under root '%s'") % (myname, root),
hint=hint)
def normasprefix(path):
'''normalize the specified path as path prefix
diff --git a/mercurial/phases.py b/mercurial/phases.py
--- a/mercurial/phases.py
+++ b/mercurial/phases.py
@@ -113,11 +113,10 @@ from .node import (
nullrev,
short,
)
from . import (
error,
- util,
)
allphases = public, draft, secret = range(3)
trackedphases = allphases[1:]
phasenames = ['public', 'draft', 'secret']
@@ -304,11 +303,11 @@ class phasecache(object):
currentroots = self.phaseroots[targetphase]
newroots = [n for n in nodes
if self.phase(repo, repo[n].rev()) < targetphase]
if newroots:
if nullid in newroots:
- raise util.Abort(_('cannot change null revision phase'))
+ raise error.Abort(_('cannot change null revision phase'))
currentroots = currentroots.copy()
currentroots.update(newroots)
ctxs = repo.set('roots(%ln::)', currentroots)
currentroots.intersection_update(ctx.node() for ctx in ctxs)
self._updateroots(targetphase, currentroots, tr)
diff --git a/mercurial/repair.py b/mercurial/repair.py
--- a/mercurial/repair.py
+++ b/mercurial/repair.py
@@ -13,10 +13,11 @@ import errno
from .i18n import _
from .node import short
from . import (
bundle2,
changegroup,
+ error,
exchange,
util,
)
def _bundle(repo, bases, heads, node, suffix, compress=True):
@@ -154,11 +155,11 @@ def strip(ui, repo, nodelist, backup=Tru
curtr = repo.currenttransaction()
if curtr is not None:
del curtr # avoid carrying reference to transaction for nothing
msg = _('programming error: cannot strip from inside a transaction')
- raise util.Abort(msg, hint=_('contact your extension maintainer'))
+ raise error.Abort(msg, hint=_('contact your extension maintainer'))
tr = repo.transaction("strip")
offset = len(tr.entries)
try:
diff --git a/mercurial/revset.py b/mercurial/revset.py
--- a/mercurial/revset.py
+++ b/mercurial/revset.py
@@ -478,46 +478,46 @@ def _mergedefaultdest(repo, subset, x):
if curhead == bmheads[0]:
node = bmheads[1]
else:
node = bmheads[0]
elif len(bmheads) > 2:
- raise util.Abort(_("multiple matching bookmarks to merge - "
+ raise error.Abort(_("multiple matching bookmarks to merge - "
"please merge with an explicit rev or bookmark"),
hint=_("run 'hg heads' to see all heads"))
elif len(bmheads) <= 1:
- raise util.Abort(_("no matching bookmark to merge - "
+ raise error.Abort(_("no matching bookmark to merge - "
"please merge with an explicit rev or bookmark"),
hint=_("run 'hg heads' to see all heads"))
else:
branch = repo[None].branch()
bheads = repo.branchheads(branch)
nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
if len(nbhs) > 2:
- raise util.Abort(_("branch '%s' has %d heads - "
+ raise error.Abort(_("branch '%s' has %d heads - "
"please merge with an explicit rev")
% (branch, len(bheads)),
hint=_("run 'hg heads .' to see heads"))
parent = repo.dirstate.p1()
if len(nbhs) <= 1:
if len(bheads) > 1:
- raise util.Abort(_("heads are bookmarked - "
+ raise error.Abort(_("heads are bookmarked - "
"please merge with an explicit rev"),
hint=_("run 'hg heads' to see all heads"))
if len(repo.heads()) > 1:
- raise util.Abort(_("branch '%s' has one head - "
+ raise error.Abort(_("branch '%s' has one head - "
"please merge with an explicit rev")
% branch,
hint=_("run 'hg heads' to see all heads"))
msg, hint = _('nothing to merge'), None
if parent != repo.lookup(branch):
hint = _("use 'hg update' instead")
- raise util.Abort(msg, hint=hint)
+ raise error.Abort(msg, hint=hint)
if parent not in bheads:
- raise util.Abort(_('working directory not at a head revision'),
+ raise error.Abort(_('working directory not at a head revision'),
hint=_("use 'hg update' or merge with an "
"explicit revision"))
if parent == nbhs[0]:
node = nbhs[-1]
else:
@@ -542,11 +542,11 @@ def _updatedefaultdest(repo, subset, x):
node = repo.branchtip(wc.branch())
except error.RepoLookupError:
if wc.branch() == 'default': # no default branch!
node = repo.lookup('tip') # update to tip
else:
- raise util.Abort(_("branch %s not found") % wc.branch())
+ raise error.Abort(_("branch %s not found") % wc.branch())
if p1.obsolete() and not p1.children():
# allow updating to successors
successors = obsmod.successorssets(repo, p1.node())
@@ -768,11 +768,11 @@ def bundle(repo, subset, x):
Bundle must be specified by the -R option."""
try:
bundlerevs = repo.changelog.bundlerevs
except AttributeError:
- raise util.Abort(_("no bundle provided - specify with -R"))
+ raise error.Abort(_("no bundle provided - specify with -R"))
return subset & bundlerevs
def checkstatus(repo, subset, pat, field):
hasset = matchmod.patkind(pat) == 'set'
@@ -2717,11 +2717,11 @@ def _expandaliases(aliases, tree, expand
# Do not expand raw strings
return tree
alias = _getalias(aliases, tree)
if alias is not None:
if alias.error:
- raise util.Abort(alias.error)
+ raise error.Abort(alias.error)
if alias in expanding:
raise error.ParseError(_('infinite expansion of revset alias "%s" '
'detected') % alias.name)
expanding.append(alias)
if alias.name not in cache:
@@ -2916,11 +2916,11 @@ def formatspec(expr, *args):
pos += 1
d = expr[pos]
ret += listexp(list(args[arg]), d)
arg += 1
else:
- raise util.Abort('unexpected revspec format character %s' % d)
+ raise error.Abort('unexpected revspec format character %s' % d)
else:
ret += c
pos += 1
return ret
diff --git a/mercurial/scmutil.py b/mercurial/scmutil.py
--- a/mercurial/scmutil.py
+++ b/mercurial/scmutil.py
@@ -121,35 +121,35 @@ def nochangesfound(ui, repo, excluded=No
def checknewlabel(repo, lbl, kind):
# Do not use the "kind" parameter in ui output.
# It makes strings difficult to translate.
if lbl in ['tip', '.', 'null']:
- raise util.Abort(_("the name '%s' is reserved") % lbl)
+ raise error.Abort(_("the name '%s' is reserved") % lbl)
for c in (':', '\0', '\n', '\r'):
if c in lbl:
- raise util.Abort(_("%r cannot be used in a name") % c)
+ raise error.Abort(_("%r cannot be used in a name") % c)
try:
int(lbl)
- raise util.Abort(_("cannot use an integer as a name"))
+ raise error.Abort(_("cannot use an integer as a name"))
except ValueError:
pass
def checkfilename(f):
'''Check that the filename f is an acceptable filename for a tracked file'''
if '\r' in f or '\n' in f:
- raise util.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
+ raise error.Abort(_("'\\n' and '\\r' disallowed in filenames: %r") % f)
def checkportable(ui, f):
'''Check if filename f is portable and warn or abort depending on config'''
checkfilename(f)
abort, warn = checkportabilityalert(ui)
if abort or warn:
msg = util.checkwinfilename(f)
if msg:
msg = "%s: %r" % (msg, f)
if abort:
- raise util.Abort(msg)
+ raise error.Abort(msg)
ui.warn(_("warning: %s\n") % msg)
def checkportabilityalert(ui):
'''check if the user's config requests nothing, a warning, or abort for
non-portable filenames'''
@@ -180,11 +180,11 @@ class casecollisionauditor(object):
return
fl = encoding.lower(f)
if fl in self._loweredfiles and f not in self._dirstate:
msg = _('possible case-folding collision for %s') % f
if self._abort:
- raise util.Abort(msg)
+ raise error.Abort(msg)
self._ui.warn(_("warning: %s\n") % msg)
self._loweredfiles.add(fl)
self._newfiles.add(f)
def filteredhash(repo, maxrev):
@@ -473,11 +473,11 @@ class vfs(abstractvfs):
for "write" mode access.
'''
if self._audit:
r = util.checkosfilename(path)
if r:
- raise util.Abort("%s: %r" % (r, path))
+ raise error.Abort("%s: %r" % (r, path))
self.audit(path)
f = self.join(path)
if not text and "b" not in mode:
mode += "b" # for that other OS
@@ -581,11 +581,11 @@ class readonlyvfs(abstractvfs, auditvfs)
def __init__(self, vfs):
auditvfs.__init__(self, vfs)
def __call__(self, path, mode='r', *args, **kw):
if mode not in ('r', 'rb'):
- raise util.Abort('this vfs is read only')
+ raise error.Abort('this vfs is read only')
return self.vfs(path, mode, *args, **kw)
def join(self, path, *insidef):
return self.vfs.join(path, *insidef)
@@ -687,11 +687,11 @@ def revsingle(repo, revspec, default='.'
if not revspec and revspec != 0:
return repo[default]
l = revrange(repo, [revspec])
if not l:
- raise util.Abort(_('empty revision set'))
+ raise error.Abort(_('empty revision set'))
return repo[l.last()]
def _pairspec(revspec):
tree = revset.parse(revspec)
tree = revset.optimize(tree, True)[1] # fix up "x^:y" -> "(x^):y"
@@ -714,11 +714,11 @@ def revpair(repo, revs):
else:
first = l.first()
second = l.last()
if first is None:
- raise util.Abort(_('empty revision range'))
+ raise error.Abort(_('empty revision range'))
# 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]):
return repo.lookup(first), None
diff --git a/mercurial/setdiscovery.py b/mercurial/setdiscovery.py
--- a/mercurial/setdiscovery.py
+++ b/mercurial/setdiscovery.py
@@ -50,11 +50,11 @@ from .node import (
nullid,
nullrev,
)
from . import (
dagutil,
- util,
+ error,
)
def _updatesample(dag, nodes, sample, quicksamplesize=0):
"""update an existing sample to match the expected size
@@ -239,11 +239,11 @@ def findcommonheads(ui, local, remote,
ui.progress(_('searching'), None)
ui.debug("%d total queries\n" % roundtrips)
if not result and srvheadhashes != [nullid]:
if abortwhenunrelated:
- raise util.Abort(_("repository is unrelated"))
+ raise error.Abort(_("repository is unrelated"))
else:
ui.warn(_("warning: repository is unrelated\n"))
return (set([nullid]), True, srvheadhashes,)
anyincoming = (srvheadhashes != [nullid])
diff --git a/mercurial/simplemerge.py b/mercurial/simplemerge.py
--- a/mercurial/simplemerge.py
+++ b/mercurial/simplemerge.py
@@ -21,10 +21,11 @@ from __future__ import absolute_import
import os
import sys
from .i18n import _
from . import (
+ error,
mdiff,
scmutil,
util,
)
@@ -359,11 +360,11 @@ def simplemerge(ui, local, base, other,
if util.binary(text):
msg = _("%s looks like a binary file.") % filename
if not opts.get('quiet'):
ui.warn(_('warning: %s\n') % msg)
if not opts.get('text'):
- raise util.Abort(msg)
+ raise error.Abort(msg)
return text
mode = opts.get('mode','merge')
if mode == 'union':
name_a = None
@@ -379,17 +380,17 @@ def simplemerge(ui, local, base, other,
if len(labels) > 1:
name_b = labels[1]
if len(labels) > 2:
name_base = labels[2]
if len(labels) > 3:
- raise util.Abort(_("can only specify three labels."))
+ raise error.Abort(_("can only specify three labels."))
try:
localtext = readfile(local)
basetext = readfile(base)
othertext = readfile(other)
- except util.Abort:
+ except error.Abort:
return 1
local = os.path.realpath(local)
if not opts.get('print'):
opener = scmutil.opener(os.path.dirname(local))
diff --git a/mercurial/sshpeer.py b/mercurial/sshpeer.py
--- a/mercurial/sshpeer.py
+++ b/mercurial/sshpeer.py
@@ -275,11 +275,11 @@ class sshpeer(wireproto.wirepeer):
def _calltwowaystream(self, cmd, fp, **args):
r = self._call(cmd, **args)
if r:
# XXX needs to be made better
- raise util.Abort('unexpected remote reply: %s' % r)
+ raise error.Abort('unexpected remote reply: %s' % r)
while True:
d = fp.read(4096)
if not d:
break
self._send(d)
diff --git a/mercurial/sshserver.py b/mercurial/sshserver.py
--- a/mercurial/sshserver.py
+++ b/mercurial/sshserver.py
@@ -10,10 +10,11 @@ from __future__ import absolute_import
import os
import sys
from . import (
+ error,
hook,
util,
wireproto,
)
@@ -37,11 +38,11 @@ class sshserver(wireproto.abstractserver
keys = args.split()
for n in xrange(len(keys)):
argline = self.fin.readline()[:-1]
arg, l = argline.split()
if arg not in keys:
- raise util.Abort("unexpected parameter %r" % arg)
+ raise error.Abort("unexpected parameter %r" % arg)
if arg == '*':
star = {}
for k in xrange(int(l)):
argline = self.fin.readline()[:-1]
arg, l = argline.split()
diff --git a/mercurial/sslutil.py b/mercurial/sslutil.py
--- a/mercurial/sslutil.py
+++ b/mercurial/sslutil.py
@@ -12,11 +12,11 @@ from __future__ import absolute_import
import os
import ssl
import sys
from .i18n import _
-from . import util
+from . import error, util
_canloaddefaultcerts = False
try:
ssl_context = ssl.SSLContext
_canloaddefaultcerts = util.safehasattr(ssl_context, 'load_default_certs')
@@ -48,11 +48,11 @@ try:
sslsocket = sslcontext.wrap_socket(sock, server_hostname=serverhostname)
# check if wrap_socket failed silently because socket had been
# closed
# - see http://bugs.python.org/issue13721
if not sslsocket.cipher():
- raise util.Abort(_('ssl connection failed'))
+ raise error.Abort(_('ssl connection failed'))
return sslsocket
except AttributeError:
def wrapsocket(sock, keyfile, certfile, ui, cert_reqs=ssl.CERT_NONE,
ca_certs=None, serverhostname=None):
sslsocket = ssl.wrap_socket(sock, keyfile, certfile,
@@ -60,11 +60,11 @@ except AttributeError:
ssl_version=ssl.PROTOCOL_TLSv1)
# check if wrap_socket failed silently because socket had been
# closed
# - see http://bugs.python.org/issue13721
if not sslsocket.cipher():
- raise util.Abort(_('ssl connection failed'))
+ raise error.Abort(_('ssl connection failed'))
return sslsocket
def _verifycert(cert, hostname):
'''Verify that cert (in socket.getpeercert() format) matches hostname.
CRLs is not handled.
@@ -138,11 +138,11 @@ def sslkwargs(ui, host):
if cacerts == '!':
pass
elif cacerts:
cacerts = util.expandpath(cacerts)
if not os.path.exists(cacerts):
- raise util.Abort(_('could not find web.cacerts: %s') % cacerts)
+ raise error.Abort(_('could not find web.cacerts: %s') % cacerts)
else:
cacerts = _defaultcacerts()
if cacerts and cacerts != '!':
ui.debug('using %s to enable OS X system CA\n' % cacerts)
ui.setconfig('web', 'cacerts', cacerts, 'defaultcacerts')
@@ -161,41 +161,41 @@ class validator(object):
host = self.host
cacerts = self.ui.config('web', 'cacerts')
hostfingerprint = self.ui.config('hostfingerprints', host)
if not sock.cipher(): # work around http://bugs.python.org/issue13721
- raise util.Abort(_('%s ssl connection error') % host)
+ raise error.Abort(_('%s ssl connection error') % host)
try:
peercert = sock.getpeercert(True)
peercert2 = sock.getpeercert()
except AttributeError:
- raise util.Abort(_('%s ssl connection error') % host)
+ raise error.Abort(_('%s ssl connection error') % host)
if not peercert:
- raise util.Abort(_('%s certificate error: '
+ raise error.Abort(_('%s certificate error: '
'no certificate received') % host)
peerfingerprint = util.sha1(peercert).hexdigest()
nicefingerprint = ":".join([peerfingerprint[x:x + 2]
for x in xrange(0, len(peerfingerprint), 2)])
if hostfingerprint:
if peerfingerprint.lower() != \
hostfingerprint.replace(':', '').lower():
- raise util.Abort(_('certificate for %s has unexpected '
+ raise error.Abort(_('certificate for %s has unexpected '
'fingerprint %s') % (host, nicefingerprint),
hint=_('check hostfingerprint configuration'))
self.ui.debug('%s certificate matched fingerprint %s\n' %
(host, nicefingerprint))
elif cacerts != '!':
msg = _verifycert(peercert2, host)
if msg:
- raise util.Abort(_('%s certificate error: %s') % (host, msg),
+ raise error.Abort(_('%s certificate error: %s') % (host, msg),
hint=_('configure hostfingerprint %s or use '
'--insecure to connect insecurely') %
nicefingerprint)
self.ui.debug('%s certificate successfully verified\n' % host)
elif strict:
- raise util.Abort(_('%s certificate with fingerprint %s not '
+ raise error.Abort(_('%s certificate with fingerprint %s not '
'verified') % (host, nicefingerprint),
hint=_('check hostfingerprints or web.cacerts '
'config setting'))
else:
self.ui.warn(_('warning: %s certificate with fingerprint %s not '
diff --git a/mercurial/statichttprepo.py b/mercurial/statichttprepo.py
--- a/mercurial/statichttprepo.py
+++ b/mercurial/statichttprepo.py
@@ -169,11 +169,11 @@ class statichttprepository(localrepo.loc
def peer(self):
return statichttppeer(self)
def lock(self, wait=True):
- raise util.Abort(_('cannot lock static-http repository'))
+ raise error.Abort(_('cannot lock static-http repository'))
def instance(ui, path, create):
if create:
- raise util.Abort(_('cannot create new static-http repository'))
+ raise error.Abort(_('cannot create new static-http repository'))
return statichttprepository(ui, path[7:])
diff --git a/mercurial/store.py b/mercurial/store.py
--- a/mercurial/store.py
+++ b/mercurial/store.py
@@ -4,11 +4,11 @@
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from i18n import _
-import scmutil, util, parsers
+import scmutil, util, parsers, error
import os, stat, errno
_sha = util.sha1
# This avoids a collision between a file named foo and a dir named
@@ -403,11 +403,11 @@ class fncache(object):
if '' in self.entries:
fp.seek(0)
for n, line in enumerate(fp):
if not line.rstrip('\n'):
t = _('invalid entry in fncache, line %s') % (n + 1)
- raise util.Abort(t)
+ raise error.Abort(t)
fp.close()
def write(self, tr):
if self._dirty:
tr.addbackup('fncache')
diff --git a/mercurial/streamclone.py b/mercurial/streamclone.py
--- a/mercurial/streamclone.py
+++ b/mercurial/streamclone.py
@@ -121,15 +121,15 @@ def maybeperformlegacystreamclone(pullop
resp = int(l)
except ValueError:
raise error.ResponseError(
_('unexpected response from remote server:'), l)
if resp == 1:
- raise util.Abort(_('operation forbidden by server'))
+ raise error.Abort(_('operation forbidden by server'))
elif resp == 2:
- raise util.Abort(_('locking the remote repository failed'))
+ raise error.Abort(_('locking the remote repository failed'))
elif resp != 0:
- raise util.Abort(_('the server sent an unknown error code'))
+ raise error.Abort(_('the server sent an unknown error code'))
l = fp.readline()
try:
filecount, bytecount = map(int, l.split(' ', 1))
except (ValueError, TypeError):
diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py
--- a/mercurial/subrepo.py
+++ b/mercurial/subrepo.py
@@ -93,11 +93,11 @@ def state(ctx, ui):
ui.warn(_("warning: subrepo spec file \'%s\' not found\n") %
repo.pathto(f))
return
p.parse(f, data, sections, remap, read)
else:
- raise util.Abort(_("subrepo spec file \'%s\' not found") %
+ raise error.Abort(_("subrepo spec file \'%s\' not found") %
repo.pathto(f))
if '.hgsub' in ctx:
read('.hgsub')
for path, src in ui.configitems('subpaths'):
@@ -111,11 +111,11 @@ def state(ctx, ui):
if not l:
continue
try:
revision, path = l.split(" ", 1)
except ValueError:
- raise util.Abort(_("invalid subrepository revision "
+ raise error.Abort(_("invalid subrepository revision "
"specifier in \'%s\' line %d")
% (repo.pathto('.hgsubstate'), (i + 1)))
rev[path] = revision
except IOError as err:
if err.errno != errno.ENOENT:
@@ -131,20 +131,20 @@ def state(ctx, ui):
# extra escapes are needed because re.sub string decodes.
repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
try:
src = re.sub(pattern, repl, src, 1)
except re.error as e:
- raise util.Abort(_("bad subrepository pattern in %s: %s")
+ raise error.Abort(_("bad subrepository pattern in %s: %s")
% (p.source('subpaths', pattern), e))
return src
state = {}
for path, src in p[''].items():
kind = 'hg'
if src.startswith('['):
if ']' not in src:
- raise util.Abort(_('missing ] in subrepo source'))
+ raise error.Abort(_('missing ] in subrepo source'))
kind, src = src.split(']', 1)
kind = kind[1:]
src = src.lstrip() # strip any extra whitespace after ']'
if not util.url(src).isabs():
@@ -322,11 +322,11 @@ def _abssource(repo, push=False, abort=T
return repo.ui.config('paths', 'default')
if repo.shared():
# chop off the .hg component to get the default path form
return os.path.dirname(repo.sharedpath)
if abort:
- raise util.Abort(_("default path for subrepository not found"))
+ raise error.Abort(_("default path for subrepository not found"))
def _sanitize(ui, vfs, ignore):
for dirname, dirs, names in vfs.walk():
for i, d in enumerate(dirs):
if d.lower() == ignore:
@@ -351,11 +351,11 @@ def subrepo(ctx, path, allowwdir=False):
hg = h
pathutil.pathauditor(ctx.repo().root)(path)
state = ctx.substate[path]
if state[2] not in types:
- raise util.Abort(_('unknown subrepo type %s') % state[2])
+ raise error.Abort(_('unknown subrepo type %s') % state[2])
if allowwdir:
state = (state[0], ctx.subrev(path), state[2])
return types[state[2]](ctx, path, state[:2])
def nullsubrepo(ctx, path, pctx):
@@ -369,11 +369,11 @@ def nullsubrepo(ctx, path, pctx):
hg = h
pathutil.pathauditor(ctx.repo().root)(path)
state = ctx.substate[path]
if state[2] not in types:
- raise util.Abort(_('unknown subrepo type %s') % state[2])
+ raise error.Abort(_('unknown subrepo type %s') % state[2])
subrev = ''
if state[2] == 'hg':
subrev = "0" * 40
return types[state[2]](pctx, path, (state[0], subrev))
@@ -382,11 +382,11 @@ def newcommitphase(ui, ctx):
substate = getattr(ctx, "substate", None)
if not substate:
return commitphase
check = ui.config('phases', 'checksubrepos', 'follow')
if check not in ('ignore', 'follow', 'abort'):
- raise util.Abort(_('invalid phases.checksubrepos configuration: %s')
+ raise error.Abort(_('invalid phases.checksubrepos configuration: %s')
% (check))
if check == 'ignore':
return commitphase
maxphase = phases.public
maxsub = None
@@ -396,11 +396,11 @@ def newcommitphase(ui, ctx):
if maxphase < subphase:
maxphase = subphase
maxsub = s
if commitphase < maxphase:
if check == 'abort':
- raise util.Abort(_("can't commit in %s phase"
+ raise error.Abort(_("can't commit in %s phase"
" conflicting %s from subrepository %s") %
(phases.phasenames[commitphase],
phases.phasenames[maxphase], maxsub))
ui.warn(_("warning: changes are committed in"
" %s phase from subrepository %s\n") %
@@ -454,11 +454,11 @@ class abstractsubrepo(object):
def bailifchanged(self, ignoreupdate=False):
"""raise Abort if subrepository is ``dirty()``
"""
dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate)
if dirtyreason:
- raise util.Abort(dirtyreason)
+ raise error.Abort(dirtyreason)
def basestate(self):
"""current working directory base state, disregarding .hgsubstate
state and working directory modifications"""
raise NotImplementedError
@@ -1071,11 +1071,11 @@ class svnsubrepo(abstractsubrepo):
def __init__(self, ctx, path, state):
super(svnsubrepo, self).__init__(ctx, path)
self._state = state
self._exe = util.findexe('svn')
if not self._exe:
- raise util.Abort(_("'svn' executable not found for subrepo '%s'")
+ raise error.Abort(_("'svn' executable not found for subrepo '%s'")
% self._path)
def _svncommand(self, commands, filename='', failok=False):
cmd = [self._exe]
extrakw = {}
@@ -1106,21 +1106,22 @@ class svnsubrepo(abstractsubrepo):
universal_newlines=True, env=env, **extrakw)
stdout, stderr = p.communicate()
stderr = stderr.strip()
if not failok:
if p.returncode:
- raise util.Abort(stderr or 'exited with code %d' % p.returncode)
+ raise error.Abort(stderr or 'exited with code %d'
+ % p.returncode)
if stderr:
self.ui.warn(stderr + '\n')
return stdout, stderr
@propertycache
def _svnversion(self):
output, err = self._svncommand(['--version', '--quiet'], filename=None)
m = re.search(r'^(\d+)\.(\d+)', output)
if not m:
- raise util.Abort(_('cannot retrieve svn tool version'))
+ raise error.Abort(_('cannot retrieve svn tool version'))
return (int(m.group(1)), int(m.group(2)))
def _wcrevs(self):
# Get the working directory revision as well as the last
# commit revision so we can compare the subrepo state with
@@ -1194,26 +1195,26 @@ class svnsubrepo(abstractsubrepo):
changed, extchanged, missing = self._wcchanged()
if not changed:
return self.basestate()
if extchanged:
# Do not try to commit externals
- raise util.Abort(_('cannot commit svn externals'))
+ raise error.Abort(_('cannot commit svn externals'))
if missing:
# svn can commit with missing entries but aborting like hg
# seems a better approach.
- raise util.Abort(_('cannot commit missing svn entries'))
+ raise error.Abort(_('cannot commit missing svn entries'))
commitinfo, err = self._svncommand(['commit', '-m', text])
self.ui.status(commitinfo)
newrev = re.search('Committed revision ([0-9]+).', commitinfo)
if not newrev:
if not commitinfo.strip():
# Sometimes, our definition of "changed" differs from
# svn one. For instance, svn ignores missing files
# when committing. If there are only missing files, no
# commit is made, no output and no error code.
- raise util.Abort(_('failed to commit svn changes'))
- raise util.Abort(commitinfo.splitlines()[-1])
+ raise error.Abort(_('failed to commit svn changes'))
+ raise error.Abort(commitinfo.splitlines()[-1])
newrev = newrev.groups()[0]
self.ui.status(self._svncommand(['update', '-r', newrev])[0])
return newrev
@annotatesubrepoerror
@@ -1248,11 +1249,11 @@ class svnsubrepo(abstractsubrepo):
and (self._wcchanged()[:2] == (False, False))):
# obstructed but clean working copy, so just blow it away.
self.remove()
self.get(state, overwrite=False)
return
- raise util.Abort((status or err).splitlines()[-1])
+ raise error.Abort((status or err).splitlines()[-1])
self.ui.status(status)
@annotatesubrepoerror
def merge(self, state):
old = self._state[1]
@@ -1305,11 +1306,11 @@ class gitsubrepo(abstractsubrepo):
out, err = self._gitnodir(['--version'])
versionstatus = self._checkversion(out)
if versionstatus == 'unknown':
self.ui.warn(_('cannot retrieve git version\n'))
elif versionstatus == 'abort':
- raise util.Abort(_('git subrepo requires at least 1.6.0 or later'))
+ raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
elif versionstatus == 'warning':
self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
@staticmethod
def _gitversion(out):
@@ -1392,11 +1393,11 @@ class gitsubrepo(abstractsubrepo):
# there are certain error codes that are ok
command = commands[0]
if command in ('cat-file', 'symbolic-ref'):
return retdata, p.returncode
# for all others, abort
- raise util.Abort('git %s error %d in %s' %
+ raise error.Abort('git %s error %d in %s' %
(command, p.returncode, self._relpath))
return retdata, p.returncode
def _gitmissing(self):
@@ -1489,11 +1490,11 @@ class gitsubrepo(abstractsubrepo):
self.ui.status(_('pulling subrepo %s from %s\n') %
(self._relpath, self._gitremote('origin')))
# try only origin: the originally cloned repo
self._gitcommand(['fetch'])
if not self._githavelocally(revision):
- raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
+ raise error.Abort(_("revision %s does not exist in subrepo %s\n") %
(revision, self._relpath))
@annotatesubrepoerror
def dirty(self, ignoreupdate=False):
if self._gitmissing():
@@ -1598,11 +1599,11 @@ class gitsubrepo(abstractsubrepo):
rawcheckout()
@annotatesubrepoerror
def commit(self, text, user, date):
if self._gitmissing():
- raise util.Abort(_("subrepo %s is missing") % self._relpath)
+ raise error.Abort(_("subrepo %s is missing") % self._relpath)
cmd = ['commit', '-a', '-m', text]
env = os.environ.copy()
if user:
cmd += ['--author', user]
if date:
@@ -1644,11 +1645,11 @@ class gitsubrepo(abstractsubrepo):
force = opts.get('force')
if not self._state[1]:
return True
if self._gitmissing():
- raise util.Abort(_("subrepo %s is missing") % self._relpath)
+ raise error.Abort(_("subrepo %s is missing") % self._relpath)
# if a branch in origin contains the revision, nothing to do
branch2rev, rev2branch = self._gitbranchmap()
if self._state[1] in rev2branch:
for b in rev2branch[self._state[1]]:
if b.startswith('refs/remotes/origin/'):
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -270,11 +270,11 @@ def runfilter(context, mapping, data):
except (ValueError, AttributeError, TypeError):
if isinstance(arg[1], tuple):
dt = arg[1][1]
else:
dt = arg[1]
- raise util.Abort(_("template filter '%s' is not compatible with "
+ raise error.Abort(_("template filter '%s' is not compatible with "
"keyword '%s'") % (filt.func_name, dt))
def buildmap(exp, context):
func, data = compileexp(exp[1], context, methods)
ctmpl = gettemplate(exp[2], context)
@@ -840,11 +840,11 @@ def stylelist():
split = file.split(".")
if split[0] == "map-cmdline":
stylelist.append(split[1])
return ", ".join(sorted(stylelist))
-class TemplateNotFound(util.Abort):
+class TemplateNotFound(error.Abort):
pass
class templater(object):
def __init__(self, mapfile, filters=None, defaults=None, cache=None,
@@ -873,11 +873,11 @@ class templater(object):
self.ecache = {}
if not mapfile:
return
if not os.path.exists(mapfile):
- raise util.Abort(_("style '%s' not found") % mapfile,
+ raise error.Abort(_("style '%s' not found") % mapfile,
hint=_("available styles: %s") % stylelist())
conf = config.config(includepaths=templatepaths())
conf.read(mapfile)
diff --git a/mercurial/transaction.py b/mercurial/transaction.py
--- a/mercurial/transaction.py
+++ b/mercurial/transaction.py
@@ -69,11 +69,11 @@ def _playback(journal, report, opener, v
try:
vfs.unlink(target)
except (IOError, OSError) as inst:
if inst.errno != errno.ENOENT:
raise
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
if not c:
raise
opener.unlink(journal)
backuppath = "%s.backupfiles" % journal
@@ -81,11 +81,11 @@ def _playback(journal, report, opener, v
opener.unlink(backuppath)
try:
for f in backupfiles:
if opener.exists(f):
opener.unlink(f)
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
# only pure backup file remains, it is sage to ignore any error
pass
class transaction(object):
def __init__(self, report, opener, vfsmap, journalname, undoname=None,
@@ -409,11 +409,11 @@ class transaction(object):
continue
vfs = self._vfsmap[l]
if not f and b and vfs.exists(b):
try:
vfs.unlink(b)
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
if not c:
raise
# Abort may be raise by read only opener
self.report("couldn't remote %s: %s\n"
% (vfs.join(b), inst))
@@ -432,11 +432,11 @@ class transaction(object):
continue
vfs = self._vfsmap[l]
if b and vfs.exists(b):
try:
vfs.unlink(b)
- except (IOError, OSError, util.Abort) as inst:
+ except (IOError, OSError, error.Abort) as inst:
if not c:
raise
# Abort may be raise by read only opener
self.report("couldn't remote %s: %s\n"
% (vfs.join(b), inst))
diff --git a/mercurial/treediscovery.py b/mercurial/treediscovery.py
--- a/mercurial/treediscovery.py
+++ b/mercurial/treediscovery.py
@@ -14,11 +14,10 @@ from .node import (
nullid,
short,
)
from . import (
error,
- util,
)
def findcommonincoming(repo, remote, heads=None, force=False):
"""Return a tuple (common, fetch, heads) used to identify the common
subset of nodes between repo and remote.
@@ -147,11 +146,11 @@ def findcommonincoming(repo, remote, hea
base = list(base)
if base == [nullid]:
if force:
repo.ui.warn(_("warning: repository is unrelated\n"))
else:
- raise util.Abort(_("repository is unrelated"))
+ raise error.Abort(_("repository is unrelated"))
repo.ui.debug("found new changesets starting at " +
" ".join([short(f) for f in fetch]) + "\n")
repo.ui.progress(_('searching'), None)
diff --git a/mercurial/ui.py b/mercurial/ui.py
--- a/mercurial/ui.py
+++ b/mercurial/ui.py
@@ -533,15 +533,16 @@ class ui(object):
user = '%s@%s' % (util.getuser(), socket.getfqdn())
self.warn(_("no username found, using '%s' instead\n") % user)
except KeyError:
pass
if not user:
- raise util.Abort(_('no username supplied'),
+ raise error.Abort(_('no username supplied'),
hint=_('use "hg config --edit" '
'to set your username'))
if "\n" in user:
- raise util.Abort(_("username %s contains a newline\n") % repr(user))
+ raise error.Abort(_("username %s contains a newline\n")
+ % repr(user))
return user
def shortuser(self, user):
"""Return a short representation of a user name or email address."""
if not self.verbose:
@@ -753,11 +754,11 @@ class ui(object):
r = default
if self.configbool('ui', 'promptecho'):
self.write(r, "\n")
return r
except EOFError:
- raise util.Abort(_('response expected'))
+ raise error.Abort(_('response expected'))
@staticmethod
def extractchoices(prompt):
"""Extract prompt message and list of choices from specified prompt.
@@ -800,11 +801,11 @@ class ui(object):
if self.configbool('ui', 'nontty'):
return self.fin.readline().rstrip('\n')
else:
return getpass.getpass('')
except EOFError:
- raise util.Abort(_('response expected'))
+ raise error.Abort(_('response expected'))
def status(self, *msg, **opts):
'''write status message to output (if ui.quiet is False)
This adds an output label of "ui.status".
'''
@@ -856,11 +857,11 @@ class ui(object):
editor = self.geteditor()
self.system("%s \"%s\"" % (editor, name),
environ=environ,
- onerr=util.Abort, errprefix=_("edit failed"))
+ onerr=error.Abort, errprefix=_("edit failed"))
f = open(name)
t = f.read()
f.close()
finally:
diff --git a/mercurial/unionrepo.py b/mercurial/unionrepo.py
--- a/mercurial/unionrepo.py
+++ b/mercurial/unionrepo.py
@@ -19,10 +19,11 @@ from .i18n import _
from .node import nullid
from . import (
changelog,
cmdutil,
+ error,
filelog,
localrepo,
manifest,
mdiff,
pathutil,
@@ -229,11 +230,11 @@ class unionrepository(localrepo.localrep
def getcwd(self):
return os.getcwd() # always outside the repo
def instance(ui, path, create):
if create:
- raise util.Abort(_('cannot create new union repository'))
+ raise error.Abort(_('cannot create new union repository'))
parentpath = ui.config("bundle", "mainreporoot", "")
if not parentpath:
# try to find the correct path to the working directory repo
parentpath = cmdutil.findrepo(os.getcwd())
if parentpath is None:
diff --git a/mercurial/url.py b/mercurial/url.py
--- a/mercurial/url.py
+++ b/mercurial/url.py
@@ -17,10 +17,11 @@ import socket
import urllib
import urllib2
from .i18n import _
from . import (
+ error,
httpconnection as httpconnectionmod,
keepalive,
sslutil,
util,
)
@@ -46,11 +47,11 @@ class passwordmgr(urllib2.HTTPPasswordMg
self.ui.debug("using auth.%s.* for authentication\n" % group)
if not user or not passwd:
u = util.url(authuri)
u.query = None
if not self.ui.interactive():
- raise util.Abort(_('http authorization required for %s') %
+ raise error.Abort(_('http authorization required for %s') %
util.hidepassword(str(u)))
self.ui.write(_("http authorization required for %s\n") %
util.hidepassword(str(u)))
self.ui.write(_("realm: %s\n") % realm)
diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1923,11 +1923,11 @@ def interpolate(prefix, mapping, s, fn=N
def getport(port):
"""Return the port for a given network service.
If port is an integer, it's returned as is. If it's a string, it's
looked up using socket.getservbyname(). If there's no matching
- service, util.Abort is raised.
+ service, error.Abort is raised.
"""
try:
return int(port)
except ValueError:
pass
diff --git a/mercurial/verify.py b/mercurial/verify.py
--- a/mercurial/verify.py
+++ b/mercurial/verify.py
@@ -48,11 +48,11 @@ def _verify(repo):
cl = repo.changelog
mf = repo.manifest
lrugetctx = util.lrucachefunc(repo.changectx)
if not repo.url().startswith('file:'):
- raise util.Abort(_("cannot verify bundle or remote repos"))
+ raise error.Abort(_("cannot verify bundle or remote repos"))
def err(linkrev, msg, filename=None):
if linkrev is not None:
badrevs.add(linkrev)
else:
diff --git a/mercurial/wireproto.py b/mercurial/wireproto.py
--- a/mercurial/wireproto.py
+++ b/mercurial/wireproto.py
@@ -688,11 +688,11 @@ def pushkey(repo, proto, namespace, key,
proto.redirect()
try:
r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
encoding.tolocal(old), new) or False
- except util.Abort:
+ except error.Abort:
r = False
output = proto.restore()
return '%s\n%s' % (int(r), output)
@@ -750,16 +750,16 @@ def unbundle(repo, proto, heads):
finally:
fp.close()
os.unlink(tempname)
- except (error.BundleValueError, util.Abort, error.PushRaced) as exc:
+ except (error.BundleValueError, error.Abort, error.PushRaced) as exc:
# handle non-bundle2 case first
if not getattr(exc, 'duringunbundle2', False):
try:
raise
- except util.Abort:
+ except error.Abort:
# The old code we moved used sys.stderr directly.
# We did not change it to minimise code change.
# This need to be moved to something proper.
# Feel free to do it.
sys.stderr.write("abort: %s\n" % exc)
@@ -796,11 +796,11 @@ def unbundle(repo, proto, heads):
errpart = bundler.newpart('error:unsupportedcontent')
if exc.parttype is not None:
errpart.addparam('parttype', exc.parttype)
if exc.params:
errpart.addparam('params', '\0'.join(exc.params))
- except util.Abort as exc:
+ except error.Abort as exc:
manargs = [('message', str(exc))]
advargs = []
if exc.hint is not None:
advargs.append(('hint', exc.hint))
bundler.addpart(bundle2.bundlepart('error:abort',
diff --git a/mercurial/worker.py b/mercurial/worker.py
--- a/mercurial/worker.py
+++ b/mercurial/worker.py
@@ -13,11 +13,11 @@ import os
import signal
import sys
import threading
from .i18n import _
-from . import util
+from . import error
def countcpus():
'''try to count the number of CPUs on the system'''
try:
return multiprocessing.cpu_count()
@@ -30,11 +30,11 @@ def _numworkers(ui):
try:
n = int(s)
if n >= 1:
return n
except ValueError:
- raise util.Abort(_('number of cpus must be an integer'))
+ raise error.Abort(_('number of cpus must be an integer'))
return min(max(countcpus(), 4), 32)
if os.name == 'posix':
_startupcost = 0.01
else:
diff --git a/tests/autodiff.py b/tests/autodiff.py
--- a/tests/autodiff.py
+++ b/tests/autodiff.py
@@ -1,9 +1,9 @@
# Extension dedicated to test patch.diff() upgrade modes
#
#
-from mercurial import cmdutil, scmutil, patch, util
+from mercurial import cmdutil, scmutil, patch, error
cmdtable = {}
command = cmdutil.command(cmdtable)
@command('autodiff',
@@ -28,13 +28,13 @@ def autodiff(ui, repo, *pats, **opts):
return True
elif git == 'abort':
diffopts.git = False
diffopts.upgrade = True
def losedatafn(fn=None, **kwargs):
- raise util.Abort('losing data for %s' % fn)
+ raise error.Abort('losing data for %s' % fn)
else:
- raise util.Abort('--git must be yes, no or auto')
+ raise error.Abort('--git must be yes, no or auto')
node1, node2 = scmutil.revpair(repo, [])
m = scmutil.match(repo[node2], pats, opts)
it = patch.diff(repo, node1, node2, match=m, opts=diffopts,
losedatafn=losedatafn)
diff --git a/tests/test-abort-checkin.t b/tests/test-abort-checkin.t
--- a/tests/test-abort-checkin.t
+++ b/tests/test-abort-checkin.t
@@ -1,9 +1,9 @@
$ cat > abortcommit.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def hook(**args):
- > raise util.Abort("no commits allowed")
+ > raise error.Abort("no commits allowed")
> def reposetup(ui, repo):
> repo.ui.setconfig("hooks", "pretxncommit.nocommits", hook)
> EOF
$ abspath=`pwd`/abortcommit.py
diff --git a/tests/test-addremove-similar.t b/tests/test-addremove-similar.t
--- a/tests/test-addremove-similar.t
+++ b/tests/test-addremove-similar.t
@@ -67,11 +67,11 @@ should all fail
abort: similarity must be between 0 and 100
[255]
$ cd ..
-Issue1527: repeated addremove causes util.Abort
+Issue1527: repeated addremove causes Abort
$ hg init rep3; cd rep3
$ mkdir d
$ echo a > d/a
$ hg add d/a
diff --git a/tests/test-annotate.t b/tests/test-annotate.t
--- a/tests/test-annotate.t
+++ b/tests/test-annotate.t
@@ -297,11 +297,11 @@ to reproduce the situation with recent M
"hg debugsetparents" to merge without ancestor check by "hg merge",
and (2) the extension to allow filelog merging between the revision
and its ancestor by overriding "repo._filecommit".
$ cat > ../legacyrepo.py <<EOF
- > from mercurial import node, util
+ > from mercurial import node, error
> def reposetup(ui, repo):
> class legacyrepo(repo.__class__):
> def _filecommit(self, fctx, manifest1, manifest2,
> linkrev, tr, changelist):
> fname = fctx.path()
@@ -310,16 +310,16 @@ and its ancestor by overriding "repo._fi
> fparent1 = manifest1.get(fname, node.nullid)
> fparent2 = manifest2.get(fname, node.nullid)
> meta = {}
> copy = fctx.renamed()
> if copy and copy[0] != fname:
- > raise util.Abort('copying is not supported')
+ > raise error.Abort('copying is not supported')
> if fparent2 != node.nullid:
> changelist.append(fname)
> return flog.add(text, meta, tr, linkrev,
> fparent1, fparent2)
- > raise util.Abort('only merging is supported')
+ > raise error.Abort('only merging is supported')
> repo.__class__ = legacyrepo
> EOF
$ cat > baz <<EOF
> 1
diff --git a/tests/test-bundle2-exchange.t b/tests/test-bundle2-exchange.t
--- a/tests/test-bundle2-exchange.t
+++ b/tests/test-bundle2-exchange.t
@@ -450,11 +450,11 @@ Setting up
> """A small extension that makes push fails when using bundle2
>
> used to test error handling in bundle2
> """
>
- > from mercurial import util
+ > from mercurial import error
> from mercurial import bundle2
> from mercurial import exchange
> from mercurial import extensions
>
> def _pushbundle2failpart(pushop, bundler):
@@ -468,11 +468,11 @@ Setting up
> # 20 Bytes of crap
> bundler.newpart('check:heads', data='01234567890123456789')
>
> @bundle2.parthandler("test:abort")
> def handleabort(op, part):
- > raise util.Abort('Abandon ship!', hint="don't panic")
+ > raise error.Abort('Abandon ship!', hint="don't panic")
>
> def uisetup(ui):
> exchange.b2partsgenmapping['failpart'] = _pushbundle2failpart
> exchange.b2partsgenorder.insert(0, 'failpart')
>
diff --git a/tests/test-bundle2-format.t b/tests/test-bundle2-format.t
--- a/tests/test-bundle2-format.t
+++ b/tests/test-bundle2-format.t
@@ -88,11 +88,11 @@ Create an extension to test bundle2 API
> for p in opts['param']:
> p = p.split('=', 1)
> try:
> bundler.addparam(*p)
> except ValueError, exc:
- > raise util.Abort('%s' % exc)
+ > raise error.Abort('%s' % exc)
>
> if opts['compress']:
> bundler.setcompression(opts['compress'])
>
> if opts['reply']:
@@ -162,11 +162,11 @@ Create an extension to test bundle2 API
> return
> try:
> for chunk in bundler.getchunks():
> file.write(chunk)
> except RuntimeError, exc:
- > raise util.Abort(exc)
+ > raise error.Abort(exc)
>
> @command('unbundle2', [], '')
> def cmdunbundle2(ui, repo, replypath=None):
> """process a bundle2 stream from stdin on the current repo"""
> try:
@@ -176,13 +176,13 @@ Create an extension to test bundle2 API
> try:
> unbundler = bundle2.getunbundler(ui, sys.stdin)
> op = bundle2.processbundle(repo, unbundler, lambda: tr)
> tr.close()
> except error.BundleValueError, exc:
- > raise util.Abort('missing support for %s' % exc)
+ > raise error.Abort('missing support for %s' % exc)
> except error.PushRaced, exc:
- > raise util.Abort('push race: %s' % exc)
+ > raise error.Abort('push race: %s' % exc)
> finally:
> if tr is not None:
> tr.release()
> lock.release()
> remains = sys.stdin.read()
@@ -202,11 +202,11 @@ Create an extension to test bundle2 API
> """print statistic on the bundle2 container read from stdin"""
> unbundler = bundle2.getunbundler(ui, sys.stdin)
> try:
> params = unbundler.params
> except error.BundleValueError, exc:
- > raise util.Abort('unknown parameters: %s' % exc)
+ > raise error.Abort('unknown parameters: %s' % exc)
> ui.write('options count: %i\n' % len(params))
> for key in sorted(params):
> ui.write('- %s\n' % key)
> value = params[key]
> if value is not None:
diff --git a/tests/test-custom-filters.t b/tests/test-custom-filters.t
--- a/tests/test-custom-filters.t
+++ b/tests/test-custom-filters.t
@@ -8,15 +8,15 @@
> [decode]
> *.txt = insertprefix: Copyright 2046, The Masters
> EOF
$ cat > prefix.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def stripprefix(s, cmd, filename, **kwargs):
> header = '%s\n' % cmd
> if s[:len(header)] != header:
- > raise util.Abort('missing header "%s" in %s' % (cmd, filename))
+ > raise error.Abort('missing header "%s" in %s' % (cmd, filename))
> return s[len(header):]
> def insertprefix(s, cmd):
> return '%s\n%s' % (cmd, s)
> def reposetup(ui, repo):
> repo.adddatafilter('stripprefix:', stripprefix)
diff --git a/tests/test-dirstate.t b/tests/test-dirstate.t
--- a/tests/test-dirstate.t
+++ b/tests/test-dirstate.t
@@ -64,14 +64,14 @@ Test modulo storage/comparison of absurd
Verify that exceptions during a dirstate change leave the dirstate
coherent (issue4353)
$ cat > ../dirstateexception.py <<EOF
- > from mercurial import merge, extensions, util
+ > from mercurial import merge, extensions, error
>
> def wraprecordupdates(orig, repo, actions, branchmerge):
- > raise util.Abort("simulated error while recording dirstateupdates")
+ > raise error.Abort("simulated error while recording dirstateupdates")
>
> def reposetup(ui, repo):
> extensions.wrapfunction(merge, 'recordupdates', wraprecordupdates)
> EOF
diff --git a/tests/test-fncache.t b/tests/test-fncache.t
--- a/tests/test-fncache.t
+++ b/tests/test-fncache.t
@@ -200,16 +200,16 @@ Encoding of reserved / long paths in the
Aborting lock does not prevent fncache writes
$ cat > exceptionext.py <<EOF
> import os
- > from mercurial import commands, util
+ > from mercurial import commands, error
> from mercurial.extensions import wrapfunction
>
> def lockexception(orig, vfs, lockname, wait, releasefn, *args, **kwargs):
> def releasewrap():
- > raise util.Abort("forced lock failure")
+ > raise error.Abort("forced lock failure")
> return orig(vfs, lockname, wait, releasewrap, *args, **kwargs)
>
> def reposetup(ui, repo):
> wrapfunction(repo, '_lock', lockexception)
>
@@ -229,17 +229,17 @@ Aborting lock does not prevent fncache w
Aborting transaction prevents fncache change
$ cat > ../exceptionext.py <<EOF
> import os
- > from mercurial import commands, util, localrepo
+ > from mercurial import commands, error, localrepo
> from mercurial.extensions import wrapfunction
>
> def wrapper(orig, self, *args, **kwargs):
> tr = orig(self, *args, **kwargs)
> def fail(tr):
- > raise util.Abort("forced transaction failure")
+ > raise error.Abort("forced transaction failure")
> # zzz prefix to ensure it sorted after store.write
> tr.addfinalize('zzz-forcefails', fail)
> return tr
>
> def uisetup(ui):
@@ -260,23 +260,23 @@ Aborting transaction prevents fncache ch
Aborted transactions can be recovered later
$ cat > ../exceptionext.py <<EOF
> import os
- > from mercurial import commands, util, transaction, localrepo
+ > from mercurial import commands, error, transaction, localrepo
> from mercurial.extensions import wrapfunction
>
> def trwrapper(orig, self, *args, **kwargs):
> tr = orig(self, *args, **kwargs)
> def fail(tr):
- > raise util.Abort("forced transaction failure")
+ > raise error.Abort("forced transaction failure")
> # zzz prefix to ensure it sorted after store.write
> tr.addfinalize('zzz-forcefails', fail)
> return tr
>
> def abortwrapper(orig, self, *args, **kwargs):
- > raise util.Abort("forced transaction failure")
+ > raise error.Abort("forced transaction failure")
>
> def uisetup(ui):
> wrapfunction(localrepo.localrepository, 'transaction', trwrapper)
> wrapfunction(transaction.transaction, '_abort', abortwrapper)
>
diff --git a/tests/test-histedit-edit.t b/tests/test-histedit-edit.t
--- a/tests/test-histedit-edit.t
+++ b/tests/test-histedit-edit.t
@@ -296,15 +296,15 @@ say we'll change the message, but don't.
modify the message
check saving last-message.txt, at first
$ cat > $TESTTMP/commitfailure.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def reposetup(ui, repo):
> class commitfailure(repo.__class__):
> def commit(self, *args, **kwargs):
- > raise util.Abort('emulating unexpected abort')
+ > raise error.Abort('emulating unexpected abort')
> repo.__class__ = commitfailure
> EOF
$ cat >> .hg/hgrc <<EOF
> [extensions]
> # this failure occurs before editor invocation
diff --git a/tests/test-hook.t b/tests/test-hook.t
--- a/tests/test-hook.t
+++ b/tests/test-hook.t
@@ -392,11 +392,11 @@ preoutgoing hook can prevent outgoing ch
[255]
$ cd "$TESTTMP/b"
$ cat > hooktests.py <<EOF
- > from mercurial import util
+ > from mercurial import error
>
> uncallable = 0
>
> def printargs(args):
> args.pop('ui', None)
@@ -419,11 +419,11 @@ preoutgoing hook can prevent outgoing ch
>
> def raisehook(**args):
> raise LocalException('exception from hook')
>
> def aborthook(**args):
- > raise util.Abort('raise abort from hook')
+ > raise error.Abort('raise abort from hook')
>
> def brokenhook(**args):
> return 1 + {}
>
> def verbosehook(ui, **args):
diff --git a/tests/test-lock-badness.t b/tests/test-lock-badness.t
--- a/tests/test-lock-badness.t
+++ b/tests/test-lock-badness.t
@@ -12,19 +12,19 @@ Prepare
1 files updated, 0 files merged, 0 files removed, 0 files unresolved
Test that raising an exception in the release function doesn't cause the lock to choke
$ cat > testlock.py << EOF
- > from mercurial import cmdutil, error, util
+ > from mercurial import cmdutil, error, error
>
> cmdtable = {}
> command = cmdutil.command(cmdtable)
>
> def acquiretestlock(repo, releaseexc):
> def unlock():
> if releaseexc:
- > raise util.Abort('expected release exception')
+ > raise error.Abort('expected release exception')
> l = repo._lock(repo.vfs, 'testlock', False, unlock, None, 'test lock')
> return l
>
> @command('testlockexc')
> def testlockexc(ui, repo):
@@ -33,11 +33,11 @@ Test that raising an exception in the re
> testlock.release()
> finally:
> try:
> testlock = acquiretestlock(repo, False)
> except error.LockHeld:
- > raise util.Abort('lockfile on disk even after releasing!')
+ > raise error.Abort('lockfile on disk even after releasing!')
> testlock.release()
> EOF
$ cat >> $HGRCPATH << EOF
> [extensions]
> testlock=$TESTTMP/testlock.py
diff --git a/tests/test-merge1.t b/tests/test-merge1.t
--- a/tests/test-merge1.t
+++ b/tests/test-merge1.t
@@ -212,14 +212,14 @@ aren't changed), even if none of mode, s
isn't changed on the filesystem (see also issue4583).
$ cat > $TESTTMP/abort.py <<EOF
> # emulate aborting before "recordupdates()". in this case, files
> # are changed without updating dirstate
- > from mercurial import extensions, merge, util
+ > from mercurial import extensions, merge, error
> def applyupdates(orig, *args, **kwargs):
> orig(*args, **kwargs)
- > raise util.Abort('intentional aborting')
+ > raise error.Abort('intentional aborting')
> def extsetup(ui):
> extensions.wrapfunction(merge, "applyupdates", applyupdates)
> EOF
$ cat >> .hg/hgrc <<EOF
diff --git a/tests/test-mq-qfold.t b/tests/test-mq-qfold.t
--- a/tests/test-mq-qfold.t
+++ b/tests/test-mq-qfold.t
@@ -147,15 +147,15 @@ Fold regular patch into a git patch, exp
Test saving last-message.txt:
$ hg qrefresh -m "original message"
$ cat > $TESTTMP/commitfailure.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def reposetup(ui, repo):
> class commitfailure(repo.__class__):
> def commit(self, *args, **kwargs):
- > raise util.Abort('emulating unexpected abort')
+ > raise error.Abort('emulating unexpected abort')
> repo.__class__ = commitfailure
> EOF
$ cat >> .hg/hgrc <<EOF
> [extensions]
diff --git a/tests/test-mq-qnew.t b/tests/test-mq-qnew.t
--- a/tests/test-mq-qnew.t
+++ b/tests/test-mq-qnew.t
@@ -246,15 +246,15 @@ Test saving last-message.txt
$ hg init repo
$ cd repo
$ cat > $TESTTMP/commitfailure.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def reposetup(ui, repo):
> class commitfailure(repo.__class__):
> def commit(self, *args, **kwargs):
- > raise util.Abort('emulating unexpected abort')
+ > raise error.Abort('emulating unexpected abort')
> repo.__class__ = commitfailure
> EOF
$ cat >> .hg/hgrc <<EOF
> [extensions]
> # this failure occurs before editor invocation
diff --git a/tests/test-mq-qrefresh-replace-log-message.t b/tests/test-mq-qrefresh-replace-log-message.t
--- a/tests/test-mq-qrefresh-replace-log-message.t
+++ b/tests/test-mq-qrefresh-replace-log-message.t
@@ -106,15 +106,15 @@ Test saving last-message.txt:
> echo "===="
> (echo; echo "test saving last-message.txt") >> \$1
> EOF
$ cat > $TESTTMP/commitfailure.py <<EOF
- > from mercurial import util
+ > from mercurial import error
> def reposetup(ui, repo):
> class commitfailure(repo.__class__):
> def commit(self, *args, **kwargs):
- > raise util.Abort('emulating unexpected abort')
+ > raise error.Abort('emulating unexpected abort')
> repo.__class__ = commitfailure
> EOF
$ cat >> .hg/hgrc <<EOF
> [extensions]
diff --git a/tests/test-simplemerge.py b/tests/test-simplemerge.py
--- a/tests/test-simplemerge.py
+++ b/tests/test-simplemerge.py
@@ -13,11 +13,11 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
import unittest
from unittest import TestCase
-from mercurial import util, simplemerge
+from mercurial import util, simplemerge, error
# bzr compatible interface, for the tests
class Merge3(simplemerge.Merge3Text):
"""3-way merge of texts.
@@ -27,11 +27,11 @@ class Merge3(simplemerge.Merge3Text):
def __init__(self, base, a, b):
basetext = '\n'.join([i.strip('\n') for i in base] + [''])
atext = '\n'.join([i.strip('\n') for i in a] + [''])
btext = '\n'.join([i.strip('\n') for i in b] + [''])
if util.binary(basetext) or util.binary(atext) or util.binary(btext):
- raise util.Abort("don't know how to merge binary files")
+ raise error.Abort("don't know how to merge binary files")
simplemerge.Merge3Text.__init__(self, basetext, atext, btext,
base, a, b)
CantReprocessAndShowBase = simplemerge.CantReprocessAndShowBase
@@ -319,11 +319,11 @@ bbb
self.log('merge result:')
self.log(''.join(ml))
self.assertEquals(ml, MERGED_RESULT)
def test_binary(self):
- self.assertRaises(util.Abort, Merge3, ['\x00'], ['a'], ['b'])
+ self.assertRaises(error.Abort, Merge3, ['\x00'], ['a'], ['b'])
def test_dos_text(self):
base_text = 'a\r\n'
this_text = 'b\r\n'
other_text = 'c\r\n'
diff --git a/tests/test-subrepo.t b/tests/test-subrepo.t
--- a/tests/test-subrepo.t
+++ b/tests/test-subrepo.t
@@ -1026,12 +1026,12 @@ Create repo without default path, pull t
abort: default path for subrepository not found (in subrepo sub/repo) (glob)
[255]
Ensure a full traceback, not just the SubrepoAbort part
- $ hg -R issue1852b update --traceback 2>&1 | grep 'raise util\.Abort'
- raise util.Abort(_("default path for subrepository not found"))
+ $ hg -R issue1852b update --traceback 2>&1 | grep 'raise error\.Abort'
+ raise error.Abort(_("default path for subrepository not found"))
Pull -u now doesn't help
$ hg -R issue1852b pull -u issue1852a
pulling from issue1852a
diff --git a/tests/test-trusted.py b/tests/test-trusted.py
--- a/tests/test-trusted.py
+++ b/tests/test-trusted.py
@@ -164,11 +164,11 @@ print 'untrusted:'
print u2.config('foobar', 'baz', untrusted=True)
print
print "# error handling"
-def assertraises(f, exc=util.Abort):
+def assertraises(f, exc=error.Abort):
try:
f()
except exc as inst:
print 'raised', inst.__class__.__name__
else:
More information about the Mercurial-devel
mailing list