]> arthur.barton.de Git - bup.git/blob - lib/cmd/ftp-cmd.py
732082abbbbd1a49e870d10ffc8b7b1257223d14
[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
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(args, onabort=OptionError)
43     except OptionError as e:
44         log('error: %s' % e)
45         return
46     return ls.within_repo(repo, opt, out)
47
48
49 def write_to_file(inf, outf):
50     for blob in chunkyreader(inf):
51         outf.write(blob)
52
53
54 def inputiter():
55     if os.isatty(stdin.fileno()):
56         while 1:
57             try:
58                 yield _helpers.readline(b'bup> ')
59             except EOFError:
60                 print()  # Clear the line for the terminal's next prompt
61                 break
62     else:
63         for line in stdin:
64             yield line
65
66
67 def _completer_get_subs(repo, line):
68     (qtype, lastword) = shquote.unfinished_word(line)
69     dir, name = os.path.split(lastword)
70     dir_path = vfs.resolve(repo, dir or b'/')
71     _, dir_item = dir_path[-1]
72     if not dir_item:
73         subs = tuple()
74     else:
75         subs = tuple(dir_path + (entry,)
76                      for entry in vfs.contents(repo, dir_item)
77                      if (entry[0] != b'.' and entry[0].startswith(name)))
78     return qtype, lastword, subs
79
80
81 _attempt_start = None
82 _attempt_end = None
83 def attempt_completion(text, start, end):
84     global _attempt_start, _attempt_end
85     _attempt_start = start
86     _attempt_end = end
87     return None
88
89 _last_line = None
90 _last_res = None
91 def enter_completion(text, iteration):
92     global repo
93     global _attempt_end
94     global _last_line
95     global _last_res
96     try:
97         line = _helpers.get_line_buffer()[:_attempt_end]
98         if _last_line != line:
99             _last_res = _completer_get_subs(repo, line)
100             _last_line = line
101         qtype, lastword, subs = _last_res
102         if iteration < len(subs):
103             path = subs[iteration]
104             leaf_name, leaf_item = path[-1]
105             res = vfs.try_resolve(repo, leaf_name, parent=path[:-1])
106             leaf_name, leaf_item = res[-1]
107             fullname = os.path.join(*(name for name, item in res))
108             if stat.S_ISDIR(vfs.item_mode(leaf_item)):
109                 ret = shquote.what_to_add(qtype, lastword, fullname + b'/',
110                                           terminate=False)
111             else:
112                 ret = shquote.what_to_add(qtype, lastword, fullname,
113                                           terminate=True) + b' '
114             return text + ret
115     except Exception as e:
116         log('\n')
117         try:
118             import traceback
119             traceback.print_tb(sys.exc_traceback)
120         except Exception as e2:
121             log('Error printing traceback: %s\n' % e2)
122         log('\nError in completion: %s\n' % e)
123
124
125 optspec = """
126 bup ftp [commands...]
127 """
128 o = options.Options(optspec)
129 opt, flags, extra = o.parse(compat.argv[1:])
130
131 git.check_repo_or_die()
132
133 sys.stdout.flush()
134 out = byte_stream(sys.stdout)
135 stdin = byte_stream(sys.stdin)
136 repo = LocalRepo()
137 pwd = vfs.resolve(repo, b'/')
138 rv = 0
139
140
141
142 if extra:
143     lines = (argv_bytes(arg) for arg in extra)
144 else:
145     if hasattr(_helpers, 'readline'):
146         _helpers.set_completer_word_break_characters(b' \t\n\r/')
147         _helpers.set_attempted_completion_function(attempt_completion)
148         _helpers.set_completion_entry_function(enter_completion)
149         if sys.platform.startswith('darwin'):
150             # MacOS uses a slightly incompatible clone of libreadline
151             _helpers.parse_and_bind(b'bind ^I rl_complete')
152         _helpers.parse_and_bind(b'tab: complete')
153     lines = inputiter()
154
155 for line in lines:
156     if not line.strip():
157         continue
158     words = [word for (wordstart,word) in shquote.quotesplit(line)]
159     cmd = words[0].lower()
160     #log('execute: %r %r\n' % (cmd, parm))
161     try:
162         if cmd == b'ls':
163             # FIXME: respect pwd (perhaps via ls accepting resolve path/parent)
164             do_ls(repo, words[1:], out)
165             out.flush()
166         elif cmd == b'cd':
167             np = pwd
168             for parm in words[1:]:
169                 res = vfs.resolve(repo, parm, parent=np)
170                 _, leaf_item = res[-1]
171                 if not leaf_item:
172                     raise Exception('%s does not exist'
173                                     % path_msg(b'/'.join(name for name, item
174                                                          in res)))
175                 if not stat.S_ISDIR(vfs.item_mode(leaf_item)):
176                     raise Exception('%s is not a directory' % path_msg(parm))
177                 np = res
178             pwd = np
179         elif cmd == b'pwd':
180             if len(pwd) == 1:
181                 out.write(b'/')
182             out.write(b'/'.join(name for name, item in pwd) + b'\n')
183             out.flush()
184         elif cmd == b'cat':
185             for parm in words[1:]:
186                 res = vfs.resolve(repo, parm, parent=pwd)
187                 _, leaf_item = res[-1]
188                 if not leaf_item:
189                     raise Exception('%s does not exist' %
190                                     path_msg(b'/'.join(name for name, item
191                                                        in res)))
192                 with vfs.fopen(repo, leaf_item) as srcfile:
193                     write_to_file(srcfile, out)
194             out.flush()
195         elif cmd == b'get':
196             if len(words) not in [2,3]:
197                 rv = 1
198                 raise Exception('Usage: get <filename> [localname]')
199             rname = words[1]
200             (dir,base) = os.path.split(rname)
201             lname = len(words) > 2 and words[2] or base
202             res = vfs.resolve(repo, rname, parent=pwd)
203             _, leaf_item = res[-1]
204             if not leaf_item:
205                 raise Exception('%s does not exist' %
206                                 path_msg(b'/'.join(name for name, item in res)))
207             with vfs.fopen(repo, leaf_item) as srcfile:
208                 with open(lname, 'wb') as destfile:
209                     log('Saving %s\n' % path_msg(lname))
210                     write_to_file(srcfile, destfile)
211         elif cmd == b'mget':
212             for parm in words[1:]:
213                 dir, base = os.path.split(parm)
214
215                 res = vfs.resolve(repo, dir, parent=pwd)
216                 _, dir_item = res[-1]
217                 if not dir_item:
218                     raise Exception('%s does not exist' % path_msg(dir))
219                 for name, item in vfs.contents(repo, dir_item):
220                     if name == b'.':
221                         continue
222                     if fnmatch.fnmatch(name, base):
223                         if stat.S_ISLNK(vfs.item_mode(item)):
224                             deref = vfs.resolve(repo, name, parent=res)
225                             deref_name, deref_item = deref[-1]
226                             if not deref_item:
227                                 raise Exception('%s does not exist' %
228                                                 path_msg('/'.join(name for name, item
229                                                                   in deref)))
230                             item = deref_item
231                         with vfs.fopen(repo, item) as srcfile:
232                             with open(name, 'wb') as destfile:
233                                 log('Saving %s\n' % path_msg(name))
234                                 write_to_file(srcfile, destfile)
235         elif cmd == b'help' or cmd == b'?':
236             out.write(b'Commands: ls cd pwd cat get mget help quit\n')
237             out.flush()
238         elif cmd in (b'quit', b'exit', b'bye'):
239             break
240         else:
241             rv = 1
242             raise Exception('no such command %r' % cmd)
243     except Exception as e:
244         rv = 1
245         log('error: %s\n' % e)
246         raise
247
248 sys.exit(rv)