Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 201 lines (173 sloc) 6.177 kB
144b18a @apenwarr executable files: don't assume python2.5.
authored
1 #!/usr/bin/env python
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
2 import sys, os, subprocess, signal, getopt
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
3
4 argv = sys.argv
5 exe = argv[0]
6 exepath = os.path.split(exe)[0] or '.'
6684f69 @apenwarr Add a 'make install' target.
authored
7 exeprefix = os.path.split(os.path.abspath(exepath))[0]
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
8
1b04790 @apenwarr Move python library files to lib/bup/
authored
9 # fix the PYTHONPATH to include our lib dir
6684f69 @apenwarr Add a 'make install' target.
authored
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
539ae29 @jbeda Convert 'bup web' directory listing to use tornado templates.
jbeda authored
15 resourcepath = libpath
6684f69 @apenwarr Add a 'make install' target.
authored
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')
539ae29 @jbeda Convert 'bup web' directory listing to use tornado templates.
jbeda authored
20 resourcepath = libpath
1b04790 @apenwarr Move python library files to lib/bup/
authored
21 sys.path[:0] = [libpath]
22 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
5bac5e5 @apenwarr 'make stupid' stopped working when I moved subcommands into their own…
authored
23 os.environ['BUP_MAIN_EXE'] = os.path.abspath(exe)
539ae29 @jbeda Convert 'bup web' directory listing to use tornado templates.
jbeda authored
24 os.environ['BUP_RESOURCE_PATH'] = resourcepath
1b04790 @apenwarr Move python library files to lib/bup/
authored
25
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
26 from bup import helpers
1b04790 @apenwarr Move python library files to lib/bup/
authored
27 from bup.helpers import *
28
4048d43 @apenwarr options.py: get the real tty width for word wrapping purposes.
authored
29 # after running 'bup newliner', the tty_width() ioctl won't work anymore
30 os.environ['WIDTH'] = str(tty_width())
3c06b9a @apenwarr main: list common commands before other ones.
authored
31
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
32 def usage(msg=""):
f97b71f @apenwarr main.py: fix whitespace in the usage string.
authored
33 log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
34 '<command> [options...]\n\n')
3c06b9a @apenwarr main: list common commands before other ones.
authored
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',
2bb6304 @apenwarr Add man pages for random, newliner, help, memtest, ftp.
authored
39 help = 'Print detailed help for the given command',
3c06b9a @apenwarr main: list common commands before other ones.
authored
40 index = 'Create or display the index of files to back up',
fd20863 @apenwarr Rename 'bup rbackup' to 'bup on'
authored
41 on = 'Backup a remote machine to the local one',
bab7b16 @apenwarr cmd/restore: embarrassingly slow implementation of 'bup restore'
authored
42 restore = 'Extract files from a backup set',
3c06b9a @apenwarr main: list common commands before other ones.
authored
43 save = 'Save files into a backup set (note: run "bup index" first)',
9665d20 @lelutin add a tag command
lelutin authored
44 tag = 'Tag commits for easier access',
92367a8 @jbeda Add new 'bup web' command.
jbeda authored
45 web = 'Launch a web server to examine backup sets',
3c06b9a @apenwarr main: list common commands before other ones.
authored
46 )
47
48 log('Common commands:\n')
49 for cmd,synopsis in sorted(common.items()):
2d7dc24 @apenwarr main: when printing help, don't mix stdout/stderr.
authored
50 log(' %-10s %s\n' % (cmd, synopsis))
3c06b9a @apenwarr main: list common commands before other ones.
authored
51 log('\n')
52
53 log('Other available commands:\n')
54 cmds = []
c2df125 @apenwarr Move cmd-*.py to cmd/*-cmd.py.
authored
55 for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
56 if c.startswith('bup-') and c.find('.') < 0:
3c06b9a @apenwarr main: list common commands before other ones.
authored
57 cname = c[4:]
58 if cname not in common:
59 cmds.append(c[4:])
2d7dc24 @apenwarr main: when printing help, don't mix stdout/stderr.
authored
60 log(columnate(cmds, ' '))
3c06b9a @apenwarr main: list common commands before other ones.
authored
61 log('\n')
62
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
63 log("See 'bup help COMMAND' for more information on " +
2f3f666 @apenwarr Add a 'bup help' command.
authored
64 "a specific command.\n")
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
65 if msg:
66 log("\n%s\n" % msg)
3db6eff @apenwarr toplevel exit() doesn't work in python 2.4.
authored
67 sys.exit(99)
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
68
3c06b9a @apenwarr main: list common commands before other ones.
authored
69
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
70 if len(argv) < 2:
71 usage()
72
73 # Handle global options.
74 try:
3101ae3 Give main.py the a --profile option
Brandon Low authored
75 optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
76 global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
77 except getopt.GetoptError, ex:
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
78 usage('error: %s' % ex.msg)
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
79
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
80 help_requested = None
2ba1c50 @rlbdv Add support for a global --bup-dir or -d argument.
rlbdv authored
81 dest_dir = None
3101ae3 Give main.py the a --profile option
Brandon Low authored
82 do_profile = False
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
83
84 for opt in global_args:
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
85 if opt[0] in ['-?', '--help']:
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
86 help_requested = True
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
87 elif opt[0] in ['-V', '--version']:
7949755 @apenwarr cmd/version, etc: fix version number detection stuff.
authored
88 subcmd = ['version']
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
89 elif opt[0] in ['-D', '--debug']:
90 helpers.buglvl += 1
91 os.environ['BUP_DEBUG'] = str(helpers.buglvl)
3101ae3 Give main.py the a --profile option
Brandon Low authored
92 elif opt[0] in ['--profile']:
93 do_profile = True
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
94 elif opt[0] in ['-d', '--bup-dir']:
2ba1c50 @rlbdv Add support for a global --bup-dir or -d argument.
rlbdv authored
95 dest_dir = opt[1]
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
96 else:
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
97 usage('error: unexpected option "%s"' % opt[0])
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
98
99 if len(subcmd) == 0:
100 if help_requested:
101 subcmd = ['help']
102 else:
103 usage()
104
105 if help_requested and subcmd[0] != 'help':
106 subcmd = ['help'] + subcmd
107
108 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
109 subcmd = ['help', subcmd[0]] + subcmd[2:]
110
111 subcmd_name = subcmd[0]
112 if not subcmd_name:
113 usage()
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
114
2ba1c50 @rlbdv Add support for a global --bup-dir or -d argument.
rlbdv authored
115 subcmd_env = os.environ
116 if dest_dir:
117 subcmd_env.update({"BUP_DIR" : dest_dir})
118
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
119 def subpath(s):
c2df125 @apenwarr Move cmd-*.py to cmd/*-cmd.py.
authored
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
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
124
3101ae3 Give main.py the a --profile option
Brandon Low authored
125 subcmd[0] = subpath(subcmd_name)
126 if not os.path.exists(subcmd[0]):
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
127 usage('error: unknown command "%s"' % subcmd_name)
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
128
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
129 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
fb3bd84 Add DemuxConn and `bup mux` for client-server
Brandon Low authored
130 if subcmd_name in ['mux', 'ftp', 'help']:
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
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:
ed23e55 @apenwarr bup random: fix progress output and don't print to a tty.
authored
137 amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
138 os.environ['BUP_FORCE_TTY'] = str(amt)
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
139 os.setsid() # make sure ctrl-c is sent just to us, not to child too
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
140
141 if fix_stdout or fix_stderr:
142 realf = fix_stderr and 2 or 1
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
143 drealf = os.dup(realf) # Popen goes crazy with stdout=2
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
144 n = subprocess.Popen([subpath('newliner')],
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
145 stdin=subprocess.PIPE, stdout=drealf,
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
146 close_fds=True, preexec_fn=force_tty)
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
147 os.close(drealf)
119f9dd @apenwarr main: fix problem when redirecting to newliner on MacOS X.
authored
148 outf = fix_stdout and n.stdin.fileno() or None
149 errf = fix_stderr and n.stdin.fileno() or None
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
150 else:
151 n = None
119f9dd @apenwarr main: fix problem when redirecting to newliner on MacOS X.
authored
152 outf = None
153 errf = None
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
154
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
155
156 class SigException(Exception):
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
157 def __init__(self, signum):
158 self.signum = signum
159 Exception.__init__(self, 'signal %d received' % signum)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
160 def handler(signum, frame):
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
161 raise SigException(signum)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
162
163 signal.signal(signal.SIGTERM, handler)
164 signal.signal(signal.SIGINT, handler)
165
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
166 ret = 95
22de155 @apenwarr main: initialize 'p' before the try/finally that uses it.
authored
167 p = None
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
168 try:
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
169 try:
3101ae3 Give main.py the a --profile option
Brandon Low authored
170 c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
5ef8f0d @apenwarr main.py: use execvp() instead of subprocess.Popen() when possible.
authored
171 if not n and not outf and not errf:
172 # shortcut when no bup-newliner stuff is needed
173 os.execvp(c[0], c)
174 else:
175 p = subprocess.Popen(c, stdout=outf, stderr=errf,
176 preexec_fn=force_tty)
da300a1 @apenwarr main: even more fixes for signal handling.
authored
177 while 1:
178 # if we get a signal while waiting, we have to keep waiting, just
179 # in case our child doesn't die.
180 try:
181 ret = p.wait()
182 break
183 except SigException, e:
184 log('\nbup: %s\n' % e)
185 os.kill(p.pid, e.signum)
186 ret = 94
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
187 except OSError, e:
3101ae3 Give main.py the a --profile option
Brandon Low authored
188 log('%s: %s\n' % (subcmd[0], e))
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
189 ret = 98
190 finally:
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
191 if p and p.poll() == None:
da300a1 @apenwarr main: even more fixes for signal handling.
authored
192 os.kill(p.pid, signal.SIGTERM)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
193 p.wait()
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
194 if n:
195 n.stdin.close()
196 try:
197 n.wait()
198 except:
199 pass
200 sys.exit(ret)
Something went wrong with that request. Please try again.