]> arthur.barton.de Git - bup.git/blob - main.py
Support exception chaining and tracebacks
[bup.git] / main.py
1 #!/bin/sh
2 """": # -*-python-*- # -*-python-*-
3 bup_python="$(dirname "$0")/cmd/bup-python" || exit $?
4 exec "$bup_python" "$0" ${1+"$@"}
5 """
6 # end of bup preamble
7
8 import sys, os, subprocess, signal, getopt
9
10
11 argv = sys.argv
12 exe = os.path.realpath(argv[0])
13 exepath = os.path.split(exe)[0] or '.'
14 exeprefix = os.path.split(os.path.abspath(exepath))[0]
15
16 # fix the PYTHONPATH to include our lib dir
17 if os.path.exists("%s/lib/bup/cmd/." % exeprefix):
18     # installed binary in /.../bin.
19     # eg. /usr/bin/bup means /usr/lib/bup/... is where our libraries are.
20     cmdpath = "%s/lib/bup/cmd" % exeprefix
21     libpath = "%s/lib/bup" % exeprefix
22     resourcepath = libpath
23 else:
24     # running from the src directory without being installed first
25     cmdpath = os.path.join(exepath, 'cmd')
26     libpath = os.path.join(exepath, 'lib')
27     resourcepath = libpath
28 sys.path[:0] = [libpath]
29 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
30 os.environ['BUP_MAIN_EXE'] = os.path.abspath(exe)
31 os.environ['BUP_RESOURCE_PATH'] = resourcepath
32
33
34 from bup import helpers
35 from bup.compat import wrap_main
36 from bup.helpers import atoi, columnate, debug1, log, tty_width
37
38
39 # after running 'bup newliner', the tty_width() ioctl won't work anymore
40 os.environ['WIDTH'] = str(tty_width())
41
42 def usage(msg=""):
43     log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
44         '<command> [options...]\n\n')
45     common = dict(
46         ftp = 'Browse backup sets using an ftp-like client',
47         fsck = 'Check backup sets for damage and add redundancy information',
48         fuse = 'Mount your backup sets as a filesystem',
49         help = 'Print detailed help for the given command',
50         index = 'Create or display the index of files to back up',
51         on = 'Backup a remote machine to the local one',
52         restore = 'Extract files from a backup set',
53         save = 'Save files into a backup set (note: run "bup index" first)',
54         tag = 'Tag commits for easier access',
55         web = 'Launch a web server to examine backup sets',
56     )
57
58     log('Common commands:\n')
59     for cmd,synopsis in sorted(common.items()):
60         log('    %-10s %s\n' % (cmd, synopsis))
61     log('\n')
62     
63     log('Other available commands:\n')
64     cmds = []
65     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
66         if c.startswith('bup-') and c.find('.') < 0:
67             cname = c[4:]
68             if cname not in common:
69                 cmds.append(c[4:])
70     log(columnate(cmds, '    '))
71     log('\n')
72     
73     log("See 'bup help COMMAND' for more information on " +
74         "a specific command.\n")
75     if msg:
76         log("\n%s\n" % msg)
77     sys.exit(99)
78
79
80 if len(argv) < 2:
81     usage()
82
83 # Handle global options.
84 try:
85     optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
86     global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
87 except getopt.GetoptError as ex:
88     usage('error: %s' % ex.msg)
89
90 help_requested = None
91 do_profile = False
92
93 for opt in global_args:
94     if opt[0] in ['-?', '--help']:
95         help_requested = True
96     elif opt[0] in ['-V', '--version']:
97         subcmd = ['version']
98     elif opt[0] in ['-D', '--debug']:
99         helpers.buglvl += 1
100         os.environ['BUP_DEBUG'] = str(helpers.buglvl)
101     elif opt[0] in ['--profile']:
102         do_profile = True
103     elif opt[0] in ['-d', '--bup-dir']:
104         os.environ['BUP_DIR'] = opt[1]
105     else:
106         usage('error: unexpected option "%s"' % opt[0])
107
108 # Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
109 if 'BUP_DIR' in os.environ:
110     os.environ['BUP_DIR'] = os.path.abspath(os.environ['BUP_DIR'])
111
112 if len(subcmd) == 0:
113     if help_requested:
114         subcmd = ['help']
115     else:
116         usage()
117
118 if help_requested and subcmd[0] != 'help':
119     subcmd = ['help'] + subcmd
120
121 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
122     subcmd = ['help', subcmd[0]] + subcmd[2:]
123
124 subcmd_name = subcmd[0]
125 if not subcmd_name:
126     usage()
127
128 def subpath(s):
129     sp = os.path.join(exepath, 'bup-%s' % s)
130     if not os.path.exists(sp):
131         sp = os.path.join(cmdpath, 'bup-%s' % s)
132     return sp
133
134 subcmd[0] = subpath(subcmd_name)
135 if not os.path.exists(subcmd[0]):
136     usage('error: unknown command "%s"' % subcmd_name)
137
138 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
139 if subcmd_name in ['mux', 'ftp', 'help']:
140     already_fixed = True
141 fix_stdout = not already_fixed and os.isatty(1)
142 fix_stderr = not already_fixed and os.isatty(2)
143
144 def force_tty():
145     if fix_stdout or fix_stderr:
146         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
147         os.environ['BUP_FORCE_TTY'] = str(amt)
148     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
149
150 if fix_stdout or fix_stderr:
151     realf = fix_stderr and 2 or 1
152     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
153     n = subprocess.Popen([subpath('newliner')],
154                          stdin=subprocess.PIPE, stdout=drealf,
155                          close_fds=True, preexec_fn=force_tty)
156     os.close(drealf)
157     outf = fix_stdout and n.stdin.fileno() or None
158     errf = fix_stderr and n.stdin.fileno() or None
159 else:
160     n = None
161     outf = None
162     errf = None
163
164 ret = 95
165 p = None
166 forward_signals = True
167
168 def handler(signum, frame):
169     debug1('\nbup: signal %d received\n' % signum)
170     if not p or not forward_signals:
171         return
172     if signum != signal.SIGTSTP:
173         os.kill(p.pid, signum)
174     else: # SIGTSTP: stop the child, then ourselves.
175         os.kill(p.pid, signal.SIGSTOP)
176         signal.signal(signal.SIGTSTP, signal.SIG_DFL)
177         os.kill(os.getpid(), signal.SIGTSTP)
178         # Back from suspend -- reestablish the handler.
179         signal.signal(signal.SIGTSTP, handler)
180     ret = 94
181
182 def main():
183     signal.signal(signal.SIGTERM, handler)
184     signal.signal(signal.SIGINT, handler)
185     signal.signal(signal.SIGTSTP, handler)
186     signal.signal(signal.SIGCONT, handler)
187
188     try:
189         try:
190             c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
191             if not n and not outf and not errf:
192                 # shortcut when no bup-newliner stuff is needed
193                 os.execvp(c[0], c)
194             else:
195                 p = subprocess.Popen(c, stdout=outf, stderr=errf,
196                                      preexec_fn=force_tty)
197             while 1:
198                 # if we get a signal while waiting, we have to keep waiting, just
199                 # in case our child doesn't die.
200                 ret = p.wait()
201                 forward_signals = False
202                 break
203         except OSError as e:
204             log('%s: %s\n' % (subcmd[0], e))
205             ret = 98
206     finally:
207         if p and p.poll() == None:
208             os.kill(p.pid, signal.SIGTERM)
209             p.wait()
210         if n:
211             n.stdin.close()
212             try:
213                 n.wait()
214             except:
215                 pass
216     sys.exit(ret)
217
218 wrap_main(main)