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