##// END OF EJS Templates
clone: updates the help text for hg clone -{r,b} (issue5654)...
clone: updates the help text for hg clone -{r,b} (issue5654) Differential Revision: https://phab.mercurial-scm.org/D2095

File last commit:

r36575:d60430dc default
r36624:4de15c54 default
Show More
common.py
548 lines | 17.2 KiB | text/x-python | PythonLexer
Martin Geisler
convert: add copyright and license headers to back-ends
r8250 # common.py - common code for the convert extension
#
# Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distributed according to the terms of the
Matt Mackall
Update license to GPLv2+
r10263 # GNU General Public License version 2 or any later version.
timeless
convert: common use absolute_import
r28410 from __future__ import absolute_import
Martin Geisler
convert: add copyright and license headers to back-ends
r8250
timeless
convert: common use absolute_import
r28410 import base64
import datetime
import errno
import os
import re
Augie Fackler
convert: add some utility code for working with shlex on Python 3...
r36575 import shlex
timeless
convert: common use absolute_import
r28410 import subprocess
Yuya Nishihara
py3: move up symbol imports to enforce import-checker rules...
r29205 from mercurial.i18n import _
timeless
convert: common use absolute_import
r28410 from mercurial import (
Augie Fackler
python3: wrap all uses of <exception>.strerror with strtolocal...
r34024 encoding,
timeless
convert: common use absolute_import
r28410 error,
phases,
Pulkit Goyal
py3: use pycompat.byteskwargs in hgext/convert/...
r36347 pycompat,
timeless
convert: common use absolute_import
r28410 util,
)
Patrick Mezard
convert: replace fork with subprocess call.
r5127
Pulkit Goyal
py3: conditionalize cPickle import by adding in util...
r29324 pickle = util.pickle
Patrick Mezard
convert: simplify getargmax() with propertycache
r15606 propertycache = util.propertycache
Augie Fackler
convert: add some utility code for working with shlex on Python 3...
r36575 def _encodeornone(d):
if d is None:
return
return d.encode('latin1')
class _shlexpy3proxy(object):
def __init__(self, l):
self._l = l
def __iter__(self):
return (_encodeornone(v) for v in self._l)
def get_token(self):
return _encodeornone(self._l.get_token())
@property
def infile(self):
return self._l.infile or '<unknown>'
@property
def lineno(self):
return self._l.lineno
def shlexer(data=None, filepath=None, wordchars=None, whitespace=None):
if data is None:
if pycompat.ispy3:
data = open(filepath, 'r', encoding=r'latin1')
else:
data = open(filepath, 'r')
else:
if filepath is not None:
raise error.ProgrammingError(
'shlexer only accepts data or filepath, not both')
if pycompat.ispy3:
data = data.decode('latin1')
l = shlex.shlex(data, infile=filepath, posix=True)
if whitespace is not None:
l.whitespace_split = True
if pycompat.ispy3:
l.whitespace += whitespace.decode('latin1')
else:
l.whitespace += whitespace
if wordchars is not None:
if pycompat.ispy3:
l.wordchars += wordchars.decode('latin1')
else:
l.wordchars += wordchars
if pycompat.ispy3:
return _shlexpy3proxy(l)
return l
Patrick Mezard
convert: replace fork with subprocess call.
r5127 def encodeargs(args):
def encodearg(s):
lines = base64.encodestring(s)
lines = [l.splitlines()[0] for l in lines]
return ''.join(lines)
Thomas Arendsen Hein
Remove trailing spaces, fix indentation
r5143
Patrick Mezard
convert: replace fork with subprocess call.
r5127 s = pickle.dumps(args)
return encodearg(s)
def decodeargs(s):
s = base64.decodestring(s)
return pickle.loads(s)
Brendan Cully
Split convert extension into common and repository type modules
r4536
Matt Mackall
many, many trivial check-code fixups
r10282 class MissingTool(Exception):
pass
Patrick Mezard
convert: allow missing tools not to stop source type detection
r6332
def checktool(exe, name=None, abort=True):
Patrick Mezard
convert: fail if an external required tool is not found
r5497 name = name or exe
Adrian Buehlmann
rename util.find_exe to findexe
r14271 if not util.findexe(exe):
Jordi Gutiérrez Hermoso
style: kill ersatz if-else ternary operators...
r24306 if abort:
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 exc = error.Abort
Jordi Gutiérrez Hermoso
style: kill ersatz if-else ternary operators...
r24306 else:
exc = MissingTool
Patrick Mezard
convert: allow missing tools not to stop source type detection
r6332 raise exc(_('cannot find required "%s" tool') % name)
Patrick Mezard
convert: fail if an external required tool is not found
r5497
Matt Mackall
many, many trivial check-code fixups
r10282 class NoRepo(Exception):
pass
Brendan Cully
Split convert extension into common and repository type modules
r4536
Alexis S. L. Carvalho
convert: change SKIPREV to 'SKIP'
r5400 SKIPREV = 'SKIP'
Alexis S. L. Carvalho
convert: allow the converter_source to say "skip this revision"...
r5374
Brendan Cully
Split convert extension into common and repository type modules
r4536 class commit(object):
Bryan O'Sullivan
convert: make contents of "extra" dict available from sources, for sinks....
r5439 def __init__(self, author, date, desc, parents, branch=None, rev=None,
Gregory Szorc
convert: don't use {} as default argument value...
r30659 extra=None, sortkey=None, saverev=True, phase=phases.draft,
Mads Kiilerich
convert: keep converted hg parents that are outside convert.hg.revs (BC)...
r28900 optparents=None):
Alexis S. L. Carvalho
convert: use 'unknown' and '0 0' if commit author or date weren't specified...
r5984 self.author = author or 'unknown'
self.date = date or '0 0'
Bryan O'Sullivan
convert: empty log messages are OK as of 7f5c3fb0a37d
r5024 self.desc = desc
Mads Kiilerich
convert: keep converted hg parents that are outside convert.hg.revs (BC)...
r28900 self.parents = parents # will be converted and used as parents
self.optparents = optparents or [] # will be used if already converted
Bryan O'Sullivan
convert: make commit constructor clearer and less magical
r5012 self.branch = branch
self.rev = rev
Gregory Szorc
convert: don't use {} as default argument value...
r30659 self.extra = extra or {}
Patrick Mezard
convert: add --sourcesort option for source specific sort...
r8690 self.sortkey = sortkey
Matt Harbison
convert: always track the hg source revision in the internal commit object...
r25570 self.saverev = saverev
Matt Harbison
convert: apply the appropriate phases to the destination (issue4165)...
r25571 self.phase = phase
Brendan Cully
Split convert extension into common and repository type modules
r4536
class converter_source(object):
"""Conversion source interface"""
Matt Harbison
convert: save an indicator of the repo type for sources and sinks...
r35168 def __init__(self, ui, repotype, path=None, revs=None):
Brendan Cully
Split convert extension into common and repository type modules
r4536 """Initialize conversion source (or raise NoRepo("message")
exception if path is not a valid repository)"""
Brendan Cully
convert: move some code into common init function
r4810 self.ui = ui
self.path = path
Durham Goode
convert: add support for specifying multiple revs...
r25748 self.revs = revs
Matt Harbison
convert: save an indicator of the repo type for sources and sinks...
r35168 self.repotype = repotype
Brendan Cully
convert: move some code into common init function
r4810
self.encoding = 'utf-8'
Brendan Cully
convert: export revmap to source....
r4812
Sean Farley
convert: add mapname parameter to checkrevformat...
r20373 def checkhexformat(self, revstr, mapname='splicemap'):
Ben Goswami
splicemap: improve error handling when source is hg (issue2084)...
r19120 """ fails if revstr is not a 40 byte hex. mercurial and git both uses
such format for their revision numbering
"""
Ben Goswami
splicemap: improve error handling when source is subversion (issue2084)...
r19122 if not re.match(r'[0-9a-fA-F]{40,40}$', revstr):
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort(_('%s entry %s is not a valid revision'
Sean Farley
convert: add mapname parameter to checkrevformat...
r20373 ' identifier') % (mapname, revstr))
Ben Goswami
splicemap: improve error handling when source is hg (issue2084)...
r19120
Bryan O'Sullivan
convert: add before/after hooks for converter sources
r5356 def before(self):
pass
def after(self):
pass
Durham Goode
convert: add function to test if file is from source...
r26035 def targetfilebelongstosource(self, targetfilename):
"""Returns true if the given targetfile belongs to the source repo. This
is useful when only a subdirectory of the target belongs to the source
repo."""
# For normal full repo converts, this is always True.
return True
Bryan O'Sullivan
convert: abstract map files into a class
r5510 def setrevmap(self, revmap):
"""set the map of already-converted revisions"""
Brendan Cully
Split convert extension into common and repository type modules
r4536
def getheads(self):
"""Return a list of this repository's heads"""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
def getfile(self, name, rev):
Patrick Mezard
convert: merge sources getmode() into getfile()
r11134 """Return a pair (data, mode) where data is the file content
as a string and mode one of '', 'x' or 'l'. rev is the
Mads Kiilerich
convert: use None value for missing files instead of overloading IOError...
r22296 identifier returned by a previous call to getchanges().
Data is None if file is missing/deleted in rev.
Patrick Mezard
convert: improve convert_source documentation
r7055 """
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
Mads Kiilerich
convert: introduce --full for converting all files...
r22300 def getchanges(self, version, full):
Mads Kiilerich
convert: optimize convert of files that are unmodified from p2 in merges...
r24395 """Returns a tuple of (files, copies, cleanp2).
Patrick Mezard
convert: improve convert_source documentation
r7055
files is a sorted list of (filename, id) tuples for all files
Greg Ward
convert: improve docstrings, comments.
r8444 changed between version and its first parent returned by
Mads Kiilerich
convert: introduce --full for converting all files...
r22300 getcommit(). If full, all files in that revision is returned.
id is the source revision id of the file.
Brendan Cully
Split convert extension into common and repository type modules
r4536
Brendan Cully
convert: look up copies in getchanges instead of getcommit...
r5121 copies is a dictionary of dest: source
Mads Kiilerich
convert: optimize convert of files that are unmodified from p2 in merges...
r24395
cleanp2 is the set of files filenames that are clean against p2.
(Files that are clean against p1 are already not in files (unless
full). This makes it possible to handle p2 clean files similarly.)
Brendan Cully
convert: look up copies in getchanges instead of getcommit...
r5121 """
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
def getcommit(self, version):
"""Return the commit object for version"""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
Augie Fackler
convert: add support for deterministic progress bar on scanning phase...
r22411 def numcommits(self):
"""Return the number of commits in this source.
If unknown, return None.
"""
return None
Brendan Cully
Split convert extension into common and repository type modules
r4536 def gettags(self):
Patrick Mezard
convert/svn: test svn tags encoding
r8887 """Return the tags as a dictionary of name: revision
Tag names must be UTF-8 strings.
"""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
Brendan Cully
convert: ove recode method into converter_source
r4759 def recode(self, s, encoding=None):
if not encoding:
Brendan Cully
convert: move some code into common init function
r4810 encoding = self.encoding or 'utf-8'
Thomas Arendsen Hein
removed trailing whitespace
r4957
Thomas Arendsen Hein
Don't decode unicode strings....
r5287 if isinstance(s, unicode):
return s.encode("utf-8")
Brendan Cully
convert: ove recode method into converter_source
r4759 try:
return s.decode(encoding).encode("utf-8")
Brodie Rao
cleanup: replace naked excepts with more specific ones
r16688 except UnicodeError:
Brendan Cully
convert: ove recode method into converter_source
r4759 try:
return s.decode("latin-1").encode("utf-8")
Brodie Rao
cleanup: replace naked excepts with more specific ones
r16688 except UnicodeError:
Brendan Cully
convert: ove recode method into converter_source
r4759 return s.decode(encoding, "replace").encode("utf-8")
Alexis S. L. Carvalho
convert: readd --filemap...
r5377 def getchangedfiles(self, rev, i):
"""Return the files changed by rev compared to parent[i].
Thomas Arendsen Hein
Removed tabs and trailing whitespace in python files
r5760
Alexis S. L. Carvalho
convert: readd --filemap...
r5377 i is an index selecting one of the parents of rev. The return
value should be the list of files that are different in rev and
this parent.
If rev has no parents, i is None.
Thomas Arendsen Hein
Removed tabs and trailing whitespace in python files
r5760
Alexis S. L. Carvalho
convert: readd --filemap...
r5377 This function is only needed to support --filemap
"""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Alexis S. L. Carvalho
convert: readd --filemap...
r5377
Bryan O'Sullivan
convert: tell the source repository when a rev has been converted...
r5554 def converted(self, rev, sinkrev):
'''Notify the source that a revision has been converted.'''
Patrick Mezard
convert: fail fast if source does not support --sourcesort
r8691 def hasnativeorder(self):
"""Return true if this source has a meaningful, native revision
order. For instance, Mercurial revisions are store sequentially
while there is no such global ordering with Darcs.
"""
return False
Constantine Linnick
convert: add closesort algorithm to mercurial sources...
r18819 def hasnativeclose(self):
"""Return true if this source has ability to close branch.
"""
return False
Patrick Mezard
convert: rewrite tags when converting from hg to hg
r8693 def lookuprev(self, rev):
"""If rev is a meaningful revision reference in source, return
the referenced identifier in the same format used by getcommit().
return None otherwise.
"""
return None
Bryan O'Sullivan
convert: tell the source repository when a rev has been converted...
r5554
Edouard Gomez
convert: add bookmark support to common sink/source implementation
r13744 def getbookmarks(self):
"""Return the bookmarks as a dictionary of name: revision
Bookmark names are to be UTF-8 strings.
"""
return {}
Sean Farley
convert: add mapname parameter to checkrevformat...
r20373 def checkrevformat(self, revstr, mapname='splicemap'):
Ben Goswami
splicemap: improve error handling when source is hg (issue2084)...
r19120 """revstr is a string that describes a revision in the given
source control system. Return true if revstr has correct
format.
"""
return True
Brendan Cully
Split convert extension into common and repository type modules
r4536 class converter_sink(object):
"""Conversion sink (target) interface"""
Matt Harbison
convert: save an indicator of the repo type for sources and sinks...
r35168 def __init__(self, ui, repotype, path):
Brendan Cully
Split convert extension into common and repository type modules
r4536 """Initialize conversion sink (or raise NoRepo("message")
Bryan O'Sullivan
convert: refactor sink initialisation, to remove hardcoding of hg...
r5441 exception if path is not a valid repository)
created is a list of paths to remove if a fatal error occurs
later"""
self.ui = ui
Bryan O'Sullivan
convert: add default constructor for converter_sink
r5440 self.path = path
Bryan O'Sullivan
convert: refactor sink initialisation, to remove hardcoding of hg...
r5441 self.created = []
Matt Harbison
convert: save an indicator of the repo type for sources and sinks...
r35168 self.repotype = repotype
Brendan Cully
Split convert extension into common and repository type modules
r4536
Bryan O'Sullivan
convert: rename mapfile to revmapfile, so we can map more than just revs
r5011 def revmapfile(self):
Brendan Cully
Split convert extension into common and repository type modules
r4536 """Path to a file that will contain lines
source_rev_id sink_rev_id
mapping equivalent revision identifiers for each system."""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
Edouard Gomez
convert extension: Add support for username mapping...
r4589 def authorfile(self):
"""Path to a file that will contain lines
srcauthor=dstauthor
mapping equivalent authors identifiers for each system."""
Brendan Cully
convert: fix various authormap handling bugs
r4590 return None
Edouard Gomez
convert extension: Add support for username mapping...
r4589
Mads Kiilerich
convert: optimize convert of files that are unmodified from p2 in merges...
r24395 def putcommit(self, files, copies, parents, commit, source, revmap, full,
cleanp2):
Brendan Cully
Split convert extension into common and repository type modules
r4536 """Create a revision with all changed files listed in 'files'
Patrick Mezard
convert: rewrite tags when converting from hg to hg
r8693 and having listed parents. 'commit' is a commit object
containing at a minimum the author, date, and message for this
changeset. 'files' is a list of (path, version) tuples,
'copies' is a dictionary mapping destinations to sources,
'source' is the source repository, and 'revmap' is a mapfile
Patrick Mezard
convert: merge sources getmode() into getfile()
r11134 of source revisions to converted revisions. Only getfile() and
Mads Kiilerich
convert: introduce --full for converting all files...
r22300 lookuprev() should be called on 'source'. 'full' means that 'files'
is complete and all other files should be removed.
Mads Kiilerich
convert: optimize convert of files that are unmodified from p2 in merges...
r24395 'cleanp2' is a set of the filenames that are unchanged from p2
(only in the common merge case where there two parents).
Patrick Mezard
convert: reintegrate file retrieval code in sinks...
r6716
Note that the sink repository is not told to update itself to
a particular revision (or even what that revision would be)
before it receives the file data.
"""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Brendan Cully
Split convert extension into common and repository type modules
r4536
def puttags(self, tags):
"""Put tags into sink.
Patrick Mezard
convert/svn: test svn tags encoding
r8887
tags: {tagname: sink_rev_id, ...} where tagname is an UTF-8 string.
Patrick Mezard
convert: fix history topology when using hg.tagsbranch...
r9431 Return a pair (tag_revision, tag_parent_revision), or (None, None)
if nothing was changed.
Patrick Mezard
convert/svn: test svn tags encoding
r8887 """
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Patrick Mezard
convert: replace fork with subprocess call.
r5127
Patrick Mezard
convert: hg.clonebranches must pull missing parents (issue941)
r5934 def setbranch(self, branch, pbranches):
Patrick Mezard
convert: reintegrate file retrieval code in sinks...
r6716 """Set the current branch name. Called before the first putcommit
Brendan Cully
convert: hg: optionally create branches as clones...
r5173 on the branch.
branch: branch name for subsequent commits
Patrick Mezard
convert: hg.clonebranches must pull missing parents (issue941)
r5934 pbranches: (converted parent revision, parent branch) tuples"""
Alexis S. L. Carvalho
convert: add a mode where mercurial_sink skips empty revisions....
r5378
def setfilemapmode(self, active):
"""Tell the destination that we're using a filemap
Some converter_sources (svn in particular) can claim that a file
was changed in a revision, even if there was no change. This method
tells the destination that we're using a filemap and that it should
filter empty revisions.
"""
Bryan O'Sullivan
convert: abstract map files into a class
r5510
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 def before(self):
pass
def after(self):
pass
Edouard Gomez
convert: add bookmark support to common sink/source implementation
r13744 def putbookmarks(self, bookmarks):
"""Put bookmarks into sink.
bookmarks: {bookmarkname: sink_rev_id, ...}
where bookmarkname is an UTF-8 string.
"""
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512
Mads Kiilerich
convert: introduce hascommitfrommap sink method...
r21635 def hascommitfrommap(self, rev):
"""Return False if a rev mentioned in a filemap is known to not be
present."""
raise NotImplementedError
Mads Kiilerich
convert: rename sink hascommit to hascommitforsplicemap...
r21634 def hascommitforsplicemap(self, rev):
"""This method is for the special needs for splicemap handling and not
for general use. Returns True if the sink contains rev, aborts on some
special cases."""
Brodie Rao
cleanup: "raise SomeException()" -> "raise SomeException"
r16687 raise NotImplementedError
Patrick Mezard
convert: use splicemap entries when sorting revisions (issue1748)...
r16106
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 class commandline(object):
def __init__(self, ui, command):
self.ui = ui
self.command = command
def prerun(self):
pass
def postrun(self):
pass
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 def _cmdline(self, cmd, *args, **kwargs):
Pulkit Goyal
py3: use pycompat.byteskwargs in hgext/convert/...
r36347 kwargs = pycompat.byteskwargs(kwargs)
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 cmdline = [self.command, cmd] + list(args)
for k, v in kwargs.iteritems():
if len(k) == 1:
cmdline.append('-' + k)
else:
cmdline.append('--' + k.replace('_', '-'))
try:
if len(k) == 1:
cmdline.append('' + v)
else:
cmdline[-1] += '=' + v
except TypeError:
pass
cmdline = [util.shellquote(arg) for arg in cmdline]
Patrick Mezard
convert: display child command output if --debug (fix 878466138b57)
r7611 if not self.ui.debugflag:
Pulkit Goyal
py3: convert os.devnull to bytes using pycompat.bytestr...
r36475 cmdline += ['2>', pycompat.bytestr(os.devnull)]
Patrick Mezard
convert: fix util.popen regression in darcs converter
r5529 cmdline = ' '.join(cmdline)
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 return cmdline
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 def _run(self, cmd, *args, **kwargs):
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 def popen(cmdline):
p = subprocess.Popen(cmdline, shell=True, bufsize=-1,
close_fds=util.closefds,
stdout=subprocess.PIPE)
return p
return self._dorun(popen, cmd, *args, **kwargs)
Daniel Atallah
convert: add support to common commandline to access stdin of the process
r13759
def _run2(self, cmd, *args, **kwargs):
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 return self._dorun(util.popen2, cmd, *args, **kwargs)
Daniel Atallah
convert: add support to common commandline to access stdin of the process
r13759
Mateusz Kwapich
convert: rewrite gitpipe to use common.commandline (SEC)...
r28662 def _run3(self, cmd, *args, **kwargs):
return self._dorun(util.popen3, cmd, *args, **kwargs)
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 def _dorun(self, openfunc, cmd, *args, **kwargs):
cmdline = self._cmdline(cmd, *args, **kwargs)
Martin Geisler
do not attempt to translate ui.debug output
r9467 self.ui.debug('running: %s\n' % (cmdline,))
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 self.prerun()
try:
Daniel Atallah
convert: add support to common commandline to access stdin of the process
r13759 return openfunc(cmdline)
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 finally:
self.postrun()
def run(self, cmd, *args, **kwargs):
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 p = self._run(cmd, *args, **kwargs)
output = p.communicate()[0]
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 self.ui.debug(output)
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 return output, p.returncode
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512
Aleix Conchillo Flaque
convert: added GNU Arch source converter
r6035 def runlines(self, cmd, *args, **kwargs):
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 p = self._run(cmd, *args, **kwargs)
output = p.stdout.readlines()
p.wait()
Aleix Conchillo Flaque
convert: improve gnu arch source performance and other fixes...
r6049 self.ui.debug(''.join(output))
Patrick Mezard
convert: use subprocess for all commandline calls...
r17413 return output, p.returncode
Aleix Conchillo Flaque
convert: added GNU Arch source converter
r6035
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 def checkexit(self, status, output=''):
if status:
if output:
self.ui.warn(_('%s error:\n') % self.command)
self.ui.warn(output)
Adrian Buehlmann
rename explain_exit to explainexit
r14234 msg = util.explainexit(status)[0]
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort('%s %s' % (self.command, msg))
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512
def run0(self, cmd, *args, **kwargs):
output, status = self.run(cmd, *args, **kwargs)
self.checkexit(status, output)
return output
Aleix Conchillo Flaque
convert: added GNU Arch source converter
r6035 def runlines0(self, cmd, *args, **kwargs):
output, status = self.runlines(cmd, *args, **kwargs)
Aleix Conchillo Flaque
convert: improve gnu arch source performance and other fixes...
r6049 self.checkexit(status, ''.join(output))
Aleix Conchillo Flaque
convert: added GNU Arch source converter
r6035 return output
Patrick Mezard
convert: simplify getargmax() with propertycache
r15606 @propertycache
def argmax(self):
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 # POSIX requires at least 4096 bytes for ARG_MAX
Patrick Mezard
convert: simplify getargmax() with propertycache
r15606 argmax = 4096
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 try:
Patrick Mezard
convert: simplify getargmax() with propertycache
r15606 argmax = os.sysconf("SC_ARG_MAX")
Brodie Rao
cleanup: replace naked excepts with more specific ones
r16688 except (AttributeError, ValueError):
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 pass
# Windows shells impose their own limits on command line length,
# down to 2047 bytes for cmd.exe under Windows NT/2k and 2500 bytes
# for older 4nt.exe. See http://support.microsoft.com/kb/830473 for
# details about cmd.exe limitations.
# Since ARG_MAX is for command line _and_ environment, lower our limit
# (and make happy Windows shells while doing this).
Martin Geisler
Use explicit integer division...
r15791 return argmax // 2 - 1
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832
Patrick Mezard
convert: make commandline.limit_arglist private, simplify
r17412 def _limit_arglist(self, arglist, cmd, *args, **kwargs):
cmdlen = len(self._cmdline(cmd, *args, **kwargs))
Patrick Mezard
convert: simplify getargmax() with propertycache
r15606 limit = self.argmax - cmdlen
Pulkit Goyal
convert: don't use bytes as a variable name...
r36349 numbytes = 0
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 fl = []
for fn in arglist:
b = len(fn) + 3
Pulkit Goyal
convert: don't use bytes as a variable name...
r36349 if numbytes + b < limit or len(fl) == 0:
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 fl.append(fn)
Pulkit Goyal
convert: don't use bytes as a variable name...
r36349 numbytes += b
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 else:
yield fl
fl = [fn]
Pulkit Goyal
convert: don't use bytes as a variable name...
r36349 numbytes = b
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 if fl:
yield fl
def xargs(self, arglist, cmd, *args, **kwargs):
Patrick Mezard
convert: make commandline.limit_arglist private, simplify
r17412 for l in self._limit_arglist(arglist, cmd, *args, **kwargs):
Maxim Dounin
convert: add commandline.xargs(), use it in svn_sink class...
r5832 self.run0(cmd, *(list(args) + l), **kwargs)
Bryan O'Sullivan
convert: abstract map files into a class
r5510
class mapfile(dict):
def __init__(self, ui, path):
super(mapfile, self).__init__()
self.ui = ui
self.path = path
self.fp = None
self.order = []
self._read()
def _read(self):
Stefan Rusek
Handle when the slicemap option is an empty string...
r7774 if not self.path:
Bryan O'Sullivan
convert: allow synthetic history to be spliced in....
r5996 return
Bryan O'Sullivan
convert: abstract map files into a class
r5510 try:
Augie Fackler
convert: open all files in binary mode...
r36149 fp = open(self.path, 'rb')
Gregory Szorc
global: mass rewrite to use modern exception syntax...
r25660 except IOError as err:
Bryan O'Sullivan
convert: abstract map files into a class
r5510 if err.errno != errno.ENOENT:
raise
return
Jun Wu
convert: migrate to util.iterfile
r30400 for i, line in enumerate(util.iterfile(fp)):
Patrick Mezard
convert: ignore blank lines in mapfiles (issue3286)
r16190 line = line.splitlines()[0].rstrip()
if not line:
# Ignore blank lines
continue
Patrick Mezard
convert: better mapfile parsing errors (issue1581/1)
r8047 try:
Patrick Mezard
convert: ignore blank lines in mapfiles (issue3286)
r16190 key, value = line.rsplit(' ', 1)
Patrick Mezard
convert: better mapfile parsing errors (issue1581/1)
r8047 except ValueError:
Pierre-Yves David
error: get Abort from 'error' instead of 'util'...
r26587 raise error.Abort(
Matt Mackall
many, many trivial check-code fixups
r10282 _('syntax error in %s(%d): key/value pair expected')
% (self.path, i + 1))
Bryan O'Sullivan
convert: abstract map files into a class
r5510 if key not in self:
self.order.append(key)
super(mapfile, self).__setitem__(key, value)
fp.close()
Thomas Arendsen Hein
Removed tabs and trailing whitespace in python files
r5760
Bryan O'Sullivan
convert: abstract map files into a class
r5510 def __setitem__(self, key, value):
if self.fp is None:
try:
Augie Fackler
convert: open all files in binary mode...
r36149 self.fp = open(self.path, 'ab')
Gregory Szorc
global: mass rewrite to use modern exception syntax...
r25660 except IOError as err:
Augie Fackler
python3: wrap all uses of <exception>.strerror with strtolocal...
r34024 raise error.Abort(
_('could not open map file %r: %s') %
(self.path, encoding.strtolocal(err.strerror)))
Yuya Nishihara
convert: fix line ending of mapfile and commit.desc file...
r36166 self.fp.write(util.tonativeeol('%s %s\n' % (key, value)))
Bryan O'Sullivan
convert: abstract map files into a class
r5510 self.fp.flush()
super(mapfile, self).__setitem__(key, value)
def close(self):
Bryan O'Sullivan
convert: abstract darcs's commandline handling
r5512 if self.fp:
self.fp.close()
self.fp = None
Patrick Mezard
convert: turn splicemap into a simple dictionary...
r16105
Julian Cowley
convert: add config option to use the local time zone...
r17974 def makedatetimestamp(t):
"""Like util.makedate() but for time t instead of current time"""
delta = (datetime.datetime.utcfromtimestamp(t) -
datetime.datetime.fromtimestamp(t))
tz = delta.days * 86400 + delta.seconds
return t, tz