]> arthur.barton.de Git - bup.git/blob - main.py
Add support for a global --bup-dir or -d argument.
[bup.git] / main.py
1 #!/usr/bin/env python
2
3 import sys, os, subprocess, signal, getopt
4
5 argv = sys.argv
6 exe = argv[0]
7 exepath = os.path.split(exe)[0] or '.'
8
9 # fix the PYTHONPATH to include our lib dir
10 libpath = os.path.join(exepath, 'lib')
11 cmdpath = os.path.join(exepath, 'cmd')
12 sys.path[:0] = [libpath]
13 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
14 os.environ['BUP_MAIN_EXE'] = os.path.abspath(exe)
15
16 from bup.helpers import *
17
18
19 def columnate(l, prefix):
20     l = l[:]
21     clen = max(len(s) for s in l)
22     ncols = (78 - len(prefix)) / (clen + 2)
23     if ncols <= 1:
24         ncols = 1
25         clen = 0
26     cols = []
27     while len(l) % ncols:
28         l.append('')
29     rows = len(l)/ncols
30     for s in range(0, len(l), rows):
31         cols.append(l[s:s+rows])
32     out = ''
33     for row in zip(*cols):
34         out += prefix + ''.join(('%-*s' % (clen+2, s)) for s in row) + '\n'
35     return out
36
37
38 def usage():
39     log('Usage: bup [-?|--help] [-d=BUP_DIR|--bup-dir=BUP_DIR] COMMAND [ARGS]'
40         + '\n\n')
41     common = dict(
42         ftp = 'Browse backup sets using an ftp-like client',
43         fsck = 'Check backup sets for damage and add redundancy information',
44         fuse = 'Mount your backup sets as a filesystem',
45         help = 'Print detailed help for the given command',
46         index = 'Create or display the index of files to back up',
47         join = 'Retrieve a file backed up using "bup split"',
48         ls = 'Browse the files in your backup sets',
49         midx = 'Index objects to speed up future backups',
50         save = 'Save files into a backup set (note: run "bup index" first)',
51         split = 'Split a single file into its own backup set',
52     )
53
54     log('Common commands:\n')
55     for cmd,synopsis in sorted(common.items()):
56         log('    %-10s %s\n' % (cmd, synopsis))
57     log('\n')
58     
59     log('Other available commands:\n')
60     cmds = []
61     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
62         if c.startswith('bup-') and c.find('.') < 0:
63             cname = c[4:]
64             if cname not in common:
65                 cmds.append(c[4:])
66     log(columnate(cmds, '    '))
67     log('\n')
68     
69     log("See 'bup help COMMAND' for more information on " +
70         "a specific command.\n")
71     sys.exit(99)
72
73
74 if len(argv) < 2:
75     usage()
76
77 # Handle global options.
78 try:
79     global_args, subcmd = getopt.getopt(argv[1:], '?d:', ['help', 'bup-dir='])
80 except getopt.GetoptError, ex:
81     log('error: ' + ex.msg + '\n')
82     usage()
83
84 help_requested = None
85 dest_dir = None
86
87 for opt in global_args:
88     if opt[0] == '-?' or opt[0] == '--help':
89         help_requested = True
90     elif opt[0] == '-d' or opt[0] == '--bup-dir':
91         dest_dir = opt[1]
92     else:
93         log('error: unexpected option "%s"\n' % opt[0])
94         usage()
95
96 if len(subcmd) == 0:
97     if help_requested:
98         subcmd = ['help']
99     else:
100         usage()
101
102 if help_requested and subcmd[0] != 'help':
103     subcmd = ['help'] + subcmd
104
105 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
106     subcmd = ['help', subcmd[0]] + subcmd[2:]
107
108 subcmd_name = subcmd[0]
109 if not subcmd_name:
110     usage()
111
112 subcmd_env = os.environ
113 if dest_dir:
114     subcmd_env.update({"BUP_DIR" : dest_dir})
115
116 def subpath(s):
117     sp = os.path.join(exepath, 'bup-%s' % s)
118     if not os.path.exists(sp):
119         sp = os.path.join(cmdpath, 'bup-%s' % s)
120     return sp
121
122 if not os.path.exists(subpath(subcmd_name)):
123     log('error: unknown command "%s"\n' % subcmd_name)
124     usage()
125
126 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
127 if subcmd_name in ['ftp', 'help']:
128     already_fixed = True
129 fix_stdout = not already_fixed and os.isatty(1)
130 fix_stderr = not already_fixed and os.isatty(2)
131
132 def force_tty():
133     if fix_stdout or fix_stderr:
134         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
135         os.environ['BUP_FORCE_TTY'] = str(amt)
136     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
137
138 if fix_stdout or fix_stderr:
139     realf = fix_stderr and 2 or 1
140     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
141     n = subprocess.Popen([subpath('newliner')],
142                          stdin=subprocess.PIPE, stdout=drealf,
143                          close_fds=True, preexec_fn=force_tty)
144     os.close(drealf)
145     outf = fix_stdout and n.stdin.fileno() or None
146     errf = fix_stderr and n.stdin.fileno() or None
147 else:
148     n = None
149     outf = None
150     errf = None
151
152
153 class SigException(Exception):
154     def __init__(self, signum):
155         self.signum = signum
156         Exception.__init__(self, 'signal %d received' % signum)
157 def handler(signum, frame):
158     raise SigException(signum)
159
160 signal.signal(signal.SIGTERM, handler)
161 signal.signal(signal.SIGINT, handler)
162
163 ret = 95
164 p = None
165 try:
166     try:
167         p = subprocess.Popen([subpath(subcmd_name)] + subcmd[1:],
168                              stdout=outf, stderr=errf, preexec_fn=force_tty)
169         while 1:
170             # if we get a signal while waiting, we have to keep waiting, just
171             # in case our child doesn't die.
172             try:
173                 ret = p.wait()
174                 break
175             except SigException, e:
176                 log('\nbup: %s\n' % e)
177                 os.kill(p.pid, e.signum)
178                 ret = 94
179     except OSError, e:
180         log('%s: %s\n' % (subpath(subcmd_name), e))
181         ret = 98
182 finally:
183     if p and p.poll() == None:
184         os.kill(p.pid, signal.SIGTERM)
185         p.wait()
186     if n:
187         n.stdin.close()
188         try:
189             n.wait()
190         except:
191             pass
192 sys.exit(ret)