]> arthur.barton.de Git - bup.git/blob - main.py
options.py: get the real tty width for word wrapping purposes.
[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] '
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         save = 'Save files into a backup set (note: run "bup index" first)',
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:], '?VDd:',
72                                     ['help', 'version', 'debug', '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] in ['-?', '--help']:
82         help_requested = True
83     elif opt[0] in ['-V', '--version']:
84         subcmd = ['version']
85     elif opt[0] in ['-D', '--debug']:
86         helpers.buglvl += 1
87         os.environ['BUP_DEBUG'] = str(helpers.buglvl)
88     elif opt[0] in ['-d', '--bup-dir']:
89         dest_dir = opt[1]
90     else:
91         log('error: unexpected option "%s"\n' % opt[0])
92         usage()
93
94 if len(subcmd) == 0:
95     if help_requested:
96         subcmd = ['help']
97     else:
98         usage()
99
100 if help_requested and subcmd[0] != 'help':
101     subcmd = ['help'] + subcmd
102
103 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
104     subcmd = ['help', subcmd[0]] + subcmd[2:]
105
106 subcmd_name = subcmd[0]
107 if not subcmd_name:
108     usage()
109
110 subcmd_env = os.environ
111 if dest_dir:
112     subcmd_env.update({"BUP_DIR" : dest_dir})
113
114 def subpath(s):
115     sp = os.path.join(exepath, 'bup-%s' % s)
116     if not os.path.exists(sp):
117         sp = os.path.join(cmdpath, 'bup-%s' % s)
118     return sp
119
120 if not os.path.exists(subpath(subcmd_name)):
121     log('error: unknown command "%s"\n' % subcmd_name)
122     usage()
123
124 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
125 if subcmd_name in ['ftp', 'help']:
126     already_fixed = True
127 fix_stdout = not already_fixed and os.isatty(1)
128 fix_stderr = not already_fixed and os.isatty(2)
129
130 def force_tty():
131     if fix_stdout or fix_stderr:
132         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
133         os.environ['BUP_FORCE_TTY'] = str(amt)
134     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
135
136 if fix_stdout or fix_stderr:
137     realf = fix_stderr and 2 or 1
138     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
139     n = subprocess.Popen([subpath('newliner')],
140                          stdin=subprocess.PIPE, stdout=drealf,
141                          close_fds=True, preexec_fn=force_tty)
142     os.close(drealf)
143     outf = fix_stdout and n.stdin.fileno() or None
144     errf = fix_stderr and n.stdin.fileno() or None
145 else:
146     n = None
147     outf = None
148     errf = None
149
150
151 class SigException(Exception):
152     def __init__(self, signum):
153         self.signum = signum
154         Exception.__init__(self, 'signal %d received' % signum)
155 def handler(signum, frame):
156     raise SigException(signum)
157
158 signal.signal(signal.SIGTERM, handler)
159 signal.signal(signal.SIGINT, handler)
160
161 ret = 95
162 p = None
163 try:
164     try:
165         p = subprocess.Popen([subpath(subcmd_name)] + subcmd[1:],
166                              stdout=outf, stderr=errf, preexec_fn=force_tty)
167         while 1:
168             # if we get a signal while waiting, we have to keep waiting, just
169             # in case our child doesn't die.
170             try:
171                 ret = p.wait()
172                 break
173             except SigException, e:
174                 log('\nbup: %s\n' % e)
175                 os.kill(p.pid, e.signum)
176                 ret = 94
177     except OSError, e:
178         log('%s: %s\n' % (subpath(subcmd_name), e))
179         ret = 98
180 finally:
181     if p and p.poll() == None:
182         os.kill(p.pid, signal.SIGTERM)
183         p.wait()
184     if n:
185         n.stdin.close()
186         try:
187             n.wait()
188         except:
189             pass
190 sys.exit(ret)