2005-08-27 12:13:28 +04:00
|
|
|
"""
|
|
|
|
util.py - Mercurial utility functions and platform specfic implementations
|
|
|
|
|
|
|
|
Copyright 2005 K. Thananchayan <thananck@yahoo.com>
|
|
|
|
|
|
|
|
This software may be used and distributed according to the terms
|
|
|
|
of the GNU General Public License, incorporated herein by reference.
|
|
|
|
|
|
|
|
This contains helper routines that are independent of the SCM core and hide
|
|
|
|
platform-specific details from the core.
|
|
|
|
"""
|
2005-06-22 07:31:13 +04:00
|
|
|
|
2005-07-15 01:51:47 +04:00
|
|
|
import os, errno
|
2005-10-19 05:37:48 +04:00
|
|
|
from i18n import gettext as _
|
2005-07-18 18:54:21 +04:00
|
|
|
from demandload import *
|
2006-01-03 02:25:33 +03:00
|
|
|
demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
|
|
|
|
demandload(globals(), "threading time")
|
2005-09-15 11:59:16 +04:00
|
|
|
|
2005-09-21 22:44:08 +04:00
|
|
|
def pipefilter(s, cmd):
|
|
|
|
'''filter string S through command CMD, returning its output'''
|
2005-09-15 11:59:16 +04:00
|
|
|
(pout, pin) = popen2.popen2(cmd, -1, 'b')
|
|
|
|
def writer():
|
|
|
|
pin.write(s)
|
|
|
|
pin.close()
|
|
|
|
|
|
|
|
# we should use select instead on UNIX, but this will work on most
|
|
|
|
# systems, including Windows
|
|
|
|
w = threading.Thread(target=writer)
|
|
|
|
w.start()
|
|
|
|
f = pout.read()
|
|
|
|
pout.close()
|
|
|
|
w.join()
|
|
|
|
return f
|
2005-06-22 07:31:13 +04:00
|
|
|
|
2005-09-21 22:44:08 +04:00
|
|
|
def tempfilter(s, cmd):
|
|
|
|
'''filter string S through a pair of temporary files with CMD.
|
|
|
|
CMD is used as a template to create the real command to be run,
|
|
|
|
with the strings INFILE and OUTFILE replaced by the real names of
|
|
|
|
the temporary files generated.'''
|
|
|
|
inname, outname = None, None
|
|
|
|
try:
|
|
|
|
infd, inname = tempfile.mkstemp(prefix='hgfin')
|
|
|
|
fp = os.fdopen(infd, 'wb')
|
|
|
|
fp.write(s)
|
|
|
|
fp.close()
|
|
|
|
outfd, outname = tempfile.mkstemp(prefix='hgfout')
|
|
|
|
os.close(outfd)
|
|
|
|
cmd = cmd.replace('INFILE', inname)
|
|
|
|
cmd = cmd.replace('OUTFILE', outname)
|
|
|
|
code = os.system(cmd)
|
2005-10-19 05:38:39 +04:00
|
|
|
if code: raise Abort(_("command '%s' failed: %s") %
|
2005-09-21 22:44:08 +04:00
|
|
|
(cmd, explain_exit(code)))
|
|
|
|
return open(outname, 'rb').read()
|
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
if inname: os.unlink(inname)
|
|
|
|
except: pass
|
|
|
|
try:
|
|
|
|
if outname: os.unlink(outname)
|
|
|
|
except: pass
|
|
|
|
|
|
|
|
filtertable = {
|
|
|
|
'tempfile:': tempfilter,
|
|
|
|
'pipe:': pipefilter,
|
|
|
|
}
|
|
|
|
|
|
|
|
def filter(s, cmd):
|
|
|
|
"filter a string through a command that transforms its input to its output"
|
|
|
|
for name, fn in filtertable.iteritems():
|
|
|
|
if cmd.startswith(name):
|
|
|
|
return fn(s, cmd[len(name):].lstrip())
|
|
|
|
return pipefilter(s, cmd)
|
|
|
|
|
2005-09-21 08:35:51 +04:00
|
|
|
def patch(strip, patchname, ui):
|
|
|
|
"""apply the patch <patchname> to the working directory.
|
|
|
|
a list of patched files is returned"""
|
|
|
|
fp = os.popen('patch -p%d < "%s"' % (strip, patchname))
|
|
|
|
files = {}
|
|
|
|
for line in fp:
|
|
|
|
line = line.rstrip()
|
|
|
|
ui.status("%s\n" % line)
|
|
|
|
if line.startswith('patching file '):
|
|
|
|
pf = parse_patch_output(line)
|
|
|
|
files.setdefault(pf, 1)
|
|
|
|
code = fp.close()
|
|
|
|
if code:
|
2005-10-19 05:38:39 +04:00
|
|
|
raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
|
2005-09-21 08:35:51 +04:00
|
|
|
return files.keys()
|
2005-09-21 20:56:30 +04:00
|
|
|
|
2005-08-24 06:58:46 +04:00
|
|
|
def binary(s):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""return true if a string is binary data using diff's heuristic"""
|
2005-08-24 06:58:46 +04:00
|
|
|
if s and '\0' in s[:4096]:
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2005-07-01 12:34:50 +04:00
|
|
|
def unique(g):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""return the uniq elements of iterable g"""
|
2005-07-01 12:34:50 +04:00
|
|
|
seen = {}
|
|
|
|
for f in g:
|
|
|
|
if f not in seen:
|
|
|
|
seen[f] = 1
|
|
|
|
yield f
|
|
|
|
|
2005-08-08 00:43:11 +04:00
|
|
|
class Abort(Exception):
|
|
|
|
"""Raised if a command needs to print an error and exit."""
|
2005-06-28 14:38:33 +04:00
|
|
|
|
2005-07-18 18:54:21 +04:00
|
|
|
def always(fn): return True
|
|
|
|
def never(fn): return False
|
|
|
|
|
2005-12-01 19:48:22 +03:00
|
|
|
def patkind(name, dflt_pat='glob'):
|
|
|
|
"""Split a string into an optional pattern kind prefix and the
|
|
|
|
actual pattern."""
|
|
|
|
for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
|
|
|
|
if name.startswith(prefix + ':'): return name.split(':', 1)
|
|
|
|
return dflt_pat, name
|
|
|
|
|
2005-08-26 15:06:58 +04:00
|
|
|
def globre(pat, head='^', tail='$'):
|
2005-07-18 18:54:21 +04:00
|
|
|
"convert a glob pattern into a regexp"
|
|
|
|
i, n = 0, len(pat)
|
|
|
|
res = ''
|
|
|
|
group = False
|
|
|
|
def peek(): return i < n and pat[i]
|
|
|
|
while i < n:
|
|
|
|
c = pat[i]
|
|
|
|
i = i+1
|
|
|
|
if c == '*':
|
|
|
|
if peek() == '*':
|
|
|
|
i += 1
|
|
|
|
res += '.*'
|
|
|
|
else:
|
|
|
|
res += '[^/]*'
|
|
|
|
elif c == '?':
|
|
|
|
res += '.'
|
|
|
|
elif c == '[':
|
|
|
|
j = i
|
|
|
|
if j < n and pat[j] in '!]':
|
|
|
|
j += 1
|
|
|
|
while j < n and pat[j] != ']':
|
|
|
|
j += 1
|
|
|
|
if j >= n:
|
|
|
|
res += '\\['
|
|
|
|
else:
|
|
|
|
stuff = pat[i:j].replace('\\','\\\\')
|
|
|
|
i = j + 1
|
|
|
|
if stuff[0] == '!':
|
|
|
|
stuff = '^' + stuff[1:]
|
|
|
|
elif stuff[0] == '^':
|
|
|
|
stuff = '\\' + stuff
|
|
|
|
res = '%s[%s]' % (res, stuff)
|
|
|
|
elif c == '{':
|
|
|
|
group = True
|
|
|
|
res += '(?:'
|
|
|
|
elif c == '}' and group:
|
|
|
|
res += ')'
|
|
|
|
group = False
|
|
|
|
elif c == ',' and group:
|
|
|
|
res += '|'
|
2006-03-24 01:39:53 +03:00
|
|
|
elif c == '\\':
|
|
|
|
p = peek()
|
|
|
|
if p:
|
|
|
|
i += 1
|
|
|
|
res += re.escape(p)
|
|
|
|
else:
|
|
|
|
res += re.escape(c)
|
2005-07-18 18:54:21 +04:00
|
|
|
else:
|
|
|
|
res += re.escape(c)
|
|
|
|
return head + res + tail
|
|
|
|
|
2005-07-30 00:30:12 +04:00
|
|
|
_globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
|
|
|
|
|
2005-08-12 23:16:58 +04:00
|
|
|
def pathto(n1, n2):
|
2005-08-13 03:06:52 +04:00
|
|
|
'''return the relative path from one place to another.
|
|
|
|
this returns a path in the form used by the local filesystem, not hg.'''
|
|
|
|
if not n1: return localpath(n2)
|
|
|
|
a, b = n1.split('/'), n2.split('/')
|
2005-11-14 04:59:35 +03:00
|
|
|
a.reverse()
|
|
|
|
b.reverse()
|
2005-08-12 23:16:58 +04:00
|
|
|
while a and b and a[-1] == b[-1]:
|
2005-11-14 04:59:35 +03:00
|
|
|
a.pop()
|
|
|
|
b.pop()
|
2005-08-12 23:16:58 +04:00
|
|
|
b.reverse()
|
|
|
|
return os.sep.join((['..'] * len(a)) + b)
|
|
|
|
|
2005-08-27 10:29:10 +04:00
|
|
|
def canonpath(root, cwd, myname):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""return the canonical path of myname, given cwd and root"""
|
2005-12-01 19:48:42 +03:00
|
|
|
if root == os.sep:
|
|
|
|
rootsep = os.sep
|
|
|
|
else:
|
2006-03-01 01:25:34 +03:00
|
|
|
rootsep = root + os.sep
|
2005-08-08 00:43:11 +04:00
|
|
|
name = myname
|
|
|
|
if not name.startswith(os.sep):
|
2005-08-27 10:29:10 +04:00
|
|
|
name = os.path.join(root, cwd, name)
|
2005-08-08 00:43:11 +04:00
|
|
|
name = os.path.normpath(name)
|
|
|
|
if name.startswith(rootsep):
|
2006-03-19 16:53:58 +03:00
|
|
|
name = name[len(rootsep):]
|
|
|
|
audit_path(name)
|
|
|
|
return pconvert(name)
|
2005-08-27 10:29:10 +04:00
|
|
|
elif name == root:
|
2005-08-08 00:43:11 +04:00
|
|
|
return ''
|
|
|
|
else:
|
2005-08-27 10:29:10 +04:00
|
|
|
raise Abort('%s not under root' % myname)
|
2005-08-15 00:23:36 +04:00
|
|
|
|
2006-01-03 02:48:16 +03:00
|
|
|
def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
|
|
|
|
return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
|
2005-10-19 11:02:41 +04:00
|
|
|
|
2006-01-03 02:48:16 +03:00
|
|
|
def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
|
2005-10-19 11:02:41 +04:00
|
|
|
if os.name == 'nt':
|
|
|
|
dflt_pat = 'glob'
|
|
|
|
else:
|
|
|
|
dflt_pat = 'relpath'
|
2006-01-03 02:48:16 +03:00
|
|
|
return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
|
2005-10-19 11:02:41 +04:00
|
|
|
|
2006-01-03 02:48:16 +03:00
|
|
|
def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""build a function to match a set of file patterns
|
|
|
|
|
|
|
|
arguments:
|
|
|
|
canonroot - the canonical root of the tree you're matching against
|
|
|
|
cwd - the current working directory, if relevant
|
|
|
|
names - patterns to find
|
|
|
|
inc - patterns to include
|
|
|
|
exc - patterns to exclude
|
|
|
|
head - a regex to prepend to patterns to control whether a match is rooted
|
|
|
|
|
|
|
|
a pattern is one of:
|
2005-09-17 11:27:27 +04:00
|
|
|
'glob:<rooted glob>'
|
|
|
|
're:<rooted regexp>'
|
|
|
|
'path:<rooted path>'
|
|
|
|
'relglob:<relative glob>'
|
2005-08-27 12:13:28 +04:00
|
|
|
'relpath:<relative path>'
|
2005-09-17 11:27:27 +04:00
|
|
|
'relre:<relative regexp>'
|
|
|
|
'<rooted path or regexp>'
|
2005-08-27 12:13:28 +04:00
|
|
|
|
|
|
|
returns:
|
|
|
|
a 3-tuple containing
|
|
|
|
- list of explicit non-pattern names passed in
|
|
|
|
- a bool match(filename) function
|
|
|
|
- a bool indicating if any patterns were passed in
|
|
|
|
|
|
|
|
todo:
|
|
|
|
make head regex a rooted bool
|
|
|
|
"""
|
|
|
|
|
2005-10-19 11:02:41 +04:00
|
|
|
def contains_glob(name):
|
2005-07-30 00:30:12 +04:00
|
|
|
for c in name:
|
2005-10-19 11:02:41 +04:00
|
|
|
if c in _globchars: return True
|
|
|
|
return False
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
|
2005-08-13 04:09:17 +04:00
|
|
|
def regex(kind, name, tail):
|
2005-07-21 21:21:33 +04:00
|
|
|
'''convert a pattern into a regular expression'''
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
if kind == 're':
|
|
|
|
return name
|
|
|
|
elif kind == 'path':
|
2005-08-13 04:09:17 +04:00
|
|
|
return '^' + re.escape(name) + '(?:/|$)'
|
2005-09-17 11:27:27 +04:00
|
|
|
elif kind == 'relglob':
|
|
|
|
return head + globre(name, '(?:|.*/)', tail)
|
2005-08-13 04:09:17 +04:00
|
|
|
elif kind == 'relpath':
|
|
|
|
return head + re.escape(name) + tail
|
2005-09-17 11:27:27 +04:00
|
|
|
elif kind == 'relre':
|
|
|
|
if name.startswith('^'):
|
|
|
|
return name
|
|
|
|
return '.*' + name
|
2005-07-21 21:21:33 +04:00
|
|
|
return head + globre(name, '', tail)
|
|
|
|
|
|
|
|
def matchfn(pats, tail):
|
|
|
|
"""build a matching function from a set of patterns"""
|
2005-10-27 03:10:56 +04:00
|
|
|
if not pats:
|
|
|
|
return
|
2005-10-26 01:58:11 +04:00
|
|
|
matches = []
|
|
|
|
for k, p in pats:
|
|
|
|
try:
|
|
|
|
pat = '(?:%s)' % regex(k, p, tail)
|
|
|
|
matches.append(re.compile(pat).match)
|
2005-11-14 04:59:35 +03:00
|
|
|
except re.error:
|
2006-01-03 02:52:56 +03:00
|
|
|
if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
|
|
|
|
else: raise Abort("invalid pattern (%s): %s" % (k, p))
|
2005-10-26 01:58:11 +04:00
|
|
|
|
|
|
|
def buildfn(text):
|
|
|
|
for m in matches:
|
|
|
|
r = m(text)
|
|
|
|
if r:
|
|
|
|
return r
|
|
|
|
|
|
|
|
return buildfn
|
2005-07-21 21:21:33 +04:00
|
|
|
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
def globprefix(pat):
|
|
|
|
'''return the non-glob prefix of a path, e.g. foo/* -> foo'''
|
|
|
|
root = []
|
|
|
|
for p in pat.split(os.sep):
|
2005-10-19 11:02:41 +04:00
|
|
|
if contains_glob(p): break
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
root.append(p)
|
2005-08-13 03:06:52 +04:00
|
|
|
return '/'.join(root)
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
|
2005-08-08 00:43:11 +04:00
|
|
|
pats = []
|
|
|
|
files = []
|
|
|
|
roots = []
|
2005-10-19 11:02:41 +04:00
|
|
|
for kind, name in [patkind(p, dflt_pat) for p in names]:
|
2005-08-08 00:43:11 +04:00
|
|
|
if kind in ('glob', 'relpath'):
|
2005-08-27 10:29:10 +04:00
|
|
|
name = canonpath(canonroot, cwd, name)
|
2005-08-08 00:43:11 +04:00
|
|
|
if name == '':
|
|
|
|
kind, name = 'glob', '**'
|
2005-08-13 04:09:17 +04:00
|
|
|
if kind in ('glob', 'path', 're'):
|
|
|
|
pats.append((kind, name))
|
2005-08-08 00:43:11 +04:00
|
|
|
if kind == 'glob':
|
|
|
|
root = globprefix(name)
|
|
|
|
if root: roots.append(root)
|
|
|
|
elif kind == 'relpath':
|
2005-08-13 04:09:17 +04:00
|
|
|
files.append((kind, name))
|
2005-08-08 00:43:11 +04:00
|
|
|
roots.append(name)
|
2005-08-15 00:23:36 +04:00
|
|
|
|
Clean up walk and changes code to use normalised names properly.
New function: commands.pathto returns the relative path from one path
to another. For example, given foo/bar and baz/quux, it will return
../../baz/quux. This new function is used by the walk and status code
to print relative paths correctly.
New command: debugwalk exercises the walk code without doing anything
more.
hg.dirstate.walk now yields normalised names. For example, if you're
in the baz directory and you ask it to walk ../foo/bar/.., it will yield
names starting with foo/.
As a result of this change, all of the other walk and changes methods
in this module also return normalised names.
The util.matcher function now normalises globs and path names, so that
it will match normalised names properly.
Finally, util.matcher uses the non-glob prefix of a glob to tell walk
which directories to scan. Perviously, a glob like foo/* would scan
everything, but only return matches for foo/*. Now, foo/* only scans
under foo (using the globprefix function), which is much faster.
2005-08-01 05:42:46 +04:00
|
|
|
patmatch = matchfn(pats, '$') or always
|
|
|
|
filematch = matchfn(files, '(?:/|$)') or always
|
2005-08-15 00:23:36 +04:00
|
|
|
incmatch = always
|
|
|
|
if inc:
|
|
|
|
incmatch = matchfn(map(patkind, inc), '(?:/|$)')
|
|
|
|
excmatch = lambda fn: False
|
|
|
|
if exc:
|
|
|
|
excmatch = matchfn(map(patkind, exc), '(?:/|$)')
|
2005-07-21 21:21:33 +04:00
|
|
|
|
2005-08-24 23:39:10 +04:00
|
|
|
return (roots,
|
|
|
|
lambda fn: (incmatch(fn) and not excmatch(fn) and
|
|
|
|
(fn.endswith('/') or
|
|
|
|
(not pats and not files) or
|
|
|
|
(pats and patmatch(fn)) or
|
|
|
|
(files and filematch(fn)))),
|
|
|
|
(inc or exc or (pats and pats != [('glob', '**')])) and True)
|
2005-07-21 21:21:33 +04:00
|
|
|
|
2006-03-11 09:42:59 +03:00
|
|
|
def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
|
2006-03-11 09:24:19 +03:00
|
|
|
'''enhanced shell command execution.
|
2006-03-11 09:42:59 +03:00
|
|
|
run with environment maybe modified, maybe in different dir.
|
|
|
|
|
|
|
|
if command fails and onerr is None, return status. if ui object,
|
|
|
|
print error message and return status, else raise onerr object as
|
|
|
|
exception.'''
|
2006-03-11 09:24:19 +03:00
|
|
|
oldenv = {}
|
|
|
|
for k in environ:
|
|
|
|
oldenv[k] = os.environ.get(k)
|
|
|
|
if cwd is not None:
|
|
|
|
oldcwd = os.getcwd()
|
|
|
|
try:
|
|
|
|
for k, v in environ.iteritems():
|
|
|
|
os.environ[k] = str(v)
|
|
|
|
if cwd is not None and oldcwd != cwd:
|
|
|
|
os.chdir(cwd)
|
2006-03-11 09:42:59 +03:00
|
|
|
rc = os.system(cmd)
|
|
|
|
if rc and onerr:
|
|
|
|
errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
|
|
|
|
explain_exit(rc)[0])
|
|
|
|
if errprefix:
|
|
|
|
errmsg = '%s: %s' % (errprefix, errmsg)
|
|
|
|
try:
|
|
|
|
onerr.warn(errmsg + '\n')
|
|
|
|
except AttributeError:
|
|
|
|
raise onerr(errmsg)
|
|
|
|
return rc
|
2006-03-11 09:24:19 +03:00
|
|
|
finally:
|
|
|
|
for k, v in oldenv.iteritems():
|
|
|
|
if v is None:
|
|
|
|
del os.environ[k]
|
|
|
|
else:
|
|
|
|
os.environ[k] = v
|
|
|
|
if cwd is not None and oldcwd != cwd:
|
|
|
|
os.chdir(oldcwd)
|
2005-06-28 14:38:33 +04:00
|
|
|
|
2005-06-22 07:36:35 +04:00
|
|
|
def rename(src, dst):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""forcibly rename a file"""
|
2005-06-22 07:36:35 +04:00
|
|
|
try:
|
|
|
|
os.rename(src, dst)
|
|
|
|
except:
|
|
|
|
os.unlink(dst)
|
|
|
|
os.rename(src, dst)
|
|
|
|
|
2005-10-19 11:10:52 +04:00
|
|
|
def unlink(f):
|
|
|
|
"""unlink and remove the directory if it is empty"""
|
|
|
|
os.unlink(f)
|
|
|
|
# try removing directories that might now be empty
|
|
|
|
try: os.removedirs(os.path.dirname(f))
|
|
|
|
except: pass
|
|
|
|
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
def copyfiles(src, dst, hardlink=None):
|
|
|
|
"""Copy a directory tree using hardlinks if possible"""
|
|
|
|
|
|
|
|
if hardlink is None:
|
|
|
|
hardlink = (os.stat(src).st_dev ==
|
|
|
|
os.stat(os.path.dirname(dst)).st_dev)
|
2005-09-08 06:21:38 +04:00
|
|
|
|
|
|
|
if os.path.isdir(src):
|
|
|
|
os.mkdir(dst)
|
|
|
|
for name in os.listdir(src):
|
|
|
|
srcname = os.path.join(src, name)
|
|
|
|
dstname = os.path.join(dst, name)
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
copyfiles(srcname, dstname, hardlink)
|
2005-09-08 06:21:38 +04:00
|
|
|
else:
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
if hardlink:
|
|
|
|
try:
|
|
|
|
os_link(src, dst)
|
2006-04-06 04:17:07 +04:00
|
|
|
except (IOError, OSError):
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
hardlink = False
|
2005-12-16 10:32:44 +03:00
|
|
|
shutil.copy(src, dst)
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
else:
|
2005-12-16 10:32:44 +03:00
|
|
|
shutil.copy(src, dst)
|
2005-07-14 18:30:49 +04:00
|
|
|
|
2006-03-04 21:01:45 +03:00
|
|
|
def audit_path(path):
|
|
|
|
"""Abort if path contains dangerous components"""
|
|
|
|
parts = os.path.normcase(path).split(os.sep)
|
|
|
|
if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
|
|
|
|
or os.pardir in parts):
|
|
|
|
raise Abort(_("path contains illegal component: %s\n") % path)
|
|
|
|
|
|
|
|
def opener(base, audit=True):
|
2005-08-28 01:31:41 +04:00
|
|
|
"""
|
|
|
|
return a function that opens files relative to base
|
|
|
|
|
|
|
|
this function is used to hide the details of COW semantics and
|
|
|
|
remote file access from higher level code.
|
|
|
|
"""
|
|
|
|
p = base
|
2006-03-04 21:01:45 +03:00
|
|
|
audit_p = audit
|
2005-11-12 02:33:59 +03:00
|
|
|
|
|
|
|
def mktempcopy(name):
|
|
|
|
d, fn = os.path.split(name)
|
|
|
|
fd, temp = tempfile.mkstemp(prefix=fn, dir=d)
|
|
|
|
fp = os.fdopen(fd, "wb")
|
|
|
|
try:
|
|
|
|
fp.write(file(name, "rb").read())
|
|
|
|
except:
|
|
|
|
try: os.unlink(temp)
|
|
|
|
except: pass
|
|
|
|
raise
|
|
|
|
fp.close()
|
|
|
|
st = os.lstat(name)
|
|
|
|
os.chmod(temp, st.st_mode)
|
|
|
|
return temp
|
|
|
|
|
|
|
|
class atomicfile(file):
|
|
|
|
"""the file will only be copied on close"""
|
|
|
|
def __init__(self, name, mode, atomic=False):
|
|
|
|
self.__name = name
|
|
|
|
self.temp = mktempcopy(name)
|
|
|
|
file.__init__(self, self.temp, mode)
|
|
|
|
def close(self):
|
|
|
|
if not self.closed:
|
2005-11-14 23:47:07 +03:00
|
|
|
file.close(self)
|
2005-11-12 02:33:59 +03:00
|
|
|
rename(self.temp, self.__name)
|
|
|
|
def __del__(self):
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
def o(path, mode="r", text=False, atomic=False):
|
2006-03-04 21:01:45 +03:00
|
|
|
if audit_p:
|
|
|
|
audit_path(path)
|
2005-08-28 01:31:41 +04:00
|
|
|
f = os.path.join(p, path)
|
|
|
|
|
2005-09-23 21:28:55 +04:00
|
|
|
if not text:
|
|
|
|
mode += "b" # for that other OS
|
2005-08-28 01:31:41 +04:00
|
|
|
|
|
|
|
if mode[0] != "r":
|
|
|
|
try:
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
nlink = nlinks(f)
|
2005-08-28 01:31:41 +04:00
|
|
|
except OSError:
|
|
|
|
d = os.path.dirname(f)
|
|
|
|
if not os.path.isdir(d):
|
|
|
|
os.makedirs(d)
|
|
|
|
else:
|
2005-11-12 02:33:59 +03:00
|
|
|
if atomic:
|
|
|
|
return atomicfile(f, mode)
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
if nlink > 1:
|
2005-11-12 02:33:59 +03:00
|
|
|
rename(mktempcopy(f), f)
|
2005-08-28 01:31:41 +04:00
|
|
|
return file(f, mode)
|
|
|
|
|
|
|
|
return o
|
|
|
|
|
2005-07-15 01:51:47 +04:00
|
|
|
def _makelock_file(info, pathname):
|
|
|
|
ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
|
|
|
|
os.write(ld, info)
|
|
|
|
os.close(ld)
|
|
|
|
|
|
|
|
def _readlock_file(pathname):
|
|
|
|
return file(pathname).read()
|
|
|
|
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
def nlinks(pathname):
|
|
|
|
"""Return number of hardlinks for the given file."""
|
|
|
|
return os.stat(pathname).st_nlink
|
|
|
|
|
|
|
|
if hasattr(os, 'link'):
|
|
|
|
os_link = os.link
|
|
|
|
else:
|
|
|
|
def os_link(src, dst):
|
2005-10-19 05:38:39 +04:00
|
|
|
raise OSError(0, _("Hardlinks not supported"))
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
|
2005-08-27 12:13:28 +04:00
|
|
|
# Platform specific variants
|
2005-06-22 07:31:13 +04:00
|
|
|
if os.name == 'nt':
|
2005-10-25 01:34:48 +04:00
|
|
|
demandload(globals(), "msvcrt")
|
2005-06-25 10:58:14 +04:00
|
|
|
nulldev = 'NUL:'
|
2006-01-03 02:25:33 +03:00
|
|
|
|
|
|
|
class winstdout:
|
|
|
|
'''stdout on windows misbehaves if sent through a pipe'''
|
|
|
|
|
|
|
|
def __init__(self, fp):
|
|
|
|
self.fp = fp
|
|
|
|
|
|
|
|
def __getattr__(self, key):
|
|
|
|
return getattr(self.fp, key)
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
try:
|
|
|
|
self.fp.close()
|
|
|
|
except: pass
|
|
|
|
|
|
|
|
def write(self, s):
|
|
|
|
try:
|
|
|
|
return self.fp.write(s)
|
|
|
|
except IOError, inst:
|
|
|
|
if inst.errno != 0: raise
|
|
|
|
self.close()
|
|
|
|
raise IOError(errno.EPIPE, 'Broken pipe')
|
|
|
|
|
|
|
|
sys.stdout = winstdout(sys.stdout)
|
|
|
|
|
2006-03-15 08:40:46 +03:00
|
|
|
def os_rcpath():
|
|
|
|
'''return default os-specific hgrc search path'''
|
|
|
|
try:
|
|
|
|
import win32api, win32process
|
|
|
|
proc = win32api.GetCurrentProcess()
|
|
|
|
filename = win32process.GetModuleFileNameEx(proc, 0)
|
|
|
|
systemrc = os.path.join(os.path.dirname(filename), 'mercurial.ini')
|
|
|
|
except ImportError:
|
|
|
|
systemrc = r'c:\mercurial\mercurial.ini'
|
2005-10-19 04:57:27 +04:00
|
|
|
|
2006-03-15 08:40:46 +03:00
|
|
|
return [systemrc,
|
|
|
|
os.path.join(os.path.expanduser('~'), 'mercurial.ini')]
|
2005-09-21 20:56:30 +04:00
|
|
|
|
2005-09-21 08:35:51 +04:00
|
|
|
def parse_patch_output(output_line):
|
|
|
|
"""parses the output produced by patch and returns the file name"""
|
|
|
|
pf = output_line[14:]
|
|
|
|
if pf[0] == '`':
|
|
|
|
pf = pf[1:-1] # Remove the quotes
|
|
|
|
return pf
|
|
|
|
|
2006-03-31 06:20:08 +04:00
|
|
|
try: # Mark Hammond's win32all package allows better functionality on Windows
|
2006-03-31 06:35:52 +04:00
|
|
|
import win32api, win32con, win32file, pywintypes
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
|
2006-03-31 06:20:08 +04:00
|
|
|
# create hard links using win32file module
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
def os_link(src, dst): # NB will only succeed on NTFS
|
|
|
|
win32file.CreateHardLink(dst, src)
|
|
|
|
|
|
|
|
def nlinks(pathname):
|
|
|
|
"""Return number of hardlinks for the given file."""
|
|
|
|
try:
|
|
|
|
fh = win32file.CreateFile(pathname,
|
|
|
|
win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
|
|
|
|
None, win32file.OPEN_EXISTING, 0, None)
|
|
|
|
res = win32file.GetFileInformationByHandle(fh)
|
|
|
|
fh.Close()
|
|
|
|
return res[7]
|
|
|
|
except:
|
|
|
|
return os.stat(pathname).st_nlink
|
|
|
|
|
2006-03-10 19:31:31 +03:00
|
|
|
def testpid(pid):
|
2006-03-31 06:27:04 +04:00
|
|
|
'''return True if pid is still running or unable to
|
|
|
|
determine, False otherwise'''
|
2006-03-10 19:31:31 +03:00
|
|
|
try:
|
2006-03-31 06:35:52 +04:00
|
|
|
import win32process, winerror
|
2006-03-31 06:27:04 +04:00
|
|
|
handle = win32api.OpenProcess(
|
|
|
|
win32con.PROCESS_QUERY_INFORMATION, False, pid)
|
2006-03-31 06:20:08 +04:00
|
|
|
if handle:
|
|
|
|
status = win32process.GetExitCodeProcess(handle)
|
2006-03-31 06:27:04 +04:00
|
|
|
return status == win32con.STILL_ACTIVE
|
2006-03-31 06:20:08 +04:00
|
|
|
except pywintypes.error, details:
|
2006-03-31 06:27:04 +04:00
|
|
|
return details[0] != winerror.ERROR_INVALID_PARAMETER
|
2006-03-31 06:20:08 +04:00
|
|
|
return True
|
2006-03-10 19:31:31 +03:00
|
|
|
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
except ImportError:
|
2006-03-10 19:31:31 +03:00
|
|
|
def testpid(pid):
|
|
|
|
'''return False if pid dead, True if running or not known'''
|
|
|
|
return True
|
Add support for cloning with hardlinks on windows.
In order to use hardlinks, the win32file module is needed, and this is
present in ActivePython. If it isn't present, or hardlinks are not supported
on the underlying filesystem, a regular copy is used.
When using hardlinks the biggest benefit is probably the saving in space,
but cloning can be much quicker. For example cloning the Xen tree
(non trivial) without an update goes from about 95s to 15s.
Unix-like platforms should be unaffected, although should be more tolerant on
filesystems that don't support hard links.
(tweaked by mpm to deal with new copyfiles function)
--- hg.orig/mercurial/commands.py 2005-09-13 19:32:53.000000000 -0500
+++ hg/mercurial/commands.py 2005-09-14 12:11:34.000000000 -0500
@@ -620,10 +620,6 @@ def clone(ui, source, dest=None, **opts)
if other.dev() != -1:
abspath = os.path.abspath(source)
- copyfile = (os.stat(dest).st_dev == other.dev()
- and getattr(os, 'link', None) or shutil.copy2)
- if copyfile is not shutil.copy2:
- ui.note("cloning by hardlink\n")
# we use a lock here because if we race with commit, we can
# end up with extra data in the cloned revlogs that's not
@@ -638,7 +634,7 @@ def clone(ui, source, dest=None, **opts)
for f in files.split():
src = os.path.join(source, ".hg", f)
dst = os.path.join(dest, ".hg", f)
- util.copyfiles(src, dst, copyfile)
+ util.copyfiles(src, dst)
repo = hg.repository(ui, dest)
Index: hg/mercurial/util.py
===================================================================
--- hg.orig/mercurial/util.py 2005-09-08 00:15:25.000000000 -0500
+++ hg/mercurial/util.py 2005-09-14 12:16:49.000000000 -0500
@@ -12,7 +12,7 @@ platform-specific details from the core.
import os, errno
from demandload import *
-demandload(globals(), "re cStringIO")
+demandload(globals(), "re cStringIO shutil")
def binary(s):
"""return true if a string is binary data using diff's heuristic"""
@@ -217,17 +217,28 @@ def rename(src, dst):
os.unlink(dst)
os.rename(src, dst)
-def copyfiles(src, dst, copyfile):
- """Copy a directory tree, files are copied using 'copyfile'."""
+def copyfiles(src, dst, hardlink=None):
+ """Copy a directory tree using hardlinks if possible"""
+
+ if hardlink is None:
+ hardlink = (os.stat(src).st_dev ==
+ os.stat(os.path.dirname(dst)).st_dev)
if os.path.isdir(src):
os.mkdir(dst)
for name in os.listdir(src):
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
- copyfiles(srcname, dstname, copyfile)
+ copyfiles(srcname, dstname, hardlink)
else:
- copyfile(src, dst)
+ if hardlink:
+ try:
+ os_link(src, dst)
+ except:
+ hardlink = False
+ shutil.copy2(src, dst)
+ else:
+ shutil.copy2(src, dst)
def opener(base):
"""
@@ -244,13 +255,13 @@ def opener(base):
if mode[0] != "r":
try:
- s = os.stat(f)
+ nlink = nlinks(f)
except OSError:
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
else:
- if s.st_nlink > 1:
+ if nlink > 1:
file(f + ".tmp", "wb").write(file(f, "rb").read())
rename(f+".tmp", f)
@@ -266,10 +277,41 @@ def _makelock_file(info, pathname):
def _readlock_file(pathname):
return file(pathname).read()
+def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ return os.stat(pathname).st_nlink
+
+if hasattr(os, 'link'):
+ os_link = os.link
+else:
+ def os_link(src, dst):
+ raise OSError(0, "Hardlinks not supported")
+
# Platform specific variants
if os.name == 'nt':
nulldev = 'NUL:'
+ try: # ActivePython can create hard links using win32file module
+ import win32file
+
+ def os_link(src, dst): # NB will only succeed on NTFS
+ win32file.CreateHardLink(dst, src)
+
+ def nlinks(pathname):
+ """Return number of hardlinks for the given file."""
+ try:
+ fh = win32file.CreateFile(pathname,
+ win32file.GENERIC_READ, win32file.FILE_SHARE_READ,
+ None, win32file.OPEN_EXISTING, 0, None)
+ res = win32file.GetFileInformationByHandle(fh)
+ fh.Close()
+ return res[7]
+ except:
+ return os.stat(pathname).st_nlink
+
+ except ImportError:
+ pass
+
def is_exec(f, last):
return last
2005-09-14 21:22:20 +04:00
|
|
|
|
2005-06-23 21:33:18 +04:00
|
|
|
def is_exec(f, last):
|
|
|
|
return last
|
|
|
|
|
|
|
|
def set_exec(f, mode):
|
|
|
|
pass
|
2005-06-29 22:42:35 +04:00
|
|
|
|
2005-10-25 01:34:48 +04:00
|
|
|
def set_binary(fd):
|
|
|
|
msvcrt.setmode(fd.fileno(), os.O_BINARY)
|
|
|
|
|
2005-06-22 07:31:13 +04:00
|
|
|
def pconvert(path):
|
|
|
|
return path.replace("\\", "/")
|
2005-06-22 07:43:40 +04:00
|
|
|
|
2005-08-13 03:06:52 +04:00
|
|
|
def localpath(path):
|
|
|
|
return path.replace('/', '\\')
|
|
|
|
|
|
|
|
def normpath(path):
|
|
|
|
return pconvert(os.path.normpath(path))
|
|
|
|
|
2005-07-15 01:51:47 +04:00
|
|
|
makelock = _makelock_file
|
|
|
|
readlock = _readlock_file
|
2005-06-25 10:58:14 +04:00
|
|
|
|
2005-07-27 22:18:22 +04:00
|
|
|
def explain_exit(code):
|
2005-10-19 05:38:39 +04:00
|
|
|
return _("exited with status %d") % code, code
|
2005-07-27 22:18:22 +04:00
|
|
|
|
2005-06-22 07:31:13 +04:00
|
|
|
else:
|
2005-06-25 10:58:14 +04:00
|
|
|
nulldev = '/dev/null'
|
|
|
|
|
2005-11-04 22:51:01 +03:00
|
|
|
def rcfiles(path):
|
|
|
|
rcs = [os.path.join(path, 'hgrc')]
|
|
|
|
rcdir = os.path.join(path, 'hgrc.d')
|
|
|
|
try:
|
|
|
|
rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
|
|
|
|
if f.endswith(".rc")])
|
|
|
|
except OSError, inst: pass
|
|
|
|
return rcs
|
2006-03-15 08:40:46 +03:00
|
|
|
|
|
|
|
def os_rcpath():
|
|
|
|
'''return default os-specific hgrc search path'''
|
|
|
|
path = []
|
|
|
|
if len(sys.argv) > 0:
|
|
|
|
path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
|
|
|
|
'/../etc/mercurial'))
|
|
|
|
path.extend(rcfiles('/etc/mercurial'))
|
|
|
|
path.append(os.path.expanduser('~/.hgrc'))
|
|
|
|
path = [os.path.normpath(f) for f in path]
|
|
|
|
return path
|
2005-09-21 20:56:30 +04:00
|
|
|
|
2005-09-21 08:35:51 +04:00
|
|
|
def parse_patch_output(output_line):
|
|
|
|
"""parses the output produced by patch and returns the file name"""
|
2005-12-15 19:50:10 +03:00
|
|
|
pf = output_line[14:]
|
|
|
|
if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
|
|
|
|
pf = pf[1:-1] # Remove the quotes
|
|
|
|
return pf
|
2005-09-21 08:35:51 +04:00
|
|
|
|
2005-06-23 21:33:18 +04:00
|
|
|
def is_exec(f, last):
|
2005-08-27 12:13:28 +04:00
|
|
|
"""check whether a file is executable"""
|
2005-06-23 21:33:18 +04:00
|
|
|
return (os.stat(f).st_mode & 0100 != 0)
|
|
|
|
|
|
|
|
def set_exec(f, mode):
|
|
|
|
s = os.stat(f).st_mode
|
|
|
|
if (s & 0100 != 0) == mode:
|
|
|
|
return
|
|
|
|
if mode:
|
|
|
|
# Turn on +x for every +r bit when making a file executable
|
|
|
|
# and obey umask.
|
|
|
|
umask = os.umask(0)
|
|
|
|
os.umask(umask)
|
|
|
|
os.chmod(f, s | (s & 0444) >> 2 & ~umask)
|
|
|
|
else:
|
|
|
|
os.chmod(f, s & 0666)
|
|
|
|
|
2005-10-25 01:34:48 +04:00
|
|
|
def set_binary(fd):
|
|
|
|
pass
|
|
|
|
|
2005-06-22 07:31:13 +04:00
|
|
|
def pconvert(path):
|
|
|
|
return path
|
|
|
|
|
2005-08-13 03:06:52 +04:00
|
|
|
def localpath(path):
|
|
|
|
return path
|
|
|
|
|
|
|
|
normpath = os.path.normpath
|
|
|
|
|
2005-06-22 07:43:40 +04:00
|
|
|
def makelock(info, pathname):
|
2005-07-15 01:51:47 +04:00
|
|
|
try:
|
|
|
|
os.symlink(info, pathname)
|
|
|
|
except OSError, why:
|
|
|
|
if why.errno == errno.EEXIST:
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
_makelock_file(info, pathname)
|
2005-06-22 07:43:40 +04:00
|
|
|
|
|
|
|
def readlock(pathname):
|
2005-07-15 01:51:47 +04:00
|
|
|
try:
|
|
|
|
return os.readlink(pathname)
|
|
|
|
except OSError, why:
|
|
|
|
if why.errno == errno.EINVAL:
|
|
|
|
return _readlock_file(pathname)
|
|
|
|
else:
|
|
|
|
raise
|
2005-07-27 22:18:22 +04:00
|
|
|
|
2006-03-10 19:31:31 +03:00
|
|
|
def testpid(pid):
|
|
|
|
'''return False if pid dead, True if running or not sure'''
|
|
|
|
try:
|
|
|
|
os.kill(pid, 0)
|
|
|
|
return True
|
|
|
|
except OSError, inst:
|
|
|
|
return inst.errno != errno.ESRCH
|
|
|
|
|
2005-07-27 22:18:22 +04:00
|
|
|
def explain_exit(code):
|
|
|
|
"""return a 2-tuple (desc, code) describing a process's status"""
|
|
|
|
if os.WIFEXITED(code):
|
|
|
|
val = os.WEXITSTATUS(code)
|
2005-10-19 05:38:39 +04:00
|
|
|
return _("exited with status %d") % val, val
|
2005-07-27 22:18:22 +04:00
|
|
|
elif os.WIFSIGNALED(code):
|
|
|
|
val = os.WTERMSIG(code)
|
2005-10-19 05:38:39 +04:00
|
|
|
return _("killed by signal %d") % val, val
|
2005-07-27 22:18:22 +04:00
|
|
|
elif os.WIFSTOPPED(code):
|
2005-08-15 23:46:41 +04:00
|
|
|
val = os.WSTOPSIG(code)
|
2005-10-19 05:38:39 +04:00
|
|
|
return _("stopped by signal %d") % val, val
|
|
|
|
raise ValueError(_("invalid exit code"))
|
2005-09-05 01:11:51 +04:00
|
|
|
|
|
|
|
class chunkbuffer(object):
|
|
|
|
"""Allow arbitrary sized chunks of data to be efficiently read from an
|
|
|
|
iterator over chunks of arbitrary size."""
|
2005-09-05 01:21:53 +04:00
|
|
|
|
2005-09-05 01:11:51 +04:00
|
|
|
def __init__(self, in_iter, targetsize = 2**16):
|
|
|
|
"""in_iter is the iterator that's iterating over the input chunks.
|
|
|
|
targetsize is how big a buffer to try to maintain."""
|
|
|
|
self.in_iter = iter(in_iter)
|
|
|
|
self.buf = ''
|
|
|
|
self.targetsize = int(targetsize)
|
2005-09-05 01:21:53 +04:00
|
|
|
if self.targetsize <= 0:
|
2005-10-19 05:38:39 +04:00
|
|
|
raise ValueError(_("targetsize must be greater than 0, was %d") %
|
2005-09-05 01:21:53 +04:00
|
|
|
targetsize)
|
2005-09-05 01:11:51 +04:00
|
|
|
self.iterempty = False
|
|
|
|
|
2005-09-05 01:21:53 +04:00
|
|
|
def fillbuf(self):
|
|
|
|
"""Ignore target size; read every chunk from iterator until empty."""
|
2005-09-05 01:11:51 +04:00
|
|
|
if not self.iterempty:
|
|
|
|
collector = cStringIO.StringIO()
|
|
|
|
collector.write(self.buf)
|
|
|
|
for ch in self.in_iter:
|
|
|
|
collector.write(ch)
|
|
|
|
self.buf = collector.getvalue()
|
|
|
|
self.iterempty = True
|
|
|
|
|
|
|
|
def read(self, l):
|
2005-09-05 01:21:53 +04:00
|
|
|
"""Read L bytes of data from the iterator of chunks of data.
|
2005-09-21 09:56:19 +04:00
|
|
|
Returns less than L bytes if the iterator runs dry."""
|
2005-09-05 01:11:51 +04:00
|
|
|
if l > len(self.buf) and not self.iterempty:
|
|
|
|
# Clamp to a multiple of self.targetsize
|
|
|
|
targetsize = self.targetsize * ((l // self.targetsize) + 1)
|
|
|
|
collector = cStringIO.StringIO()
|
|
|
|
collector.write(self.buf)
|
|
|
|
collected = len(self.buf)
|
|
|
|
for chunk in self.in_iter:
|
|
|
|
collector.write(chunk)
|
|
|
|
collected += len(chunk)
|
|
|
|
if collected >= targetsize:
|
|
|
|
break
|
|
|
|
if collected < targetsize:
|
|
|
|
self.iterempty = True
|
|
|
|
self.buf = collector.getvalue()
|
2005-09-05 01:21:53 +04:00
|
|
|
s, self.buf = self.buf[:l], buffer(self.buf, l)
|
2005-09-05 01:11:51 +04:00
|
|
|
return s
|
|
|
|
|
|
|
|
def filechunkiter(f, size = 65536):
|
2005-09-05 01:21:53 +04:00
|
|
|
"""Create a generator that produces all the data in the file size
|
|
|
|
(default 65536) bytes at a time. Chunks may be less than size
|
|
|
|
bytes if the chunk is the last chunk in the file, or the file is a
|
|
|
|
socket or some other type of file that sometimes reads less data
|
|
|
|
than is requested."""
|
2005-09-05 01:11:51 +04:00
|
|
|
s = f.read(size)
|
2005-10-04 03:07:54 +04:00
|
|
|
while len(s) > 0:
|
2005-09-05 01:11:51 +04:00
|
|
|
yield s
|
|
|
|
s = f.read(size)
|
2005-09-23 09:46:50 +04:00
|
|
|
|
2005-09-23 10:19:47 +04:00
|
|
|
def makedate():
|
2005-10-31 20:56:42 +03:00
|
|
|
lt = time.localtime()
|
|
|
|
if lt[8] == 1 and time.daylight:
|
|
|
|
tz = time.altzone
|
|
|
|
else:
|
|
|
|
tz = time.timezone
|
|
|
|
return time.mktime(lt), tz
|
2005-09-23 21:28:55 +04:00
|
|
|
|
2006-03-22 10:29:21 +03:00
|
|
|
def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
|
2005-09-23 10:19:47 +04:00
|
|
|
"""represent a (unixtime, offset) tuple as a localized time.
|
|
|
|
unixtime is seconds since the epoch, and offset is the time zone's
|
2006-03-22 10:29:21 +03:00
|
|
|
number of seconds away from UTC. if timezone is false, do not
|
|
|
|
append time zone to string."""
|
2005-09-23 10:19:47 +04:00
|
|
|
t, tz = date or makedate()
|
2006-03-22 10:29:21 +03:00
|
|
|
s = time.strftime(format, time.gmtime(float(t) - tz))
|
|
|
|
if timezone:
|
|
|
|
s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
|
|
|
|
return s
|
2006-02-27 22:32:10 +03:00
|
|
|
|
|
|
|
def shortuser(user):
|
|
|
|
"""Return a short representation of a user name or email address."""
|
|
|
|
f = user.find('@')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[:f]
|
|
|
|
f = user.find('<')
|
|
|
|
if f >= 0:
|
|
|
|
user = user[f+1:]
|
|
|
|
return user
|
2006-03-13 03:21:59 +03:00
|
|
|
|
2006-02-10 22:25:07 +03:00
|
|
|
def walkrepos(path):
|
|
|
|
'''yield every hg repository under path, recursively.'''
|
|
|
|
def errhandler(err):
|
|
|
|
if err.filename == path:
|
|
|
|
raise err
|
|
|
|
|
|
|
|
for root, dirs, files in os.walk(path, onerror=errhandler):
|
|
|
|
for d in dirs:
|
|
|
|
if d == '.hg':
|
|
|
|
yield root
|
|
|
|
dirs[:] = []
|
|
|
|
break
|
2006-03-15 08:40:46 +03:00
|
|
|
|
|
|
|
_rcpath = None
|
|
|
|
|
|
|
|
def rcpath():
|
|
|
|
'''return hgrc search path. if env var HGRCPATH is set, use it.
|
|
|
|
for each item in path, if directory, use files ending in .rc,
|
|
|
|
else use item.
|
|
|
|
make HGRCPATH empty to only look in .hg/hgrc of current repo.
|
|
|
|
if no HGRCPATH, use default os-specific path.'''
|
|
|
|
global _rcpath
|
|
|
|
if _rcpath is None:
|
|
|
|
if 'HGRCPATH' in os.environ:
|
|
|
|
_rcpath = []
|
|
|
|
for p in os.environ['HGRCPATH'].split(os.pathsep):
|
|
|
|
if not p: continue
|
2006-03-15 09:09:42 +03:00
|
|
|
if os.path.isdir(p):
|
2006-03-15 08:40:46 +03:00
|
|
|
for f in os.listdir(p):
|
|
|
|
if f.endswith('.rc'):
|
|
|
|
_rcpath.append(os.path.join(p, f))
|
2006-03-15 09:09:42 +03:00
|
|
|
else:
|
|
|
|
_rcpath.append(p)
|
2006-03-15 08:40:46 +03:00
|
|
|
else:
|
|
|
|
_rcpath = os_rcpath()
|
|
|
|
return _rcpath
|