]> Tony Duckles's Git Repositories (git.nynim.org) - svn2svn.git/blob - svn2svn/ui.py
Refactor find_svn_ancestors() to make more generic
[svn2svn.git] / svn2svn / ui.py
1 """ User interface functions """
2
3 import os
4 import sys
5
6 def termwidth():
7 if 'COLUMNS' in os.environ:
8 try:
9 return int(os.environ['COLUMNS'])
10 except ValueError:
11 pass
12 try:
13 import termios, array, fcntl
14 for dev in (sys.stdout, sys.stdin):
15 try:
16 fd = dev.fileno()
17 if not os.isatty(fd):
18 continue
19 arri = fcntl.ioctl(fd, termios.TIOCGWINSZ, '\0' * 8)
20 return array.array('h', arri)[1]
21 except ValueError:
22 pass
23 except ImportError:
24 pass
25 return 80
26
27 # Log levels
28 ERROR = 0
29 DEFAULT = 10
30 VERBOSE = 20
31 EXTRA = 30
32 DEBUG = 40
33
34 # SGR foreground color codes
35 _colors = {
36 'BLACK': '30', 'BLACK_B': '90',
37 'RED': '31', 'RED_B': '91',
38 'GREEN': '32', 'GREEN_B': '92',
39 'YELLOW': '33', 'YELLOW_B': '93',
40 'BLUE': '34', 'BLUE_B': '94',
41 'MAGENTA': '35', 'MAGENTA_B': '95',
42 'CYAN': '36', 'CYAN_B': '96',
43 'WHITE': '37', 'WHITE_B': '97' }
44
45 # Configuration
46 _level = DEFAULT
47
48 def status(msg, *args, **kwargs):
49 """Write a status message.
50
51 args are treated as substitutions for msg.
52
53 The following keyword arguments are allowed:
54 level : One of DEFAULT, VERBOSE or DEBUG.
55 linebreak: If True a new line is appended to msg (default: True).
56 truncate : Truncate output if larger then term width (default: True).
57 """
58 global _level
59 level = kwargs.get('level', DEFAULT)
60 if level > _level:
61 return
62 width = termwidth()
63 if args:
64 msg = msg % args
65 if kwargs.get('linebreak', True):
66 msg = '%s%s' % (msg, os.linesep)
67 if level == ERROR:
68 stream = sys.stderr
69 else:
70 stream = sys.stdout
71 if kwargs.get('truncate', False) and level != ERROR:
72 add_newline = msg.endswith('\n')
73 msglines = msg.splitlines()
74 for no, line in enumerate(msglines):
75 if len(line) > width:
76 msglines[no] = line[:width-3]+"..."
77 msg = os.linesep.join(msglines)
78 if add_newline:
79 msg = '%s%s' % (msg, os.linesep)
80 if isinstance(msg, unicode):
81 msg = msg.encode('utf-8')
82 color = kwargs.get('color', None)
83 bold = kwargs.get('bold', None)
84 if color in _colors:
85 msg = '%s%s%s' % ("\x1b["+_colors[color]+(";1" if bold else "")+"m", msg, "\x1b[0m")
86 stream.write(msg)
87 stream.flush()
88
89 def update_config(options):
90 """Update UI configuration."""
91 global _level
92 _level = options.verbosity
93
94 def get_level():
95 """Verbosity level"""
96 global _level
97 return _level