4 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
5 export "BUP_ARGV_0"="$0"
8 export "BUP_ARGV_${arg_i}"="$arg"
12 # Here to end of preamble replaced during install
16 # loop because macos doesn't have recursive readlink/realpath utils
17 while test -L "$cmdpath"; do
18 link="$(readlink "$cmdpath")"
19 cd "$(dirname "$cmdpath")"
22 script_home="$(cd "$(dirname "$cmdpath")" && pwd -P)"
24 exec "$script_home/bup-python" "$0"
28 from __future__ import absolute_import, print_function
29 import errno, getopt, os, re, select, signal, subprocess, sys
30 from subprocess import PIPE
32 from bup.compat import environ, restore_lc_env
33 from bup.io import path_msg
35 if sys.version_info[0] != 2 \
36 and not environ.get(b'BUP_ALLOW_UNEXPECTED_PYTHON_VERSION') == b'true':
37 print('error: bup may crash with python versions other than 2, or eat your data',
43 from bup import compat, path, helpers
44 from bup.compat import add_ex_tb, add_ex_ctx, argv_bytes, wrap_main
45 from bup.helpers import atoi, columnate, debug1, log, merge_dict, tty_width
46 from bup.io import byte_stream, path_msg
48 cmdpath = path.cmddir()
50 # We manipulate the subcmds here as strings, but they must be ASCII
51 # compatible, since we're going to be looking for exactly
52 # b'bup-SUBCMD' to exec.
55 log('Usage: bup [-?|--help] [-d BUP_DIR] [--debug] [--profile] '
56 '<command> [options...]\n\n')
58 ftp = 'Browse backup sets using an ftp-like client',
59 fsck = 'Check backup sets for damage and add redundancy information',
60 fuse = 'Mount your backup sets as a filesystem',
61 help = 'Print detailed help for the given command',
62 index = 'Create or display the index of files to back up',
63 on = 'Backup a remote machine to the local one',
64 restore = 'Extract files from a backup set',
65 save = 'Save files into a backup set (note: run "bup index" first)',
66 tag = 'Tag commits for easier access',
67 web = 'Launch a web server to examine backup sets',
70 log('Common commands:\n')
71 for cmd,synopsis in sorted(common.items()):
72 log(' %-10s %s\n' % (cmd, synopsis))
75 log('Other available commands:\n')
77 for c in sorted(os.listdir(cmdpath)):
78 if c.startswith(b'bup-') and c.find(b'.') < 0:
79 cname = c[4:].decode('iso-8859-1')
80 if cname not in common:
81 cmds.append(c[4:].decode(errors='backslashreplace'))
82 log(columnate(cmds, ' '))
85 log("See 'bup help COMMAND' for more information on " +
86 "a specific command.\n")
95 # Handle global options.
97 optspec = ['help', 'version', 'debug', 'profile', 'bup-dir=']
98 global_args, subcmd = getopt.getopt(argv[1:], '?VDd:', optspec)
99 except getopt.GetoptError as ex:
100 usage('error: %s' % ex.msg)
102 subcmd = [argv_bytes(x) for x in subcmd]
103 help_requested = None
107 for opt in global_args:
108 if opt[0] in ['-?', '--help']:
109 help_requested = True
110 elif opt[0] in ['-V', '--version']:
111 subcmd = [b'version']
112 elif opt[0] in ['-D', '--debug']:
114 environ[b'BUP_DEBUG'] = b'%d' % helpers.buglvl
115 elif opt[0] in ['--profile']:
117 elif opt[0] in ['-d', '--bup-dir']:
118 bup_dir = argv_bytes(opt[1])
120 usage('error: unexpected option "%s"' % opt[0])
123 bup_dir = argv_bytes(bup_dir)
125 # Make BUP_DIR absolute, so we aren't affected by chdir (i.e. save -C, etc.).
127 environ[b'BUP_DIR'] = os.path.abspath(bup_dir)
135 if help_requested and subcmd[0] != b'help':
136 subcmd = [b'help'] + subcmd
138 if len(subcmd) > 1 and subcmd[1] == b'--help' and subcmd[0] != b'help':
139 subcmd = [b'help', subcmd[0]] + subcmd[2:]
141 subcmd_name = subcmd[0]
146 return os.path.join(cmdpath, b'bup-' + subcmd)
148 subcmd[0] = subpath(subcmd_name)
149 if not os.path.exists(subcmd[0]):
150 usage('error: unknown command "%s"' % path_msg(subcmd_name))
152 already_fixed = atoi(environ.get(b'BUP_FORCE_TTY'))
153 if subcmd_name in [b'mux', b'ftp', b'help']:
155 fix_stdout = not already_fixed and os.isatty(1)
156 fix_stderr = not already_fixed and os.isatty(2)
158 if fix_stdout or fix_stderr:
159 tty_env = merge_dict(environ,
160 {b'BUP_FORCE_TTY': (b'%d'
161 % ((fix_stdout and 1 or 0)
162 + (fix_stderr and 2 or 0)))})
167 sep_rx = re.compile(br'([\r\n])')
169 def print_clean_line(dest, content, width, sep=None):
170 """Write some or all of content, followed by sep, to the dest fd after
171 padding the content with enough spaces to fill the current
172 terminal width or truncating it to the terminal width if sep is a
175 assert sep in (b'\r', b'\n', None)
181 assert not sep_rx.match(x)
182 content = b''.join(content)
183 if sep == b'\r' and len(content) > width:
184 content = content[width:]
185 os.write(dest, content)
186 if len(content) < width:
187 os.write(dest, b' ' * (width - len(content)))
191 def filter_output(src_out, src_err, dest_out, dest_err):
192 """Transfer data from src_out to dest_out and src_err to dest_err via
193 print_clean_line until src_out and src_err close."""
195 assert not isinstance(src_out, bool)
196 assert not isinstance(src_err, bool)
197 assert not isinstance(dest_out, bool)
198 assert not isinstance(dest_err, bool)
199 assert src_out is not None or src_err is not None
200 assert (src_out is None) == (dest_out is None)
201 assert (src_err is None) == (dest_err is None)
205 fds = tuple([x for x in (src_out, src_err) if x is not None])
207 ready_fds, _, _ = select.select(fds, [], [])
210 buf = os.read(fd, 4096)
211 dest = dest_out if fd == src_out else dest_err
213 fds = tuple([x for x in fds if x is not fd])
214 print_clean_line(dest, pending.pop(fd, []), width)
216 split = sep_rx.split(buf)
217 while len(split) > 1:
218 content, sep = split[:2]
220 print_clean_line(dest,
221 pending.pop(fd, []) + [content],
224 assert(len(split) == 1)
226 pending.setdefault(fd, []).extend(split)
227 except BaseException as ex:
228 pending_ex = add_ex_ctx(add_ex_tb(ex), pending_ex)
230 # Try to finish each of the streams
231 for fd, pending_items in compat.items(pending):
232 dest = dest_out if fd == src_out else dest_err
234 print_clean_line(dest, pending_items, width)
235 except (EnvironmentError, EOFError) as ex:
236 pending_ex = add_ex_ctx(add_ex_tb(ex), pending_ex)
237 except BaseException as ex:
238 pending_ex = add_ex_ctx(add_ex_tb(ex), pending_ex)
242 def run_subcmd(subcmd):
244 c = (do_profile and [sys.executable, b'-m', b'cProfile'] or []) + subcmd
245 if not (fix_stdout or fix_stderr):
250 out = byte_stream(sys.stdout)
251 err = byte_stream(sys.stderr)
254 p = subprocess.Popen(c,
255 stdout=PIPE if fix_stdout else out,
256 stderr=PIPE if fix_stderr else err,
257 env=tty_env, bufsize=4096, close_fds=True)
258 # Assume p will receive these signals and quit, which will
259 # then cause us to quit.
260 for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGQUIT):
261 signal.signal(sig, signal.SIG_IGN)
263 filter_output(fix_stdout and p.stdout.fileno() or None,
264 fix_stderr and p.stderr.fileno() or None,
265 fix_stdout and out.fileno() or None,
266 fix_stderr and err.fileno() or None)
268 except BaseException as ex:
271 if p and p.poll() == None:
272 os.kill(p.pid, signal.SIGTERM)
274 except BaseException as kill_ex:
275 raise add_ex_ctx(add_ex_tb(kill_ex), ex)
278 wrap_main(lambda : run_subcmd(subcmd))