]> arthur.barton.de Git - bup.git/blob - main.py
Fix formatting of usage message (especially newlines)
[bup.git] / main.py
1 #!/usr/bin/env python
2 import sys, os, subprocess, signal, getopt
3
4 argv = sys.argv
5 exe = os.path.realpath(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(msg=""):
33     log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
34         '<command> [options...]')
35     log('')
36     common = dict(
37         ftp = 'Browse backup sets using an ftp-like client',
38         fsck = 'Check backup sets for damage and add redundancy information',
39         fuse = 'Mount your backup sets as a filesystem',
40         help = 'Print detailed help for the given command',
41         index = 'Create or display the index of files to back up',
42         on = 'Backup a remote machine to the local one',
43         restore = 'Extract files from a backup set',
44         save = 'Save files into a backup set (note: run "bup index" first)',
45         tag = 'Tag commits for easier access',
46         web = 'Launch a web server to examine backup sets',
47     )
48
49     log('Common commands:')
50     for cmd,synopsis in sorted(common.items()):
51         log('    %-10s %s' % (cmd, synopsis))
52     log('')
53
54     log('Other available commands:')
55     cmds = []
56     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
57         if c.startswith('bup-') and c.find('.') < 0:
58             cname = c[4:]
59             if cname not in common:
60                 cmds.append(c[4:])
61     log(columnate(cmds, '    '))
62
63     log("See 'bup help COMMAND' for more information on " +
64         "a specific command.")
65     if msg:
66         log('')
67         log("%s" % msg)
68     sys.exit(99)
69
70
71 if len(argv) < 2:
72     usage()
73
74 # Handle global options.
75 try:
76     optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
77     global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
78 except getopt.GetoptError, ex:
79     usage('error: %s' % ex.msg)
80
81 help_requested = None
82 do_profile = False
83
84 for opt in global_args:
85     if opt[0] in ['-?', '--help']:
86         help_requested = True
87     elif opt[0] in ['-V', '--version']:
88         subcmd = ['version']
89     elif opt[0] in ['-D', '--debug']:
90         helpers.buglvl += 1
91         os.environ['BUP_DEBUG'] = str(helpers.buglvl)
92     elif opt[0] in ['--profile']:
93         do_profile = True
94     elif opt[0] in ['-d', '--bup-dir']:
95         os.environ['BUP_DIR'] = opt[1]
96     else:
97         usage('error: unexpected option "%s"' % opt[0])
98
99 # Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
100 if 'BUP_DIR' in os.environ:
101     os.environ['BUP_DIR'] = os.path.abspath(os.environ['BUP_DIR'])
102
103 if len(subcmd) == 0:
104     if help_requested:
105         subcmd = ['help']
106     else:
107         usage()
108
109 if help_requested and subcmd[0] != 'help':
110     subcmd = ['help'] + subcmd
111
112 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
113     subcmd = ['help', subcmd[0]] + subcmd[2:]
114
115 subcmd_name = subcmd[0]
116 if not subcmd_name:
117     usage()
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     usage('error: unknown command "%s"' % subcmd_name)
128
129 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
130 if subcmd_name in ['mux', 'ftp', 'help']:
131     already_fixed = True
132 fix_stdout = not already_fixed and os.isatty(1)
133 fix_stderr = not already_fixed and os.isatty(2)
134
135 def force_tty():
136     if fix_stdout or fix_stderr:
137         amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
138         os.environ['BUP_FORCE_TTY'] = str(amt)
139     os.setsid()  # make sure ctrl-c is sent just to us, not to child too
140
141 if fix_stdout or fix_stderr:
142     realf = fix_stderr and 2 or 1
143     drealf = os.dup(realf)  # Popen goes crazy with stdout=2
144     n = subprocess.Popen([subpath('newliner')],
145                          stdin=subprocess.PIPE, stdout=drealf,
146                          close_fds=True, preexec_fn=force_tty)
147     os.close(drealf)
148     outf = fix_stdout and n.stdin.fileno() or None
149     errf = fix_stderr and n.stdin.fileno() or None
150 else:
151     n = None
152     outf = None
153     errf = None
154
155 ret = 95
156 p = None
157 forward_signals = True
158
159 def handler(signum, frame):
160     debug1('bup: Signal %d received.' % signum)
161     if not p or not forward_signals:
162         return
163     if signum != signal.SIGTSTP:
164         os.kill(p.pid, signum)
165     else: # SIGTSTP: stop the child, then ourselves.
166         os.kill(p.pid, signal.SIGSTOP)
167         signal.signal(signal.SIGTSTP, signal.SIG_DFL)
168         os.kill(os.getpid(), signal.SIGTSTP)
169         # Back from suspend -- reestablish the handler.
170         signal.signal(signal.SIGTSTP, handler)
171     ret = 94
172
173 signal.signal(signal.SIGTERM, handler)
174 signal.signal(signal.SIGINT, handler)
175 signal.signal(signal.SIGTSTP, handler)
176 signal.signal(signal.SIGCONT, handler)
177
178 try:
179     try:
180         c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
181         if not n and not outf and not errf:
182             # shortcut when no bup-newliner stuff is needed
183             os.execvp(c[0], c)
184         else:
185             p = subprocess.Popen(c, stdout=outf, stderr=errf,
186                                  preexec_fn=force_tty)
187         while 1:
188             # if we get a signal while waiting, we have to keep waiting, just
189             # in case our child doesn't die.
190             ret = p.wait()
191             forward_signals = False
192             break
193     except OSError, e:
194         log('%s: %s' % (subcmd[0], e))
195         ret = 98
196 finally:
197     if p and p.poll() == None:
198         os.kill(p.pid, signal.SIGTERM)
199         p.wait()
200     if n:
201         n.stdin.close()
202         try:
203             n.wait()
204         except:
205             pass
206 sys.exit(ret)