]> arthur.barton.de Git - bup.git/blob - main.py
wvtest.py: correct bup-python in #! preamble
[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 argv = sys.argv
11 exe = os.path.realpath(argv[0])
12 exepath = os.path.split(exe)[0] or '.'
13 exeprefix = os.path.split(os.path.abspath(exepath))[0]
14
15 # fix the PYTHONPATH to include our lib dir
16 if os.path.exists("%s/lib/bup/cmd/." % exeprefix):
17     # installed binary in /.../bin.
18     # eg. /usr/bin/bup means /usr/lib/bup/... is where our libraries are.
19     cmdpath = "%s/lib/bup/cmd" % exeprefix
20     libpath = "%s/lib/bup" % exeprefix
21     resourcepath = libpath
22 else:
23     # running from the src directory without being installed first
24     cmdpath = os.path.join(exepath, 'cmd')
25     libpath = os.path.join(exepath, 'lib')
26     resourcepath = libpath
27 sys.path[:0] = [libpath]
28 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
29 os.environ['BUP_MAIN_EXE'] = os.path.abspath(exe)
30 os.environ['BUP_RESOURCE_PATH'] = resourcepath
31
32 from bup import helpers
33 from bup.helpers import *
34
35 # after running 'bup newliner', the tty_width() ioctl won't work anymore
36 os.environ['WIDTH'] = str(tty_width())
37
38 def usage(msg=""):
39     log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
40         '<command> [options...]\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         on = 'Backup a remote machine to the local one',
48         restore = 'Extract files from a backup set',
49         save = 'Save files into a backup set (note: run "bup index" first)',
50         tag = 'Tag commits for easier access',
51         web = 'Launch a web server to examine backup sets',
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     if msg:
72         log("\n%s\n" % msg)
73     sys.exit(99)
74
75
76 if len(argv) < 2:
77     usage()
78
79 # Handle global options.
80 try:
81     optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
82     global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
83 except getopt.GetoptError, ex:
84     usage('error: %s' % ex.msg)
85
86 help_requested = None
87 do_profile = False
88
89 for opt in global_args:
90     if opt[0] in ['-?', '--help']:
91         help_requested = True
92     elif opt[0] in ['-V', '--version']:
93         subcmd = ['version']
94     elif opt[0] in ['-D', '--debug']:
95         helpers.buglvl += 1
96         os.environ['BUP_DEBUG'] = str(helpers.buglvl)
97     elif opt[0] in ['--profile']:
98         do_profile = True
99     elif opt[0] in ['-d', '--bup-dir']:
100         os.environ['BUP_DIR'] = opt[1]
101     else:
102         usage('error: unexpected option "%s"' % opt[0])
103
104 # Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
105 if 'BUP_DIR' in os.environ:
106     os.environ['BUP_DIR'] = os.path.abspath(os.environ['BUP_DIR'])
107
108 if len(subcmd) == 0:
109     if help_requested:
110         subcmd = ['help']
111     else:
112         usage()
113
114 if help_requested and subcmd[0] != 'help':
115     subcmd = ['help'] + subcmd
116
117 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
118     subcmd = ['help', subcmd[0]] + subcmd[2:]
119
120 subcmd_name = subcmd[0]
121 if not subcmd_name:
122     usage()
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 subcmd[0] = subpath(subcmd_name)
131 if not os.path.exists(subcmd[0]):
132     usage('error: unknown command "%s"' % subcmd_name)
133
134 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
135 if subcmd_name in ['mux', '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 ret = 95
161 p = None
162 forward_signals = True
163
164 def handler(signum, frame):
165     debug1('\nbup: signal %d received\n' % signum)
166     if not p or not forward_signals:
167         return
168     if signum != signal.SIGTSTP:
169         os.kill(p.pid, signum)
170     else: # SIGTSTP: stop the child, then ourselves.
171         os.kill(p.pid, signal.SIGSTOP)
172         signal.signal(signal.SIGTSTP, signal.SIG_DFL)
173         os.kill(os.getpid(), signal.SIGTSTP)
174         # Back from suspend -- reestablish the handler.
175         signal.signal(signal.SIGTSTP, handler)
176     ret = 94
177
178 signal.signal(signal.SIGTERM, handler)
179 signal.signal(signal.SIGINT, handler)
180 signal.signal(signal.SIGTSTP, handler)
181 signal.signal(signal.SIGCONT, handler)
182
183 try:
184     try:
185         c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
186         if not n and not outf and not errf:
187             # shortcut when no bup-newliner stuff is needed
188             os.execvp(c[0], c)
189         else:
190             p = subprocess.Popen(c, stdout=outf, stderr=errf,
191                                  preexec_fn=force_tty)
192         while 1:
193             # if we get a signal while waiting, we have to keep waiting, just
194             # in case our child doesn't die.
195             ret = p.wait()
196             forward_signals = False
197             break
198     except OSError, e:
199         log('%s: %s\n' % (subcmd[0], e))
200         ret = 98
201 finally:
202     if p and p.poll() == None:
203         os.kill(p.pid, signal.SIGTERM)
204         p.wait()
205     if n:
206         n.stdin.close()
207         try:
208             n.wait()
209         except:
210             pass
211 sys.exit(ret)