##// END OF EJS Templates
merge with crew.
Vadim Gelfer -
r2194:ee90e5a9 merge default
parent child Browse files
Show More
@@ -1,868 +1,872 b''
1 """
1 """
2 util.py - Mercurial utility functions and platform specfic implementations
2 util.py - Mercurial utility functions and platform specfic implementations
3
3
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
5
5
6 This software may be used and distributed according to the terms
6 This software may be used and distributed according to the terms
7 of the GNU General Public License, incorporated herein by reference.
7 of the GNU General Public License, incorporated herein by reference.
8
8
9 This contains helper routines that are independent of the SCM core and hide
9 This contains helper routines that are independent of the SCM core and hide
10 platform-specific details from the core.
10 platform-specific details from the core.
11 """
11 """
12
12
13 import os, errno
13 import os, errno
14 from i18n import gettext as _
14 from i18n import gettext as _
15 from demandload import *
15 from demandload import *
16 demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
16 demandload(globals(), "cStringIO errno popen2 re shutil sys tempfile")
17 demandload(globals(), "threading time")
17 demandload(globals(), "threading time")
18
18
19 class SignalInterrupt(Exception):
19 class SignalInterrupt(Exception):
20 """Exception raised on SIGTERM and SIGHUP."""
20 """Exception raised on SIGTERM and SIGHUP."""
21
21
22 def pipefilter(s, cmd):
22 def pipefilter(s, cmd):
23 '''filter string S through command CMD, returning its output'''
23 '''filter string S through command CMD, returning its output'''
24 (pout, pin) = popen2.popen2(cmd, -1, 'b')
24 (pout, pin) = popen2.popen2(cmd, -1, 'b')
25 def writer():
25 def writer():
26 try:
26 try:
27 pin.write(s)
27 pin.write(s)
28 pin.close()
28 pin.close()
29 except IOError, inst:
29 except IOError, inst:
30 if inst.errno != errno.EPIPE:
30 if inst.errno != errno.EPIPE:
31 raise
31 raise
32
32
33 # we should use select instead on UNIX, but this will work on most
33 # we should use select instead on UNIX, but this will work on most
34 # systems, including Windows
34 # systems, including Windows
35 w = threading.Thread(target=writer)
35 w = threading.Thread(target=writer)
36 w.start()
36 w.start()
37 f = pout.read()
37 f = pout.read()
38 pout.close()
38 pout.close()
39 w.join()
39 w.join()
40 return f
40 return f
41
41
42 def tempfilter(s, cmd):
42 def tempfilter(s, cmd):
43 '''filter string S through a pair of temporary files with CMD.
43 '''filter string S through a pair of temporary files with CMD.
44 CMD is used as a template to create the real command to be run,
44 CMD is used as a template to create the real command to be run,
45 with the strings INFILE and OUTFILE replaced by the real names of
45 with the strings INFILE and OUTFILE replaced by the real names of
46 the temporary files generated.'''
46 the temporary files generated.'''
47 inname, outname = None, None
47 inname, outname = None, None
48 try:
48 try:
49 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
49 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
50 fp = os.fdopen(infd, 'wb')
50 fp = os.fdopen(infd, 'wb')
51 fp.write(s)
51 fp.write(s)
52 fp.close()
52 fp.close()
53 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
53 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
54 os.close(outfd)
54 os.close(outfd)
55 cmd = cmd.replace('INFILE', inname)
55 cmd = cmd.replace('INFILE', inname)
56 cmd = cmd.replace('OUTFILE', outname)
56 cmd = cmd.replace('OUTFILE', outname)
57 code = os.system(cmd)
57 code = os.system(cmd)
58 if code: raise Abort(_("command '%s' failed: %s") %
58 if code: raise Abort(_("command '%s' failed: %s") %
59 (cmd, explain_exit(code)))
59 (cmd, explain_exit(code)))
60 return open(outname, 'rb').read()
60 return open(outname, 'rb').read()
61 finally:
61 finally:
62 try:
62 try:
63 if inname: os.unlink(inname)
63 if inname: os.unlink(inname)
64 except: pass
64 except: pass
65 try:
65 try:
66 if outname: os.unlink(outname)
66 if outname: os.unlink(outname)
67 except: pass
67 except: pass
68
68
69 filtertable = {
69 filtertable = {
70 'tempfile:': tempfilter,
70 'tempfile:': tempfilter,
71 'pipe:': pipefilter,
71 'pipe:': pipefilter,
72 }
72 }
73
73
74 def filter(s, cmd):
74 def filter(s, cmd):
75 "filter a string through a command that transforms its input to its output"
75 "filter a string through a command that transforms its input to its output"
76 for name, fn in filtertable.iteritems():
76 for name, fn in filtertable.iteritems():
77 if cmd.startswith(name):
77 if cmd.startswith(name):
78 return fn(s, cmd[len(name):].lstrip())
78 return fn(s, cmd[len(name):].lstrip())
79 return pipefilter(s, cmd)
79 return pipefilter(s, cmd)
80
80
81 def find_in_path(name, path, default=None):
81 def find_in_path(name, path, default=None):
82 '''find name in search path. path can be string (will be split
82 '''find name in search path. path can be string (will be split
83 with os.pathsep), or iterable thing that returns strings. if name
83 with os.pathsep), or iterable thing that returns strings. if name
84 found, return path to name. else return default.'''
84 found, return path to name. else return default.'''
85 if isinstance(path, str):
85 if isinstance(path, str):
86 path = path.split(os.pathsep)
86 path = path.split(os.pathsep)
87 for p in path:
87 for p in path:
88 p_name = os.path.join(p, name)
88 p_name = os.path.join(p, name)
89 if os.path.exists(p_name):
89 if os.path.exists(p_name):
90 return p_name
90 return p_name
91 return default
91 return default
92
92
93 def patch(strip, patchname, ui):
93 def patch(strip, patchname, ui):
94 """apply the patch <patchname> to the working directory.
94 """apply the patch <patchname> to the working directory.
95 a list of patched files is returned"""
95 a list of patched files is returned"""
96 patcher = find_in_path('gpatch', os.environ.get('PATH', ''), 'patch')
96 patcher = find_in_path('gpatch', os.environ.get('PATH', ''), 'patch')
97 fp = os.popen('"%s" -p%d < "%s"' % (patcher, strip, patchname))
97 fp = os.popen('"%s" -p%d < "%s"' % (patcher, strip, patchname))
98 files = {}
98 files = {}
99 for line in fp:
99 for line in fp:
100 line = line.rstrip()
100 line = line.rstrip()
101 ui.status("%s\n" % line)
101 ui.status("%s\n" % line)
102 if line.startswith('patching file '):
102 if line.startswith('patching file '):
103 pf = parse_patch_output(line)
103 pf = parse_patch_output(line)
104 files.setdefault(pf, 1)
104 files.setdefault(pf, 1)
105 code = fp.close()
105 code = fp.close()
106 if code:
106 if code:
107 raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
107 raise Abort(_("patch command failed: %s") % explain_exit(code)[0])
108 return files.keys()
108 return files.keys()
109
109
110 def binary(s):
110 def binary(s):
111 """return true if a string is binary data using diff's heuristic"""
111 """return true if a string is binary data using diff's heuristic"""
112 if s and '\0' in s[:4096]:
112 if s and '\0' in s[:4096]:
113 return True
113 return True
114 return False
114 return False
115
115
116 def unique(g):
116 def unique(g):
117 """return the uniq elements of iterable g"""
117 """return the uniq elements of iterable g"""
118 seen = {}
118 seen = {}
119 for f in g:
119 for f in g:
120 if f not in seen:
120 if f not in seen:
121 seen[f] = 1
121 seen[f] = 1
122 yield f
122 yield f
123
123
124 class Abort(Exception):
124 class Abort(Exception):
125 """Raised if a command needs to print an error and exit."""
125 """Raised if a command needs to print an error and exit."""
126
126
127 def always(fn): return True
127 def always(fn): return True
128 def never(fn): return False
128 def never(fn): return False
129
129
130 def patkind(name, dflt_pat='glob'):
130 def patkind(name, dflt_pat='glob'):
131 """Split a string into an optional pattern kind prefix and the
131 """Split a string into an optional pattern kind prefix and the
132 actual pattern."""
132 actual pattern."""
133 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
133 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
134 if name.startswith(prefix + ':'): return name.split(':', 1)
134 if name.startswith(prefix + ':'): return name.split(':', 1)
135 return dflt_pat, name
135 return dflt_pat, name
136
136
137 def globre(pat, head='^', tail='$'):
137 def globre(pat, head='^', tail='$'):
138 "convert a glob pattern into a regexp"
138 "convert a glob pattern into a regexp"
139 i, n = 0, len(pat)
139 i, n = 0, len(pat)
140 res = ''
140 res = ''
141 group = False
141 group = False
142 def peek(): return i < n and pat[i]
142 def peek(): return i < n and pat[i]
143 while i < n:
143 while i < n:
144 c = pat[i]
144 c = pat[i]
145 i = i+1
145 i = i+1
146 if c == '*':
146 if c == '*':
147 if peek() == '*':
147 if peek() == '*':
148 i += 1
148 i += 1
149 res += '.*'
149 res += '.*'
150 else:
150 else:
151 res += '[^/]*'
151 res += '[^/]*'
152 elif c == '?':
152 elif c == '?':
153 res += '.'
153 res += '.'
154 elif c == '[':
154 elif c == '[':
155 j = i
155 j = i
156 if j < n and pat[j] in '!]':
156 if j < n and pat[j] in '!]':
157 j += 1
157 j += 1
158 while j < n and pat[j] != ']':
158 while j < n and pat[j] != ']':
159 j += 1
159 j += 1
160 if j >= n:
160 if j >= n:
161 res += '\\['
161 res += '\\['
162 else:
162 else:
163 stuff = pat[i:j].replace('\\','\\\\')
163 stuff = pat[i:j].replace('\\','\\\\')
164 i = j + 1
164 i = j + 1
165 if stuff[0] == '!':
165 if stuff[0] == '!':
166 stuff = '^' + stuff[1:]
166 stuff = '^' + stuff[1:]
167 elif stuff[0] == '^':
167 elif stuff[0] == '^':
168 stuff = '\\' + stuff
168 stuff = '\\' + stuff
169 res = '%s[%s]' % (res, stuff)
169 res = '%s[%s]' % (res, stuff)
170 elif c == '{':
170 elif c == '{':
171 group = True
171 group = True
172 res += '(?:'
172 res += '(?:'
173 elif c == '}' and group:
173 elif c == '}' and group:
174 res += ')'
174 res += ')'
175 group = False
175 group = False
176 elif c == ',' and group:
176 elif c == ',' and group:
177 res += '|'
177 res += '|'
178 elif c == '\\':
178 elif c == '\\':
179 p = peek()
179 p = peek()
180 if p:
180 if p:
181 i += 1
181 i += 1
182 res += re.escape(p)
182 res += re.escape(p)
183 else:
183 else:
184 res += re.escape(c)
184 res += re.escape(c)
185 else:
185 else:
186 res += re.escape(c)
186 res += re.escape(c)
187 return head + res + tail
187 return head + res + tail
188
188
189 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
189 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
190
190
191 def pathto(n1, n2):
191 def pathto(n1, n2):
192 '''return the relative path from one place to another.
192 '''return the relative path from one place to another.
193 this returns a path in the form used by the local filesystem, not hg.'''
193 this returns a path in the form used by the local filesystem, not hg.'''
194 if not n1: return localpath(n2)
194 if not n1: return localpath(n2)
195 a, b = n1.split('/'), n2.split('/')
195 a, b = n1.split('/'), n2.split('/')
196 a.reverse()
196 a.reverse()
197 b.reverse()
197 b.reverse()
198 while a and b and a[-1] == b[-1]:
198 while a and b and a[-1] == b[-1]:
199 a.pop()
199 a.pop()
200 b.pop()
200 b.pop()
201 b.reverse()
201 b.reverse()
202 return os.sep.join((['..'] * len(a)) + b)
202 return os.sep.join((['..'] * len(a)) + b)
203
203
204 def canonpath(root, cwd, myname):
204 def canonpath(root, cwd, myname):
205 """return the canonical path of myname, given cwd and root"""
205 """return the canonical path of myname, given cwd and root"""
206 if root == os.sep:
206 if root == os.sep:
207 rootsep = os.sep
207 rootsep = os.sep
208 else:
208 else:
209 rootsep = root + os.sep
209 rootsep = root + os.sep
210 name = myname
210 name = myname
211 if not os.path.isabs(name):
211 if not os.path.isabs(name):
212 name = os.path.join(root, cwd, name)
212 name = os.path.join(root, cwd, name)
213 name = os.path.normpath(name)
213 name = os.path.normpath(name)
214 if name.startswith(rootsep):
214 if name.startswith(rootsep):
215 name = name[len(rootsep):]
215 name = name[len(rootsep):]
216 audit_path(name)
216 audit_path(name)
217 return pconvert(name)
217 return pconvert(name)
218 elif name == root:
218 elif name == root:
219 return ''
219 return ''
220 else:
220 else:
221 # Determine whether `name' is in the hierarchy at or beneath `root',
221 # Determine whether `name' is in the hierarchy at or beneath `root',
222 # by iterating name=dirname(name) until that causes no change (can't
222 # by iterating name=dirname(name) until that causes no change (can't
223 # check name == '/', because that doesn't work on windows). For each
223 # check name == '/', because that doesn't work on windows). For each
224 # `name', compare dev/inode numbers. If they match, the list `rel'
224 # `name', compare dev/inode numbers. If they match, the list `rel'
225 # holds the reversed list of components making up the relative file
225 # holds the reversed list of components making up the relative file
226 # name we want.
226 # name we want.
227 root_st = os.stat(root)
227 root_st = os.stat(root)
228 rel = []
228 rel = []
229 while True:
229 while True:
230 try:
230 try:
231 name_st = os.stat(name)
231 name_st = os.stat(name)
232 except OSError:
232 except OSError:
233 break
233 break
234 if os.path.samestat(name_st, root_st):
234 if samestat(name_st, root_st):
235 rel.reverse()
235 rel.reverse()
236 name = os.path.join(*rel)
236 name = os.path.join(*rel)
237 audit_path(name)
237 audit_path(name)
238 return pconvert(name)
238 return pconvert(name)
239 dirname, basename = os.path.split(name)
239 dirname, basename = os.path.split(name)
240 rel.append(basename)
240 rel.append(basename)
241 if dirname == name:
241 if dirname == name:
242 break
242 break
243 name = dirname
243 name = dirname
244
244
245 raise Abort('%s not under root' % myname)
245 raise Abort('%s not under root' % myname)
246
246
247 def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
247 def matcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
248 return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
248 return _matcher(canonroot, cwd, names, inc, exc, head, 'glob', src)
249
249
250 def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
250 def cmdmatcher(canonroot, cwd='', names=['.'], inc=[], exc=[], head='', src=None):
251 if os.name == 'nt':
251 if os.name == 'nt':
252 dflt_pat = 'glob'
252 dflt_pat = 'glob'
253 else:
253 else:
254 dflt_pat = 'relpath'
254 dflt_pat = 'relpath'
255 return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
255 return _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src)
256
256
257 def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
257 def _matcher(canonroot, cwd, names, inc, exc, head, dflt_pat, src):
258 """build a function to match a set of file patterns
258 """build a function to match a set of file patterns
259
259
260 arguments:
260 arguments:
261 canonroot - the canonical root of the tree you're matching against
261 canonroot - the canonical root of the tree you're matching against
262 cwd - the current working directory, if relevant
262 cwd - the current working directory, if relevant
263 names - patterns to find
263 names - patterns to find
264 inc - patterns to include
264 inc - patterns to include
265 exc - patterns to exclude
265 exc - patterns to exclude
266 head - a regex to prepend to patterns to control whether a match is rooted
266 head - a regex to prepend to patterns to control whether a match is rooted
267
267
268 a pattern is one of:
268 a pattern is one of:
269 'glob:<rooted glob>'
269 'glob:<rooted glob>'
270 're:<rooted regexp>'
270 're:<rooted regexp>'
271 'path:<rooted path>'
271 'path:<rooted path>'
272 'relglob:<relative glob>'
272 'relglob:<relative glob>'
273 'relpath:<relative path>'
273 'relpath:<relative path>'
274 'relre:<relative regexp>'
274 'relre:<relative regexp>'
275 '<rooted path or regexp>'
275 '<rooted path or regexp>'
276
276
277 returns:
277 returns:
278 a 3-tuple containing
278 a 3-tuple containing
279 - list of explicit non-pattern names passed in
279 - list of explicit non-pattern names passed in
280 - a bool match(filename) function
280 - a bool match(filename) function
281 - a bool indicating if any patterns were passed in
281 - a bool indicating if any patterns were passed in
282
282
283 todo:
283 todo:
284 make head regex a rooted bool
284 make head regex a rooted bool
285 """
285 """
286
286
287 def contains_glob(name):
287 def contains_glob(name):
288 for c in name:
288 for c in name:
289 if c in _globchars: return True
289 if c in _globchars: return True
290 return False
290 return False
291
291
292 def regex(kind, name, tail):
292 def regex(kind, name, tail):
293 '''convert a pattern into a regular expression'''
293 '''convert a pattern into a regular expression'''
294 if kind == 're':
294 if kind == 're':
295 return name
295 return name
296 elif kind == 'path':
296 elif kind == 'path':
297 return '^' + re.escape(name) + '(?:/|$)'
297 return '^' + re.escape(name) + '(?:/|$)'
298 elif kind == 'relglob':
298 elif kind == 'relglob':
299 return head + globre(name, '(?:|.*/)', tail)
299 return head + globre(name, '(?:|.*/)', tail)
300 elif kind == 'relpath':
300 elif kind == 'relpath':
301 return head + re.escape(name) + tail
301 return head + re.escape(name) + tail
302 elif kind == 'relre':
302 elif kind == 'relre':
303 if name.startswith('^'):
303 if name.startswith('^'):
304 return name
304 return name
305 return '.*' + name
305 return '.*' + name
306 return head + globre(name, '', tail)
306 return head + globre(name, '', tail)
307
307
308 def matchfn(pats, tail):
308 def matchfn(pats, tail):
309 """build a matching function from a set of patterns"""
309 """build a matching function from a set of patterns"""
310 if not pats:
310 if not pats:
311 return
311 return
312 matches = []
312 matches = []
313 for k, p in pats:
313 for k, p in pats:
314 try:
314 try:
315 pat = '(?:%s)' % regex(k, p, tail)
315 pat = '(?:%s)' % regex(k, p, tail)
316 matches.append(re.compile(pat).match)
316 matches.append(re.compile(pat).match)
317 except re.error:
317 except re.error:
318 if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
318 if src: raise Abort("%s: invalid pattern (%s): %s" % (src, k, p))
319 else: raise Abort("invalid pattern (%s): %s" % (k, p))
319 else: raise Abort("invalid pattern (%s): %s" % (k, p))
320
320
321 def buildfn(text):
321 def buildfn(text):
322 for m in matches:
322 for m in matches:
323 r = m(text)
323 r = m(text)
324 if r:
324 if r:
325 return r
325 return r
326
326
327 return buildfn
327 return buildfn
328
328
329 def globprefix(pat):
329 def globprefix(pat):
330 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
330 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
331 root = []
331 root = []
332 for p in pat.split(os.sep):
332 for p in pat.split(os.sep):
333 if contains_glob(p): break
333 if contains_glob(p): break
334 root.append(p)
334 root.append(p)
335 return '/'.join(root)
335 return '/'.join(root)
336
336
337 pats = []
337 pats = []
338 files = []
338 files = []
339 roots = []
339 roots = []
340 for kind, name in [patkind(p, dflt_pat) for p in names]:
340 for kind, name in [patkind(p, dflt_pat) for p in names]:
341 if kind in ('glob', 'relpath'):
341 if kind in ('glob', 'relpath'):
342 name = canonpath(canonroot, cwd, name)
342 name = canonpath(canonroot, cwd, name)
343 if name == '':
343 if name == '':
344 kind, name = 'glob', '**'
344 kind, name = 'glob', '**'
345 if kind in ('glob', 'path', 're'):
345 if kind in ('glob', 'path', 're'):
346 pats.append((kind, name))
346 pats.append((kind, name))
347 if kind == 'glob':
347 if kind == 'glob':
348 root = globprefix(name)
348 root = globprefix(name)
349 if root: roots.append(root)
349 if root: roots.append(root)
350 elif kind == 'relpath':
350 elif kind == 'relpath':
351 files.append((kind, name))
351 files.append((kind, name))
352 roots.append(name)
352 roots.append(name)
353
353
354 patmatch = matchfn(pats, '$') or always
354 patmatch = matchfn(pats, '$') or always
355 filematch = matchfn(files, '(?:/|$)') or always
355 filematch = matchfn(files, '(?:/|$)') or always
356 incmatch = always
356 incmatch = always
357 if inc:
357 if inc:
358 incmatch = matchfn(map(patkind, inc), '(?:/|$)')
358 incmatch = matchfn(map(patkind, inc), '(?:/|$)')
359 excmatch = lambda fn: False
359 excmatch = lambda fn: False
360 if exc:
360 if exc:
361 excmatch = matchfn(map(patkind, exc), '(?:/|$)')
361 excmatch = matchfn(map(patkind, exc), '(?:/|$)')
362
362
363 return (roots,
363 return (roots,
364 lambda fn: (incmatch(fn) and not excmatch(fn) and
364 lambda fn: (incmatch(fn) and not excmatch(fn) and
365 (fn.endswith('/') or
365 (fn.endswith('/') or
366 (not pats and not files) or
366 (not pats and not files) or
367 (pats and patmatch(fn)) or
367 (pats and patmatch(fn)) or
368 (files and filematch(fn)))),
368 (files and filematch(fn)))),
369 (inc or exc or (pats and pats != [('glob', '**')])) and True)
369 (inc or exc or (pats and pats != [('glob', '**')])) and True)
370
370
371 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
371 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
372 '''enhanced shell command execution.
372 '''enhanced shell command execution.
373 run with environment maybe modified, maybe in different dir.
373 run with environment maybe modified, maybe in different dir.
374
374
375 if command fails and onerr is None, return status. if ui object,
375 if command fails and onerr is None, return status. if ui object,
376 print error message and return status, else raise onerr object as
376 print error message and return status, else raise onerr object as
377 exception.'''
377 exception.'''
378 oldenv = {}
378 oldenv = {}
379 for k in environ:
379 for k in environ:
380 oldenv[k] = os.environ.get(k)
380 oldenv[k] = os.environ.get(k)
381 if cwd is not None:
381 if cwd is not None:
382 oldcwd = os.getcwd()
382 oldcwd = os.getcwd()
383 try:
383 try:
384 for k, v in environ.iteritems():
384 for k, v in environ.iteritems():
385 os.environ[k] = str(v)
385 os.environ[k] = str(v)
386 if cwd is not None and oldcwd != cwd:
386 if cwd is not None and oldcwd != cwd:
387 os.chdir(cwd)
387 os.chdir(cwd)
388 rc = os.system(cmd)
388 rc = os.system(cmd)
389 if rc and onerr:
389 if rc and onerr:
390 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
390 errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
391 explain_exit(rc)[0])
391 explain_exit(rc)[0])
392 if errprefix:
392 if errprefix:
393 errmsg = '%s: %s' % (errprefix, errmsg)
393 errmsg = '%s: %s' % (errprefix, errmsg)
394 try:
394 try:
395 onerr.warn(errmsg + '\n')
395 onerr.warn(errmsg + '\n')
396 except AttributeError:
396 except AttributeError:
397 raise onerr(errmsg)
397 raise onerr(errmsg)
398 return rc
398 return rc
399 finally:
399 finally:
400 for k, v in oldenv.iteritems():
400 for k, v in oldenv.iteritems():
401 if v is None:
401 if v is None:
402 del os.environ[k]
402 del os.environ[k]
403 else:
403 else:
404 os.environ[k] = v
404 os.environ[k] = v
405 if cwd is not None and oldcwd != cwd:
405 if cwd is not None and oldcwd != cwd:
406 os.chdir(oldcwd)
406 os.chdir(oldcwd)
407
407
408 def rename(src, dst):
408 def rename(src, dst):
409 """forcibly rename a file"""
409 """forcibly rename a file"""
410 try:
410 try:
411 os.rename(src, dst)
411 os.rename(src, dst)
412 except OSError, err:
412 except OSError, err:
413 # on windows, rename to existing file is not allowed, so we
413 # on windows, rename to existing file is not allowed, so we
414 # must delete destination first. but if file is open, unlink
414 # must delete destination first. but if file is open, unlink
415 # schedules it for delete but does not delete it. rename
415 # schedules it for delete but does not delete it. rename
416 # happens immediately even for open files, so we create
416 # happens immediately even for open files, so we create
417 # temporary file, delete it, rename destination to that name,
417 # temporary file, delete it, rename destination to that name,
418 # then delete that. then rename is safe to do.
418 # then delete that. then rename is safe to do.
419 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
419 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
420 os.close(fd)
420 os.close(fd)
421 os.unlink(temp)
421 os.unlink(temp)
422 os.rename(dst, temp)
422 os.rename(dst, temp)
423 os.unlink(temp)
423 os.unlink(temp)
424 os.rename(src, dst)
424 os.rename(src, dst)
425
425
426 def unlink(f):
426 def unlink(f):
427 """unlink and remove the directory if it is empty"""
427 """unlink and remove the directory if it is empty"""
428 os.unlink(f)
428 os.unlink(f)
429 # try removing directories that might now be empty
429 # try removing directories that might now be empty
430 try:
430 try:
431 os.removedirs(os.path.dirname(f))
431 os.removedirs(os.path.dirname(f))
432 except OSError:
432 except OSError:
433 pass
433 pass
434
434
435 def copyfiles(src, dst, hardlink=None):
435 def copyfiles(src, dst, hardlink=None):
436 """Copy a directory tree using hardlinks if possible"""
436 """Copy a directory tree using hardlinks if possible"""
437
437
438 if hardlink is None:
438 if hardlink is None:
439 hardlink = (os.stat(src).st_dev ==
439 hardlink = (os.stat(src).st_dev ==
440 os.stat(os.path.dirname(dst)).st_dev)
440 os.stat(os.path.dirname(dst)).st_dev)
441
441
442 if os.path.isdir(src):
442 if os.path.isdir(src):
443 os.mkdir(dst)
443 os.mkdir(dst)
444 for name in os.listdir(src):
444 for name in os.listdir(src):
445 srcname = os.path.join(src, name)
445 srcname = os.path.join(src, name)
446 dstname = os.path.join(dst, name)
446 dstname = os.path.join(dst, name)
447 copyfiles(srcname, dstname, hardlink)
447 copyfiles(srcname, dstname, hardlink)
448 else:
448 else:
449 if hardlink:
449 if hardlink:
450 try:
450 try:
451 os_link(src, dst)
451 os_link(src, dst)
452 except (IOError, OSError):
452 except (IOError, OSError):
453 hardlink = False
453 hardlink = False
454 shutil.copy(src, dst)
454 shutil.copy(src, dst)
455 else:
455 else:
456 shutil.copy(src, dst)
456 shutil.copy(src, dst)
457
457
458 def audit_path(path):
458 def audit_path(path):
459 """Abort if path contains dangerous components"""
459 """Abort if path contains dangerous components"""
460 parts = os.path.normcase(path).split(os.sep)
460 parts = os.path.normcase(path).split(os.sep)
461 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
461 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
462 or os.pardir in parts):
462 or os.pardir in parts):
463 raise Abort(_("path contains illegal component: %s\n") % path)
463 raise Abort(_("path contains illegal component: %s\n") % path)
464
464
465 def _makelock_file(info, pathname):
465 def _makelock_file(info, pathname):
466 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
466 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
467 os.write(ld, info)
467 os.write(ld, info)
468 os.close(ld)
468 os.close(ld)
469
469
470 def _readlock_file(pathname):
470 def _readlock_file(pathname):
471 return posixfile(pathname).read()
471 return posixfile(pathname).read()
472
472
473 def nlinks(pathname):
473 def nlinks(pathname):
474 """Return number of hardlinks for the given file."""
474 """Return number of hardlinks for the given file."""
475 return os.stat(pathname).st_nlink
475 return os.stat(pathname).st_nlink
476
476
477 if hasattr(os, 'link'):
477 if hasattr(os, 'link'):
478 os_link = os.link
478 os_link = os.link
479 else:
479 else:
480 def os_link(src, dst):
480 def os_link(src, dst):
481 raise OSError(0, _("Hardlinks not supported"))
481 raise OSError(0, _("Hardlinks not supported"))
482
482
483 def fstat(fp):
483 def fstat(fp):
484 '''stat file object that may not have fileno method.'''
484 '''stat file object that may not have fileno method.'''
485 try:
485 try:
486 return os.fstat(fp.fileno())
486 return os.fstat(fp.fileno())
487 except AttributeError:
487 except AttributeError:
488 return os.stat(fp.name)
488 return os.stat(fp.name)
489
489
490 posixfile = file
490 posixfile = file
491
491
492 # Platform specific variants
492 # Platform specific variants
493 if os.name == 'nt':
493 if os.name == 'nt':
494 demandload(globals(), "msvcrt")
494 demandload(globals(), "msvcrt")
495 nulldev = 'NUL:'
495 nulldev = 'NUL:'
496
496
497 class winstdout:
497 class winstdout:
498 '''stdout on windows misbehaves if sent through a pipe'''
498 '''stdout on windows misbehaves if sent through a pipe'''
499
499
500 def __init__(self, fp):
500 def __init__(self, fp):
501 self.fp = fp
501 self.fp = fp
502
502
503 def __getattr__(self, key):
503 def __getattr__(self, key):
504 return getattr(self.fp, key)
504 return getattr(self.fp, key)
505
505
506 def close(self):
506 def close(self):
507 try:
507 try:
508 self.fp.close()
508 self.fp.close()
509 except: pass
509 except: pass
510
510
511 def write(self, s):
511 def write(self, s):
512 try:
512 try:
513 return self.fp.write(s)
513 return self.fp.write(s)
514 except IOError, inst:
514 except IOError, inst:
515 if inst.errno != 0: raise
515 if inst.errno != 0: raise
516 self.close()
516 self.close()
517 raise IOError(errno.EPIPE, 'Broken pipe')
517 raise IOError(errno.EPIPE, 'Broken pipe')
518
518
519 sys.stdout = winstdout(sys.stdout)
519 sys.stdout = winstdout(sys.stdout)
520
520
521 def system_rcpath():
521 def system_rcpath():
522 try:
522 try:
523 return system_rcpath_win32()
523 return system_rcpath_win32()
524 except:
524 except:
525 return [r'c:\mercurial\mercurial.ini']
525 return [r'c:\mercurial\mercurial.ini']
526
526
527 def os_rcpath():
527 def os_rcpath():
528 '''return default os-specific hgrc search path'''
528 '''return default os-specific hgrc search path'''
529 return system_rcpath() + [os.path.join(os.path.expanduser('~'),
529 return system_rcpath() + [os.path.join(os.path.expanduser('~'),
530 'mercurial.ini')]
530 'mercurial.ini')]
531
531
532 def parse_patch_output(output_line):
532 def parse_patch_output(output_line):
533 """parses the output produced by patch and returns the file name"""
533 """parses the output produced by patch and returns the file name"""
534 pf = output_line[14:]
534 pf = output_line[14:]
535 if pf[0] == '`':
535 if pf[0] == '`':
536 pf = pf[1:-1] # Remove the quotes
536 pf = pf[1:-1] # Remove the quotes
537 return pf
537 return pf
538
538
539 def testpid(pid):
539 def testpid(pid):
540 '''return False if pid dead, True if running or not known'''
540 '''return False if pid dead, True if running or not known'''
541 return True
541 return True
542
542
543 def is_exec(f, last):
543 def is_exec(f, last):
544 return last
544 return last
545
545
546 def set_exec(f, mode):
546 def set_exec(f, mode):
547 pass
547 pass
548
548
549 def set_binary(fd):
549 def set_binary(fd):
550 msvcrt.setmode(fd.fileno(), os.O_BINARY)
550 msvcrt.setmode(fd.fileno(), os.O_BINARY)
551
551
552 def pconvert(path):
552 def pconvert(path):
553 return path.replace("\\", "/")
553 return path.replace("\\", "/")
554
554
555 def localpath(path):
555 def localpath(path):
556 return path.replace('/', '\\')
556 return path.replace('/', '\\')
557
557
558 def normpath(path):
558 def normpath(path):
559 return pconvert(os.path.normpath(path))
559 return pconvert(os.path.normpath(path))
560
560
561 makelock = _makelock_file
561 makelock = _makelock_file
562 readlock = _readlock_file
562 readlock = _readlock_file
563
563
564 def samestat(s1, s2):
565 return False
566
564 def explain_exit(code):
567 def explain_exit(code):
565 return _("exited with status %d") % code, code
568 return _("exited with status %d") % code, code
566
569
567 try:
570 try:
568 # override functions with win32 versions if possible
571 # override functions with win32 versions if possible
569 from util_win32 import *
572 from util_win32 import *
570 except ImportError:
573 except ImportError:
571 pass
574 pass
572
575
573 else:
576 else:
574 nulldev = '/dev/null'
577 nulldev = '/dev/null'
575
578
576 def rcfiles(path):
579 def rcfiles(path):
577 rcs = [os.path.join(path, 'hgrc')]
580 rcs = [os.path.join(path, 'hgrc')]
578 rcdir = os.path.join(path, 'hgrc.d')
581 rcdir = os.path.join(path, 'hgrc.d')
579 try:
582 try:
580 rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
583 rcs.extend([os.path.join(rcdir, f) for f in os.listdir(rcdir)
581 if f.endswith(".rc")])
584 if f.endswith(".rc")])
582 except OSError, inst: pass
585 except OSError, inst: pass
583 return rcs
586 return rcs
584
587
585 def os_rcpath():
588 def os_rcpath():
586 '''return default os-specific hgrc search path'''
589 '''return default os-specific hgrc search path'''
587 path = []
590 path = []
588 if len(sys.argv) > 0:
591 if len(sys.argv) > 0:
589 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
592 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
590 '/../etc/mercurial'))
593 '/../etc/mercurial'))
591 path.extend(rcfiles('/etc/mercurial'))
594 path.extend(rcfiles('/etc/mercurial'))
592 path.append(os.path.expanduser('~/.hgrc'))
595 path.append(os.path.expanduser('~/.hgrc'))
593 path = [os.path.normpath(f) for f in path]
596 path = [os.path.normpath(f) for f in path]
594 return path
597 return path
595
598
596 def parse_patch_output(output_line):
599 def parse_patch_output(output_line):
597 """parses the output produced by patch and returns the file name"""
600 """parses the output produced by patch and returns the file name"""
598 pf = output_line[14:]
601 pf = output_line[14:]
599 if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
602 if pf.startswith("'") and pf.endswith("'") and pf.find(" ") >= 0:
600 pf = pf[1:-1] # Remove the quotes
603 pf = pf[1:-1] # Remove the quotes
601 return pf
604 return pf
602
605
603 def is_exec(f, last):
606 def is_exec(f, last):
604 """check whether a file is executable"""
607 """check whether a file is executable"""
605 return (os.stat(f).st_mode & 0100 != 0)
608 return (os.stat(f).st_mode & 0100 != 0)
606
609
607 def set_exec(f, mode):
610 def set_exec(f, mode):
608 s = os.stat(f).st_mode
611 s = os.stat(f).st_mode
609 if (s & 0100 != 0) == mode:
612 if (s & 0100 != 0) == mode:
610 return
613 return
611 if mode:
614 if mode:
612 # Turn on +x for every +r bit when making a file executable
615 # Turn on +x for every +r bit when making a file executable
613 # and obey umask.
616 # and obey umask.
614 umask = os.umask(0)
617 umask = os.umask(0)
615 os.umask(umask)
618 os.umask(umask)
616 os.chmod(f, s | (s & 0444) >> 2 & ~umask)
619 os.chmod(f, s | (s & 0444) >> 2 & ~umask)
617 else:
620 else:
618 os.chmod(f, s & 0666)
621 os.chmod(f, s & 0666)
619
622
620 def set_binary(fd):
623 def set_binary(fd):
621 pass
624 pass
622
625
623 def pconvert(path):
626 def pconvert(path):
624 return path
627 return path
625
628
626 def localpath(path):
629 def localpath(path):
627 return path
630 return path
628
631
629 normpath = os.path.normpath
632 normpath = os.path.normpath
633 samestat = os.path.samestat
630
634
631 def makelock(info, pathname):
635 def makelock(info, pathname):
632 try:
636 try:
633 os.symlink(info, pathname)
637 os.symlink(info, pathname)
634 except OSError, why:
638 except OSError, why:
635 if why.errno == errno.EEXIST:
639 if why.errno == errno.EEXIST:
636 raise
640 raise
637 else:
641 else:
638 _makelock_file(info, pathname)
642 _makelock_file(info, pathname)
639
643
640 def readlock(pathname):
644 def readlock(pathname):
641 try:
645 try:
642 return os.readlink(pathname)
646 return os.readlink(pathname)
643 except OSError, why:
647 except OSError, why:
644 if why.errno == errno.EINVAL:
648 if why.errno == errno.EINVAL:
645 return _readlock_file(pathname)
649 return _readlock_file(pathname)
646 else:
650 else:
647 raise
651 raise
648
652
649 def testpid(pid):
653 def testpid(pid):
650 '''return False if pid dead, True if running or not sure'''
654 '''return False if pid dead, True if running or not sure'''
651 try:
655 try:
652 os.kill(pid, 0)
656 os.kill(pid, 0)
653 return True
657 return True
654 except OSError, inst:
658 except OSError, inst:
655 return inst.errno != errno.ESRCH
659 return inst.errno != errno.ESRCH
656
660
657 def explain_exit(code):
661 def explain_exit(code):
658 """return a 2-tuple (desc, code) describing a process's status"""
662 """return a 2-tuple (desc, code) describing a process's status"""
659 if os.WIFEXITED(code):
663 if os.WIFEXITED(code):
660 val = os.WEXITSTATUS(code)
664 val = os.WEXITSTATUS(code)
661 return _("exited with status %d") % val, val
665 return _("exited with status %d") % val, val
662 elif os.WIFSIGNALED(code):
666 elif os.WIFSIGNALED(code):
663 val = os.WTERMSIG(code)
667 val = os.WTERMSIG(code)
664 return _("killed by signal %d") % val, val
668 return _("killed by signal %d") % val, val
665 elif os.WIFSTOPPED(code):
669 elif os.WIFSTOPPED(code):
666 val = os.WSTOPSIG(code)
670 val = os.WSTOPSIG(code)
667 return _("stopped by signal %d") % val, val
671 return _("stopped by signal %d") % val, val
668 raise ValueError(_("invalid exit code"))
672 raise ValueError(_("invalid exit code"))
669
673
670 def opener(base, audit=True):
674 def opener(base, audit=True):
671 """
675 """
672 return a function that opens files relative to base
676 return a function that opens files relative to base
673
677
674 this function is used to hide the details of COW semantics and
678 this function is used to hide the details of COW semantics and
675 remote file access from higher level code.
679 remote file access from higher level code.
676 """
680 """
677 p = base
681 p = base
678 audit_p = audit
682 audit_p = audit
679
683
680 def mktempcopy(name):
684 def mktempcopy(name):
681 d, fn = os.path.split(name)
685 d, fn = os.path.split(name)
682 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
686 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
683 os.close(fd)
687 os.close(fd)
684 fp = posixfile(temp, "wb")
688 fp = posixfile(temp, "wb")
685 try:
689 try:
686 fp.write(posixfile(name, "rb").read())
690 fp.write(posixfile(name, "rb").read())
687 except:
691 except:
688 try: os.unlink(temp)
692 try: os.unlink(temp)
689 except: pass
693 except: pass
690 raise
694 raise
691 fp.close()
695 fp.close()
692 st = os.lstat(name)
696 st = os.lstat(name)
693 os.chmod(temp, st.st_mode)
697 os.chmod(temp, st.st_mode)
694 return temp
698 return temp
695
699
696 class atomictempfile(posixfile):
700 class atomictempfile(posixfile):
697 """the file will only be copied when rename is called"""
701 """the file will only be copied when rename is called"""
698 def __init__(self, name, mode):
702 def __init__(self, name, mode):
699 self.__name = name
703 self.__name = name
700 self.temp = mktempcopy(name)
704 self.temp = mktempcopy(name)
701 posixfile.__init__(self, self.temp, mode)
705 posixfile.__init__(self, self.temp, mode)
702 def rename(self):
706 def rename(self):
703 if not self.closed:
707 if not self.closed:
704 posixfile.close(self)
708 posixfile.close(self)
705 rename(self.temp, self.__name)
709 rename(self.temp, self.__name)
706 def __del__(self):
710 def __del__(self):
707 if not self.closed:
711 if not self.closed:
708 try:
712 try:
709 os.unlink(self.temp)
713 os.unlink(self.temp)
710 except: pass
714 except: pass
711 posixfile.close(self)
715 posixfile.close(self)
712
716
713 class atomicfile(atomictempfile):
717 class atomicfile(atomictempfile):
714 """the file will only be copied on close"""
718 """the file will only be copied on close"""
715 def __init__(self, name, mode):
719 def __init__(self, name, mode):
716 atomictempfile.__init__(self, name, mode)
720 atomictempfile.__init__(self, name, mode)
717 def close(self):
721 def close(self):
718 self.rename()
722 self.rename()
719 def __del__(self):
723 def __del__(self):
720 self.rename()
724 self.rename()
721
725
722 def o(path, mode="r", text=False, atomic=False, atomictemp=False):
726 def o(path, mode="r", text=False, atomic=False, atomictemp=False):
723 if audit_p:
727 if audit_p:
724 audit_path(path)
728 audit_path(path)
725 f = os.path.join(p, path)
729 f = os.path.join(p, path)
726
730
727 if not text:
731 if not text:
728 mode += "b" # for that other OS
732 mode += "b" # for that other OS
729
733
730 if mode[0] != "r":
734 if mode[0] != "r":
731 try:
735 try:
732 nlink = nlinks(f)
736 nlink = nlinks(f)
733 except OSError:
737 except OSError:
734 d = os.path.dirname(f)
738 d = os.path.dirname(f)
735 if not os.path.isdir(d):
739 if not os.path.isdir(d):
736 os.makedirs(d)
740 os.makedirs(d)
737 else:
741 else:
738 if atomic:
742 if atomic:
739 return atomicfile(f, mode)
743 return atomicfile(f, mode)
740 elif atomictemp:
744 elif atomictemp:
741 return atomictempfile(f, mode)
745 return atomictempfile(f, mode)
742 if nlink > 1:
746 if nlink > 1:
743 rename(mktempcopy(f), f)
747 rename(mktempcopy(f), f)
744 return posixfile(f, mode)
748 return posixfile(f, mode)
745
749
746 return o
750 return o
747
751
748 class chunkbuffer(object):
752 class chunkbuffer(object):
749 """Allow arbitrary sized chunks of data to be efficiently read from an
753 """Allow arbitrary sized chunks of data to be efficiently read from an
750 iterator over chunks of arbitrary size."""
754 iterator over chunks of arbitrary size."""
751
755
752 def __init__(self, in_iter, targetsize = 2**16):
756 def __init__(self, in_iter, targetsize = 2**16):
753 """in_iter is the iterator that's iterating over the input chunks.
757 """in_iter is the iterator that's iterating over the input chunks.
754 targetsize is how big a buffer to try to maintain."""
758 targetsize is how big a buffer to try to maintain."""
755 self.in_iter = iter(in_iter)
759 self.in_iter = iter(in_iter)
756 self.buf = ''
760 self.buf = ''
757 self.targetsize = int(targetsize)
761 self.targetsize = int(targetsize)
758 if self.targetsize <= 0:
762 if self.targetsize <= 0:
759 raise ValueError(_("targetsize must be greater than 0, was %d") %
763 raise ValueError(_("targetsize must be greater than 0, was %d") %
760 targetsize)
764 targetsize)
761 self.iterempty = False
765 self.iterempty = False
762
766
763 def fillbuf(self):
767 def fillbuf(self):
764 """Ignore target size; read every chunk from iterator until empty."""
768 """Ignore target size; read every chunk from iterator until empty."""
765 if not self.iterempty:
769 if not self.iterempty:
766 collector = cStringIO.StringIO()
770 collector = cStringIO.StringIO()
767 collector.write(self.buf)
771 collector.write(self.buf)
768 for ch in self.in_iter:
772 for ch in self.in_iter:
769 collector.write(ch)
773 collector.write(ch)
770 self.buf = collector.getvalue()
774 self.buf = collector.getvalue()
771 self.iterempty = True
775 self.iterempty = True
772
776
773 def read(self, l):
777 def read(self, l):
774 """Read L bytes of data from the iterator of chunks of data.
778 """Read L bytes of data from the iterator of chunks of data.
775 Returns less than L bytes if the iterator runs dry."""
779 Returns less than L bytes if the iterator runs dry."""
776 if l > len(self.buf) and not self.iterempty:
780 if l > len(self.buf) and not self.iterempty:
777 # Clamp to a multiple of self.targetsize
781 # Clamp to a multiple of self.targetsize
778 targetsize = self.targetsize * ((l // self.targetsize) + 1)
782 targetsize = self.targetsize * ((l // self.targetsize) + 1)
779 collector = cStringIO.StringIO()
783 collector = cStringIO.StringIO()
780 collector.write(self.buf)
784 collector.write(self.buf)
781 collected = len(self.buf)
785 collected = len(self.buf)
782 for chunk in self.in_iter:
786 for chunk in self.in_iter:
783 collector.write(chunk)
787 collector.write(chunk)
784 collected += len(chunk)
788 collected += len(chunk)
785 if collected >= targetsize:
789 if collected >= targetsize:
786 break
790 break
787 if collected < targetsize:
791 if collected < targetsize:
788 self.iterempty = True
792 self.iterempty = True
789 self.buf = collector.getvalue()
793 self.buf = collector.getvalue()
790 s, self.buf = self.buf[:l], buffer(self.buf, l)
794 s, self.buf = self.buf[:l], buffer(self.buf, l)
791 return s
795 return s
792
796
793 def filechunkiter(f, size = 65536):
797 def filechunkiter(f, size = 65536):
794 """Create a generator that produces all the data in the file size
798 """Create a generator that produces all the data in the file size
795 (default 65536) bytes at a time. Chunks may be less than size
799 (default 65536) bytes at a time. Chunks may be less than size
796 bytes if the chunk is the last chunk in the file, or the file is a
800 bytes if the chunk is the last chunk in the file, or the file is a
797 socket or some other type of file that sometimes reads less data
801 socket or some other type of file that sometimes reads less data
798 than is requested."""
802 than is requested."""
799 s = f.read(size)
803 s = f.read(size)
800 while len(s) > 0:
804 while len(s) > 0:
801 yield s
805 yield s
802 s = f.read(size)
806 s = f.read(size)
803
807
804 def makedate():
808 def makedate():
805 lt = time.localtime()
809 lt = time.localtime()
806 if lt[8] == 1 and time.daylight:
810 if lt[8] == 1 and time.daylight:
807 tz = time.altzone
811 tz = time.altzone
808 else:
812 else:
809 tz = time.timezone
813 tz = time.timezone
810 return time.mktime(lt), tz
814 return time.mktime(lt), tz
811
815
812 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
816 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True):
813 """represent a (unixtime, offset) tuple as a localized time.
817 """represent a (unixtime, offset) tuple as a localized time.
814 unixtime is seconds since the epoch, and offset is the time zone's
818 unixtime is seconds since the epoch, and offset is the time zone's
815 number of seconds away from UTC. if timezone is false, do not
819 number of seconds away from UTC. if timezone is false, do not
816 append time zone to string."""
820 append time zone to string."""
817 t, tz = date or makedate()
821 t, tz = date or makedate()
818 s = time.strftime(format, time.gmtime(float(t) - tz))
822 s = time.strftime(format, time.gmtime(float(t) - tz))
819 if timezone:
823 if timezone:
820 s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
824 s += " %+03d%02d" % (-tz / 3600, ((-tz % 3600) / 60))
821 return s
825 return s
822
826
823 def shortuser(user):
827 def shortuser(user):
824 """Return a short representation of a user name or email address."""
828 """Return a short representation of a user name or email address."""
825 f = user.find('@')
829 f = user.find('@')
826 if f >= 0:
830 if f >= 0:
827 user = user[:f]
831 user = user[:f]
828 f = user.find('<')
832 f = user.find('<')
829 if f >= 0:
833 if f >= 0:
830 user = user[f+1:]
834 user = user[f+1:]
831 return user
835 return user
832
836
833 def walkrepos(path):
837 def walkrepos(path):
834 '''yield every hg repository under path, recursively.'''
838 '''yield every hg repository under path, recursively.'''
835 def errhandler(err):
839 def errhandler(err):
836 if err.filename == path:
840 if err.filename == path:
837 raise err
841 raise err
838
842
839 for root, dirs, files in os.walk(path, onerror=errhandler):
843 for root, dirs, files in os.walk(path, onerror=errhandler):
840 for d in dirs:
844 for d in dirs:
841 if d == '.hg':
845 if d == '.hg':
842 yield root
846 yield root
843 dirs[:] = []
847 dirs[:] = []
844 break
848 break
845
849
846 _rcpath = None
850 _rcpath = None
847
851
848 def rcpath():
852 def rcpath():
849 '''return hgrc search path. if env var HGRCPATH is set, use it.
853 '''return hgrc search path. if env var HGRCPATH is set, use it.
850 for each item in path, if directory, use files ending in .rc,
854 for each item in path, if directory, use files ending in .rc,
851 else use item.
855 else use item.
852 make HGRCPATH empty to only look in .hg/hgrc of current repo.
856 make HGRCPATH empty to only look in .hg/hgrc of current repo.
853 if no HGRCPATH, use default os-specific path.'''
857 if no HGRCPATH, use default os-specific path.'''
854 global _rcpath
858 global _rcpath
855 if _rcpath is None:
859 if _rcpath is None:
856 if 'HGRCPATH' in os.environ:
860 if 'HGRCPATH' in os.environ:
857 _rcpath = []
861 _rcpath = []
858 for p in os.environ['HGRCPATH'].split(os.pathsep):
862 for p in os.environ['HGRCPATH'].split(os.pathsep):
859 if not p: continue
863 if not p: continue
860 if os.path.isdir(p):
864 if os.path.isdir(p):
861 for f in os.listdir(p):
865 for f in os.listdir(p):
862 if f.endswith('.rc'):
866 if f.endswith('.rc'):
863 _rcpath.append(os.path.join(p, f))
867 _rcpath.append(os.path.join(p, f))
864 else:
868 else:
865 _rcpath.append(p)
869 _rcpath.append(p)
866 else:
870 else:
867 _rcpath = os_rcpath()
871 _rcpath = os_rcpath()
868 return _rcpath
872 return _rcpath
General Comments 0
You need to be logged in to leave comments. Login now