]> arthur.barton.de Git - bup.git/blob - cmd/ftp-cmd.py
bup ftp: work even if the 'readline' module isn't available.
[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 try:
7     import readline
8 except ImportError:
9     log('* readline module not available: line editing disabled.\n')
10     readline = None
11
12
13 def node_name(text, n):
14     if stat.S_ISDIR(n.mode):
15         return '%s/' % text
16     elif stat.S_ISLNK(n.mode):
17         return '%s@' % text
18     else:
19         return '%s' % text
20
21
22 def do_ls(path, n):
23     l = []
24     if stat.S_ISDIR(n.mode):
25         for sub in n:
26             l.append(node_name(sub.name, sub))
27     else:
28         l.append(node_name(path, n))
29     print columnate(l, '')
30     
31
32 def write_to_file(inf, outf):
33     for blob in chunkyreader(inf):
34         outf.write(blob)
35     
36
37 def inputiter():
38     if os.isatty(sys.stdin.fileno()):
39         while 1:
40             try:
41                 yield raw_input('bup> ')
42             except EOFError:
43                 break
44     else:
45         for line in sys.stdin:
46             yield line
47
48
49 def _completer_get_subs(line):
50     (qtype, lastword) = shquote.unfinished_word(line)
51     (dir,name) = os.path.split(lastword)
52     #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
53     n = pwd.resolve(dir)
54     subs = list(filter(lambda x: x.name.startswith(name),
55                        n.subs()))
56     return (dir, name, qtype, lastword, subs)
57
58
59 _last_line = None
60 _last_res = None
61 def completer(text, state):
62     global _last_line
63     global _last_res
64     try:
65         line = readline.get_line_buffer()[:readline.get_endidx()]
66         if _last_line != line:
67             _last_res = _completer_get_subs(line)
68             _last_line = line
69         (dir, name, qtype, lastword, subs) = _last_res
70         if state < len(subs):
71             sn = subs[state]
72             sn1 = sn.resolve('')  # deref symlinks
73             fullname = os.path.join(dir, sn.name)
74             if stat.S_ISDIR(sn1.mode):
75                 ret = shquote.what_to_add(qtype, lastword, fullname+'/',
76                                           terminate=False)
77             else:
78                 ret = shquote.what_to_add(qtype, lastword, fullname,
79                                           terminate=True) + ' '
80             return text + ret
81     except Exception, e:
82         log('\nerror in completion: %s\n' % e)
83
84             
85 optspec = """
86 bup ftp
87 """
88 o = options.Options('bup ftp', optspec)
89 (opt, flags, extra) = o.parse(sys.argv[1:])
90
91 git.check_repo_or_die()
92
93 top = vfs.RefList(None)
94 pwd = top
95
96 if extra:
97     lines = extra
98 else:
99     if readline:
100         readline.set_completer_delims(' \t\n\r/')
101         readline.set_completer(completer)
102         readline.parse_and_bind("tab: complete")
103     lines = inputiter()
104
105 for line in lines:
106     if not line.strip():
107         continue
108     words = [word for (wordstart,word) in shquote.quotesplit(line)]
109     cmd = words[0].lower()
110     #log('execute: %r %r\n' % (cmd, parm))
111     try:
112         if cmd == 'ls':
113             for parm in (words[1:] or ['.']):
114                 do_ls(parm, pwd.resolve(parm))
115         elif cmd == 'cd':
116             for parm in words[1:]:
117                 pwd = pwd.resolve(parm)
118         elif cmd == 'pwd':
119             print pwd.fullname()
120         elif cmd == 'cat':
121             for parm in words[1:]:
122                 write_to_file(pwd.resolve(parm).open(), sys.stdout)
123         elif cmd == 'get':
124             if len(words) not in [2,3]:
125                 raise Exception('Usage: get <filename> [localname]')
126             rname = words[1]
127             (dir,base) = os.path.split(rname)
128             lname = len(words)>2 and words[2] or base
129             inf = pwd.resolve(rname).open()
130             log('Saving %r\n' % lname)
131             write_to_file(inf, open(lname, 'wb'))
132         elif cmd == 'mget':
133             for parm in words[1:]:
134                 (dir,base) = os.path.split(parm)
135                 for n in pwd.resolve(dir).subs():
136                     if fnmatch.fnmatch(n.name, base):
137                         try:
138                             log('Saving %r\n' % n.name)
139                             inf = n.open()
140                             outf = open(n.name, 'wb')
141                             write_to_file(inf, outf)
142                             outf.close()
143                         except Exception, e:
144                             log('  error: %s\n' % e)
145         elif cmd == 'help' or cmd == '?':
146             log('Commands: ls cd pwd cat get mget help quit\n')
147         elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
148             break
149         else:
150             raise Exception('no such command %r' % cmd)
151     except Exception, e:
152         log('error: %s\n' % e)
153         #raise