Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100755 200 lines (172 sloc) 6.282 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
39a1433 @blueyed Resolve bup argv[0] symlinks.
blueyed authored
5 exe = os.path.realpath(argv[0])
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
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 di...
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
3101ae3 Give main.py the a --profile option
Brandon Low authored
81 do_profile = False
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
82
83 for opt in global_args:
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
84 if opt[0] in ['-?', '--help']:
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
85 help_requested = True
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
86 elif opt[0] in ['-V', '--version']:
7949755 @apenwarr cmd/version, etc: fix version number detection stuff.
authored
87 subcmd = ['version']
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
88 elif opt[0] in ['-D', '--debug']:
89 helpers.buglvl += 1
90 os.environ['BUP_DEBUG'] = str(helpers.buglvl)
3101ae3 Give main.py the a --profile option
Brandon Low authored
91 elif opt[0] in ['--profile']:
92 do_profile = True
e3d6462 @apenwarr Introduce BUP_DEBUG, --debug, and tone down the log messages a lot.
authored
93 elif opt[0] in ['-d', '--bup-dir']:
8023ad2 @lelutin Remove useless code in main.py around the -d option
lelutin authored
94 os.environ['BUP_DIR'] = opt[1]
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
95 else:
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
96 usage('error: unexpected option "%s"' % opt[0])
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
97
847f8b5 @rlbdv Convert BUP_DIR to an absolute path so chdir() won't cause trouble.
rlbdv authored
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'])
101
7401298 @rlbdv Add support for global command-line options (before any subcmd).
rlbdv authored
102 if len(subcmd) == 0:
103 if help_requested:
104 subcmd = ['help']
105 else:
106 usage()
107
108 if help_requested and subcmd[0] != 'help':
109 subcmd = ['help'] + subcmd
110
111 if len(subcmd) > 1 and subcmd[1] == '--help' and subcmd[0] != 'help':
112 subcmd = ['help', subcmd[0]] + subcmd[2:]
113
114 subcmd_name = subcmd[0]
115 if not subcmd_name:
116 usage()
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
117
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
118 def subpath(s):
c2df125 @apenwarr Move cmd-*.py to cmd/*-cmd.py.
authored
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)
122 return sp
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
123
3101ae3 Give main.py the a --profile option
Brandon Low authored
124 subcmd[0] = subpath(subcmd_name)
125 if not os.path.exists(subcmd[0]):
5a9bc0a @apenwarr options.py: o.fatal(): print error after, not before, usage message.
authored
126 usage('error: unknown command "%s"' % subcmd_name)
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
127
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
128 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
fb3bd84 Add DemuxConn and `bup mux` for client-server
Brandon Low authored
129 if subcmd_name in ['mux', 'ftp', 'help']:
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
130 already_fixed = True
131 fix_stdout = not already_fixed and os.isatty(1)
132 fix_stderr = not already_fixed and os.isatty(2)
133
134 def force_tty():
135 if fix_stdout or fix_stderr:
ed23e55 @apenwarr bup random: fix progress output and don't print to a tty.
authored
136 amt = (fix_stdout and 1 or 0) + (fix_stderr and 2 or 0)
137 os.environ['BUP_FORCE_TTY'] = str(amt)
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
138 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
139
140 if fix_stdout or fix_stderr:
141 realf = fix_stderr and 2 or 1
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
142 drealf = os.dup(realf) # Popen goes crazy with stdout=2
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
143 n = subprocess.Popen([subpath('newliner')],
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
144 stdin=subprocess.PIPE, stdout=drealf,
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
145 close_fds=True, preexec_fn=force_tty)
1eaed38 @apenwarr main.py: don't leak a file descriptor.
authored
146 os.close(drealf)
119f9dd @apenwarr main: fix problem when redirecting to newliner on MacOS X.
authored
147 outf = fix_stdout and n.stdin.fileno() or None
148 errf = fix_stderr and n.stdin.fileno() or None
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
149 else:
150 n = None
119f9dd @apenwarr main: fix problem when redirecting to newliner on MacOS X.
authored
151 outf = None
152 errf = None
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
153
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
154
155 class SigException(Exception):
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
156 def __init__(self, signum):
157 self.signum = signum
158 Exception.__init__(self, 'signal %d received' % signum)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
159 def handler(signum, frame):
b7a524c @apenwarr Correctly pass along SIGINT to child processes.
authored
160 raise SigException(signum)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
161
162 signal.signal(signal.SIGTERM, handler)
163 signal.signal(signal.SIGINT, handler)
164
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
165 ret = 95
22de155 @apenwarr main: initialize 'p' before the try/finally that uses it.
authored
166 p = None
9e4ef17 @apenwarr Add a 'bup' wrapper program.
authored
167 try:
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
168 try:
3101ae3 Give main.py the a --profile option
Brandon Low authored
169 c = (do_profile and [sys.executable, '-m', 'cProfile'] or []) + subcmd
5ef8f0d @apenwarr main.py: use execvp() instead of subprocess.Popen() when possible.
authored
170 if not n and not outf and not errf:
171 # shortcut when no bup-newliner stuff is needed
172 os.execvp(c[0], c)
173 else:
174 p = subprocess.Popen(c, stdout=outf, stderr=errf,
175 preexec_fn=force_tty)
da300a1 @apenwarr main: even more fixes for signal handling.
authored
176 while 1:
177 # if we get a signal while waiting, we have to keep waiting, just
178 # in case our child doesn't die.
179 try:
180 ret = p.wait()
181 break
182 except SigException, e:
183 log('\nbup: %s\n' % e)
184 os.kill(p.pid, e.signum)
185 ret = 94
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
186 except OSError, e:
3101ae3 Give main.py the a --profile option
Brandon Low authored
187 log('%s: %s\n' % (subcmd[0], e))
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
188 ret = 98
189 finally:
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
190 if p and p.poll() == None:
da300a1 @apenwarr main: even more fixes for signal handling.
authored
191 os.kill(p.pid, signal.SIGTERM)
1345eb6 @apenwarr main.py: clean up subprocesses dying on signal.
authored
192 p.wait()
073b383 @apenwarr Add a new 'bup newliner' that fixes progress message whitespace.
authored
193 if n:
194 n.stdin.close()
195 try:
196 n.wait()
197 except:
198 pass
199 sys.exit(ret)
Something went wrong with that request. Please try again.