]> arthur.barton.de Git - bup.git/blob - lib/cmd/ftp-cmd.py
ftp: fix ls arguments for python3
[bup.git] / lib / cmd / ftp-cmd.py
1 #!/bin/sh
2 """": # -*-python-*-
3 # https://sourceware.org/bugzilla/show_bug.cgi?id=26034
4 export "BUP_ARGV_0"="$0"
5 arg_i=1
6 for arg in "$@"; do
7     export "BUP_ARGV_${arg_i}"="$arg"
8     shift
9     arg_i=$((arg_i + 1))
10 done
11 # Here to end of preamble replaced during install
12 bup_python="$(dirname "$0")/../../config/bin/python" || exit $?
13 exec "$bup_python" "$0"
14 """
15 # end of bup preamble
16
17 # For now, this completely relies on the assumption that the current
18 # encoding (LC_CTYPE, etc.) is ASCII compatible, and that it returns
19 # the exact same bytes from a decode/encode round-trip (or the reverse
20 # (e.g. ISO-8859-1).
21
22 from __future__ import absolute_import, print_function
23 import os, fnmatch, stat, sys
24
25 sys.path[:0] = [os.path.dirname(os.path.realpath(__file__)) + '/..']
26
27 from bup import _helpers, compat, options, git, shquote, ls, vfs
28 from bup.compat import argv_bytes, fsdecode
29 from bup.helpers import chunkyreader, handle_ctrl_c, log
30 from bup.io import byte_stream, path_msg
31 from bup.repo import LocalRepo
32
33 handle_ctrl_c()
34
35
36 class OptionError(Exception):
37     pass
38
39
40 def do_ls(repo, args, out):
41     try:
42         opt = ls.opts_from_cmdline([fsdecode(arg) for arg in args],
43                                    onabort=OptionError)
44     except OptionError as e:
45         log('error: %s' % e)
46         return
47     return ls.within_repo(repo, opt, out)
48
49
50 def write_to_file(inf, outf):
51     for blob in chunkyreader(inf):
52         outf.write(blob)
53
54
55 def inputiter():
56     if os.isatty(stdin.fileno()):
57         while 1:
58             try:
59                 yield _helpers.readline(b'bup> ')
60             except EOFError:
61                 print()  # Clear the line for the terminal's next prompt
62                 break
63     else:
64         for line in stdin:
65             yield line
66
67
68 def _completer_get_subs(repo, line):
69     (qtype, lastword) = shquote.unfinished_word(line)
70     dir, name = os.path.split(lastword)
71     dir_path = vfs.resolve(repo, dir or b'/')
72     _, dir_item = dir_path[-1]
73     if not dir_item:
74         subs = tuple()
75     else:
76         subs = tuple(dir_path + (entry,)
77                      for entry in vfs.contents(repo, dir_item)
78                      if (entry[0] != b'.' and entry[0].startswith(name)))
79     return qtype, lastword, subs
80
81
82 _attempt_start = None
83 _attempt_end = None
84 def attempt_completion(text, start, end):
85     global _attempt_start, _attempt_end
86     _attempt_start = start
87     _attempt_end = end
88     return None
89
90 _last_line = None
91 _last_res = None
92 def enter_completion(text, iteration):
93     global repo
94     global _attempt_end
95     global _last_line
96     global _last_res
97     try:
98         line = _helpers.get_line_buffer()[:_attempt_end]
99         if _last_line != line:
100             _last_res = _completer_get_subs(repo, line)
101             _last_line = line
102         qtype, lastword, subs = _last_res
103         if iteration < len(subs):
104             path = subs[iteration]
105             leaf_name, leaf_item = path[-1]
106             res = vfs.try_resolve(repo, leaf_name, parent=path[:-1])
107             leaf_name, leaf_item = res[-1]
108             fullname = os.path.join(*(name for name, item in res))
109             if stat.S_ISDIR(vfs.item_mode(leaf_item)):
110                 ret = shquote.what_to_add(qtype, lastword, fullname + b'/',
111                                           terminate=False)
112             else:
113                 ret = shquote.what_to_add(qtype, lastword, fullname,
114                                           terminate=True) + b' '
115             return text + ret
116     except Exception as e:
117         log('\n')
118         try:
119             import traceback
120             traceback.print_tb(sys.exc_traceback)
121         except Exception as e2:
122             log('Error printing traceback: %s\n' % e2)
123         log('\nError in completion: %s\n' % e)
124
125
126 optspec = """
127 bup ftp [commands...]
128 """
129 o = options.Options(optspec)
130 opt, flags, extra = o.parse(compat.argv[1:])
131
132 git.check_repo_or_die()
133
134 sys.stdout.flush()
135 out = byte_stream(sys.stdout)
136 stdin = byte_stream(sys.stdin)
137 repo = LocalRepo()
138 pwd = vfs.resolve(repo, b'/')
139 rv = 0
140
141
142
143 if extra:
144     lines = (argv_bytes(arg) for arg in extra)
145 else:
146     if hasattr(_helpers, 'readline'):
147         _helpers.set_completer_word_break_characters(b' \t\n\r/')
148         _helpers.set_attempted_completion_function(attempt_completion)
149         _helpers.set_completion_entry_function(enter_completion)
150         if sys.platform.startswith('darwin'):
151             # MacOS uses a slightly incompatible clone of libreadline
152             _helpers.parse_and_bind(b'bind ^I rl_complete')
153         _helpers.parse_and_bind(b'tab: complete')
154     lines = inputiter()
155
156 for line in lines:
157     if not line.strip():
158         continue
159     words = [word for (wordstart,word) in shquote.quotesplit(line)]
160     cmd = words[0].lower()
161     #log('execute: %r %r\n' % (cmd, parm))
162     try:
163         if cmd == b'ls':
164             # FIXME: respect pwd (perhaps via ls accepting resolve path/parent)
165             do_ls(repo, words[1:], out)
166             out.flush()
167         elif cmd == b'cd':
168             np = pwd
169             for parm in words[1:]:
170                 res = vfs.resolve(repo, parm, parent=np)
171                 _, leaf_item = res[-1]
172                 if not leaf_item:
173                     raise Exception('%s does not exist'
174                                     % path_msg(b'/'.join(name for name, item
175                                                          in res)))
176                 if not stat.S_ISDIR(vfs.item_mode(leaf_item)):
177                     raise Exception('%s is not a directory' % path_msg(parm))
178                 np = res
179             pwd = np
180         elif cmd == b'pwd':
181             if len(pwd) == 1:
182                 out.write(b'/')
183             out.write(b'/'.join(name for name, item in pwd) + b'\n')
184             out.flush()
185         elif cmd == b'cat':
186             for parm in words[1:]:
187                 res = vfs.resolve(repo, parm, parent=pwd)
188                 _, leaf_item = res[-1]
189                 if not leaf_item:
190                     raise Exception('%s does not exist' %
191                                     path_msg(b'/'.join(name for name, item
192                                                        in res)))
193                 with vfs.fopen(repo, leaf_item) as srcfile:
194                     write_to_file(srcfile, out)
195             out.flush()
196         elif cmd == b'get':
197             if len(words) not in [2,3]:
198                 rv = 1
199                 raise Exception('Usage: get <filename> [localname]')
200             rname = words[1]
201             (dir,base) = os.path.split(rname)
202             lname = len(words) > 2 and words[2] or base
203             res = vfs.resolve(repo, rname, parent=pwd)
204             _, leaf_item = res[-1]
205             if not leaf_item:
206                 raise Exception('%s does not exist' %
207                                 path_msg(b'/'.join(name for name, item in res)))
208             with vfs.fopen(repo, leaf_item) as srcfile:
209                 with open(lname, 'wb') as destfile:
210                     log('Saving %s\n' % path_msg(lname))
211                     write_to_file(srcfile, destfile)
212         elif cmd == b'mget':
213             for parm in words[1:]:
214                 dir, base = os.path.split(parm)
215
216                 res = vfs.resolve(repo, dir, parent=pwd)
217                 _, dir_item = res[-1]
218                 if not dir_item:
219                     raise Exception('%s does not exist' % path_msg(dir))
220                 for name, item in vfs.contents(repo, dir_item):
221                     if name == b'.':
222                         continue
223                     if fnmatch.fnmatch(name, base):
224                         if stat.S_ISLNK(vfs.item_mode(item)):
225                             deref = vfs.resolve(repo, name, parent=res)
226                             deref_name, deref_item = deref[-1]
227                             if not deref_item:
228                                 raise Exception('%s does not exist' %
229                                                 path_msg('/'.join(name for name, item
230                                                                   in deref)))
231                             item = deref_item
232                         with vfs.fopen(repo, item) as srcfile:
233                             with open(name, 'wb') as destfile:
234                                 log('Saving %s\n' % path_msg(name))
235                                 write_to_file(srcfile, destfile)
236         elif cmd == b'help' or cmd == b'?':
237             out.write(b'Commands: ls cd pwd cat get mget help quit\n')
238             out.flush()
239         elif cmd in (b'quit', b'exit', b'bye'):
240             break
241         else:
242             rv = 1
243             raise Exception('no such command %r' % cmd)
244     except Exception as e:
245         rv = 1
246         log('error: %s\n' % e)
247         raise
248
249 sys.exit(rv)