2 # For now, this completely relies on the assumption that the current
3 # encoding (LC_CTYPE, etc.) is ASCII compatible, and that it returns
4 # the exact same bytes from a decode/encode round-trip (or the reverse
7 from __future__ import absolute_import, print_function
8 import os, fnmatch, stat, sys
10 from bup import _helpers, options, git, shquote, ls, vfs
11 from bup.compat import argv_bytes
12 from bup.helpers import chunkyreader, log
13 from bup.io import byte_stream, path_msg
14 from bup.repo import LocalRepo
19 class OptionError(Exception):
23 def do_ls(repo, pwd, args, out):
24 pwd_str = b'/'.join(name for name, item in pwd) or b'/'
26 opt = ls.opts_from_cmdline(args, onabort=OptionError, pwd=pwd_str)
27 except OptionError as e:
30 return ls.within_repo(repo, opt, out, pwd_str)
33 def write_to_file(inf, outf):
34 for blob in chunkyreader(inf):
38 def _completer_get_subs(repo, line):
39 (qtype, lastword) = shquote.unfinished_word(line)
40 dir, name = os.path.split(lastword)
41 dir_path = vfs.resolve(repo, dir or b'/')
42 _, dir_item = dir_path[-1]
46 subs = tuple(dir_path + (entry,)
47 for entry in vfs.contents(repo, dir_item)
48 if (entry[0] != b'.' and entry[0].startswith(name)))
49 return qtype, lastword, subs
54 def attempt_completion(text, start, end):
55 global _attempt_start, _attempt_end
56 _attempt_start = start
62 def enter_completion(text, iteration):
68 line = _helpers.get_line_buffer()[:_attempt_end]
69 if _last_line != line:
70 _last_res = _completer_get_subs(repo, line)
72 qtype, lastword, subs = _last_res
73 if iteration < len(subs):
74 path = subs[iteration]
75 leaf_name, leaf_item = path[-1]
76 res = vfs.try_resolve(repo, leaf_name, parent=path[:-1])
77 leaf_name, leaf_item = res[-1]
78 fullname = os.path.join(*(name for name, item in res))
79 if stat.S_ISDIR(vfs.item_mode(leaf_item)):
80 ret = shquote.what_to_add(qtype, lastword, fullname + b'/',
83 ret = shquote.what_to_add(qtype, lastword, fullname,
84 terminate=True) + b' '
86 except Exception as e:
90 traceback.print_tb(sys.exc_traceback)
91 except Exception as e2:
92 log('Error printing traceback: %s\n' % e2)
93 log('\nError in completion: %s\n' % e)
101 o = options.Options(optspec)
102 opt, flags, extra = o.parse_bytes(argv[1:])
104 git.check_repo_or_die()
109 out = byte_stream(sys.stdout)
110 stdin = byte_stream(sys.stdin)
112 pwd = vfs.resolve(repo, b'/')
116 if os.isatty(f.fileno()):
118 prompt = b'bup %s> ' % (b'/'.join(name for name, item in pwd) or b'/', )
119 if hasattr(_helpers, 'readline'):
121 yield _helpers.readline(prompt)
123 print() # Clear the line for the terminal's next prompt
128 read_line = f.readline()
139 lines = (argv_bytes(arg) for arg in extra)
141 if hasattr(_helpers, 'readline'):
142 _helpers.set_completer_word_break_characters(b' \t\n\r/')
143 _helpers.set_attempted_completion_function(attempt_completion)
144 _helpers.set_completion_entry_function(enter_completion)
145 if sys.platform.startswith('darwin'):
146 # MacOS uses a slightly incompatible clone of libreadline
147 _helpers.parse_and_bind(b'bind ^I rl_complete')
148 _helpers.parse_and_bind(b'tab: complete')
149 lines = inputiter(stdin)
154 words = [word for (wordstart,word) in shquote.quotesplit(line)]
155 cmd = words[0].lower()
156 #log('execute: %r %r\n' % (cmd, parm))
159 do_ls(repo, pwd, words[1:], out)
163 for parm in words[1:]:
164 res = vfs.resolve(repo, parm, parent=np)
165 _, leaf_item = res[-1]
167 raise Exception('%s does not exist'
168 % path_msg(b'/'.join(name for name, item
170 if not stat.S_ISDIR(vfs.item_mode(leaf_item)):
171 raise Exception('%s is not a directory' % path_msg(parm))
177 out.write(b'/'.join(name for name, item in pwd) + b'\n')
180 for parm in words[1:]:
181 res = vfs.resolve(repo, parm, parent=pwd)
182 _, leaf_item = res[-1]
184 raise Exception('%s does not exist' %
185 path_msg(b'/'.join(name for name, item
187 with vfs.fopen(repo, leaf_item) as srcfile:
188 write_to_file(srcfile, out)
191 if len(words) not in [2,3]:
193 raise Exception('Usage: get <filename> [localname]')
195 (dir,base) = os.path.split(rname)
196 lname = len(words) > 2 and words[2] or base
197 res = vfs.resolve(repo, rname, parent=pwd)
198 _, leaf_item = res[-1]
200 raise Exception('%s does not exist' %
201 path_msg(b'/'.join(name for name, item in res)))
202 with vfs.fopen(repo, leaf_item) as srcfile:
203 with open(lname, 'wb') as destfile:
204 log('Saving %s\n' % path_msg(lname))
205 write_to_file(srcfile, destfile)
207 for parm in words[1:]:
208 dir, base = os.path.split(parm)
210 res = vfs.resolve(repo, dir, parent=pwd)
211 _, dir_item = res[-1]
213 raise Exception('%s does not exist' % path_msg(dir))
214 for name, item in vfs.contents(repo, dir_item):
217 if fnmatch.fnmatch(name, base):
218 if stat.S_ISLNK(vfs.item_mode(item)):
219 deref = vfs.resolve(repo, name, parent=res)
220 deref_name, deref_item = deref[-1]
222 raise Exception('%s does not exist' %
223 path_msg('/'.join(name for name, item
226 with vfs.fopen(repo, item) as srcfile:
227 with open(name, 'wb') as destfile:
228 log('Saving %s\n' % path_msg(name))
229 write_to_file(srcfile, destfile)
230 elif cmd == b'help' or cmd == b'?':
231 out.write(b'Commands: ls cd pwd cat get mget help quit\n')
233 elif cmd in (b'quit', b'exit', b'bye'):
237 raise Exception('no such command %r' % cmd)
238 except Exception as e:
240 log('error: %s\n' % e)