comparison mercurial/util.py @ 28497:906fece80cfa

util: refactor getstackframes
author timeless <timeless@mozdev.org>
date Fri, 11 Mar 2016 17:22:04 +0000
parents b592564a803c
children 6041fb8f2da8
comparison
equal deleted inserted replaced
28496:b592564a803c 28497:906fece80cfa
2548 results = [] 2548 results = []
2549 for source, hook in self._hooks: 2549 for source, hook in self._hooks:
2550 results.append(hook(*args)) 2550 results.append(hook(*args))
2551 return results 2551 return results
2552 2552
2553 def getstackframes(skip=0, line=' %-*s in %s\n', fileline='%s:%s'):
2554 '''Yields lines for a nicely formatted stacktrace.
2555 Skips the 'skip' last entries.
2556 Each file+linenumber is formatted according to fileline.
2557 Each line is formatted according to line.
2558 If line is None, it yields:
2559 length of longest filepath+line number,
2560 filepath+linenumber,
2561 function
2562
2563 Not be used in production code but very convenient while developing.
2564 '''
2565 entries = [(fileline % (fn, ln), func)
2566 for fn, ln, func, _text in traceback.extract_stack()[:-skip - 1]]
2567 if entries:
2568 fnmax = max(len(entry[0]) for entry in entries)
2569 for fnln, func in entries:
2570 if line is None:
2571 yield (fnmax, fnln, func)
2572 else:
2573 yield line % (fnmax, fnln, func)
2574
2553 def debugstacktrace(msg='stacktrace', skip=0, f=sys.stderr, otherf=sys.stdout): 2575 def debugstacktrace(msg='stacktrace', skip=0, f=sys.stderr, otherf=sys.stdout):
2554 '''Writes a message to f (stderr) with a nicely formatted stacktrace. 2576 '''Writes a message to f (stderr) with a nicely formatted stacktrace.
2555 Skips the 'skip' last entries. By default it will flush stdout first. 2577 Skips the 'skip' last entries. By default it will flush stdout first.
2556 It can be used everywhere and intentionally does not require an ui object. 2578 It can be used everywhere and intentionally does not require an ui object.
2557 Not be used in production code but very convenient while developing. 2579 Not be used in production code but very convenient while developing.
2558 ''' 2580 '''
2559 if otherf: 2581 if otherf:
2560 otherf.flush() 2582 otherf.flush()
2561 f.write('%s at:\n' % msg) 2583 f.write('%s at:\n' % msg)
2562 entries = [('%s:%s' % (fn, ln), func) 2584 for line in getstackframes(skip + 1):
2563 for fn, ln, func, _text in traceback.extract_stack()[:-skip - 1]] 2585 f.write(line)
2564 if entries:
2565 fnmax = max(len(entry[0]) for entry in entries)
2566 for fnln, func in entries:
2567 f.write(' %-*s in %s\n' % (fnmax, fnln, func))
2568 f.flush() 2586 f.flush()
2569 2587
2570 class dirs(object): 2588 class dirs(object):
2571 '''a multiset of directory names from a dirstate or manifest''' 2589 '''a multiset of directory names from a dirstate or manifest'''
2572 2590