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