]> arthur.barton.de Git - bup.git/blob - main.py
cmd/ftp: 'ls' command should print filenames in columns.
[bup.git] / main.py
1 #!/usr/bin/env python
2
3 import sys, os, subprocess, signal, getopt
4
5 argv = sys.argv
6 exe = argv[0]
7 exepath = os.path.split(exe)[0] or '.'
8 exeprefix = os.path.split(os.path.abspath(exepath))[0]
9
10 # fix the PYTHONPATH to include our lib dir
11 if os.path.exists("%s/lib/bup/cmd/." % exeprefix):
12     # installed binary in /.../bin.
13     # eg. /usr/bin/bup means /usr/lib/bup/... is where our libraries are.
14     cmdpath = "%s/lib/bup/cmd" % exeprefix
15     libpath = "%s/lib/bup" % exeprefix
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 sys.path[:0] = [libpath]
21 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
22 os.environ['BUP_MAIN_EXE'] = os.path.abspath(exe)
23
24 from bup.helpers import *
25
26
27 def usage():
28     log('Usage: bup [-?|--help] [-d=BUP_DIR|--bup-dir=BUP_DIR] COMMAND [ARGS]'
29         + '\n\n')
30     common = dict(
31         ftp = 'Browse backup sets using an ftp-like client',
32         fsck = 'Check backup sets for damage and add redundancy information',
33         fuse = 'Mount your backup sets as a filesystem',
34         help = 'Print detailed help for the given command',
35         index = 'Create or display the index of files to back up',
36         join = 'Retrieve a file backed up using "bup split"',
37         ls = 'Browse the files in your backup sets',
38         midx = 'Index objects to speed up future backups',
39         save = 'Save files into a backup set (note: run "bup index" first)',
40         split = 'Split a single file into its own backup set',
41     )
42
43     log('Common commands:\n')
44     for cmd,synopsis in sorted(common.items()):
45         log('    %-10s %s\n' % (cmd, synopsis))
46     log('\n')
47     
48     log('Other available commands:\n')
49     cmds = []
50     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
51         if c.startswith('bup-') and c.find('.') < 0:
52             cname = c[4:]
53             if cname not in common:
54                 cmds.append(c[4:])
55     log(columnate(cmds, '    '))
56     log('\n')
57     
58     log("See 'bup help COMMAND' for more information on " +
59         "a specific command.\n")
60     sys.exit(99)
61
62
63 if len(argv) < 2:
64     usage()
65
66 # Handle global options.
67 try:
68     global_args, subcmd = getopt.getopt(argv[1:], '?d:', ['help', '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     elif opt[0] == '-d' or opt[0] == '--bup-dir':
80         dest_dir = opt[1]
81     else:
82         log('error: unexpected option "%s"\n' % opt[0])
83         usage()
84
85 if len(subcmd) == 0:
86     if help_requested:
87         subcmd = ['help']
88     else:
89         usage()
90
91 if help_requested and subcmd[0] != 'help':
92     subcmd = ['help'] + subcmd
93
94 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
95     subcmd = ['help', subcmd[0]] + subcmd[2:]
96
97 subcmd_name = subcmd[0]
98 if not subcmd_name:
99     usage()
100
101 subcmd_env = os.environ
102 if dest_dir:
103     subcmd_env.update({"BUP_DIR" : dest_dir})
104
105 def subpath(s):
106     sp = os.path.join(exepath, 'bup-%s' % s)
107     if not os.path.exists(sp):
108         sp = os.path.join(cmdpath, 'bup-%s' % s)
109     return sp
110
111 if not os.path.exists(subpath(subcmd_name)):
112     log('error: unknown command "%s"\n' % subcmd_name)
113     usage()
114
115 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
116 if subcmd_name in ['ftp', 'help']:
117     already_fixed = True
118 fix_stdout = not already_fixed and os.isatty(1)
119 fix_stderr = not already_fixed and os.isatty(2)
120
121 def force_tty():
122     if fix_stdout or fix_stderr:
123         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
124         os.environ['BUP_FORCE_TTY'] = str(amt)
125     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
126
127 if fix_stdout or fix_stderr:
128     realf = fix_stderr and 2 or 1
129     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
130     n = subprocess.Popen([subpath('newliner')],
131                          stdin=subprocess.PIPE, stdout=drealf,
132                          close_fds=True, preexec_fn=force_tty)
133     os.close(drealf)
134     outf = fix_stdout and n.stdin.fileno() or None
135     errf = fix_stderr and n.stdin.fileno() or None
136 else:
137     n = None
138     outf = None
139     errf = None
140
141
142 class SigException(Exception):
143     def __init__(self, signum):
144         self.signum = signum
145         Exception.__init__(self, 'signal %d received' % signum)
146 def handler(signum, frame):
147     raise SigException(signum)
148
149 signal.signal(signal.SIGTERM, handler)
150 signal.signal(signal.SIGINT, handler)
151
152 ret = 95
153 p = None
154 try:
155     try:
156         p = subprocess.Popen([subpath(subcmd_name)] + subcmd[1:],
157                              stdout=outf, stderr=errf, preexec_fn=force_tty)
158         while 1:
159             # if we get a signal while waiting, we have to keep waiting, just
160             # in case our child doesn't die.
161             try:
162                 ret = p.wait()
163                 break
164             except SigException, e:
165                 log('\nbup: %s\n' % e)
166                 os.kill(p.pid, e.signum)
167                 ret = 94
168     except OSError, e:
169         log('%s: %s\n' % (subpath(subcmd_name), e))
170         ret = 98
171 finally:
172     if p and p.poll() == None:
173         os.kill(p.pid, signal.SIGTERM)
174         p.wait()
175     if n:
176         n.stdin.close()
177         try:
178             n.wait()
179         except:
180             pass
181 sys.exit(ret)