]> Tony Duckles's Git Repositories (git.nynim.org) - svn2svn.git/blob - svn2svn/ui.py
Remove hgsvn-centric exception classes
[svn2svn.git] / svn2svn / ui.py
1 # -*- coding: utf-8 -*-
2
3 """User interface functions."""
4
5 import os
6 import sys
7
8 try:
9 # First try to import the Mercurial implementation.
10 import mercurial.ui
11 if getattr(mercurial.ui.ui(), 'termwidth', False):
12 termwidth = mercurial.ui.ui().termwidth
13 else:
14 from mercurial.util import termwidth
15 except ImportError:
16 # Fallback to local copy of Mercurial's implementation.
17 def termwidth():
18 if 'COLUMNS' in os.environ:
19 try:
20 return int(os.environ['COLUMNS'])
21 except ValueError:
22 pass
23 try:
24 import termios, array, fcntl
25 for dev in (sys.stdout, sys.stdin):
26 try:
27 fd = dev.fileno()
28 if not os.isatty(fd):
29 continue
30 arri = fcntl.ioctl(fd, termios.TIOCGWINSZ, '\0' * 8)
31 return array.array('h', arri)[1]
32 except ValueError:
33 pass
34 except ImportError:
35 pass
36 return 80
37
38
39 # Log levels
40 ERROR = 0
41 DEFAULT = 10
42 VERBOSE = 20
43 DEBUG = 30
44
45
46 # Configuration
47 _level = DEFAULT
48
49
50 def status(msg, *args, **kwargs):
51 """Write a status message.
52
53 args are treated as substitutions for msg.
54
55 The following keyword arguments are allowed:
56 level : One of DEFAULT, VERBOSE or DEBUG.
57 linebreak: If True a new line is appended to msg (default: True).
58 truncate : Truncate output if larger then term width (default: True).
59 """
60 global _level
61 level = kwargs.get('level', DEFAULT)
62 if level > _level:
63 return
64 width = termwidth()
65 if args:
66 msg = msg % args
67 if kwargs.get('linebreak', True):
68 msg = '%s%s' % (msg, os.linesep)
69 if level == ERROR:
70 stream = sys.stderr
71 else:
72 stream = sys.stdout
73 if kwargs.get('truncate', True) and level != ERROR:
74 add_newline = msg.endswith('\n')
75 msglines = msg.splitlines()
76 for no, line in enumerate(msglines):
77 if len(line) > width:
78 msglines[no] = line[:width-3]+"..."
79 msg = os.linesep.join(msglines)
80 if add_newline:
81 msg = '%s%s' % (msg, os.linesep)
82 if isinstance(msg, unicode):
83 msg = msg.encode('utf-8')
84 stream.write(msg)
85 stream.flush()
86
87
88 def update_config(options):
89 """Update UI configuration."""
90 global _level
91 _level = options.verbosity