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