]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/cli.py
CLI: implement the easy part of cp (no -r, only two arguments)
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / cli.py
1
2 import os.path, re, sys
3 from twisted.python import usage
4 from allmydata.scripts.common import BaseOptions, get_aliases
5
6 NODEURL_RE=re.compile("http://([^:]*)(:([1-9][0-9]*))?")
7
8 class VDriveOptions(BaseOptions, usage.Options):
9     optParameters = [
10         ["node-directory", "d", "~/.tahoe",
11          "Look here to find out which Tahoe node should be used for all "
12          "operations. The directory should either contain a full Tahoe node, "
13          "or a file named node.url which points to some other Tahoe node. "
14          "It should also contain a file named root_dir.cap which contains "
15          "the root dirnode URI that should be used."
16          ],
17         ["node-url", "u", None,
18          "URL of the tahoe node to use, a URL like \"http://127.0.0.1:8123\". "
19          "This overrides the URL found in the --node-directory ."],
20         ["dir-cap", "r", None,
21          "Which dirnode URI should be used as the 'tahoe' alias."]
22         ]
23
24     def postOptions(self):
25         # compute a node-url from the existing options, put in self['node-url']
26         if self['node-directory']:
27             if sys.platform == 'win32' and self['node-directory'] == '~/.tahoe':
28                 from allmydata.windows import registry
29                 self['node-directory'] = registry.get_base_dir_path()
30             else:
31                 self['node-directory'] = os.path.expanduser(self['node-directory'])
32         if self['node-url']:
33             if (not isinstance(self['node-url'], basestring)
34                 or not NODEURL_RE.match(self['node-url'])):
35                 msg = ("--node-url is required to be a string and look like "
36                        "\"http://HOSTNAMEORADDR:PORT\", not: %r" %
37                        (self['node-url'],))
38                 raise usage.UsageError(msg)
39         else:
40             node_url_file = os.path.join(self['node-directory'], "node.url")
41             self['node-url'] = open(node_url_file, "r").read().strip()
42
43         aliases = get_aliases(self['node-directory'])
44         if self['dir-cap']:
45             aliases["tahoe"] = self['dir-cap']
46         self.aliases = aliases # maps alias name to dircap
47
48
49 class MakeDirectoryOptions(VDriveOptions):
50     def parseArgs(self, where=""):
51         self.where = where
52     longdesc = """Create a new directory, either unlinked or as a subdirectory."""
53
54 class AddAliasOptions(VDriveOptions):
55     def parseArgs(self, alias, cap):
56         self.alias = alias
57         self.cap = cap
58
59 class ListAliasOptions(VDriveOptions):
60     pass
61
62 class ListOptions(VDriveOptions):
63     optFlags = [
64         ("long", "l", "Use long format: show file sizes, and timestamps"),
65         ("uri", "u", "Show file/directory URIs"),
66         ("readonly-uri", None, "Show readonly file/directory URIs"),
67         ("classify", "F", "Append '/' to directory names, and '*' to mutable"),
68         ("json", None, "Show the raw JSON output"),
69         ]
70     def parseArgs(self, where=""):
71         self.where = where
72
73     longdesc = """List the contents of some portion of the virtual drive."""
74
75 class GetOptions(VDriveOptions):
76     def parseArgs(self, arg1, arg2=None):
77         # tahoe get FOO |less            # write to stdout
78         # tahoe get tahoe:FOO |less      # same
79         # tahoe get FOO bar              # write to local file
80         # tahoe get tahoe:FOO bar        # same
81
82         self.from_file = arg1
83         self.to_file = arg2
84         if self.to_file == "-":
85             self.to_file = None
86
87     def getSynopsis(self):
88         return "%s get VDRIVE_FILE LOCAL_FILE" % (os.path.basename(sys.argv[0]),)
89
90     longdesc = """Retrieve a file from the virtual drive and write it to the
91     local filesystem. If LOCAL_FILE is omitted or '-', the contents of the file
92     will be written to stdout."""
93
94 class PutOptions(VDriveOptions):
95     optFlags = [
96         ("mutable", "m", "Create a mutable file instead of an immutable one."),
97         ]
98
99     def parseArgs(self, arg1=None, arg2=None):
100         # cat FILE > tahoe put           # create unlinked file from stdin
101         # cat FILE > tahoe put FOO       # create tahoe:FOO from stdin
102         # cat FILE > tahoe put tahoe:FOO # same
103         # tahoe put bar FOO              # copy local 'bar' to tahoe:FOO
104         # tahoe put bar tahoe:FOO        # same
105
106         if arg1 is not None and arg2 is not None:
107             self.from_file = arg1
108             self.to_file = arg2
109         elif arg1 is not None and arg2 is None:
110             self.from_file = None
111             self.to_file = arg1
112         else:
113             self.from_file = arg1
114             self.to_file = arg2
115         if self.from_file == "-":
116             self.from_file = None
117
118     def getSynopsis(self):
119         return "%s put LOCAL_FILE VDRIVE_FILE" % (os.path.basename(sys.argv[0]),)
120
121     longdesc = """Put a file into the virtual drive (copying the file's
122     contents from the local filesystem). LOCAL_FILE is required to be a
123     local file (it can't be stdin)."""
124
125 class CpOptions(VDriveOptions):
126     optFlags = [
127         ("recursive", "r", "Copy source directory recursively."),
128         ]
129     def parseArgs(self, *args):
130         if len(args) < 2:
131             raise usage.UsageError("cp requires at least two arguments")
132         self.sources = args[:-1]
133         self.destination = args[-1]
134
135 class RmOptions(VDriveOptions):
136     def parseArgs(self, where):
137         self.where = where
138
139     def getSynopsis(self):
140         return "%s rm VE_FILE" % (os.path.basename(sys.argv[0]),)
141
142 class MvOptions(VDriveOptions):
143     def parseArgs(self, frompath, topath):
144         self.from_file = frompath
145         self.to_file = topath
146
147     def getSynopsis(self):
148         return "%s mv FROM TO" % (os.path.basename(sys.argv[0]),)
149
150 class LnOptions(VDriveOptions):
151     def parseArgs(self, frompath, topath):
152         self.from_file = frompath
153         self.to_file = topath
154
155     def getSynopsis(self):
156         return "%s ln FROM TO" % (os.path.basename(sys.argv[0]),)
157
158 class WebopenOptions(VDriveOptions):
159     def parseArgs(self, vdrive_pathname=""):
160         self['vdrive_pathname'] = vdrive_pathname
161
162     longdesc = """Opens a webbrowser to the contents of some portion of the virtual drive."""
163
164 class ReplOptions(usage.Options):
165     pass
166
167 subCommands = [
168     ["mkdir", None, MakeDirectoryOptions, "Create a new directory"],
169     ["add-alias", None, AddAliasOptions, "Add a new alias cap"],
170     ["list-aliases", None, ListAliasOptions, "List all alias caps"],
171     ["ls", None, ListOptions, "List a directory"],
172     ["get", None, GetOptions, "Retrieve a file from the virtual drive."],
173     ["put", None, PutOptions, "Upload a file into the virtual drive."],
174     ["cp", None, CpOptions, "Copy one or more files."],
175     ["rm", None, RmOptions, "Unlink a file or directory in the virtual drive."],
176     ["mv", None, MvOptions, "Move a file within the virtual drive."],
177     ["ln", None, LnOptions, "Make an additional link to an existing file."],
178     ["webopen", None, WebopenOptions, "Open a webbrowser to the root_dir"],
179     ["repl", None, ReplOptions, "Open a python interpreter"],
180     ]
181
182 def mkdir(config, stdout, stderr):
183     from allmydata.scripts import tahoe_mkdir
184     rc = tahoe_mkdir.mkdir(config['node-url'],
185                            config.aliases,
186                            config.where,
187                            stdout, stderr)
188     return rc
189
190 def add_alias(config, stdout, stderr):
191     from allmydata.scripts import tahoe_add_alias
192     rc = tahoe_add_alias.add_alias(config['node-directory'],
193                                    config.alias,
194                                    config.cap,
195                                    stdout, stderr)
196     return rc
197
198 def list_aliases(config, stdout, stderr):
199     from allmydata.scripts import tahoe_add_alias
200     rc = tahoe_add_alias.list_aliases(config['node-directory'],
201                                       stdout, stderr)
202     return rc
203
204 def list(config, stdout, stderr):
205     from allmydata.scripts import tahoe_ls
206     rc = tahoe_ls.list(config['node-url'],
207                        config.aliases,
208                        config.where,
209                        config,
210                        stdout, stderr)
211     return rc
212
213 def get(config, stdout, stderr):
214     from allmydata.scripts import tahoe_get
215     rc = tahoe_get.get(config['node-url'],
216                        config.aliases,
217                        config.from_file,
218                        config.to_file,
219                        stdout, stderr)
220     if rc == 0:
221         if config.to_file is None:
222             # be quiet, since the file being written to stdout should be
223             # proof enough that it worked, unless the user is unlucky
224             # enough to have picked an empty file
225             pass
226         else:
227             print >>stderr, "%s retrieved and written to %s" % \
228                   (config.from_file, config.to_file)
229     return rc
230
231 def put(config, stdout, stderr, stdin=sys.stdin):
232     from allmydata.scripts import tahoe_put
233     if config['quiet']:
234         verbosity = 0
235     else:
236         verbosity = 2
237     rc = tahoe_put.put(config['node-url'],
238                        config.aliases,
239                        config.from_file,
240                        config.to_file,
241                        config['mutable'],
242                        verbosity,
243                        stdin, stdout, stderr)
244     return rc
245
246 def cp(config, stdout, stderr):
247     from allmydata.scripts import tahoe_cp
248     if config['quiet']:
249         verbosity = 0
250     else:
251         verbosity = 2
252     rc = tahoe_cp.copy(config['node-url'],
253                        config,
254                        config.aliases,
255                        config.sources,
256                        config.destination,
257                        verbosity,
258                        stdout, stderr)
259     return rc
260
261 def rm(config, stdout, stderr):
262     from allmydata.scripts import tahoe_rm
263     if config['quiet']:
264         verbosity = 0
265     else:
266         verbosity = 2
267     rc = tahoe_rm.rm(config['node-url'],
268                      config.aliases,
269                      config.where,
270                      verbosity,
271                      stdout, stderr)
272     return rc
273
274 def mv(config, stdout, stderr):
275     from allmydata.scripts import tahoe_mv
276     rc = tahoe_mv.mv(config['node-url'],
277                      config.aliases,
278                      config.from_file,
279                      config.to_file,
280                      stdout, stderr,
281                      mode="move")
282     return rc
283
284 def ln(config, stdout, stderr):
285     from allmydata.scripts import tahoe_mv
286     rc = tahoe_mv.mv(config['node-url'],
287                      config.aliases,
288                      config.from_file,
289                      config.to_file,
290                      stdout, stderr,
291                      mode="link")
292     return rc
293
294 def webopen(config, stdout, stderr):
295     import urllib, webbrowser
296     nodeurl = config['node-url']
297     if nodeurl[-1] != "/":
298         nodeurl += "/"
299     url = nodeurl + "uri/%s/" % urllib.quote(config['dir-cap'])
300     if config['vdrive_pathname']:
301         url += urllib.quote(config['vdrive_pathname'])
302     webbrowser.open(url)
303     return 0
304
305 def repl(config, stdout, stderr):
306     import code
307     return code.interact()
308
309 dispatch = {
310     "mkdir": mkdir,
311     "add-alias": add_alias,
312     "list-aliases": list_aliases,
313     "ls": list,
314     "get": get,
315     "put": put,
316     "cp": cp,
317     "rm": rm,
318     "mv": mv,
319     "ln": ln,
320     "webopen": webopen,
321     "repl": repl,
322     }
323