##// END OF EJS Templates
util: remove needbinary(), no longer used for external patching
Patrick Mezard -
r12672:9b324c5e default
parent child Browse files
Show More
@@ -1,1448 +1,1444 b''
1 1 # util.py - Mercurial utility functions and platform specfic implementations
2 2 #
3 3 # Copyright 2005 K. Thananchayan <thananck@yahoo.com>
4 4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 5 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
6 6 #
7 7 # This software may be used and distributed according to the terms of the
8 8 # GNU General Public License version 2 or any later version.
9 9
10 10 """Mercurial utility functions and platform specfic implementations.
11 11
12 12 This contains helper routines that are independent of the SCM core and
13 13 hide platform-specific details from the core.
14 14 """
15 15
16 16 from i18n import _
17 17 import error, osutil, encoding
18 18 import errno, re, shutil, sys, tempfile, traceback
19 19 import os, stat, time, calendar, textwrap, unicodedata, signal
20 20 import imp, socket
21 21
22 22 # Python compatibility
23 23
24 24 def sha1(s):
25 25 return _fastsha1(s)
26 26
27 27 def _fastsha1(s):
28 28 # This function will import sha1 from hashlib or sha (whichever is
29 29 # available) and overwrite itself with it on the first call.
30 30 # Subsequent calls will go directly to the imported function.
31 31 if sys.version_info >= (2, 5):
32 32 from hashlib import sha1 as _sha1
33 33 else:
34 34 from sha import sha as _sha1
35 35 global _fastsha1, sha1
36 36 _fastsha1 = sha1 = _sha1
37 37 return _sha1(s)
38 38
39 39 import __builtin__
40 40
41 41 if sys.version_info[0] < 3:
42 42 def fakebuffer(sliceable, offset=0):
43 43 return sliceable[offset:]
44 44 else:
45 45 def fakebuffer(sliceable, offset=0):
46 46 return memoryview(sliceable)[offset:]
47 47 try:
48 48 buffer
49 49 except NameError:
50 50 __builtin__.buffer = fakebuffer
51 51
52 52 import subprocess
53 53 closefds = os.name == 'posix'
54 54
55 55 def popen2(cmd, env=None, newlines=False):
56 56 # Setting bufsize to -1 lets the system decide the buffer size.
57 57 # The default for bufsize is 0, meaning unbuffered. This leads to
58 58 # poor performance on Mac OS X: http://bugs.python.org/issue4194
59 59 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
60 60 close_fds=closefds,
61 61 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
62 62 universal_newlines=newlines,
63 63 env=env)
64 64 return p.stdin, p.stdout
65 65
66 66 def popen3(cmd, env=None, newlines=False):
67 67 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
68 68 close_fds=closefds,
69 69 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
70 70 stderr=subprocess.PIPE,
71 71 universal_newlines=newlines,
72 72 env=env)
73 73 return p.stdin, p.stdout, p.stderr
74 74
75 75 def version():
76 76 """Return version information if available."""
77 77 try:
78 78 import __version__
79 79 return __version__.version
80 80 except ImportError:
81 81 return 'unknown'
82 82
83 83 # used by parsedate
84 84 defaultdateformats = (
85 85 '%Y-%m-%d %H:%M:%S',
86 86 '%Y-%m-%d %I:%M:%S%p',
87 87 '%Y-%m-%d %H:%M',
88 88 '%Y-%m-%d %I:%M%p',
89 89 '%Y-%m-%d',
90 90 '%m-%d',
91 91 '%m/%d',
92 92 '%m/%d/%y',
93 93 '%m/%d/%Y',
94 94 '%a %b %d %H:%M:%S %Y',
95 95 '%a %b %d %I:%M:%S%p %Y',
96 96 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
97 97 '%b %d %H:%M:%S %Y',
98 98 '%b %d %I:%M:%S%p %Y',
99 99 '%b %d %H:%M:%S',
100 100 '%b %d %I:%M:%S%p',
101 101 '%b %d %H:%M',
102 102 '%b %d %I:%M%p',
103 103 '%b %d %Y',
104 104 '%b %d',
105 105 '%H:%M:%S',
106 106 '%I:%M:%S%p',
107 107 '%H:%M',
108 108 '%I:%M%p',
109 109 )
110 110
111 111 extendeddateformats = defaultdateformats + (
112 112 "%Y",
113 113 "%Y-%m",
114 114 "%b",
115 115 "%b %Y",
116 116 )
117 117
118 118 def cachefunc(func):
119 119 '''cache the result of function calls'''
120 120 # XXX doesn't handle keywords args
121 121 cache = {}
122 122 if func.func_code.co_argcount == 1:
123 123 # we gain a small amount of time because
124 124 # we don't need to pack/unpack the list
125 125 def f(arg):
126 126 if arg not in cache:
127 127 cache[arg] = func(arg)
128 128 return cache[arg]
129 129 else:
130 130 def f(*args):
131 131 if args not in cache:
132 132 cache[args] = func(*args)
133 133 return cache[args]
134 134
135 135 return f
136 136
137 137 def lrucachefunc(func):
138 138 '''cache most recent results of function calls'''
139 139 cache = {}
140 140 order = []
141 141 if func.func_code.co_argcount == 1:
142 142 def f(arg):
143 143 if arg not in cache:
144 144 if len(cache) > 20:
145 145 del cache[order.pop(0)]
146 146 cache[arg] = func(arg)
147 147 else:
148 148 order.remove(arg)
149 149 order.append(arg)
150 150 return cache[arg]
151 151 else:
152 152 def f(*args):
153 153 if args not in cache:
154 154 if len(cache) > 20:
155 155 del cache[order.pop(0)]
156 156 cache[args] = func(*args)
157 157 else:
158 158 order.remove(args)
159 159 order.append(args)
160 160 return cache[args]
161 161
162 162 return f
163 163
164 164 class propertycache(object):
165 165 def __init__(self, func):
166 166 self.func = func
167 167 self.name = func.__name__
168 168 def __get__(self, obj, type=None):
169 169 result = self.func(obj)
170 170 setattr(obj, self.name, result)
171 171 return result
172 172
173 173 def pipefilter(s, cmd):
174 174 '''filter string S through command CMD, returning its output'''
175 175 p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
176 176 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
177 177 pout, perr = p.communicate(s)
178 178 return pout
179 179
180 180 def tempfilter(s, cmd):
181 181 '''filter string S through a pair of temporary files with CMD.
182 182 CMD is used as a template to create the real command to be run,
183 183 with the strings INFILE and OUTFILE replaced by the real names of
184 184 the temporary files generated.'''
185 185 inname, outname = None, None
186 186 try:
187 187 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
188 188 fp = os.fdopen(infd, 'wb')
189 189 fp.write(s)
190 190 fp.close()
191 191 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
192 192 os.close(outfd)
193 193 cmd = cmd.replace('INFILE', inname)
194 194 cmd = cmd.replace('OUTFILE', outname)
195 195 code = os.system(cmd)
196 196 if sys.platform == 'OpenVMS' and code & 1:
197 197 code = 0
198 198 if code:
199 199 raise Abort(_("command '%s' failed: %s") %
200 200 (cmd, explain_exit(code)))
201 201 return open(outname, 'rb').read()
202 202 finally:
203 203 try:
204 204 if inname:
205 205 os.unlink(inname)
206 206 except:
207 207 pass
208 208 try:
209 209 if outname:
210 210 os.unlink(outname)
211 211 except:
212 212 pass
213 213
214 214 filtertable = {
215 215 'tempfile:': tempfilter,
216 216 'pipe:': pipefilter,
217 217 }
218 218
219 219 def filter(s, cmd):
220 220 "filter a string through a command that transforms its input to its output"
221 221 for name, fn in filtertable.iteritems():
222 222 if cmd.startswith(name):
223 223 return fn(s, cmd[len(name):].lstrip())
224 224 return pipefilter(s, cmd)
225 225
226 226 def binary(s):
227 227 """return true if a string is binary data"""
228 228 return bool(s and '\0' in s)
229 229
230 230 def increasingchunks(source, min=1024, max=65536):
231 231 '''return no less than min bytes per chunk while data remains,
232 232 doubling min after each chunk until it reaches max'''
233 233 def log2(x):
234 234 if not x:
235 235 return 0
236 236 i = 0
237 237 while x:
238 238 x >>= 1
239 239 i += 1
240 240 return i - 1
241 241
242 242 buf = []
243 243 blen = 0
244 244 for chunk in source:
245 245 buf.append(chunk)
246 246 blen += len(chunk)
247 247 if blen >= min:
248 248 if min < max:
249 249 min = min << 1
250 250 nmin = 1 << log2(blen)
251 251 if nmin > min:
252 252 min = nmin
253 253 if min > max:
254 254 min = max
255 255 yield ''.join(buf)
256 256 blen = 0
257 257 buf = []
258 258 if buf:
259 259 yield ''.join(buf)
260 260
261 261 Abort = error.Abort
262 262
263 263 def always(fn):
264 264 return True
265 265
266 266 def never(fn):
267 267 return False
268 268
269 269 def pathto(root, n1, n2):
270 270 '''return the relative path from one place to another.
271 271 root should use os.sep to separate directories
272 272 n1 should use os.sep to separate directories
273 273 n2 should use "/" to separate directories
274 274 returns an os.sep-separated path.
275 275
276 276 If n1 is a relative path, it's assumed it's
277 277 relative to root.
278 278 n2 should always be relative to root.
279 279 '''
280 280 if not n1:
281 281 return localpath(n2)
282 282 if os.path.isabs(n1):
283 283 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
284 284 return os.path.join(root, localpath(n2))
285 285 n2 = '/'.join((pconvert(root), n2))
286 286 a, b = splitpath(n1), n2.split('/')
287 287 a.reverse()
288 288 b.reverse()
289 289 while a and b and a[-1] == b[-1]:
290 290 a.pop()
291 291 b.pop()
292 292 b.reverse()
293 293 return os.sep.join((['..'] * len(a)) + b) or '.'
294 294
295 295 def canonpath(root, cwd, myname, auditor=None):
296 296 """return the canonical path of myname, given cwd and root"""
297 297 if endswithsep(root):
298 298 rootsep = root
299 299 else:
300 300 rootsep = root + os.sep
301 301 name = myname
302 302 if not os.path.isabs(name):
303 303 name = os.path.join(root, cwd, name)
304 304 name = os.path.normpath(name)
305 305 if auditor is None:
306 306 auditor = path_auditor(root)
307 307 if name != rootsep and name.startswith(rootsep):
308 308 name = name[len(rootsep):]
309 309 auditor(name)
310 310 return pconvert(name)
311 311 elif name == root:
312 312 return ''
313 313 else:
314 314 # Determine whether `name' is in the hierarchy at or beneath `root',
315 315 # by iterating name=dirname(name) until that causes no change (can't
316 316 # check name == '/', because that doesn't work on windows). For each
317 317 # `name', compare dev/inode numbers. If they match, the list `rel'
318 318 # holds the reversed list of components making up the relative file
319 319 # name we want.
320 320 root_st = os.stat(root)
321 321 rel = []
322 322 while True:
323 323 try:
324 324 name_st = os.stat(name)
325 325 except OSError:
326 326 break
327 327 if samestat(name_st, root_st):
328 328 if not rel:
329 329 # name was actually the same as root (maybe a symlink)
330 330 return ''
331 331 rel.reverse()
332 332 name = os.path.join(*rel)
333 333 auditor(name)
334 334 return pconvert(name)
335 335 dirname, basename = os.path.split(name)
336 336 rel.append(basename)
337 337 if dirname == name:
338 338 break
339 339 name = dirname
340 340
341 341 raise Abort('%s not under root' % myname)
342 342
343 343 _hgexecutable = None
344 344
345 345 def main_is_frozen():
346 346 """return True if we are a frozen executable.
347 347
348 348 The code supports py2exe (most common, Windows only) and tools/freeze
349 349 (portable, not much used).
350 350 """
351 351 return (hasattr(sys, "frozen") or # new py2exe
352 352 hasattr(sys, "importers") or # old py2exe
353 353 imp.is_frozen("__main__")) # tools/freeze
354 354
355 355 def hgexecutable():
356 356 """return location of the 'hg' executable.
357 357
358 358 Defaults to $HG or 'hg' in the search path.
359 359 """
360 360 if _hgexecutable is None:
361 361 hg = os.environ.get('HG')
362 362 if hg:
363 363 set_hgexecutable(hg)
364 364 elif main_is_frozen():
365 365 set_hgexecutable(sys.executable)
366 366 else:
367 367 exe = find_exe('hg') or os.path.basename(sys.argv[0])
368 368 set_hgexecutable(exe)
369 369 return _hgexecutable
370 370
371 371 def set_hgexecutable(path):
372 372 """set location of the 'hg' executable"""
373 373 global _hgexecutable
374 374 _hgexecutable = path
375 375
376 376 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
377 377 '''enhanced shell command execution.
378 378 run with environment maybe modified, maybe in different dir.
379 379
380 380 if command fails and onerr is None, return status. if ui object,
381 381 print error message and return status, else raise onerr object as
382 382 exception.
383 383
384 384 if out is specified, it is assumed to be a file-like object that has a
385 385 write() method. stdout and stderr will be redirected to out.'''
386 386 def py2shell(val):
387 387 'convert python object into string that is useful to shell'
388 388 if val is None or val is False:
389 389 return '0'
390 390 if val is True:
391 391 return '1'
392 392 return str(val)
393 393 origcmd = cmd
394 394 if os.name == 'nt':
395 395 cmd = '"%s"' % cmd
396 396 env = dict(os.environ)
397 397 env.update((k, py2shell(v)) for k, v in environ.iteritems())
398 398 env['HG'] = hgexecutable()
399 399 if out is None:
400 400 rc = subprocess.call(cmd, shell=True, close_fds=closefds,
401 401 env=env, cwd=cwd)
402 402 else:
403 403 proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
404 404 env=env, cwd=cwd, stdout=subprocess.PIPE,
405 405 stderr=subprocess.STDOUT)
406 406 for line in proc.stdout:
407 407 out.write(line)
408 408 proc.wait()
409 409 rc = proc.returncode
410 410 if sys.platform == 'OpenVMS' and rc & 1:
411 411 rc = 0
412 412 if rc and onerr:
413 413 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
414 414 explain_exit(rc)[0])
415 415 if errprefix:
416 416 errmsg = '%s: %s' % (errprefix, errmsg)
417 417 try:
418 418 onerr.warn(errmsg + '\n')
419 419 except AttributeError:
420 420 raise onerr(errmsg)
421 421 return rc
422 422
423 423 def checksignature(func):
424 424 '''wrap a function with code to check for calling errors'''
425 425 def check(*args, **kwargs):
426 426 try:
427 427 return func(*args, **kwargs)
428 428 except TypeError:
429 429 if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
430 430 raise error.SignatureError
431 431 raise
432 432
433 433 return check
434 434
435 435 def unlink(f):
436 436 """unlink and remove the directory if it is empty"""
437 437 os.unlink(f)
438 438 # try removing directories that might now be empty
439 439 try:
440 440 os.removedirs(os.path.dirname(f))
441 441 except OSError:
442 442 pass
443 443
444 444 def copyfile(src, dest):
445 445 "copy a file, preserving mode and atime/mtime"
446 446 if os.path.islink(src):
447 447 try:
448 448 os.unlink(dest)
449 449 except:
450 450 pass
451 451 os.symlink(os.readlink(src), dest)
452 452 else:
453 453 try:
454 454 shutil.copyfile(src, dest)
455 455 shutil.copystat(src, dest)
456 456 except shutil.Error, inst:
457 457 raise Abort(str(inst))
458 458
459 459 def copyfiles(src, dst, hardlink=None):
460 460 """Copy a directory tree using hardlinks if possible"""
461 461
462 462 if hardlink is None:
463 463 hardlink = (os.stat(src).st_dev ==
464 464 os.stat(os.path.dirname(dst)).st_dev)
465 465
466 466 num = 0
467 467 if os.path.isdir(src):
468 468 os.mkdir(dst)
469 469 for name, kind in osutil.listdir(src):
470 470 srcname = os.path.join(src, name)
471 471 dstname = os.path.join(dst, name)
472 472 hardlink, n = copyfiles(srcname, dstname, hardlink)
473 473 num += n
474 474 else:
475 475 if hardlink:
476 476 try:
477 477 os_link(src, dst)
478 478 except (IOError, OSError):
479 479 hardlink = False
480 480 shutil.copy(src, dst)
481 481 else:
482 482 shutil.copy(src, dst)
483 483 num += 1
484 484
485 485 return hardlink, num
486 486
487 487 class path_auditor(object):
488 488 '''ensure that a filesystem path contains no banned components.
489 489 the following properties of a path are checked:
490 490
491 491 - under top-level .hg
492 492 - starts at the root of a windows drive
493 493 - contains ".."
494 494 - traverses a symlink (e.g. a/symlink_here/b)
495 495 - inside a nested repository (a callback can be used to approve
496 496 some nested repositories, e.g., subrepositories)
497 497 '''
498 498
499 499 def __init__(self, root, callback=None):
500 500 self.audited = set()
501 501 self.auditeddir = set()
502 502 self.root = root
503 503 self.callback = callback
504 504
505 505 def __call__(self, path):
506 506 if path in self.audited:
507 507 return
508 508 normpath = os.path.normcase(path)
509 509 parts = splitpath(normpath)
510 510 if (os.path.splitdrive(path)[0]
511 511 or parts[0].lower() in ('.hg', '.hg.', '')
512 512 or os.pardir in parts):
513 513 raise Abort(_("path contains illegal component: %s") % path)
514 514 if '.hg' in path.lower():
515 515 lparts = [p.lower() for p in parts]
516 516 for p in '.hg', '.hg.':
517 517 if p in lparts[1:]:
518 518 pos = lparts.index(p)
519 519 base = os.path.join(*parts[:pos])
520 520 raise Abort(_('path %r is inside repo %r') % (path, base))
521 521 def check(prefix):
522 522 curpath = os.path.join(self.root, prefix)
523 523 try:
524 524 st = os.lstat(curpath)
525 525 except OSError, err:
526 526 # EINVAL can be raised as invalid path syntax under win32.
527 527 # They must be ignored for patterns can be checked too.
528 528 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
529 529 raise
530 530 else:
531 531 if stat.S_ISLNK(st.st_mode):
532 532 raise Abort(_('path %r traverses symbolic link %r') %
533 533 (path, prefix))
534 534 elif (stat.S_ISDIR(st.st_mode) and
535 535 os.path.isdir(os.path.join(curpath, '.hg'))):
536 536 if not self.callback or not self.callback(curpath):
537 537 raise Abort(_('path %r is inside repo %r') %
538 538 (path, prefix))
539 539 parts.pop()
540 540 prefixes = []
541 541 while parts:
542 542 prefix = os.sep.join(parts)
543 543 if prefix in self.auditeddir:
544 544 break
545 545 check(prefix)
546 546 prefixes.append(prefix)
547 547 parts.pop()
548 548
549 549 self.audited.add(path)
550 550 # only add prefixes to the cache after checking everything: we don't
551 551 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
552 552 self.auditeddir.update(prefixes)
553 553
554 554 def nlinks(pathname):
555 555 """Return number of hardlinks for the given file."""
556 556 return os.lstat(pathname).st_nlink
557 557
558 558 if hasattr(os, 'link'):
559 559 os_link = os.link
560 560 else:
561 561 def os_link(src, dst):
562 562 raise OSError(0, _("Hardlinks not supported"))
563 563
564 564 def lookup_reg(key, name=None, scope=None):
565 565 return None
566 566
567 567 def hidewindow():
568 568 """Hide current shell window.
569 569
570 570 Used to hide the window opened when starting asynchronous
571 571 child process under Windows, unneeded on other systems.
572 572 """
573 573 pass
574 574
575 575 if os.name == 'nt':
576 576 from windows import *
577 577 else:
578 578 from posix import *
579 579
580 580 def makelock(info, pathname):
581 581 try:
582 582 return os.symlink(info, pathname)
583 583 except OSError, why:
584 584 if why.errno == errno.EEXIST:
585 585 raise
586 586 except AttributeError: # no symlink in os
587 587 pass
588 588
589 589 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
590 590 os.write(ld, info)
591 591 os.close(ld)
592 592
593 593 def readlock(pathname):
594 594 try:
595 595 return os.readlink(pathname)
596 596 except OSError, why:
597 597 if why.errno not in (errno.EINVAL, errno.ENOSYS):
598 598 raise
599 599 except AttributeError: # no symlink in os
600 600 pass
601 601 return posixfile(pathname).read()
602 602
603 603 def fstat(fp):
604 604 '''stat file object that may not have fileno method.'''
605 605 try:
606 606 return os.fstat(fp.fileno())
607 607 except AttributeError:
608 608 return os.stat(fp.name)
609 609
610 610 # File system features
611 611
612 612 def checkcase(path):
613 613 """
614 614 Check whether the given path is on a case-sensitive filesystem
615 615
616 616 Requires a path (like /foo/.hg) ending with a foldable final
617 617 directory component.
618 618 """
619 619 s1 = os.stat(path)
620 620 d, b = os.path.split(path)
621 621 p2 = os.path.join(d, b.upper())
622 622 if path == p2:
623 623 p2 = os.path.join(d, b.lower())
624 624 try:
625 625 s2 = os.stat(p2)
626 626 if s2 == s1:
627 627 return False
628 628 return True
629 629 except:
630 630 return True
631 631
632 632 _fspathcache = {}
633 633 def fspath(name, root):
634 634 '''Get name in the case stored in the filesystem
635 635
636 636 The name is either relative to root, or it is an absolute path starting
637 637 with root. Note that this function is unnecessary, and should not be
638 638 called, for case-sensitive filesystems (simply because it's expensive).
639 639 '''
640 640 # If name is absolute, make it relative
641 641 if name.lower().startswith(root.lower()):
642 642 l = len(root)
643 643 if name[l] == os.sep or name[l] == os.altsep:
644 644 l = l + 1
645 645 name = name[l:]
646 646
647 647 if not os.path.lexists(os.path.join(root, name)):
648 648 return None
649 649
650 650 seps = os.sep
651 651 if os.altsep:
652 652 seps = seps + os.altsep
653 653 # Protect backslashes. This gets silly very quickly.
654 654 seps.replace('\\','\\\\')
655 655 pattern = re.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
656 656 dir = os.path.normcase(os.path.normpath(root))
657 657 result = []
658 658 for part, sep in pattern.findall(name):
659 659 if sep:
660 660 result.append(sep)
661 661 continue
662 662
663 663 if dir not in _fspathcache:
664 664 _fspathcache[dir] = os.listdir(dir)
665 665 contents = _fspathcache[dir]
666 666
667 667 lpart = part.lower()
668 668 lenp = len(part)
669 669 for n in contents:
670 670 if lenp == len(n) and n.lower() == lpart:
671 671 result.append(n)
672 672 break
673 673 else:
674 674 # Cannot happen, as the file exists!
675 675 result.append(part)
676 676 dir = os.path.join(dir, lpart)
677 677
678 678 return ''.join(result)
679 679
680 680 def checkexec(path):
681 681 """
682 682 Check whether the given path is on a filesystem with UNIX-like exec flags
683 683
684 684 Requires a directory (like /foo/.hg)
685 685 """
686 686
687 687 # VFAT on some Linux versions can flip mode but it doesn't persist
688 688 # a FS remount. Frequently we can detect it if files are created
689 689 # with exec bit on.
690 690
691 691 try:
692 692 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
693 693 fh, fn = tempfile.mkstemp(dir=path, prefix='hg-checkexec-')
694 694 try:
695 695 os.close(fh)
696 696 m = os.stat(fn).st_mode & 0777
697 697 new_file_has_exec = m & EXECFLAGS
698 698 os.chmod(fn, m ^ EXECFLAGS)
699 699 exec_flags_cannot_flip = ((os.stat(fn).st_mode & 0777) == m)
700 700 finally:
701 701 os.unlink(fn)
702 702 except (IOError, OSError):
703 703 # we don't care, the user probably won't be able to commit anyway
704 704 return False
705 705 return not (new_file_has_exec or exec_flags_cannot_flip)
706 706
707 707 def checklink(path):
708 708 """check whether the given path is on a symlink-capable filesystem"""
709 709 # mktemp is not racy because symlink creation will fail if the
710 710 # file already exists
711 711 name = tempfile.mktemp(dir=path, prefix='hg-checklink-')
712 712 try:
713 713 os.symlink(".", name)
714 714 os.unlink(name)
715 715 return True
716 716 except (OSError, AttributeError):
717 717 return False
718 718
719 def needbinarypatch():
720 """return True if patches should be applied in binary mode by default."""
721 return os.name == 'nt'
722
723 719 def endswithsep(path):
724 720 '''Check path ends with os.sep or os.altsep.'''
725 721 return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
726 722
727 723 def splitpath(path):
728 724 '''Split path by os.sep.
729 725 Note that this function does not use os.altsep because this is
730 726 an alternative of simple "xxx.split(os.sep)".
731 727 It is recommended to use os.path.normpath() before using this
732 728 function if need.'''
733 729 return path.split(os.sep)
734 730
735 731 def gui():
736 732 '''Are we running in a GUI?'''
737 733 return os.name == "nt" or os.name == "mac" or os.environ.get("DISPLAY")
738 734
739 735 def mktempcopy(name, emptyok=False, createmode=None):
740 736 """Create a temporary file with the same contents from name
741 737
742 738 The permission bits are copied from the original file.
743 739
744 740 If the temporary file is going to be truncated immediately, you
745 741 can use emptyok=True as an optimization.
746 742
747 743 Returns the name of the temporary file.
748 744 """
749 745 d, fn = os.path.split(name)
750 746 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
751 747 os.close(fd)
752 748 # Temporary files are created with mode 0600, which is usually not
753 749 # what we want. If the original file already exists, just copy
754 750 # its mode. Otherwise, manually obey umask.
755 751 try:
756 752 st_mode = os.lstat(name).st_mode & 0777
757 753 except OSError, inst:
758 754 if inst.errno != errno.ENOENT:
759 755 raise
760 756 st_mode = createmode
761 757 if st_mode is None:
762 758 st_mode = ~umask
763 759 st_mode &= 0666
764 760 os.chmod(temp, st_mode)
765 761 if emptyok:
766 762 return temp
767 763 try:
768 764 try:
769 765 ifp = posixfile(name, "rb")
770 766 except IOError, inst:
771 767 if inst.errno == errno.ENOENT:
772 768 return temp
773 769 if not getattr(inst, 'filename', None):
774 770 inst.filename = name
775 771 raise
776 772 ofp = posixfile(temp, "wb")
777 773 for chunk in filechunkiter(ifp):
778 774 ofp.write(chunk)
779 775 ifp.close()
780 776 ofp.close()
781 777 except:
782 778 try: os.unlink(temp)
783 779 except: pass
784 780 raise
785 781 return temp
786 782
787 783 class atomictempfile(object):
788 784 """file-like object that atomically updates a file
789 785
790 786 All writes will be redirected to a temporary copy of the original
791 787 file. When rename is called, the copy is renamed to the original
792 788 name, making the changes visible.
793 789 """
794 790 def __init__(self, name, mode='w+b', createmode=None):
795 791 self.__name = name
796 792 self._fp = None
797 793 self.temp = mktempcopy(name, emptyok=('w' in mode),
798 794 createmode=createmode)
799 795 self._fp = posixfile(self.temp, mode)
800 796
801 797 def __getattr__(self, name):
802 798 return getattr(self._fp, name)
803 799
804 800 def rename(self):
805 801 if not self._fp.closed:
806 802 self._fp.close()
807 803 rename(self.temp, localpath(self.__name))
808 804
809 805 def __del__(self):
810 806 if not self._fp:
811 807 return
812 808 if not self._fp.closed:
813 809 try:
814 810 os.unlink(self.temp)
815 811 except: pass
816 812 self._fp.close()
817 813
818 814 def makedirs(name, mode=None):
819 815 """recursive directory creation with parent mode inheritance"""
820 816 try:
821 817 os.mkdir(name)
822 818 if mode is not None:
823 819 os.chmod(name, mode)
824 820 return
825 821 except OSError, err:
826 822 if err.errno == errno.EEXIST:
827 823 return
828 824 if err.errno != errno.ENOENT:
829 825 raise
830 826 parent = os.path.abspath(os.path.dirname(name))
831 827 makedirs(parent, mode)
832 828 makedirs(name, mode)
833 829
834 830 class opener(object):
835 831 """Open files relative to a base directory
836 832
837 833 This class is used to hide the details of COW semantics and
838 834 remote file access from higher level code.
839 835 """
840 836 def __init__(self, base, audit=True):
841 837 self.base = base
842 838 if audit:
843 839 self.auditor = path_auditor(base)
844 840 else:
845 841 self.auditor = always
846 842 self.createmode = None
847 843
848 844 @propertycache
849 845 def _can_symlink(self):
850 846 return checklink(self.base)
851 847
852 848 def _fixfilemode(self, name):
853 849 if self.createmode is None:
854 850 return
855 851 os.chmod(name, self.createmode & 0666)
856 852
857 853 def __call__(self, path, mode="r", text=False, atomictemp=False):
858 854 self.auditor(path)
859 855 f = os.path.join(self.base, path)
860 856
861 857 if not text and "b" not in mode:
862 858 mode += "b" # for that other OS
863 859
864 860 nlink = -1
865 861 if mode not in ("r", "rb"):
866 862 try:
867 863 nlink = nlinks(f)
868 864 except OSError:
869 865 nlink = 0
870 866 d = os.path.dirname(f)
871 867 if not os.path.isdir(d):
872 868 makedirs(d, self.createmode)
873 869 if atomictemp:
874 870 return atomictempfile(f, mode, self.createmode)
875 871 if nlink > 1:
876 872 rename(mktempcopy(f), f)
877 873 fp = posixfile(f, mode)
878 874 if nlink == 0:
879 875 self._fixfilemode(f)
880 876 return fp
881 877
882 878 def symlink(self, src, dst):
883 879 self.auditor(dst)
884 880 linkname = os.path.join(self.base, dst)
885 881 try:
886 882 os.unlink(linkname)
887 883 except OSError:
888 884 pass
889 885
890 886 dirname = os.path.dirname(linkname)
891 887 if not os.path.exists(dirname):
892 888 makedirs(dirname, self.createmode)
893 889
894 890 if self._can_symlink:
895 891 try:
896 892 os.symlink(src, linkname)
897 893 except OSError, err:
898 894 raise OSError(err.errno, _('could not symlink to %r: %s') %
899 895 (src, err.strerror), linkname)
900 896 else:
901 897 f = self(dst, "w")
902 898 f.write(src)
903 899 f.close()
904 900 self._fixfilemode(dst)
905 901
906 902 class chunkbuffer(object):
907 903 """Allow arbitrary sized chunks of data to be efficiently read from an
908 904 iterator over chunks of arbitrary size."""
909 905
910 906 def __init__(self, in_iter):
911 907 """in_iter is the iterator that's iterating over the input chunks.
912 908 targetsize is how big a buffer to try to maintain."""
913 909 def splitbig(chunks):
914 910 for chunk in chunks:
915 911 if len(chunk) > 2**20:
916 912 pos = 0
917 913 while pos < len(chunk):
918 914 end = pos + 2 ** 18
919 915 yield chunk[pos:end]
920 916 pos = end
921 917 else:
922 918 yield chunk
923 919 self.iter = splitbig(in_iter)
924 920 self._queue = []
925 921
926 922 def read(self, l):
927 923 """Read L bytes of data from the iterator of chunks of data.
928 924 Returns less than L bytes if the iterator runs dry."""
929 925 left = l
930 926 buf = ''
931 927 queue = self._queue
932 928 while left > 0:
933 929 # refill the queue
934 930 if not queue:
935 931 target = 2**18
936 932 for chunk in self.iter:
937 933 queue.append(chunk)
938 934 target -= len(chunk)
939 935 if target <= 0:
940 936 break
941 937 if not queue:
942 938 break
943 939
944 940 chunk = queue.pop(0)
945 941 left -= len(chunk)
946 942 if left < 0:
947 943 queue.insert(0, chunk[left:])
948 944 buf += chunk[:left]
949 945 else:
950 946 buf += chunk
951 947
952 948 return buf
953 949
954 950 def filechunkiter(f, size=65536, limit=None):
955 951 """Create a generator that produces the data in the file size
956 952 (default 65536) bytes at a time, up to optional limit (default is
957 953 to read all data). Chunks may be less than size bytes if the
958 954 chunk is the last chunk in the file, or the file is a socket or
959 955 some other type of file that sometimes reads less data than is
960 956 requested."""
961 957 assert size >= 0
962 958 assert limit is None or limit >= 0
963 959 while True:
964 960 if limit is None:
965 961 nbytes = size
966 962 else:
967 963 nbytes = min(limit, size)
968 964 s = nbytes and f.read(nbytes)
969 965 if not s:
970 966 break
971 967 if limit:
972 968 limit -= len(s)
973 969 yield s
974 970
975 971 def makedate():
976 972 lt = time.localtime()
977 973 if lt[8] == 1 and time.daylight:
978 974 tz = time.altzone
979 975 else:
980 976 tz = time.timezone
981 977 return time.mktime(lt), tz
982 978
983 979 def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
984 980 """represent a (unixtime, offset) tuple as a localized time.
985 981 unixtime is seconds since the epoch, and offset is the time zone's
986 982 number of seconds away from UTC. if timezone is false, do not
987 983 append time zone to string."""
988 984 t, tz = date or makedate()
989 985 if "%1" in format or "%2" in format:
990 986 sign = (tz > 0) and "-" or "+"
991 987 minutes = abs(tz) // 60
992 988 format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
993 989 format = format.replace("%2", "%02d" % (minutes % 60))
994 990 s = time.strftime(format, time.gmtime(float(t) - tz))
995 991 return s
996 992
997 993 def shortdate(date=None):
998 994 """turn (timestamp, tzoff) tuple into iso 8631 date."""
999 995 return datestr(date, format='%Y-%m-%d')
1000 996
1001 997 def strdate(string, format, defaults=[]):
1002 998 """parse a localized time string and return a (unixtime, offset) tuple.
1003 999 if the string cannot be parsed, ValueError is raised."""
1004 1000 def timezone(string):
1005 1001 tz = string.split()[-1]
1006 1002 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1007 1003 sign = (tz[0] == "+") and 1 or -1
1008 1004 hours = int(tz[1:3])
1009 1005 minutes = int(tz[3:5])
1010 1006 return -sign * (hours * 60 + minutes) * 60
1011 1007 if tz == "GMT" or tz == "UTC":
1012 1008 return 0
1013 1009 return None
1014 1010
1015 1011 # NOTE: unixtime = localunixtime + offset
1016 1012 offset, date = timezone(string), string
1017 1013 if offset != None:
1018 1014 date = " ".join(string.split()[:-1])
1019 1015
1020 1016 # add missing elements from defaults
1021 1017 for part in defaults:
1022 1018 found = [True for p in part if ("%"+p) in format]
1023 1019 if not found:
1024 1020 date += "@" + defaults[part]
1025 1021 format += "@%" + part[0]
1026 1022
1027 1023 timetuple = time.strptime(date, format)
1028 1024 localunixtime = int(calendar.timegm(timetuple))
1029 1025 if offset is None:
1030 1026 # local timezone
1031 1027 unixtime = int(time.mktime(timetuple))
1032 1028 offset = unixtime - localunixtime
1033 1029 else:
1034 1030 unixtime = localunixtime + offset
1035 1031 return unixtime, offset
1036 1032
1037 1033 def parsedate(date, formats=None, defaults=None):
1038 1034 """parse a localized date/time string and return a (unixtime, offset) tuple.
1039 1035
1040 1036 The date may be a "unixtime offset" string or in one of the specified
1041 1037 formats. If the date already is a (unixtime, offset) tuple, it is returned.
1042 1038 """
1043 1039 if not date:
1044 1040 return 0, 0
1045 1041 if isinstance(date, tuple) and len(date) == 2:
1046 1042 return date
1047 1043 if not formats:
1048 1044 formats = defaultdateformats
1049 1045 date = date.strip()
1050 1046 try:
1051 1047 when, offset = map(int, date.split(' '))
1052 1048 except ValueError:
1053 1049 # fill out defaults
1054 1050 if not defaults:
1055 1051 defaults = {}
1056 1052 now = makedate()
1057 1053 for part in "d mb yY HI M S".split():
1058 1054 if part not in defaults:
1059 1055 if part[0] in "HMS":
1060 1056 defaults[part] = "00"
1061 1057 else:
1062 1058 defaults[part] = datestr(now, "%" + part[0])
1063 1059
1064 1060 for format in formats:
1065 1061 try:
1066 1062 when, offset = strdate(date, format, defaults)
1067 1063 except (ValueError, OverflowError):
1068 1064 pass
1069 1065 else:
1070 1066 break
1071 1067 else:
1072 1068 raise Abort(_('invalid date: %r') % date)
1073 1069 # validate explicit (probably user-specified) date and
1074 1070 # time zone offset. values must fit in signed 32 bits for
1075 1071 # current 32-bit linux runtimes. timezones go from UTC-12
1076 1072 # to UTC+14
1077 1073 if abs(when) > 0x7fffffff:
1078 1074 raise Abort(_('date exceeds 32 bits: %d') % when)
1079 1075 if offset < -50400 or offset > 43200:
1080 1076 raise Abort(_('impossible time zone offset: %d') % offset)
1081 1077 return when, offset
1082 1078
1083 1079 def matchdate(date):
1084 1080 """Return a function that matches a given date match specifier
1085 1081
1086 1082 Formats include:
1087 1083
1088 1084 '{date}' match a given date to the accuracy provided
1089 1085
1090 1086 '<{date}' on or before a given date
1091 1087
1092 1088 '>{date}' on or after a given date
1093 1089
1094 1090 """
1095 1091
1096 1092 def lower(date):
1097 1093 d = dict(mb="1", d="1")
1098 1094 return parsedate(date, extendeddateformats, d)[0]
1099 1095
1100 1096 def upper(date):
1101 1097 d = dict(mb="12", HI="23", M="59", S="59")
1102 1098 for days in "31 30 29".split():
1103 1099 try:
1104 1100 d["d"] = days
1105 1101 return parsedate(date, extendeddateformats, d)[0]
1106 1102 except:
1107 1103 pass
1108 1104 d["d"] = "28"
1109 1105 return parsedate(date, extendeddateformats, d)[0]
1110 1106
1111 1107 date = date.strip()
1112 1108 if date[0] == "<":
1113 1109 when = upper(date[1:])
1114 1110 return lambda x: x <= when
1115 1111 elif date[0] == ">":
1116 1112 when = lower(date[1:])
1117 1113 return lambda x: x >= when
1118 1114 elif date[0] == "-":
1119 1115 try:
1120 1116 days = int(date[1:])
1121 1117 except ValueError:
1122 1118 raise Abort(_("invalid day spec: %s") % date[1:])
1123 1119 when = makedate()[0] - days * 3600 * 24
1124 1120 return lambda x: x >= when
1125 1121 elif " to " in date:
1126 1122 a, b = date.split(" to ")
1127 1123 start, stop = lower(a), upper(b)
1128 1124 return lambda x: x >= start and x <= stop
1129 1125 else:
1130 1126 start, stop = lower(date), upper(date)
1131 1127 return lambda x: x >= start and x <= stop
1132 1128
1133 1129 def shortuser(user):
1134 1130 """Return a short representation of a user name or email address."""
1135 1131 f = user.find('@')
1136 1132 if f >= 0:
1137 1133 user = user[:f]
1138 1134 f = user.find('<')
1139 1135 if f >= 0:
1140 1136 user = user[f + 1:]
1141 1137 f = user.find(' ')
1142 1138 if f >= 0:
1143 1139 user = user[:f]
1144 1140 f = user.find('.')
1145 1141 if f >= 0:
1146 1142 user = user[:f]
1147 1143 return user
1148 1144
1149 1145 def email(author):
1150 1146 '''get email of author.'''
1151 1147 r = author.find('>')
1152 1148 if r == -1:
1153 1149 r = None
1154 1150 return author[author.find('<') + 1:r]
1155 1151
1156 1152 def ellipsis(text, maxlength=400):
1157 1153 """Trim string to at most maxlength (default: 400) characters."""
1158 1154 if len(text) <= maxlength:
1159 1155 return text
1160 1156 else:
1161 1157 return "%s..." % (text[:maxlength - 3])
1162 1158
1163 1159 def walkrepos(path, followsym=False, seen_dirs=None, recurse=False):
1164 1160 '''yield every hg repository under path, recursively.'''
1165 1161 def errhandler(err):
1166 1162 if err.filename == path:
1167 1163 raise err
1168 1164 if followsym and hasattr(os.path, 'samestat'):
1169 1165 def _add_dir_if_not_there(dirlst, dirname):
1170 1166 match = False
1171 1167 samestat = os.path.samestat
1172 1168 dirstat = os.stat(dirname)
1173 1169 for lstdirstat in dirlst:
1174 1170 if samestat(dirstat, lstdirstat):
1175 1171 match = True
1176 1172 break
1177 1173 if not match:
1178 1174 dirlst.append(dirstat)
1179 1175 return not match
1180 1176 else:
1181 1177 followsym = False
1182 1178
1183 1179 if (seen_dirs is None) and followsym:
1184 1180 seen_dirs = []
1185 1181 _add_dir_if_not_there(seen_dirs, path)
1186 1182 for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
1187 1183 dirs.sort()
1188 1184 if '.hg' in dirs:
1189 1185 yield root # found a repository
1190 1186 qroot = os.path.join(root, '.hg', 'patches')
1191 1187 if os.path.isdir(os.path.join(qroot, '.hg')):
1192 1188 yield qroot # we have a patch queue repo here
1193 1189 if recurse:
1194 1190 # avoid recursing inside the .hg directory
1195 1191 dirs.remove('.hg')
1196 1192 else:
1197 1193 dirs[:] = [] # don't descend further
1198 1194 elif followsym:
1199 1195 newdirs = []
1200 1196 for d in dirs:
1201 1197 fname = os.path.join(root, d)
1202 1198 if _add_dir_if_not_there(seen_dirs, fname):
1203 1199 if os.path.islink(fname):
1204 1200 for hgname in walkrepos(fname, True, seen_dirs):
1205 1201 yield hgname
1206 1202 else:
1207 1203 newdirs.append(d)
1208 1204 dirs[:] = newdirs
1209 1205
1210 1206 _rcpath = None
1211 1207
1212 1208 def os_rcpath():
1213 1209 '''return default os-specific hgrc search path'''
1214 1210 path = system_rcpath()
1215 1211 path.extend(user_rcpath())
1216 1212 path = [os.path.normpath(f) for f in path]
1217 1213 return path
1218 1214
1219 1215 def rcpath():
1220 1216 '''return hgrc search path. if env var HGRCPATH is set, use it.
1221 1217 for each item in path, if directory, use files ending in .rc,
1222 1218 else use item.
1223 1219 make HGRCPATH empty to only look in .hg/hgrc of current repo.
1224 1220 if no HGRCPATH, use default os-specific path.'''
1225 1221 global _rcpath
1226 1222 if _rcpath is None:
1227 1223 if 'HGRCPATH' in os.environ:
1228 1224 _rcpath = []
1229 1225 for p in os.environ['HGRCPATH'].split(os.pathsep):
1230 1226 if not p:
1231 1227 continue
1232 1228 p = expandpath(p)
1233 1229 if os.path.isdir(p):
1234 1230 for f, kind in osutil.listdir(p):
1235 1231 if f.endswith('.rc'):
1236 1232 _rcpath.append(os.path.join(p, f))
1237 1233 else:
1238 1234 _rcpath.append(p)
1239 1235 else:
1240 1236 _rcpath = os_rcpath()
1241 1237 return _rcpath
1242 1238
1243 1239 def bytecount(nbytes):
1244 1240 '''return byte count formatted as readable string, with units'''
1245 1241
1246 1242 units = (
1247 1243 (100, 1 << 30, _('%.0f GB')),
1248 1244 (10, 1 << 30, _('%.1f GB')),
1249 1245 (1, 1 << 30, _('%.2f GB')),
1250 1246 (100, 1 << 20, _('%.0f MB')),
1251 1247 (10, 1 << 20, _('%.1f MB')),
1252 1248 (1, 1 << 20, _('%.2f MB')),
1253 1249 (100, 1 << 10, _('%.0f KB')),
1254 1250 (10, 1 << 10, _('%.1f KB')),
1255 1251 (1, 1 << 10, _('%.2f KB')),
1256 1252 (1, 1, _('%.0f bytes')),
1257 1253 )
1258 1254
1259 1255 for multiplier, divisor, format in units:
1260 1256 if nbytes >= divisor * multiplier:
1261 1257 return format % (nbytes / float(divisor))
1262 1258 return units[-1][2] % nbytes
1263 1259
1264 1260 def drop_scheme(scheme, path):
1265 1261 sc = scheme + ':'
1266 1262 if path.startswith(sc):
1267 1263 path = path[len(sc):]
1268 1264 if path.startswith('//'):
1269 1265 if scheme == 'file':
1270 1266 i = path.find('/', 2)
1271 1267 if i == -1:
1272 1268 return ''
1273 1269 # On Windows, absolute paths are rooted at the current drive
1274 1270 # root. On POSIX they are rooted at the file system root.
1275 1271 if os.name == 'nt':
1276 1272 droot = os.path.splitdrive(os.getcwd())[0] + '/'
1277 1273 path = os.path.join(droot, path[i + 1:])
1278 1274 else:
1279 1275 path = path[i:]
1280 1276 else:
1281 1277 path = path[2:]
1282 1278 return path
1283 1279
1284 1280 def uirepr(s):
1285 1281 # Avoid double backslash in Windows path repr()
1286 1282 return repr(s).replace('\\\\', '\\')
1287 1283
1288 1284 #### naming convention of below implementation follows 'textwrap' module
1289 1285
1290 1286 class MBTextWrapper(textwrap.TextWrapper):
1291 1287 def __init__(self, **kwargs):
1292 1288 textwrap.TextWrapper.__init__(self, **kwargs)
1293 1289
1294 1290 def _cutdown(self, str, space_left):
1295 1291 l = 0
1296 1292 ucstr = unicode(str, encoding.encoding)
1297 1293 w = unicodedata.east_asian_width
1298 1294 for i in xrange(len(ucstr)):
1299 1295 l += w(ucstr[i]) in 'WFA' and 2 or 1
1300 1296 if space_left < l:
1301 1297 return (ucstr[:i].encode(encoding.encoding),
1302 1298 ucstr[i:].encode(encoding.encoding))
1303 1299 return str, ''
1304 1300
1305 1301 # ----------------------------------------
1306 1302 # overriding of base class
1307 1303
1308 1304 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
1309 1305 space_left = max(width - cur_len, 1)
1310 1306
1311 1307 if self.break_long_words:
1312 1308 cut, res = self._cutdown(reversed_chunks[-1], space_left)
1313 1309 cur_line.append(cut)
1314 1310 reversed_chunks[-1] = res
1315 1311 elif not cur_line:
1316 1312 cur_line.append(reversed_chunks.pop())
1317 1313
1318 1314 #### naming convention of above implementation follows 'textwrap' module
1319 1315
1320 1316 def wrap(line, width=None, initindent='', hangindent=''):
1321 1317 if width is None:
1322 1318 width = termwidth() - 2
1323 1319 maxindent = max(len(hangindent), len(initindent))
1324 1320 if width <= maxindent:
1325 1321 # adjust for weird terminal size
1326 1322 width = max(78, maxindent + 1)
1327 1323 wrapper = MBTextWrapper(width=width,
1328 1324 initial_indent=initindent,
1329 1325 subsequent_indent=hangindent)
1330 1326 return wrapper.fill(line)
1331 1327
1332 1328 def iterlines(iterator):
1333 1329 for chunk in iterator:
1334 1330 for line in chunk.splitlines():
1335 1331 yield line
1336 1332
1337 1333 def expandpath(path):
1338 1334 return os.path.expanduser(os.path.expandvars(path))
1339 1335
1340 1336 def hgcmd():
1341 1337 """Return the command used to execute current hg
1342 1338
1343 1339 This is different from hgexecutable() because on Windows we want
1344 1340 to avoid things opening new shell windows like batch files, so we
1345 1341 get either the python call or current executable.
1346 1342 """
1347 1343 if main_is_frozen():
1348 1344 return [sys.executable]
1349 1345 return gethgcmd()
1350 1346
1351 1347 def rundetached(args, condfn):
1352 1348 """Execute the argument list in a detached process.
1353 1349
1354 1350 condfn is a callable which is called repeatedly and should return
1355 1351 True once the child process is known to have started successfully.
1356 1352 At this point, the child process PID is returned. If the child
1357 1353 process fails to start or finishes before condfn() evaluates to
1358 1354 True, return -1.
1359 1355 """
1360 1356 # Windows case is easier because the child process is either
1361 1357 # successfully starting and validating the condition or exiting
1362 1358 # on failure. We just poll on its PID. On Unix, if the child
1363 1359 # process fails to start, it will be left in a zombie state until
1364 1360 # the parent wait on it, which we cannot do since we expect a long
1365 1361 # running process on success. Instead we listen for SIGCHLD telling
1366 1362 # us our child process terminated.
1367 1363 terminated = set()
1368 1364 def handler(signum, frame):
1369 1365 terminated.add(os.wait())
1370 1366 prevhandler = None
1371 1367 if hasattr(signal, 'SIGCHLD'):
1372 1368 prevhandler = signal.signal(signal.SIGCHLD, handler)
1373 1369 try:
1374 1370 pid = spawndetached(args)
1375 1371 while not condfn():
1376 1372 if ((pid in terminated or not testpid(pid))
1377 1373 and not condfn()):
1378 1374 return -1
1379 1375 time.sleep(0.1)
1380 1376 return pid
1381 1377 finally:
1382 1378 if prevhandler is not None:
1383 1379 signal.signal(signal.SIGCHLD, prevhandler)
1384 1380
1385 1381 try:
1386 1382 any, all = any, all
1387 1383 except NameError:
1388 1384 def any(iterable):
1389 1385 for i in iterable:
1390 1386 if i:
1391 1387 return True
1392 1388 return False
1393 1389
1394 1390 def all(iterable):
1395 1391 for i in iterable:
1396 1392 if not i:
1397 1393 return False
1398 1394 return True
1399 1395
1400 1396 def termwidth():
1401 1397 if 'COLUMNS' in os.environ:
1402 1398 try:
1403 1399 return int(os.environ['COLUMNS'])
1404 1400 except ValueError:
1405 1401 pass
1406 1402 return termwidth_()
1407 1403
1408 1404 def interpolate(prefix, mapping, s, fn=None):
1409 1405 """Return the result of interpolating items in the mapping into string s.
1410 1406
1411 1407 prefix is a single character string, or a two character string with
1412 1408 a backslash as the first character if the prefix needs to be escaped in
1413 1409 a regular expression.
1414 1410
1415 1411 fn is an optional function that will be applied to the replacement text
1416 1412 just before replacement.
1417 1413 """
1418 1414 fn = fn or (lambda s: s)
1419 1415 r = re.compile(r'%s(%s)' % (prefix, '|'.join(mapping.keys())))
1420 1416 return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
1421 1417
1422 1418 def getport(port):
1423 1419 """Return the port for a given network service.
1424 1420
1425 1421 If port is an integer, it's returned as is. If it's a string, it's
1426 1422 looked up using socket.getservbyname(). If there's no matching
1427 1423 service, util.Abort is raised.
1428 1424 """
1429 1425 try:
1430 1426 return int(port)
1431 1427 except ValueError:
1432 1428 pass
1433 1429
1434 1430 try:
1435 1431 return socket.getservbyname(port)
1436 1432 except socket.error:
1437 1433 raise Abort(_("no port number associated with service '%s'") % port)
1438 1434
1439 1435 _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
1440 1436 '0': False, 'no': False, 'false': False, 'off': False,
1441 1437 'never': False}
1442 1438
1443 1439 def parsebool(s):
1444 1440 """Parse s into a boolean.
1445 1441
1446 1442 If s is not a valid boolean, returns None.
1447 1443 """
1448 1444 return _booleans.get(s.lower(), None)
General Comments 0
You need to be logged in to leave comments. Login now