2 import sys, os, subprocess, signal, getopt
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]
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
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
26 from bup import helpers
27 from bup.helpers import *
29 # after running 'bup newliner', the tty_width() ioctl won't work anymore
30 os.environ['WIDTH'] = str(tty_width())
33 log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
34 '<command> [options...]\n\n')
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 restore = 'Extract files from a backup set',
43 save = 'Save files into a backup set (note: run "bup index" first)',
44 tag = 'Tag commits for easier access',
45 web = 'Launch a web server to examine backup sets',
48 log('Common commands:\n')
49 for cmd,synopsis in sorted(common.items()):
50 log(' %-10s %s\n' % (cmd, synopsis))
53 log('Other available commands:\n')
55 for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
56 if c.startswith('bup-') and c.find('.') < 0:
58 if cname not in common:
60 log(columnate(cmds, ' '))
63 log("See 'bup help COMMAND' for more information on " +
64 "a specific command.\n")
73 # Handle global options.
75 optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
76 global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
77 except getopt.GetoptError, ex:
78 usage('error: %s' % ex.msg)
83 for opt in global_args:
84 if opt[0] in ['-?', '--help']:
86 elif opt[0] in ['-V', '--version']:
88 elif opt[0] in ['-D', '--debug']:
90 os.environ['BUP_DEBUG'] = str(helpers.buglvl)
91 elif opt[0] in ['--profile']:
93 elif opt[0] in ['-d', '--bup-dir']:
94 os.environ['BUP_DIR'] = opt[1]
96 usage('error: unexpected option "%s"' % opt[0])
98 # Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
99 if 'BUP_DIR' in os.environ:
100 os.environ['BUP_DIR'] = os.path.abspath(os.environ['BUP_DIR'])
108 if help_requested and subcmd[0] != 'help':
109 subcmd = ['help'] + subcmd
111 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
112 subcmd = ['help', subcmd[0]] + subcmd[2:]
114 subcmd_name = subcmd[0]
119 sp = os.path.join(exepath, 'bup-%s' % s)
120 if not os.path.exists(sp):
121 sp = os.path.join(cmdpath, 'bup-%s' % s)
124 subcmd[0] = subpath(subcmd_name)
125 if not os.path.exists(subcmd[0]):
126 usage('error: unknown command "%s"' % subcmd_name)
128 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
129 if subcmd_name in ['mux', 'ftp', 'help']:
131 fix_stdout = not already_fixed and os.isatty(1)
132 fix_stderr = not already_fixed and os.isatty(2)
135 if fix_stdout or fix_stderr:
136 amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
137 os.environ['BUP_FORCE_TTY'] = str(amt)
138 os.setsid() # make sure ctrl-c is sent just to us, not to child too
140 if fix_stdout or fix_stderr:
141 realf = fix_stderr and 2 or 1
142 drealf = os.dup(realf) # Popen goes crazy with stdout=2
143 n = subprocess.Popen([subpath('newliner')],
144 stdin=subprocess.PIPE, stdout=drealf,
145 close_fds=True, preexec_fn=force_tty)
147 outf = fix_stdout and n.stdin.fileno() or None
148 errf = fix_stderr and n.stdin.fileno() or None
155 class SigException(Exception):
156 def __init__(self, signum):
158 Exception.__init__(self, 'signal %d received' % signum)
159 def handler(signum, frame):
160 raise SigException(signum)
162 signal.signal(signal.SIGTERM, handler)
163 signal.signal(signal.SIGINT, handler)
169 c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
170 if not n and not outf and not errf:
171 # shortcut when no bup-newliner stuff is needed
174 p = subprocess.Popen(c, stdout=outf, stderr=errf,
175 preexec_fn=force_tty)
177 # if we get a signal while waiting, we have to keep waiting, just
178 # in case our child doesn't die.
182 except SigException, e:
183 log('\nbup: %s\n' % e)
184 os.kill(p.pid, e.signum)
187 log('%s: %s\n' % (subcmd[0], e))
190 if p and p.poll() == None:
191 os.kill(p.pid, signal.SIGTERM)