##// END OF EJS Templates
util: add notindexed optional parameter to makedirs function
Angel Ezquerra -
r18938:e22107cf default
parent child Browse files
Show More
@@ -1,1926 +1,1926 b''
1 1 # util.py - Mercurial utility functions and platform specific 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 specific 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, collections
18 18 import errno, re, shutil, sys, tempfile, traceback
19 19 import os, time, datetime, calendar, textwrap, signal
20 20 import imp, socket, urllib
21 21
22 22 if os.name == 'nt':
23 23 import windows as platform
24 24 else:
25 25 import posix as platform
26 26
27 27 cachestat = platform.cachestat
28 28 checkexec = platform.checkexec
29 29 checklink = platform.checklink
30 30 copymode = platform.copymode
31 31 executablepath = platform.executablepath
32 32 expandglobs = platform.expandglobs
33 33 explainexit = platform.explainexit
34 34 findexe = platform.findexe
35 35 gethgcmd = platform.gethgcmd
36 36 getuser = platform.getuser
37 37 groupmembers = platform.groupmembers
38 38 groupname = platform.groupname
39 39 hidewindow = platform.hidewindow
40 40 isexec = platform.isexec
41 41 isowner = platform.isowner
42 42 localpath = platform.localpath
43 43 lookupreg = platform.lookupreg
44 44 makedir = platform.makedir
45 45 nlinks = platform.nlinks
46 46 normpath = platform.normpath
47 47 normcase = platform.normcase
48 48 openhardlinks = platform.openhardlinks
49 49 oslink = platform.oslink
50 50 parsepatchoutput = platform.parsepatchoutput
51 51 pconvert = platform.pconvert
52 52 popen = platform.popen
53 53 posixfile = platform.posixfile
54 54 quotecommand = platform.quotecommand
55 55 realpath = platform.realpath
56 56 rename = platform.rename
57 57 samedevice = platform.samedevice
58 58 samefile = platform.samefile
59 59 samestat = platform.samestat
60 60 setbinary = platform.setbinary
61 61 setflags = platform.setflags
62 62 setsignalhandler = platform.setsignalhandler
63 63 shellquote = platform.shellquote
64 64 spawndetached = platform.spawndetached
65 65 split = platform.split
66 66 sshargs = platform.sshargs
67 67 statfiles = getattr(osutil, 'statfiles', platform.statfiles)
68 68 statisexec = platform.statisexec
69 69 statislink = platform.statislink
70 70 termwidth = platform.termwidth
71 71 testpid = platform.testpid
72 72 umask = platform.umask
73 73 unlink = platform.unlink
74 74 unlinkpath = platform.unlinkpath
75 75 username = platform.username
76 76
77 77 # Python compatibility
78 78
79 79 _notset = object()
80 80
81 81 def safehasattr(thing, attr):
82 82 return getattr(thing, attr, _notset) is not _notset
83 83
84 84 def sha1(s=''):
85 85 '''
86 86 Low-overhead wrapper around Python's SHA support
87 87
88 88 >>> f = _fastsha1
89 89 >>> a = sha1()
90 90 >>> a = f()
91 91 >>> a.hexdigest()
92 92 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
93 93 '''
94 94
95 95 return _fastsha1(s)
96 96
97 97 def _fastsha1(s=''):
98 98 # This function will import sha1 from hashlib or sha (whichever is
99 99 # available) and overwrite itself with it on the first call.
100 100 # Subsequent calls will go directly to the imported function.
101 101 if sys.version_info >= (2, 5):
102 102 from hashlib import sha1 as _sha1
103 103 else:
104 104 from sha import sha as _sha1
105 105 global _fastsha1, sha1
106 106 _fastsha1 = sha1 = _sha1
107 107 return _sha1(s)
108 108
109 109 try:
110 110 buffer = buffer
111 111 except NameError:
112 112 if sys.version_info[0] < 3:
113 113 def buffer(sliceable, offset=0):
114 114 return sliceable[offset:]
115 115 else:
116 116 def buffer(sliceable, offset=0):
117 117 return memoryview(sliceable)[offset:]
118 118
119 119 import subprocess
120 120 closefds = os.name == 'posix'
121 121
122 122 def popen2(cmd, env=None, newlines=False):
123 123 # Setting bufsize to -1 lets the system decide the buffer size.
124 124 # The default for bufsize is 0, meaning unbuffered. This leads to
125 125 # poor performance on Mac OS X: http://bugs.python.org/issue4194
126 126 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
127 127 close_fds=closefds,
128 128 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
129 129 universal_newlines=newlines,
130 130 env=env)
131 131 return p.stdin, p.stdout
132 132
133 133 def popen3(cmd, env=None, newlines=False):
134 134 stdin, stdout, stderr, p = popen4(cmd, env, newlines)
135 135 return stdin, stdout, stderr
136 136
137 137 def popen4(cmd, env=None, newlines=False):
138 138 p = subprocess.Popen(cmd, shell=True, bufsize=-1,
139 139 close_fds=closefds,
140 140 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
141 141 stderr=subprocess.PIPE,
142 142 universal_newlines=newlines,
143 143 env=env)
144 144 return p.stdin, p.stdout, p.stderr, p
145 145
146 146 def version():
147 147 """Return version information if available."""
148 148 try:
149 149 import __version__
150 150 return __version__.version
151 151 except ImportError:
152 152 return 'unknown'
153 153
154 154 # used by parsedate
155 155 defaultdateformats = (
156 156 '%Y-%m-%d %H:%M:%S',
157 157 '%Y-%m-%d %I:%M:%S%p',
158 158 '%Y-%m-%d %H:%M',
159 159 '%Y-%m-%d %I:%M%p',
160 160 '%Y-%m-%d',
161 161 '%m-%d',
162 162 '%m/%d',
163 163 '%m/%d/%y',
164 164 '%m/%d/%Y',
165 165 '%a %b %d %H:%M:%S %Y',
166 166 '%a %b %d %I:%M:%S%p %Y',
167 167 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
168 168 '%b %d %H:%M:%S %Y',
169 169 '%b %d %I:%M:%S%p %Y',
170 170 '%b %d %H:%M:%S',
171 171 '%b %d %I:%M:%S%p',
172 172 '%b %d %H:%M',
173 173 '%b %d %I:%M%p',
174 174 '%b %d %Y',
175 175 '%b %d',
176 176 '%H:%M:%S',
177 177 '%I:%M:%S%p',
178 178 '%H:%M',
179 179 '%I:%M%p',
180 180 )
181 181
182 182 extendeddateformats = defaultdateformats + (
183 183 "%Y",
184 184 "%Y-%m",
185 185 "%b",
186 186 "%b %Y",
187 187 )
188 188
189 189 def cachefunc(func):
190 190 '''cache the result of function calls'''
191 191 # XXX doesn't handle keywords args
192 192 cache = {}
193 193 if func.func_code.co_argcount == 1:
194 194 # we gain a small amount of time because
195 195 # we don't need to pack/unpack the list
196 196 def f(arg):
197 197 if arg not in cache:
198 198 cache[arg] = func(arg)
199 199 return cache[arg]
200 200 else:
201 201 def f(*args):
202 202 if args not in cache:
203 203 cache[args] = func(*args)
204 204 return cache[args]
205 205
206 206 return f
207 207
208 208 try:
209 209 collections.deque.remove
210 210 deque = collections.deque
211 211 except AttributeError:
212 212 # python 2.4 lacks deque.remove
213 213 class deque(collections.deque):
214 214 def remove(self, val):
215 215 for i, v in enumerate(self):
216 216 if v == val:
217 217 del self[i]
218 218 break
219 219
220 220 class lrucachedict(object):
221 221 '''cache most recent gets from or sets to this dictionary'''
222 222 def __init__(self, maxsize):
223 223 self._cache = {}
224 224 self._maxsize = maxsize
225 225 self._order = deque()
226 226
227 227 def __getitem__(self, key):
228 228 value = self._cache[key]
229 229 self._order.remove(key)
230 230 self._order.append(key)
231 231 return value
232 232
233 233 def __setitem__(self, key, value):
234 234 if key not in self._cache:
235 235 if len(self._cache) >= self._maxsize:
236 236 del self._cache[self._order.popleft()]
237 237 else:
238 238 self._order.remove(key)
239 239 self._cache[key] = value
240 240 self._order.append(key)
241 241
242 242 def __contains__(self, key):
243 243 return key in self._cache
244 244
245 245 def lrucachefunc(func):
246 246 '''cache most recent results of function calls'''
247 247 cache = {}
248 248 order = deque()
249 249 if func.func_code.co_argcount == 1:
250 250 def f(arg):
251 251 if arg not in cache:
252 252 if len(cache) > 20:
253 253 del cache[order.popleft()]
254 254 cache[arg] = func(arg)
255 255 else:
256 256 order.remove(arg)
257 257 order.append(arg)
258 258 return cache[arg]
259 259 else:
260 260 def f(*args):
261 261 if args not in cache:
262 262 if len(cache) > 20:
263 263 del cache[order.popleft()]
264 264 cache[args] = func(*args)
265 265 else:
266 266 order.remove(args)
267 267 order.append(args)
268 268 return cache[args]
269 269
270 270 return f
271 271
272 272 class propertycache(object):
273 273 def __init__(self, func):
274 274 self.func = func
275 275 self.name = func.__name__
276 276 def __get__(self, obj, type=None):
277 277 result = self.func(obj)
278 278 self.cachevalue(obj, result)
279 279 return result
280 280
281 281 def cachevalue(self, obj, value):
282 282 setattr(obj, self.name, value)
283 283
284 284 def pipefilter(s, cmd):
285 285 '''filter string S through command CMD, returning its output'''
286 286 p = subprocess.Popen(cmd, shell=True, close_fds=closefds,
287 287 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
288 288 pout, perr = p.communicate(s)
289 289 return pout
290 290
291 291 def tempfilter(s, cmd):
292 292 '''filter string S through a pair of temporary files with CMD.
293 293 CMD is used as a template to create the real command to be run,
294 294 with the strings INFILE and OUTFILE replaced by the real names of
295 295 the temporary files generated.'''
296 296 inname, outname = None, None
297 297 try:
298 298 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
299 299 fp = os.fdopen(infd, 'wb')
300 300 fp.write(s)
301 301 fp.close()
302 302 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
303 303 os.close(outfd)
304 304 cmd = cmd.replace('INFILE', inname)
305 305 cmd = cmd.replace('OUTFILE', outname)
306 306 code = os.system(cmd)
307 307 if sys.platform == 'OpenVMS' and code & 1:
308 308 code = 0
309 309 if code:
310 310 raise Abort(_("command '%s' failed: %s") %
311 311 (cmd, explainexit(code)))
312 312 fp = open(outname, 'rb')
313 313 r = fp.read()
314 314 fp.close()
315 315 return r
316 316 finally:
317 317 try:
318 318 if inname:
319 319 os.unlink(inname)
320 320 except OSError:
321 321 pass
322 322 try:
323 323 if outname:
324 324 os.unlink(outname)
325 325 except OSError:
326 326 pass
327 327
328 328 filtertable = {
329 329 'tempfile:': tempfilter,
330 330 'pipe:': pipefilter,
331 331 }
332 332
333 333 def filter(s, cmd):
334 334 "filter a string through a command that transforms its input to its output"
335 335 for name, fn in filtertable.iteritems():
336 336 if cmd.startswith(name):
337 337 return fn(s, cmd[len(name):].lstrip())
338 338 return pipefilter(s, cmd)
339 339
340 340 def binary(s):
341 341 """return true if a string is binary data"""
342 342 return bool(s and '\0' in s)
343 343
344 344 def increasingchunks(source, min=1024, max=65536):
345 345 '''return no less than min bytes per chunk while data remains,
346 346 doubling min after each chunk until it reaches max'''
347 347 def log2(x):
348 348 if not x:
349 349 return 0
350 350 i = 0
351 351 while x:
352 352 x >>= 1
353 353 i += 1
354 354 return i - 1
355 355
356 356 buf = []
357 357 blen = 0
358 358 for chunk in source:
359 359 buf.append(chunk)
360 360 blen += len(chunk)
361 361 if blen >= min:
362 362 if min < max:
363 363 min = min << 1
364 364 nmin = 1 << log2(blen)
365 365 if nmin > min:
366 366 min = nmin
367 367 if min > max:
368 368 min = max
369 369 yield ''.join(buf)
370 370 blen = 0
371 371 buf = []
372 372 if buf:
373 373 yield ''.join(buf)
374 374
375 375 Abort = error.Abort
376 376
377 377 def always(fn):
378 378 return True
379 379
380 380 def never(fn):
381 381 return False
382 382
383 383 def pathto(root, n1, n2):
384 384 '''return the relative path from one place to another.
385 385 root should use os.sep to separate directories
386 386 n1 should use os.sep to separate directories
387 387 n2 should use "/" to separate directories
388 388 returns an os.sep-separated path.
389 389
390 390 If n1 is a relative path, it's assumed it's
391 391 relative to root.
392 392 n2 should always be relative to root.
393 393 '''
394 394 if not n1:
395 395 return localpath(n2)
396 396 if os.path.isabs(n1):
397 397 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
398 398 return os.path.join(root, localpath(n2))
399 399 n2 = '/'.join((pconvert(root), n2))
400 400 a, b = splitpath(n1), n2.split('/')
401 401 a.reverse()
402 402 b.reverse()
403 403 while a and b and a[-1] == b[-1]:
404 404 a.pop()
405 405 b.pop()
406 406 b.reverse()
407 407 return os.sep.join((['..'] * len(a)) + b) or '.'
408 408
409 409 _hgexecutable = None
410 410
411 411 def mainfrozen():
412 412 """return True if we are a frozen executable.
413 413
414 414 The code supports py2exe (most common, Windows only) and tools/freeze
415 415 (portable, not much used).
416 416 """
417 417 return (safehasattr(sys, "frozen") or # new py2exe
418 418 safehasattr(sys, "importers") or # old py2exe
419 419 imp.is_frozen("__main__")) # tools/freeze
420 420
421 421 def hgexecutable():
422 422 """return location of the 'hg' executable.
423 423
424 424 Defaults to $HG or 'hg' in the search path.
425 425 """
426 426 if _hgexecutable is None:
427 427 hg = os.environ.get('HG')
428 428 mainmod = sys.modules['__main__']
429 429 if hg:
430 430 _sethgexecutable(hg)
431 431 elif mainfrozen():
432 432 _sethgexecutable(sys.executable)
433 433 elif os.path.basename(getattr(mainmod, '__file__', '')) == 'hg':
434 434 _sethgexecutable(mainmod.__file__)
435 435 else:
436 436 exe = findexe('hg') or os.path.basename(sys.argv[0])
437 437 _sethgexecutable(exe)
438 438 return _hgexecutable
439 439
440 440 def _sethgexecutable(path):
441 441 """set location of the 'hg' executable"""
442 442 global _hgexecutable
443 443 _hgexecutable = path
444 444
445 445 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None, out=None):
446 446 '''enhanced shell command execution.
447 447 run with environment maybe modified, maybe in different dir.
448 448
449 449 if command fails and onerr is None, return status. if ui object,
450 450 print error message and return status, else raise onerr object as
451 451 exception.
452 452
453 453 if out is specified, it is assumed to be a file-like object that has a
454 454 write() method. stdout and stderr will be redirected to out.'''
455 455 try:
456 456 sys.stdout.flush()
457 457 except Exception:
458 458 pass
459 459 def py2shell(val):
460 460 'convert python object into string that is useful to shell'
461 461 if val is None or val is False:
462 462 return '0'
463 463 if val is True:
464 464 return '1'
465 465 return str(val)
466 466 origcmd = cmd
467 467 cmd = quotecommand(cmd)
468 468 if sys.platform == 'plan9':
469 469 # subprocess kludge to work around issues in half-baked Python
470 470 # ports, notably bichued/python:
471 471 if not cwd is None:
472 472 os.chdir(cwd)
473 473 rc = os.system(cmd)
474 474 else:
475 475 env = dict(os.environ)
476 476 env.update((k, py2shell(v)) for k, v in environ.iteritems())
477 477 env['HG'] = hgexecutable()
478 478 if out is None or out == sys.__stdout__:
479 479 rc = subprocess.call(cmd, shell=True, close_fds=closefds,
480 480 env=env, cwd=cwd)
481 481 else:
482 482 proc = subprocess.Popen(cmd, shell=True, close_fds=closefds,
483 483 env=env, cwd=cwd, stdout=subprocess.PIPE,
484 484 stderr=subprocess.STDOUT)
485 485 for line in proc.stdout:
486 486 out.write(line)
487 487 proc.wait()
488 488 rc = proc.returncode
489 489 if sys.platform == 'OpenVMS' and rc & 1:
490 490 rc = 0
491 491 if rc and onerr:
492 492 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
493 493 explainexit(rc)[0])
494 494 if errprefix:
495 495 errmsg = '%s: %s' % (errprefix, errmsg)
496 496 try:
497 497 onerr.warn(errmsg + '\n')
498 498 except AttributeError:
499 499 raise onerr(errmsg)
500 500 return rc
501 501
502 502 def checksignature(func):
503 503 '''wrap a function with code to check for calling errors'''
504 504 def check(*args, **kwargs):
505 505 try:
506 506 return func(*args, **kwargs)
507 507 except TypeError:
508 508 if len(traceback.extract_tb(sys.exc_info()[2])) == 1:
509 509 raise error.SignatureError
510 510 raise
511 511
512 512 return check
513 513
514 514 def copyfile(src, dest):
515 515 "copy a file, preserving mode and atime/mtime"
516 516 if os.path.lexists(dest):
517 517 unlink(dest)
518 518 if os.path.islink(src):
519 519 os.symlink(os.readlink(src), dest)
520 520 else:
521 521 try:
522 522 shutil.copyfile(src, dest)
523 523 shutil.copymode(src, dest)
524 524 except shutil.Error, inst:
525 525 raise Abort(str(inst))
526 526
527 527 def copyfiles(src, dst, hardlink=None):
528 528 """Copy a directory tree using hardlinks if possible"""
529 529
530 530 if hardlink is None:
531 531 hardlink = (os.stat(src).st_dev ==
532 532 os.stat(os.path.dirname(dst)).st_dev)
533 533
534 534 num = 0
535 535 if os.path.isdir(src):
536 536 os.mkdir(dst)
537 537 for name, kind in osutil.listdir(src):
538 538 srcname = os.path.join(src, name)
539 539 dstname = os.path.join(dst, name)
540 540 hardlink, n = copyfiles(srcname, dstname, hardlink)
541 541 num += n
542 542 else:
543 543 if hardlink:
544 544 try:
545 545 oslink(src, dst)
546 546 except (IOError, OSError):
547 547 hardlink = False
548 548 shutil.copy(src, dst)
549 549 else:
550 550 shutil.copy(src, dst)
551 551 num += 1
552 552
553 553 return hardlink, num
554 554
555 555 _winreservednames = '''con prn aux nul
556 556 com1 com2 com3 com4 com5 com6 com7 com8 com9
557 557 lpt1 lpt2 lpt3 lpt4 lpt5 lpt6 lpt7 lpt8 lpt9'''.split()
558 558 _winreservedchars = ':*?"<>|'
559 559 def checkwinfilename(path):
560 560 '''Check that the base-relative path is a valid filename on Windows.
561 561 Returns None if the path is ok, or a UI string describing the problem.
562 562
563 563 >>> checkwinfilename("just/a/normal/path")
564 564 >>> checkwinfilename("foo/bar/con.xml")
565 565 "filename contains 'con', which is reserved on Windows"
566 566 >>> checkwinfilename("foo/con.xml/bar")
567 567 "filename contains 'con', which is reserved on Windows"
568 568 >>> checkwinfilename("foo/bar/xml.con")
569 569 >>> checkwinfilename("foo/bar/AUX/bla.txt")
570 570 "filename contains 'AUX', which is reserved on Windows"
571 571 >>> checkwinfilename("foo/bar/bla:.txt")
572 572 "filename contains ':', which is reserved on Windows"
573 573 >>> checkwinfilename("foo/bar/b\07la.txt")
574 574 "filename contains '\\\\x07', which is invalid on Windows"
575 575 >>> checkwinfilename("foo/bar/bla ")
576 576 "filename ends with ' ', which is not allowed on Windows"
577 577 >>> checkwinfilename("../bar")
578 578 '''
579 579 for n in path.replace('\\', '/').split('/'):
580 580 if not n:
581 581 continue
582 582 for c in n:
583 583 if c in _winreservedchars:
584 584 return _("filename contains '%s', which is reserved "
585 585 "on Windows") % c
586 586 if ord(c) <= 31:
587 587 return _("filename contains %r, which is invalid "
588 588 "on Windows") % c
589 589 base = n.split('.')[0]
590 590 if base and base.lower() in _winreservednames:
591 591 return _("filename contains '%s', which is reserved "
592 592 "on Windows") % base
593 593 t = n[-1]
594 594 if t in '. ' and n not in '..':
595 595 return _("filename ends with '%s', which is not allowed "
596 596 "on Windows") % t
597 597
598 598 if os.name == 'nt':
599 599 checkosfilename = checkwinfilename
600 600 else:
601 601 checkosfilename = platform.checkosfilename
602 602
603 603 def makelock(info, pathname):
604 604 try:
605 605 return os.symlink(info, pathname)
606 606 except OSError, why:
607 607 if why.errno == errno.EEXIST:
608 608 raise
609 609 except AttributeError: # no symlink in os
610 610 pass
611 611
612 612 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
613 613 os.write(ld, info)
614 614 os.close(ld)
615 615
616 616 def readlock(pathname):
617 617 try:
618 618 return os.readlink(pathname)
619 619 except OSError, why:
620 620 if why.errno not in (errno.EINVAL, errno.ENOSYS):
621 621 raise
622 622 except AttributeError: # no symlink in os
623 623 pass
624 624 fp = posixfile(pathname)
625 625 r = fp.read()
626 626 fp.close()
627 627 return r
628 628
629 629 def fstat(fp):
630 630 '''stat file object that may not have fileno method.'''
631 631 try:
632 632 return os.fstat(fp.fileno())
633 633 except AttributeError:
634 634 return os.stat(fp.name)
635 635
636 636 # File system features
637 637
638 638 def checkcase(path):
639 639 """
640 640 Return true if the given path is on a case-sensitive filesystem
641 641
642 642 Requires a path (like /foo/.hg) ending with a foldable final
643 643 directory component.
644 644 """
645 645 s1 = os.stat(path)
646 646 d, b = os.path.split(path)
647 647 b2 = b.upper()
648 648 if b == b2:
649 649 b2 = b.lower()
650 650 if b == b2:
651 651 return True # no evidence against case sensitivity
652 652 p2 = os.path.join(d, b2)
653 653 try:
654 654 s2 = os.stat(p2)
655 655 if s2 == s1:
656 656 return False
657 657 return True
658 658 except OSError:
659 659 return True
660 660
661 661 try:
662 662 import re2
663 663 _re2 = None
664 664 except ImportError:
665 665 _re2 = False
666 666
667 667 def compilere(pat, flags=0):
668 668 '''Compile a regular expression, using re2 if possible
669 669
670 670 For best performance, use only re2-compatible regexp features. The
671 671 only flags from the re module that are re2-compatible are
672 672 IGNORECASE and MULTILINE.'''
673 673 global _re2
674 674 if _re2 is None:
675 675 try:
676 676 re2.compile
677 677 _re2 = True
678 678 except ImportError:
679 679 _re2 = False
680 680 if _re2 and (flags & ~(re.IGNORECASE | re.MULTILINE)) == 0:
681 681 if flags & re.IGNORECASE:
682 682 pat = '(?i)' + pat
683 683 if flags & re.MULTILINE:
684 684 pat = '(?m)' + pat
685 685 try:
686 686 return re2.compile(pat)
687 687 except re2.error:
688 688 pass
689 689 return re.compile(pat, flags)
690 690
691 691 _fspathcache = {}
692 692 def fspath(name, root):
693 693 '''Get name in the case stored in the filesystem
694 694
695 695 The name should be relative to root, and be normcase-ed for efficiency.
696 696
697 697 Note that this function is unnecessary, and should not be
698 698 called, for case-sensitive filesystems (simply because it's expensive).
699 699
700 700 The root should be normcase-ed, too.
701 701 '''
702 702 def find(p, contents):
703 703 for n in contents:
704 704 if normcase(n) == p:
705 705 return n
706 706 return None
707 707
708 708 seps = os.sep
709 709 if os.altsep:
710 710 seps = seps + os.altsep
711 711 # Protect backslashes. This gets silly very quickly.
712 712 seps.replace('\\','\\\\')
713 713 pattern = re.compile(r'([^%s]+)|([%s]+)' % (seps, seps))
714 714 dir = os.path.normpath(root)
715 715 result = []
716 716 for part, sep in pattern.findall(name):
717 717 if sep:
718 718 result.append(sep)
719 719 continue
720 720
721 721 if dir not in _fspathcache:
722 722 _fspathcache[dir] = os.listdir(dir)
723 723 contents = _fspathcache[dir]
724 724
725 725 found = find(part, contents)
726 726 if not found:
727 727 # retry "once per directory" per "dirstate.walk" which
728 728 # may take place for each patches of "hg qpush", for example
729 729 contents = os.listdir(dir)
730 730 _fspathcache[dir] = contents
731 731 found = find(part, contents)
732 732
733 733 result.append(found or part)
734 734 dir = os.path.join(dir, part)
735 735
736 736 return ''.join(result)
737 737
738 738 def checknlink(testfile):
739 739 '''check whether hardlink count reporting works properly'''
740 740
741 741 # testfile may be open, so we need a separate file for checking to
742 742 # work around issue2543 (or testfile may get lost on Samba shares)
743 743 f1 = testfile + ".hgtmp1"
744 744 if os.path.lexists(f1):
745 745 return False
746 746 try:
747 747 posixfile(f1, 'w').close()
748 748 except IOError:
749 749 return False
750 750
751 751 f2 = testfile + ".hgtmp2"
752 752 fd = None
753 753 try:
754 754 try:
755 755 oslink(f1, f2)
756 756 except OSError:
757 757 return False
758 758
759 759 # nlinks() may behave differently for files on Windows shares if
760 760 # the file is open.
761 761 fd = posixfile(f2)
762 762 return nlinks(f2) > 1
763 763 finally:
764 764 if fd is not None:
765 765 fd.close()
766 766 for f in (f1, f2):
767 767 try:
768 768 os.unlink(f)
769 769 except OSError:
770 770 pass
771 771
772 772 def endswithsep(path):
773 773 '''Check path ends with os.sep or os.altsep.'''
774 774 return path.endswith(os.sep) or os.altsep and path.endswith(os.altsep)
775 775
776 776 def splitpath(path):
777 777 '''Split path by os.sep.
778 778 Note that this function does not use os.altsep because this is
779 779 an alternative of simple "xxx.split(os.sep)".
780 780 It is recommended to use os.path.normpath() before using this
781 781 function if need.'''
782 782 return path.split(os.sep)
783 783
784 784 def gui():
785 785 '''Are we running in a GUI?'''
786 786 if sys.platform == 'darwin':
787 787 if 'SSH_CONNECTION' in os.environ:
788 788 # handle SSH access to a box where the user is logged in
789 789 return False
790 790 elif getattr(osutil, 'isgui', None):
791 791 # check if a CoreGraphics session is available
792 792 return osutil.isgui()
793 793 else:
794 794 # pure build; use a safe default
795 795 return True
796 796 else:
797 797 return os.name == "nt" or os.environ.get("DISPLAY")
798 798
799 799 def mktempcopy(name, emptyok=False, createmode=None):
800 800 """Create a temporary file with the same contents from name
801 801
802 802 The permission bits are copied from the original file.
803 803
804 804 If the temporary file is going to be truncated immediately, you
805 805 can use emptyok=True as an optimization.
806 806
807 807 Returns the name of the temporary file.
808 808 """
809 809 d, fn = os.path.split(name)
810 810 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
811 811 os.close(fd)
812 812 # Temporary files are created with mode 0600, which is usually not
813 813 # what we want. If the original file already exists, just copy
814 814 # its mode. Otherwise, manually obey umask.
815 815 copymode(name, temp, createmode)
816 816 if emptyok:
817 817 return temp
818 818 try:
819 819 try:
820 820 ifp = posixfile(name, "rb")
821 821 except IOError, inst:
822 822 if inst.errno == errno.ENOENT:
823 823 return temp
824 824 if not getattr(inst, 'filename', None):
825 825 inst.filename = name
826 826 raise
827 827 ofp = posixfile(temp, "wb")
828 828 for chunk in filechunkiter(ifp):
829 829 ofp.write(chunk)
830 830 ifp.close()
831 831 ofp.close()
832 832 except: # re-raises
833 833 try: os.unlink(temp)
834 834 except OSError: pass
835 835 raise
836 836 return temp
837 837
838 838 class atomictempfile(object):
839 839 '''writable file object that atomically updates a file
840 840
841 841 All writes will go to a temporary copy of the original file. Call
842 842 close() when you are done writing, and atomictempfile will rename
843 843 the temporary copy to the original name, making the changes
844 844 visible. If the object is destroyed without being closed, all your
845 845 writes are discarded.
846 846 '''
847 847 def __init__(self, name, mode='w+b', createmode=None):
848 848 self.__name = name # permanent name
849 849 self._tempname = mktempcopy(name, emptyok=('w' in mode),
850 850 createmode=createmode)
851 851 self._fp = posixfile(self._tempname, mode)
852 852
853 853 # delegated methods
854 854 self.write = self._fp.write
855 855 self.seek = self._fp.seek
856 856 self.tell = self._fp.tell
857 857 self.fileno = self._fp.fileno
858 858
859 859 def close(self):
860 860 if not self._fp.closed:
861 861 self._fp.close()
862 862 rename(self._tempname, localpath(self.__name))
863 863
864 864 def discard(self):
865 865 if not self._fp.closed:
866 866 try:
867 867 os.unlink(self._tempname)
868 868 except OSError:
869 869 pass
870 870 self._fp.close()
871 871
872 872 def __del__(self):
873 873 if safehasattr(self, '_fp'): # constructor actually did something
874 874 self.discard()
875 875
876 def makedirs(name, mode=None):
876 def makedirs(name, mode=None, notindexed=False):
877 877 """recursive directory creation with parent mode inheritance"""
878 878 try:
879 os.mkdir(name)
879 makedir(name, notindexed)
880 880 except OSError, err:
881 881 if err.errno == errno.EEXIST:
882 882 return
883 883 if err.errno != errno.ENOENT or not name:
884 884 raise
885 885 parent = os.path.dirname(os.path.abspath(name))
886 886 if parent == name:
887 887 raise
888 makedirs(parent, mode)
889 os.mkdir(name)
888 makedirs(parent, mode, notindexed)
889 makedir(name, notindexed)
890 890 if mode is not None:
891 891 os.chmod(name, mode)
892 892
893 893 def ensuredirs(name, mode=None):
894 894 """race-safe recursive directory creation"""
895 895 if os.path.isdir(name):
896 896 return
897 897 parent = os.path.dirname(os.path.abspath(name))
898 898 if parent != name:
899 899 ensuredirs(parent, mode)
900 900 try:
901 901 os.mkdir(name)
902 902 except OSError, err:
903 903 if err.errno == errno.EEXIST and os.path.isdir(name):
904 904 # someone else seems to have won a directory creation race
905 905 return
906 906 raise
907 907 if mode is not None:
908 908 os.chmod(name, mode)
909 909
910 910 def readfile(path):
911 911 fp = open(path, 'rb')
912 912 try:
913 913 return fp.read()
914 914 finally:
915 915 fp.close()
916 916
917 917 def writefile(path, text):
918 918 fp = open(path, 'wb')
919 919 try:
920 920 fp.write(text)
921 921 finally:
922 922 fp.close()
923 923
924 924 def appendfile(path, text):
925 925 fp = open(path, 'ab')
926 926 try:
927 927 fp.write(text)
928 928 finally:
929 929 fp.close()
930 930
931 931 class chunkbuffer(object):
932 932 """Allow arbitrary sized chunks of data to be efficiently read from an
933 933 iterator over chunks of arbitrary size."""
934 934
935 935 def __init__(self, in_iter):
936 936 """in_iter is the iterator that's iterating over the input chunks.
937 937 targetsize is how big a buffer to try to maintain."""
938 938 def splitbig(chunks):
939 939 for chunk in chunks:
940 940 if len(chunk) > 2**20:
941 941 pos = 0
942 942 while pos < len(chunk):
943 943 end = pos + 2 ** 18
944 944 yield chunk[pos:end]
945 945 pos = end
946 946 else:
947 947 yield chunk
948 948 self.iter = splitbig(in_iter)
949 949 self._queue = deque()
950 950
951 951 def read(self, l):
952 952 """Read L bytes of data from the iterator of chunks of data.
953 953 Returns less than L bytes if the iterator runs dry."""
954 954 left = l
955 955 buf = []
956 956 queue = self._queue
957 957 while left > 0:
958 958 # refill the queue
959 959 if not queue:
960 960 target = 2**18
961 961 for chunk in self.iter:
962 962 queue.append(chunk)
963 963 target -= len(chunk)
964 964 if target <= 0:
965 965 break
966 966 if not queue:
967 967 break
968 968
969 969 chunk = queue.popleft()
970 970 left -= len(chunk)
971 971 if left < 0:
972 972 queue.appendleft(chunk[left:])
973 973 buf.append(chunk[:left])
974 974 else:
975 975 buf.append(chunk)
976 976
977 977 return ''.join(buf)
978 978
979 979 def filechunkiter(f, size=65536, limit=None):
980 980 """Create a generator that produces the data in the file size
981 981 (default 65536) bytes at a time, up to optional limit (default is
982 982 to read all data). Chunks may be less than size bytes if the
983 983 chunk is the last chunk in the file, or the file is a socket or
984 984 some other type of file that sometimes reads less data than is
985 985 requested."""
986 986 assert size >= 0
987 987 assert limit is None or limit >= 0
988 988 while True:
989 989 if limit is None:
990 990 nbytes = size
991 991 else:
992 992 nbytes = min(limit, size)
993 993 s = nbytes and f.read(nbytes)
994 994 if not s:
995 995 break
996 996 if limit:
997 997 limit -= len(s)
998 998 yield s
999 999
1000 1000 def makedate():
1001 1001 ct = time.time()
1002 1002 if ct < 0:
1003 1003 hint = _("check your clock")
1004 1004 raise Abort(_("negative timestamp: %d") % ct, hint=hint)
1005 1005 delta = (datetime.datetime.utcfromtimestamp(ct) -
1006 1006 datetime.datetime.fromtimestamp(ct))
1007 1007 tz = delta.days * 86400 + delta.seconds
1008 1008 return ct, tz
1009 1009
1010 1010 def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
1011 1011 """represent a (unixtime, offset) tuple as a localized time.
1012 1012 unixtime is seconds since the epoch, and offset is the time zone's
1013 1013 number of seconds away from UTC. if timezone is false, do not
1014 1014 append time zone to string."""
1015 1015 t, tz = date or makedate()
1016 1016 if t < 0:
1017 1017 t = 0 # time.gmtime(lt) fails on Windows for lt < -43200
1018 1018 tz = 0
1019 1019 if "%1" in format or "%2" in format:
1020 1020 sign = (tz > 0) and "-" or "+"
1021 1021 minutes = abs(tz) // 60
1022 1022 format = format.replace("%1", "%c%02d" % (sign, minutes // 60))
1023 1023 format = format.replace("%2", "%02d" % (minutes % 60))
1024 1024 try:
1025 1025 t = time.gmtime(float(t) - tz)
1026 1026 except ValueError:
1027 1027 # time was out of range
1028 1028 t = time.gmtime(sys.maxint)
1029 1029 s = time.strftime(format, t)
1030 1030 return s
1031 1031
1032 1032 def shortdate(date=None):
1033 1033 """turn (timestamp, tzoff) tuple into iso 8631 date."""
1034 1034 return datestr(date, format='%Y-%m-%d')
1035 1035
1036 1036 def strdate(string, format, defaults=[]):
1037 1037 """parse a localized time string and return a (unixtime, offset) tuple.
1038 1038 if the string cannot be parsed, ValueError is raised."""
1039 1039 def timezone(string):
1040 1040 tz = string.split()[-1]
1041 1041 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1042 1042 sign = (tz[0] == "+") and 1 or -1
1043 1043 hours = int(tz[1:3])
1044 1044 minutes = int(tz[3:5])
1045 1045 return -sign * (hours * 60 + minutes) * 60
1046 1046 if tz == "GMT" or tz == "UTC":
1047 1047 return 0
1048 1048 return None
1049 1049
1050 1050 # NOTE: unixtime = localunixtime + offset
1051 1051 offset, date = timezone(string), string
1052 1052 if offset is not None:
1053 1053 date = " ".join(string.split()[:-1])
1054 1054
1055 1055 # add missing elements from defaults
1056 1056 usenow = False # default to using biased defaults
1057 1057 for part in ("S", "M", "HI", "d", "mb", "yY"): # decreasing specificity
1058 1058 found = [True for p in part if ("%"+p) in format]
1059 1059 if not found:
1060 1060 date += "@" + defaults[part][usenow]
1061 1061 format += "@%" + part[0]
1062 1062 else:
1063 1063 # We've found a specific time element, less specific time
1064 1064 # elements are relative to today
1065 1065 usenow = True
1066 1066
1067 1067 timetuple = time.strptime(date, format)
1068 1068 localunixtime = int(calendar.timegm(timetuple))
1069 1069 if offset is None:
1070 1070 # local timezone
1071 1071 unixtime = int(time.mktime(timetuple))
1072 1072 offset = unixtime - localunixtime
1073 1073 else:
1074 1074 unixtime = localunixtime + offset
1075 1075 return unixtime, offset
1076 1076
1077 1077 def parsedate(date, formats=None, bias={}):
1078 1078 """parse a localized date/time and return a (unixtime, offset) tuple.
1079 1079
1080 1080 The date may be a "unixtime offset" string or in one of the specified
1081 1081 formats. If the date already is a (unixtime, offset) tuple, it is returned.
1082 1082
1083 1083 >>> parsedate(' today ') == parsedate(\
1084 1084 datetime.date.today().strftime('%b %d'))
1085 1085 True
1086 1086 >>> parsedate( 'yesterday ') == parsedate((datetime.date.today() -\
1087 1087 datetime.timedelta(days=1)\
1088 1088 ).strftime('%b %d'))
1089 1089 True
1090 1090 >>> now, tz = makedate()
1091 1091 >>> strnow, strtz = parsedate('now')
1092 1092 >>> (strnow - now) < 1
1093 1093 True
1094 1094 >>> tz == strtz
1095 1095 True
1096 1096 """
1097 1097 if not date:
1098 1098 return 0, 0
1099 1099 if isinstance(date, tuple) and len(date) == 2:
1100 1100 return date
1101 1101 if not formats:
1102 1102 formats = defaultdateformats
1103 1103 date = date.strip()
1104 1104
1105 1105 if date == _('now'):
1106 1106 return makedate()
1107 1107 if date == _('today'):
1108 1108 date = datetime.date.today().strftime('%b %d')
1109 1109 elif date == _('yesterday'):
1110 1110 date = (datetime.date.today() -
1111 1111 datetime.timedelta(days=1)).strftime('%b %d')
1112 1112
1113 1113 try:
1114 1114 when, offset = map(int, date.split(' '))
1115 1115 except ValueError:
1116 1116 # fill out defaults
1117 1117 now = makedate()
1118 1118 defaults = {}
1119 1119 for part in ("d", "mb", "yY", "HI", "M", "S"):
1120 1120 # this piece is for rounding the specific end of unknowns
1121 1121 b = bias.get(part)
1122 1122 if b is None:
1123 1123 if part[0] in "HMS":
1124 1124 b = "00"
1125 1125 else:
1126 1126 b = "0"
1127 1127
1128 1128 # this piece is for matching the generic end to today's date
1129 1129 n = datestr(now, "%" + part[0])
1130 1130
1131 1131 defaults[part] = (b, n)
1132 1132
1133 1133 for format in formats:
1134 1134 try:
1135 1135 when, offset = strdate(date, format, defaults)
1136 1136 except (ValueError, OverflowError):
1137 1137 pass
1138 1138 else:
1139 1139 break
1140 1140 else:
1141 1141 raise Abort(_('invalid date: %r') % date)
1142 1142 # validate explicit (probably user-specified) date and
1143 1143 # time zone offset. values must fit in signed 32 bits for
1144 1144 # current 32-bit linux runtimes. timezones go from UTC-12
1145 1145 # to UTC+14
1146 1146 if abs(when) > 0x7fffffff:
1147 1147 raise Abort(_('date exceeds 32 bits: %d') % when)
1148 1148 if when < 0:
1149 1149 raise Abort(_('negative date value: %d') % when)
1150 1150 if offset < -50400 or offset > 43200:
1151 1151 raise Abort(_('impossible time zone offset: %d') % offset)
1152 1152 return when, offset
1153 1153
1154 1154 def matchdate(date):
1155 1155 """Return a function that matches a given date match specifier
1156 1156
1157 1157 Formats include:
1158 1158
1159 1159 '{date}' match a given date to the accuracy provided
1160 1160
1161 1161 '<{date}' on or before a given date
1162 1162
1163 1163 '>{date}' on or after a given date
1164 1164
1165 1165 >>> p1 = parsedate("10:29:59")
1166 1166 >>> p2 = parsedate("10:30:00")
1167 1167 >>> p3 = parsedate("10:30:59")
1168 1168 >>> p4 = parsedate("10:31:00")
1169 1169 >>> p5 = parsedate("Sep 15 10:30:00 1999")
1170 1170 >>> f = matchdate("10:30")
1171 1171 >>> f(p1[0])
1172 1172 False
1173 1173 >>> f(p2[0])
1174 1174 True
1175 1175 >>> f(p3[0])
1176 1176 True
1177 1177 >>> f(p4[0])
1178 1178 False
1179 1179 >>> f(p5[0])
1180 1180 False
1181 1181 """
1182 1182
1183 1183 def lower(date):
1184 1184 d = dict(mb="1", d="1")
1185 1185 return parsedate(date, extendeddateformats, d)[0]
1186 1186
1187 1187 def upper(date):
1188 1188 d = dict(mb="12", HI="23", M="59", S="59")
1189 1189 for days in ("31", "30", "29"):
1190 1190 try:
1191 1191 d["d"] = days
1192 1192 return parsedate(date, extendeddateformats, d)[0]
1193 1193 except Abort:
1194 1194 pass
1195 1195 d["d"] = "28"
1196 1196 return parsedate(date, extendeddateformats, d)[0]
1197 1197
1198 1198 date = date.strip()
1199 1199
1200 1200 if not date:
1201 1201 raise Abort(_("dates cannot consist entirely of whitespace"))
1202 1202 elif date[0] == "<":
1203 1203 if not date[1:]:
1204 1204 raise Abort(_("invalid day spec, use '<DATE'"))
1205 1205 when = upper(date[1:])
1206 1206 return lambda x: x <= when
1207 1207 elif date[0] == ">":
1208 1208 if not date[1:]:
1209 1209 raise Abort(_("invalid day spec, use '>DATE'"))
1210 1210 when = lower(date[1:])
1211 1211 return lambda x: x >= when
1212 1212 elif date[0] == "-":
1213 1213 try:
1214 1214 days = int(date[1:])
1215 1215 except ValueError:
1216 1216 raise Abort(_("invalid day spec: %s") % date[1:])
1217 1217 if days < 0:
1218 1218 raise Abort(_("%s must be nonnegative (see 'hg help dates')")
1219 1219 % date[1:])
1220 1220 when = makedate()[0] - days * 3600 * 24
1221 1221 return lambda x: x >= when
1222 1222 elif " to " in date:
1223 1223 a, b = date.split(" to ")
1224 1224 start, stop = lower(a), upper(b)
1225 1225 return lambda x: x >= start and x <= stop
1226 1226 else:
1227 1227 start, stop = lower(date), upper(date)
1228 1228 return lambda x: x >= start and x <= stop
1229 1229
1230 1230 def shortuser(user):
1231 1231 """Return a short representation of a user name or email address."""
1232 1232 f = user.find('@')
1233 1233 if f >= 0:
1234 1234 user = user[:f]
1235 1235 f = user.find('<')
1236 1236 if f >= 0:
1237 1237 user = user[f + 1:]
1238 1238 f = user.find(' ')
1239 1239 if f >= 0:
1240 1240 user = user[:f]
1241 1241 f = user.find('.')
1242 1242 if f >= 0:
1243 1243 user = user[:f]
1244 1244 return user
1245 1245
1246 1246 def emailuser(user):
1247 1247 """Return the user portion of an email address."""
1248 1248 f = user.find('@')
1249 1249 if f >= 0:
1250 1250 user = user[:f]
1251 1251 f = user.find('<')
1252 1252 if f >= 0:
1253 1253 user = user[f + 1:]
1254 1254 return user
1255 1255
1256 1256 def email(author):
1257 1257 '''get email of author.'''
1258 1258 r = author.find('>')
1259 1259 if r == -1:
1260 1260 r = None
1261 1261 return author[author.find('<') + 1:r]
1262 1262
1263 1263 def _ellipsis(text, maxlength):
1264 1264 if len(text) <= maxlength:
1265 1265 return text, False
1266 1266 else:
1267 1267 return "%s..." % (text[:maxlength - 3]), True
1268 1268
1269 1269 def ellipsis(text, maxlength=400):
1270 1270 """Trim string to at most maxlength (default: 400) characters."""
1271 1271 try:
1272 1272 # use unicode not to split at intermediate multi-byte sequence
1273 1273 utext, truncated = _ellipsis(text.decode(encoding.encoding),
1274 1274 maxlength)
1275 1275 if not truncated:
1276 1276 return text
1277 1277 return utext.encode(encoding.encoding)
1278 1278 except (UnicodeDecodeError, UnicodeEncodeError):
1279 1279 return _ellipsis(text, maxlength)[0]
1280 1280
1281 1281 def unitcountfn(*unittable):
1282 1282 '''return a function that renders a readable count of some quantity'''
1283 1283
1284 1284 def go(count):
1285 1285 for multiplier, divisor, format in unittable:
1286 1286 if count >= divisor * multiplier:
1287 1287 return format % (count / float(divisor))
1288 1288 return unittable[-1][2] % count
1289 1289
1290 1290 return go
1291 1291
1292 1292 bytecount = unitcountfn(
1293 1293 (100, 1 << 30, _('%.0f GB')),
1294 1294 (10, 1 << 30, _('%.1f GB')),
1295 1295 (1, 1 << 30, _('%.2f GB')),
1296 1296 (100, 1 << 20, _('%.0f MB')),
1297 1297 (10, 1 << 20, _('%.1f MB')),
1298 1298 (1, 1 << 20, _('%.2f MB')),
1299 1299 (100, 1 << 10, _('%.0f KB')),
1300 1300 (10, 1 << 10, _('%.1f KB')),
1301 1301 (1, 1 << 10, _('%.2f KB')),
1302 1302 (1, 1, _('%.0f bytes')),
1303 1303 )
1304 1304
1305 1305 def uirepr(s):
1306 1306 # Avoid double backslash in Windows path repr()
1307 1307 return repr(s).replace('\\\\', '\\')
1308 1308
1309 1309 # delay import of textwrap
1310 1310 def MBTextWrapper(**kwargs):
1311 1311 class tw(textwrap.TextWrapper):
1312 1312 """
1313 1313 Extend TextWrapper for width-awareness.
1314 1314
1315 1315 Neither number of 'bytes' in any encoding nor 'characters' is
1316 1316 appropriate to calculate terminal columns for specified string.
1317 1317
1318 1318 Original TextWrapper implementation uses built-in 'len()' directly,
1319 1319 so overriding is needed to use width information of each characters.
1320 1320
1321 1321 In addition, characters classified into 'ambiguous' width are
1322 1322 treated as wide in East Asian area, but as narrow in other.
1323 1323
1324 1324 This requires use decision to determine width of such characters.
1325 1325 """
1326 1326 def __init__(self, **kwargs):
1327 1327 textwrap.TextWrapper.__init__(self, **kwargs)
1328 1328
1329 1329 # for compatibility between 2.4 and 2.6
1330 1330 if getattr(self, 'drop_whitespace', None) is None:
1331 1331 self.drop_whitespace = kwargs.get('drop_whitespace', True)
1332 1332
1333 1333 def _cutdown(self, ucstr, space_left):
1334 1334 l = 0
1335 1335 colwidth = encoding.ucolwidth
1336 1336 for i in xrange(len(ucstr)):
1337 1337 l += colwidth(ucstr[i])
1338 1338 if space_left < l:
1339 1339 return (ucstr[:i], ucstr[i:])
1340 1340 return ucstr, ''
1341 1341
1342 1342 # overriding of base class
1343 1343 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):
1344 1344 space_left = max(width - cur_len, 1)
1345 1345
1346 1346 if self.break_long_words:
1347 1347 cut, res = self._cutdown(reversed_chunks[-1], space_left)
1348 1348 cur_line.append(cut)
1349 1349 reversed_chunks[-1] = res
1350 1350 elif not cur_line:
1351 1351 cur_line.append(reversed_chunks.pop())
1352 1352
1353 1353 # this overriding code is imported from TextWrapper of python 2.6
1354 1354 # to calculate columns of string by 'encoding.ucolwidth()'
1355 1355 def _wrap_chunks(self, chunks):
1356 1356 colwidth = encoding.ucolwidth
1357 1357
1358 1358 lines = []
1359 1359 if self.width <= 0:
1360 1360 raise ValueError("invalid width %r (must be > 0)" % self.width)
1361 1361
1362 1362 # Arrange in reverse order so items can be efficiently popped
1363 1363 # from a stack of chucks.
1364 1364 chunks.reverse()
1365 1365
1366 1366 while chunks:
1367 1367
1368 1368 # Start the list of chunks that will make up the current line.
1369 1369 # cur_len is just the length of all the chunks in cur_line.
1370 1370 cur_line = []
1371 1371 cur_len = 0
1372 1372
1373 1373 # Figure out which static string will prefix this line.
1374 1374 if lines:
1375 1375 indent = self.subsequent_indent
1376 1376 else:
1377 1377 indent = self.initial_indent
1378 1378
1379 1379 # Maximum width for this line.
1380 1380 width = self.width - len(indent)
1381 1381
1382 1382 # First chunk on line is whitespace -- drop it, unless this
1383 1383 # is the very beginning of the text (i.e. no lines started yet).
1384 1384 if self.drop_whitespace and chunks[-1].strip() == '' and lines:
1385 1385 del chunks[-1]
1386 1386
1387 1387 while chunks:
1388 1388 l = colwidth(chunks[-1])
1389 1389
1390 1390 # Can at least squeeze this chunk onto the current line.
1391 1391 if cur_len + l <= width:
1392 1392 cur_line.append(chunks.pop())
1393 1393 cur_len += l
1394 1394
1395 1395 # Nope, this line is full.
1396 1396 else:
1397 1397 break
1398 1398
1399 1399 # The current line is full, and the next chunk is too big to
1400 1400 # fit on *any* line (not just this one).
1401 1401 if chunks and colwidth(chunks[-1]) > width:
1402 1402 self._handle_long_word(chunks, cur_line, cur_len, width)
1403 1403
1404 1404 # If the last chunk on this line is all whitespace, drop it.
1405 1405 if (self.drop_whitespace and
1406 1406 cur_line and cur_line[-1].strip() == ''):
1407 1407 del cur_line[-1]
1408 1408
1409 1409 # Convert current line back to a string and store it in list
1410 1410 # of all lines (return value).
1411 1411 if cur_line:
1412 1412 lines.append(indent + ''.join(cur_line))
1413 1413
1414 1414 return lines
1415 1415
1416 1416 global MBTextWrapper
1417 1417 MBTextWrapper = tw
1418 1418 return tw(**kwargs)
1419 1419
1420 1420 def wrap(line, width, initindent='', hangindent=''):
1421 1421 maxindent = max(len(hangindent), len(initindent))
1422 1422 if width <= maxindent:
1423 1423 # adjust for weird terminal size
1424 1424 width = max(78, maxindent + 1)
1425 1425 line = line.decode(encoding.encoding, encoding.encodingmode)
1426 1426 initindent = initindent.decode(encoding.encoding, encoding.encodingmode)
1427 1427 hangindent = hangindent.decode(encoding.encoding, encoding.encodingmode)
1428 1428 wrapper = MBTextWrapper(width=width,
1429 1429 initial_indent=initindent,
1430 1430 subsequent_indent=hangindent)
1431 1431 return wrapper.fill(line).encode(encoding.encoding)
1432 1432
1433 1433 def iterlines(iterator):
1434 1434 for chunk in iterator:
1435 1435 for line in chunk.splitlines():
1436 1436 yield line
1437 1437
1438 1438 def expandpath(path):
1439 1439 return os.path.expanduser(os.path.expandvars(path))
1440 1440
1441 1441 def hgcmd():
1442 1442 """Return the command used to execute current hg
1443 1443
1444 1444 This is different from hgexecutable() because on Windows we want
1445 1445 to avoid things opening new shell windows like batch files, so we
1446 1446 get either the python call or current executable.
1447 1447 """
1448 1448 if mainfrozen():
1449 1449 return [sys.executable]
1450 1450 return gethgcmd()
1451 1451
1452 1452 def rundetached(args, condfn):
1453 1453 """Execute the argument list in a detached process.
1454 1454
1455 1455 condfn is a callable which is called repeatedly and should return
1456 1456 True once the child process is known to have started successfully.
1457 1457 At this point, the child process PID is returned. If the child
1458 1458 process fails to start or finishes before condfn() evaluates to
1459 1459 True, return -1.
1460 1460 """
1461 1461 # Windows case is easier because the child process is either
1462 1462 # successfully starting and validating the condition or exiting
1463 1463 # on failure. We just poll on its PID. On Unix, if the child
1464 1464 # process fails to start, it will be left in a zombie state until
1465 1465 # the parent wait on it, which we cannot do since we expect a long
1466 1466 # running process on success. Instead we listen for SIGCHLD telling
1467 1467 # us our child process terminated.
1468 1468 terminated = set()
1469 1469 def handler(signum, frame):
1470 1470 terminated.add(os.wait())
1471 1471 prevhandler = None
1472 1472 SIGCHLD = getattr(signal, 'SIGCHLD', None)
1473 1473 if SIGCHLD is not None:
1474 1474 prevhandler = signal.signal(SIGCHLD, handler)
1475 1475 try:
1476 1476 pid = spawndetached(args)
1477 1477 while not condfn():
1478 1478 if ((pid in terminated or not testpid(pid))
1479 1479 and not condfn()):
1480 1480 return -1
1481 1481 time.sleep(0.1)
1482 1482 return pid
1483 1483 finally:
1484 1484 if prevhandler is not None:
1485 1485 signal.signal(signal.SIGCHLD, prevhandler)
1486 1486
1487 1487 try:
1488 1488 any, all = any, all
1489 1489 except NameError:
1490 1490 def any(iterable):
1491 1491 for i in iterable:
1492 1492 if i:
1493 1493 return True
1494 1494 return False
1495 1495
1496 1496 def all(iterable):
1497 1497 for i in iterable:
1498 1498 if not i:
1499 1499 return False
1500 1500 return True
1501 1501
1502 1502 def interpolate(prefix, mapping, s, fn=None, escape_prefix=False):
1503 1503 """Return the result of interpolating items in the mapping into string s.
1504 1504
1505 1505 prefix is a single character string, or a two character string with
1506 1506 a backslash as the first character if the prefix needs to be escaped in
1507 1507 a regular expression.
1508 1508
1509 1509 fn is an optional function that will be applied to the replacement text
1510 1510 just before replacement.
1511 1511
1512 1512 escape_prefix is an optional flag that allows using doubled prefix for
1513 1513 its escaping.
1514 1514 """
1515 1515 fn = fn or (lambda s: s)
1516 1516 patterns = '|'.join(mapping.keys())
1517 1517 if escape_prefix:
1518 1518 patterns += '|' + prefix
1519 1519 if len(prefix) > 1:
1520 1520 prefix_char = prefix[1:]
1521 1521 else:
1522 1522 prefix_char = prefix
1523 1523 mapping[prefix_char] = prefix_char
1524 1524 r = re.compile(r'%s(%s)' % (prefix, patterns))
1525 1525 return r.sub(lambda x: fn(mapping[x.group()[1:]]), s)
1526 1526
1527 1527 def getport(port):
1528 1528 """Return the port for a given network service.
1529 1529
1530 1530 If port is an integer, it's returned as is. If it's a string, it's
1531 1531 looked up using socket.getservbyname(). If there's no matching
1532 1532 service, util.Abort is raised.
1533 1533 """
1534 1534 try:
1535 1535 return int(port)
1536 1536 except ValueError:
1537 1537 pass
1538 1538
1539 1539 try:
1540 1540 return socket.getservbyname(port)
1541 1541 except socket.error:
1542 1542 raise Abort(_("no port number associated with service '%s'") % port)
1543 1543
1544 1544 _booleans = {'1': True, 'yes': True, 'true': True, 'on': True, 'always': True,
1545 1545 '0': False, 'no': False, 'false': False, 'off': False,
1546 1546 'never': False}
1547 1547
1548 1548 def parsebool(s):
1549 1549 """Parse s into a boolean.
1550 1550
1551 1551 If s is not a valid boolean, returns None.
1552 1552 """
1553 1553 return _booleans.get(s.lower(), None)
1554 1554
1555 1555 _hexdig = '0123456789ABCDEFabcdef'
1556 1556 _hextochr = dict((a + b, chr(int(a + b, 16)))
1557 1557 for a in _hexdig for b in _hexdig)
1558 1558
1559 1559 def _urlunquote(s):
1560 1560 """Decode HTTP/HTML % encoding.
1561 1561
1562 1562 >>> _urlunquote('abc%20def')
1563 1563 'abc def'
1564 1564 """
1565 1565 res = s.split('%')
1566 1566 # fastpath
1567 1567 if len(res) == 1:
1568 1568 return s
1569 1569 s = res[0]
1570 1570 for item in res[1:]:
1571 1571 try:
1572 1572 s += _hextochr[item[:2]] + item[2:]
1573 1573 except KeyError:
1574 1574 s += '%' + item
1575 1575 except UnicodeDecodeError:
1576 1576 s += unichr(int(item[:2], 16)) + item[2:]
1577 1577 return s
1578 1578
1579 1579 class url(object):
1580 1580 r"""Reliable URL parser.
1581 1581
1582 1582 This parses URLs and provides attributes for the following
1583 1583 components:
1584 1584
1585 1585 <scheme>://<user>:<passwd>@<host>:<port>/<path>?<query>#<fragment>
1586 1586
1587 1587 Missing components are set to None. The only exception is
1588 1588 fragment, which is set to '' if present but empty.
1589 1589
1590 1590 If parsefragment is False, fragment is included in query. If
1591 1591 parsequery is False, query is included in path. If both are
1592 1592 False, both fragment and query are included in path.
1593 1593
1594 1594 See http://www.ietf.org/rfc/rfc2396.txt for more information.
1595 1595
1596 1596 Note that for backward compatibility reasons, bundle URLs do not
1597 1597 take host names. That means 'bundle://../' has a path of '../'.
1598 1598
1599 1599 Examples:
1600 1600
1601 1601 >>> url('http://www.ietf.org/rfc/rfc2396.txt')
1602 1602 <url scheme: 'http', host: 'www.ietf.org', path: 'rfc/rfc2396.txt'>
1603 1603 >>> url('ssh://[::1]:2200//home/joe/repo')
1604 1604 <url scheme: 'ssh', host: '[::1]', port: '2200', path: '/home/joe/repo'>
1605 1605 >>> url('file:///home/joe/repo')
1606 1606 <url scheme: 'file', path: '/home/joe/repo'>
1607 1607 >>> url('file:///c:/temp/foo/')
1608 1608 <url scheme: 'file', path: 'c:/temp/foo/'>
1609 1609 >>> url('bundle:foo')
1610 1610 <url scheme: 'bundle', path: 'foo'>
1611 1611 >>> url('bundle://../foo')
1612 1612 <url scheme: 'bundle', path: '../foo'>
1613 1613 >>> url(r'c:\foo\bar')
1614 1614 <url path: 'c:\\foo\\bar'>
1615 1615 >>> url(r'\\blah\blah\blah')
1616 1616 <url path: '\\\\blah\\blah\\blah'>
1617 1617 >>> url(r'\\blah\blah\blah#baz')
1618 1618 <url path: '\\\\blah\\blah\\blah', fragment: 'baz'>
1619 1619
1620 1620 Authentication credentials:
1621 1621
1622 1622 >>> url('ssh://joe:xyz@x/repo')
1623 1623 <url scheme: 'ssh', user: 'joe', passwd: 'xyz', host: 'x', path: 'repo'>
1624 1624 >>> url('ssh://joe@x/repo')
1625 1625 <url scheme: 'ssh', user: 'joe', host: 'x', path: 'repo'>
1626 1626
1627 1627 Query strings and fragments:
1628 1628
1629 1629 >>> url('http://host/a?b#c')
1630 1630 <url scheme: 'http', host: 'host', path: 'a', query: 'b', fragment: 'c'>
1631 1631 >>> url('http://host/a?b#c', parsequery=False, parsefragment=False)
1632 1632 <url scheme: 'http', host: 'host', path: 'a?b#c'>
1633 1633 """
1634 1634
1635 1635 _safechars = "!~*'()+"
1636 1636 _safepchars = "/!~*'()+:"
1637 1637 _matchscheme = re.compile(r'^[a-zA-Z0-9+.\-]+:').match
1638 1638
1639 1639 def __init__(self, path, parsequery=True, parsefragment=True):
1640 1640 # We slowly chomp away at path until we have only the path left
1641 1641 self.scheme = self.user = self.passwd = self.host = None
1642 1642 self.port = self.path = self.query = self.fragment = None
1643 1643 self._localpath = True
1644 1644 self._hostport = ''
1645 1645 self._origpath = path
1646 1646
1647 1647 if parsefragment and '#' in path:
1648 1648 path, self.fragment = path.split('#', 1)
1649 1649 if not path:
1650 1650 path = None
1651 1651
1652 1652 # special case for Windows drive letters and UNC paths
1653 1653 if hasdriveletter(path) or path.startswith(r'\\'):
1654 1654 self.path = path
1655 1655 return
1656 1656
1657 1657 # For compatibility reasons, we can't handle bundle paths as
1658 1658 # normal URLS
1659 1659 if path.startswith('bundle:'):
1660 1660 self.scheme = 'bundle'
1661 1661 path = path[7:]
1662 1662 if path.startswith('//'):
1663 1663 path = path[2:]
1664 1664 self.path = path
1665 1665 return
1666 1666
1667 1667 if self._matchscheme(path):
1668 1668 parts = path.split(':', 1)
1669 1669 if parts[0]:
1670 1670 self.scheme, path = parts
1671 1671 self._localpath = False
1672 1672
1673 1673 if not path:
1674 1674 path = None
1675 1675 if self._localpath:
1676 1676 self.path = ''
1677 1677 return
1678 1678 else:
1679 1679 if self._localpath:
1680 1680 self.path = path
1681 1681 return
1682 1682
1683 1683 if parsequery and '?' in path:
1684 1684 path, self.query = path.split('?', 1)
1685 1685 if not path:
1686 1686 path = None
1687 1687 if not self.query:
1688 1688 self.query = None
1689 1689
1690 1690 # // is required to specify a host/authority
1691 1691 if path and path.startswith('//'):
1692 1692 parts = path[2:].split('/', 1)
1693 1693 if len(parts) > 1:
1694 1694 self.host, path = parts
1695 1695 else:
1696 1696 self.host = parts[0]
1697 1697 path = None
1698 1698 if not self.host:
1699 1699 self.host = None
1700 1700 # path of file:///d is /d
1701 1701 # path of file:///d:/ is d:/, not /d:/
1702 1702 if path and not hasdriveletter(path):
1703 1703 path = '/' + path
1704 1704
1705 1705 if self.host and '@' in self.host:
1706 1706 self.user, self.host = self.host.rsplit('@', 1)
1707 1707 if ':' in self.user:
1708 1708 self.user, self.passwd = self.user.split(':', 1)
1709 1709 if not self.host:
1710 1710 self.host = None
1711 1711
1712 1712 # Don't split on colons in IPv6 addresses without ports
1713 1713 if (self.host and ':' in self.host and
1714 1714 not (self.host.startswith('[') and self.host.endswith(']'))):
1715 1715 self._hostport = self.host
1716 1716 self.host, self.port = self.host.rsplit(':', 1)
1717 1717 if not self.host:
1718 1718 self.host = None
1719 1719
1720 1720 if (self.host and self.scheme == 'file' and
1721 1721 self.host not in ('localhost', '127.0.0.1', '[::1]')):
1722 1722 raise Abort(_('file:// URLs can only refer to localhost'))
1723 1723
1724 1724 self.path = path
1725 1725
1726 1726 # leave the query string escaped
1727 1727 for a in ('user', 'passwd', 'host', 'port',
1728 1728 'path', 'fragment'):
1729 1729 v = getattr(self, a)
1730 1730 if v is not None:
1731 1731 setattr(self, a, _urlunquote(v))
1732 1732
1733 1733 def __repr__(self):
1734 1734 attrs = []
1735 1735 for a in ('scheme', 'user', 'passwd', 'host', 'port', 'path',
1736 1736 'query', 'fragment'):
1737 1737 v = getattr(self, a)
1738 1738 if v is not None:
1739 1739 attrs.append('%s: %r' % (a, v))
1740 1740 return '<url %s>' % ', '.join(attrs)
1741 1741
1742 1742 def __str__(self):
1743 1743 r"""Join the URL's components back into a URL string.
1744 1744
1745 1745 Examples:
1746 1746
1747 1747 >>> str(url('http://user:pw@host:80/c:/bob?fo:oo#ba:ar'))
1748 1748 'http://user:pw@host:80/c:/bob?fo:oo#ba:ar'
1749 1749 >>> str(url('http://user:pw@host:80/?foo=bar&baz=42'))
1750 1750 'http://user:pw@host:80/?foo=bar&baz=42'
1751 1751 >>> str(url('http://user:pw@host:80/?foo=bar%3dbaz'))
1752 1752 'http://user:pw@host:80/?foo=bar%3dbaz'
1753 1753 >>> str(url('ssh://user:pw@[::1]:2200//home/joe#'))
1754 1754 'ssh://user:pw@[::1]:2200//home/joe#'
1755 1755 >>> str(url('http://localhost:80//'))
1756 1756 'http://localhost:80//'
1757 1757 >>> str(url('http://localhost:80/'))
1758 1758 'http://localhost:80/'
1759 1759 >>> str(url('http://localhost:80'))
1760 1760 'http://localhost:80/'
1761 1761 >>> str(url('bundle:foo'))
1762 1762 'bundle:foo'
1763 1763 >>> str(url('bundle://../foo'))
1764 1764 'bundle:../foo'
1765 1765 >>> str(url('path'))
1766 1766 'path'
1767 1767 >>> str(url('file:///tmp/foo/bar'))
1768 1768 'file:///tmp/foo/bar'
1769 1769 >>> str(url('file:///c:/tmp/foo/bar'))
1770 1770 'file:///c:/tmp/foo/bar'
1771 1771 >>> print url(r'bundle:foo\bar')
1772 1772 bundle:foo\bar
1773 1773 """
1774 1774 if self._localpath:
1775 1775 s = self.path
1776 1776 if self.scheme == 'bundle':
1777 1777 s = 'bundle:' + s
1778 1778 if self.fragment:
1779 1779 s += '#' + self.fragment
1780 1780 return s
1781 1781
1782 1782 s = self.scheme + ':'
1783 1783 if self.user or self.passwd or self.host:
1784 1784 s += '//'
1785 1785 elif self.scheme and (not self.path or self.path.startswith('/')
1786 1786 or hasdriveletter(self.path)):
1787 1787 s += '//'
1788 1788 if hasdriveletter(self.path):
1789 1789 s += '/'
1790 1790 if self.user:
1791 1791 s += urllib.quote(self.user, safe=self._safechars)
1792 1792 if self.passwd:
1793 1793 s += ':' + urllib.quote(self.passwd, safe=self._safechars)
1794 1794 if self.user or self.passwd:
1795 1795 s += '@'
1796 1796 if self.host:
1797 1797 if not (self.host.startswith('[') and self.host.endswith(']')):
1798 1798 s += urllib.quote(self.host)
1799 1799 else:
1800 1800 s += self.host
1801 1801 if self.port:
1802 1802 s += ':' + urllib.quote(self.port)
1803 1803 if self.host:
1804 1804 s += '/'
1805 1805 if self.path:
1806 1806 # TODO: similar to the query string, we should not unescape the
1807 1807 # path when we store it, the path might contain '%2f' = '/',
1808 1808 # which we should *not* escape.
1809 1809 s += urllib.quote(self.path, safe=self._safepchars)
1810 1810 if self.query:
1811 1811 # we store the query in escaped form.
1812 1812 s += '?' + self.query
1813 1813 if self.fragment is not None:
1814 1814 s += '#' + urllib.quote(self.fragment, safe=self._safepchars)
1815 1815 return s
1816 1816
1817 1817 def authinfo(self):
1818 1818 user, passwd = self.user, self.passwd
1819 1819 try:
1820 1820 self.user, self.passwd = None, None
1821 1821 s = str(self)
1822 1822 finally:
1823 1823 self.user, self.passwd = user, passwd
1824 1824 if not self.user:
1825 1825 return (s, None)
1826 1826 # authinfo[1] is passed to urllib2 password manager, and its
1827 1827 # URIs must not contain credentials. The host is passed in the
1828 1828 # URIs list because Python < 2.4.3 uses only that to search for
1829 1829 # a password.
1830 1830 return (s, (None, (s, self.host),
1831 1831 self.user, self.passwd or ''))
1832 1832
1833 1833 def isabs(self):
1834 1834 if self.scheme and self.scheme != 'file':
1835 1835 return True # remote URL
1836 1836 if hasdriveletter(self.path):
1837 1837 return True # absolute for our purposes - can't be joined()
1838 1838 if self.path.startswith(r'\\'):
1839 1839 return True # Windows UNC path
1840 1840 if self.path.startswith('/'):
1841 1841 return True # POSIX-style
1842 1842 return False
1843 1843
1844 1844 def localpath(self):
1845 1845 if self.scheme == 'file' or self.scheme == 'bundle':
1846 1846 path = self.path or '/'
1847 1847 # For Windows, we need to promote hosts containing drive
1848 1848 # letters to paths with drive letters.
1849 1849 if hasdriveletter(self._hostport):
1850 1850 path = self._hostport + '/' + self.path
1851 1851 elif (self.host is not None and self.path
1852 1852 and not hasdriveletter(path)):
1853 1853 path = '/' + path
1854 1854 return path
1855 1855 return self._origpath
1856 1856
1857 1857 def hasscheme(path):
1858 1858 return bool(url(path).scheme)
1859 1859
1860 1860 def hasdriveletter(path):
1861 1861 return path and path[1:2] == ':' and path[0:1].isalpha()
1862 1862
1863 1863 def urllocalpath(path):
1864 1864 return url(path, parsequery=False, parsefragment=False).localpath()
1865 1865
1866 1866 def hidepassword(u):
1867 1867 '''hide user credential in a url string'''
1868 1868 u = url(u)
1869 1869 if u.passwd:
1870 1870 u.passwd = '***'
1871 1871 return str(u)
1872 1872
1873 1873 def removeauth(u):
1874 1874 '''remove all authentication information from a url string'''
1875 1875 u = url(u)
1876 1876 u.user = u.passwd = None
1877 1877 return str(u)
1878 1878
1879 1879 def isatty(fd):
1880 1880 try:
1881 1881 return fd.isatty()
1882 1882 except AttributeError:
1883 1883 return False
1884 1884
1885 1885 timecount = unitcountfn(
1886 1886 (1, 1e3, _('%.0f s')),
1887 1887 (100, 1, _('%.1f s')),
1888 1888 (10, 1, _('%.2f s')),
1889 1889 (1, 1, _('%.3f s')),
1890 1890 (100, 0.001, _('%.1f ms')),
1891 1891 (10, 0.001, _('%.2f ms')),
1892 1892 (1, 0.001, _('%.3f ms')),
1893 1893 (100, 0.000001, _('%.1f us')),
1894 1894 (10, 0.000001, _('%.2f us')),
1895 1895 (1, 0.000001, _('%.3f us')),
1896 1896 (100, 0.000000001, _('%.1f ns')),
1897 1897 (10, 0.000000001, _('%.2f ns')),
1898 1898 (1, 0.000000001, _('%.3f ns')),
1899 1899 )
1900 1900
1901 1901 _timenesting = [0]
1902 1902
1903 1903 def timed(func):
1904 1904 '''Report the execution time of a function call to stderr.
1905 1905
1906 1906 During development, use as a decorator when you need to measure
1907 1907 the cost of a function, e.g. as follows:
1908 1908
1909 1909 @util.timed
1910 1910 def foo(a, b, c):
1911 1911 pass
1912 1912 '''
1913 1913
1914 1914 def wrapper(*args, **kwargs):
1915 1915 start = time.time()
1916 1916 indent = 2
1917 1917 _timenesting[0] += indent
1918 1918 try:
1919 1919 return func(*args, **kwargs)
1920 1920 finally:
1921 1921 elapsed = time.time() - start
1922 1922 _timenesting[0] -= indent
1923 1923 sys.stderr.write('%s%s: %s\n' %
1924 1924 (' ' * _timenesting[0], func.__name__,
1925 1925 timecount(elapsed)))
1926 1926 return wrapper
General Comments 0
You need to be logged in to leave comments. Login now