]> arthur.barton.de Git - bup.git/blob - cmd/ftp-cmd.py
ftp: output a newline on EOF when on a tty
[bup.git] / cmd / ftp-cmd.py
1 #!/usr/bin/env python
2 import sys, os, stat, fnmatch
3 from bup import options, git, shquote, vfs
4 from bup.helpers import *
5
6 handle_ctrl_c()
7
8
9 def node_name(text, n):
10     if stat.S_ISDIR(n.mode):
11         return '%s/' % text
12     elif stat.S_ISLNK(n.mode):
13         return '%s@' % text
14     else:
15         return '%s' % text
16
17
18 class OptionError(Exception):
19     pass
20
21
22 ls_optspec = """
23 ls [-a] [path...]
24 --
25 a,all   include hidden files in the listing
26 """
27 ls_opt = options.Options(ls_optspec, onabort=OptionError)
28
29 def do_ls(cmd_args):
30     try:
31         (opt, flags, extra) = ls_opt.parse(cmd_args)
32     except OptionError, e:
33         return
34
35     L = []
36
37     for path in (extra or ['.']):
38         n = pwd.try_resolve(path)
39
40         if stat.S_ISDIR(n.mode):
41             for sub in n:
42                 name = sub.name
43                 if opt.all or not len(name)>1 or not name.startswith('.'):
44                     L.append(node_name(name, sub))
45         else:
46             L.append(node_name(path, n))
47         print columnate(L, '')
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(sys.stdin.fileno()):
57         while 1:
58             try:
59                 yield raw_input('bup> ')
60             except EOFError:
61                 print ''  # Clear the line for the terminal's next prompt
62                 break
63     else:
64         for line in sys.stdin:
65             yield line
66
67
68 def _completer_get_subs(line):
69     (qtype, lastword) = shquote.unfinished_word(line)
70     (dir,name) = os.path.split(lastword)
71     #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
72     try:
73         n = pwd.resolve(dir)
74         subs = list(filter(lambda x: x.name.startswith(name),
75                            n.subs()))
76     except vfs.NoSuchFile, e:
77         subs = []
78     return (dir, name, qtype, lastword, subs)
79
80
81 def find_readline_lib():
82     """Return the name (and possibly the full path) of the readline library
83     linked to the given readline module.
84     """
85     import readline
86     f = open(readline.__file__, "rb")
87     try:
88         data = f.read()
89     finally:
90         f.close()
91     import re
92     m = re.search('\0([^\0]*libreadline[^\0]*)\0', data)
93     if m:
94         return m.group(1)
95     return None
96
97
98 def init_readline_vars():
99     """Work around trailing space automatically inserted by readline.
100     See http://bugs.python.org/issue5833"""
101     try:
102         import ctypes
103     except ImportError:
104         # python before 2.5 didn't have the ctypes module; but those
105         # old systems probably also didn't have this readline bug, so
106         # just ignore it.
107         return
108     lib_name = find_readline_lib()
109     if lib_name is not None:
110         lib = ctypes.cdll.LoadLibrary(lib_name)
111         global rl_completion_suppress_append
112         rl_completion_suppress_append = ctypes.c_int.in_dll(lib,
113                                     "rl_completion_suppress_append")
114
115
116 rl_completion_suppress_append = None
117 _last_line = None
118 _last_res = None
119 def completer(text, state):
120     global _last_line
121     global _last_res
122     global rl_completion_suppress_append
123     if rl_completion_suppress_append is not None:
124         rl_completion_suppress_append.value = 1
125     try:
126         line = readline.get_line_buffer()[:readline.get_endidx()]
127         if _last_line != line:
128             _last_res = _completer_get_subs(line)
129             _last_line = line
130         (dir, name, qtype, lastword, subs) = _last_res
131         if state < len(subs):
132             sn = subs[state]
133             sn1 = sn.try_resolve()  # find the type of any symlink target
134             fullname = os.path.join(dir, sn.name)
135             if stat.S_ISDIR(sn1.mode):
136                 ret = shquote.what_to_add(qtype, lastword, fullname+'/',
137                                           terminate=False)
138             else:
139                 ret = shquote.what_to_add(qtype, lastword, fullname,
140                                           terminate=True) + ' '
141             return text + ret
142     except Exception, e:
143         log('\n')
144         try:
145             import traceback
146             traceback.print_tb(sys.exc_traceback)
147         except Exception, e2:
148             log('Error printing traceback: %s\n' % e2)
149         log('\nError in completion: %s\n' % e)
150
151
152 optspec = """
153 bup ftp [commands...]
154 """
155 o = options.Options(optspec)
156 (opt, flags, extra) = o.parse(sys.argv[1:])
157
158 git.check_repo_or_die()
159
160 top = vfs.RefList(None)
161 pwd = top
162 rv = 0
163
164 if extra:
165     lines = extra
166 else:
167     try:
168         import readline
169     except ImportError:
170         log('* readline module not available: line editing disabled.\n')
171         readline = None
172
173     if readline:
174         readline.set_completer_delims(' \t\n\r/')
175         readline.set_completer(completer)
176         readline.parse_and_bind("tab: complete")
177         init_readline_vars()
178     lines = inputiter()
179
180 for line in lines:
181     if not line.strip():
182         continue
183     words = [word for (wordstart,word) in shquote.quotesplit(line)]
184     cmd = words[0].lower()
185     #log('execute: %r %r\n' % (cmd, parm))
186     try:
187         if cmd == 'ls':
188             do_ls(words[1:])
189         elif cmd == 'cd':
190             np = pwd
191             for parm in words[1:]:
192                 np = np.resolve(parm)
193                 if not stat.S_ISDIR(np.mode):
194                     raise vfs.NotDir('%s is not a directory' % parm)
195             pwd = np
196         elif cmd == 'pwd':
197             print pwd.fullname()
198         elif cmd == 'cat':
199             for parm in words[1:]:
200                 write_to_file(pwd.resolve(parm).open(), sys.stdout)
201         elif cmd == 'get':
202             if len(words) not in [2,3]:
203                 rv = 1
204                 raise Exception('Usage: get <filename> [localname]')
205             rname = words[1]
206             (dir,base) = os.path.split(rname)
207             lname = len(words)>2 and words[2] or base
208             inf = pwd.resolve(rname).open()
209             log('Saving %r\n' % lname)
210             write_to_file(inf, open(lname, 'wb'))
211         elif cmd == 'mget':
212             for parm in words[1:]:
213                 (dir,base) = os.path.split(parm)
214                 for n in pwd.resolve(dir).subs():
215                     if fnmatch.fnmatch(n.name, base):
216                         try:
217                             log('Saving %r\n' % n.name)
218                             inf = n.open()
219                             outf = open(n.name, 'wb')
220                             write_to_file(inf, outf)
221                             outf.close()
222                         except Exception, e:
223                             rv = 1
224                             log('  error: %s\n' % e)
225         elif cmd == 'help' or cmd == '?':
226             log('Commands: ls cd pwd cat get mget help quit\n')
227         elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
228             break
229         else:
230             rv = 1
231             raise Exception('no such command %r' % cmd)
232     except Exception, e:
233         rv = 1
234         log('error: %s\n' % e)
235         #raise
236
237 sys.exit(rv)