]> arthur.barton.de Git - bup.git/blob - main.py
bd6fb0b8964925f78a7f61899899e01457f6915e
[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] [--profile] '
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         tag = 'Tag commits for easier access',
45         web = 'Launch a web server to examine backup sets',
46     )
47
48     log('Common commands:\n')
49     for cmd,synopsis in sorted(common.items()):
50         log('    %-10s %s\n' % (cmd, synopsis))
51     log('\n')
52     
53     log('Other available commands:\n')
54     cmds = []
55     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
56         if c.startswith('bup-') and c.find('.') < 0:
57             cname = c[4:]
58             if cname not in common:
59                 cmds.append(c[4:])
60     log(columnate(cmds, '    '))
61     log('\n')
62     
63     log("See 'bup help COMMAND' for more information on " +
64         "a specific command.\n")
65     sys.exit(99)
66
67
68 if len(argv) < 2:
69     usage()
70
71 # Handle global options.
72 try:
73     optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
74     global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
75 except getopt.GetoptError, ex:
76     log('error: ' + ex.msg + '\n')
77     usage()
78
79 help_requested = None
80 dest_dir = None
81 do_profile = False
82
83 for opt in global_args:
84     if opt[0] in ['-?', '--help']:
85         help_requested = True
86     elif opt[0] in ['-V', '--version']:
87         subcmd = ['version']
88     elif opt[0] in ['-D', '--debug']:
89         helpers.buglvl += 1
90         os.environ['BUP_DEBUG'] = str(helpers.buglvl)
91     elif opt[0] in ['--profile']:
92         do_profile = True
93     elif opt[0] in ['-d', '--bup-dir']:
94         dest_dir = opt[1]
95     else:
96         log('error: unexpected option "%s"\n' % opt[0])
97         usage()
98
99 if len(subcmd) == 0:
100     if help_requested:
101         subcmd = ['help']
102     else:
103         usage()
104
105 if help_requested and subcmd[0] != 'help':
106     subcmd = ['help'] + subcmd
107
108 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
109     subcmd = ['help', subcmd[0]] + subcmd[2:]
110
111 subcmd_name = subcmd[0]
112 if not subcmd_name:
113     usage()
114
115 subcmd_env = os.environ
116 if dest_dir:
117     subcmd_env.update({"BUP_DIR" : dest_dir})
118
119 def subpath(s):
120     sp = os.path.join(exepath, 'bup-%s' % s)
121     if not os.path.exists(sp):
122         sp = os.path.join(cmdpath, 'bup-%s' % s)
123     return sp
124
125 subcmd[0] = subpath(subcmd_name)
126 if not os.path.exists(subcmd[0]):
127     log('error: unknown command "%s"\n' % subcmd_name)
128     usage()
129
130 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
131 if subcmd_name in ['mux', 'ftp', 'help']:
132     already_fixed = True
133 fix_stdout = not already_fixed and os.isatty(1)
134 fix_stderr = not already_fixed and os.isatty(2)
135
136 def force_tty():
137     if fix_stdout or fix_stderr:
138         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
139         os.environ['BUP_FORCE_TTY'] = str(amt)
140     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
141
142 if fix_stdout or fix_stderr:
143     realf = fix_stderr and 2 or 1
144     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
145     n = subprocess.Popen([subpath('newliner')],
146                          stdin=subprocess.PIPE, stdout=drealf,
147                          close_fds=True, preexec_fn=force_tty)
148     os.close(drealf)
149     outf = fix_stdout and n.stdin.fileno() or None
150     errf = fix_stderr and n.stdin.fileno() or None
151 else:
152     n = None
153     outf = None
154     errf = None
155
156
157 class SigException(Exception):
158     def __init__(self, signum):
159         self.signum = signum
160         Exception.__init__(self, 'signal %d received' % signum)
161 def handler(signum, frame):
162     raise SigException(signum)
163
164 signal.signal(signal.SIGTERM, handler)
165 signal.signal(signal.SIGINT, handler)
166
167 ret = 95
168 p = None
169 try:
170     try:
171         c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
172         if not n and not outf and not errf:
173             # shortcut when no bup-newliner stuff is needed
174             os.execvp(c[0], c)
175         else:
176             p = subprocess.Popen(c, stdout=outf, stderr=errf,
177                                  preexec_fn=force_tty)
178         while 1:
179             # if we get a signal while waiting, we have to keep waiting, just
180             # in case our child doesn't die.
181             try:
182                 ret = p.wait()
183                 break
184             except SigException, e:
185                 log('\nbup: %s\n' % e)
186                 os.kill(p.pid, e.signum)
187                 ret = 94
188     except OSError, e:
189         log('%s: %s\n' % (subcmd[0], e))
190         ret = 98
191 finally:
192     if p and p.poll() == None:
193         os.kill(p.pid, signal.SIGTERM)
194         p.wait()
195     if n:
196         n.stdin.close()
197         try:
198             n.wait()
199         except:
200             pass
201 sys.exit(ret)