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