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