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