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