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