]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/cli.py
Fix handling of correctly encoded unicode filenames (#534)
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / cli.py
1 import os.path, re, sys, fnmatch
2 from twisted.python import usage
3 from allmydata.scripts.common import BaseOptions, get_aliases
4 from allmydata.util.stringutils import argv_to_unicode
5
6 NODEURL_RE=re.compile("http(s?)://([^:]*)(:([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 private/aliases which contains "
15          "the mapping from alias name to root dirnode URI."
16          ],
17         ["node-url", "u", None,
18          "URL of the tahoe node to use, a URL like \"http://127.0.0.1:3456\". "
19          "This overrides the URL found in the --node-directory ."],
20         ["dir-cap", None, 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         if self['node-url'][-1] != "/":
43             self['node-url'] += "/"
44
45         aliases = get_aliases(self['node-directory'])
46         if self['dir-cap']:
47             aliases["tahoe"] = self['dir-cap']
48         self.aliases = aliases # maps alias name to dircap
49
50
51 class MakeDirectoryOptions(VDriveOptions):
52     def parseArgs(self, where=""):
53         self.where = argv_to_unicode(where)
54     longdesc = """Create a new directory, either unlinked or as a subdirectory."""
55
56 class AddAliasOptions(VDriveOptions):
57     def parseArgs(self, alias, cap):
58         self.alias = argv_to_unicode(alias)
59         self.cap = cap
60
61     def getSynopsis(self):
62         return "%s add-alias ALIAS DIRCAP" % (os.path.basename(sys.argv[0]),)
63
64     longdesc = """Add a new alias for an existing directory."""
65
66 class CreateAliasOptions(VDriveOptions):
67     def parseArgs(self, alias):
68         self.alias = argv_to_unicode(alias)
69
70     def getSynopsis(self):
71         return "%s create-alias ALIAS" % (os.path.basename(sys.argv[0]),)
72
73     longdesc = """Create a new directory and add an alias for it."""
74
75 class ListAliasOptions(VDriveOptions):
76     longdesc = """Display a table of all configured aliases."""
77
78 class ListOptions(VDriveOptions):
79     optFlags = [
80         ("long", "l", "Use long format: show file sizes, and timestamps"),
81         ("uri", "u", "Show file/directory URIs"),
82         ("readonly-uri", None, "Show readonly file/directory URIs"),
83         ("classify", "F", "Append '/' to directory names, and '*' to mutable"),
84         ("json", None, "Show the raw JSON output"),
85         ]
86     def parseArgs(self, where=""):
87         self.where = argv_to_unicode(where)
88
89     longdesc = """
90     List the contents of some portion of the grid.
91
92     When the -l or --long option is used, each line is shown in the
93     following format:
94
95     drwx <size> <date/time> <name in this directory>
96
97     where each of the letters on the left may be replaced by '-'.
98     If 'd' is present, it indicates that the object is a directory.
99     If the 'd' is replaced by a '?', the object type is unknown.
100     'rwx' is a Unix-like permissions mask: if the mask includes 'w',
101     then the object is writeable through its link in this directory
102     (note that the link might be replaceable even if the object is
103     not writeable through the current link).
104     The 'x' is a legacy of Unix filesystems. In Tahoe it is used
105     only to indicate that the contents of a directory can be listed.
106
107     Directories have no size, so their size field is shown as '-'.
108     Otherwise the size of the file, when known, is given in bytes.
109     The size of mutable files or unknown objects is shown as '?'.
110
111     The date/time shows when this link in the Tahoe filesystem was
112     last modified.
113     """
114
115 class GetOptions(VDriveOptions):
116     def parseArgs(self, arg1, arg2=None):
117         # tahoe get FOO |less            # write to stdout
118         # tahoe get tahoe:FOO |less      # same
119         # tahoe get FOO bar              # write to local file
120         # tahoe get tahoe:FOO bar        # same
121
122         self.from_file = argv_to_unicode(arg1)
123
124         if arg2:
125             self.to_file = argv_to_unicode(arg2)
126         else:
127             self.to_file = None
128
129         if self.to_file == "-":
130             self.to_file = None
131
132     def getSynopsis(self):
133         return "%s get REMOTE_FILE LOCAL_FILE" % (os.path.basename(sys.argv[0]),)
134
135     longdesc = """
136     Retrieve a file from the grid and write it to the local filesystem. If
137     LOCAL_FILE is omitted or '-', the contents of the file will be written to
138     stdout."""
139
140     def getUsage(self, width=None):
141         t = VDriveOptions.getUsage(self, width)
142         t += """
143 Examples:
144  % tahoe get FOO |less            # write to stdout
145  % tahoe get tahoe:FOO |less      # same
146  % tahoe get FOO bar              # write to local file
147  % tahoe get tahoe:FOO bar        # same
148 """
149         return t
150
151 class PutOptions(VDriveOptions):
152     optFlags = [
153         ("mutable", "m", "Create a mutable file instead of an immutable one."),
154         ]
155
156     def parseArgs(self, arg1=None, arg2=None):
157         # see Examples below
158
159         if arg1 is not None and arg2 is not None:
160             self.from_file = argv_to_unicode(arg1)
161             self.to_file =  argv_to_unicode(arg2)
162         elif arg1 is not None and arg2 is None:
163             self.from_file = argv_to_unicode(arg1) # might be "-"
164             self.to_file = None
165         else:
166             self.from_file = None
167             self.to_file = None
168         if self.from_file == u"-":
169             self.from_file = None
170
171     def getSynopsis(self):
172         return "%s put LOCAL_FILE REMOTE_FILE" % (os.path.basename(sys.argv[0]),)
173
174     longdesc = """
175     Put a file into the grid, copying its contents from the local filesystem.
176     If REMOTE_FILE is missing, upload the file but do not link it into a
177     directory; also print the new filecap to stdout. If LOCAL_FILE is missing
178     or '-', data will be copied from stdin. REMOTE_FILE is assumed to start
179     with tahoe: unless otherwise specified."""
180
181     def getUsage(self, width=None):
182         t = VDriveOptions.getUsage(self, width)
183         t += """
184 Examples:
185  % cat FILE | tahoe put                # create unlinked file from stdin
186  % cat FILE | tahoe -                  # same
187  % tahoe put bar                       # create unlinked file from local 'bar'
188  % cat FILE | tahoe put - FOO          # create tahoe:FOO from stdin
189  % tahoe put bar FOO                   # copy local 'bar' to tahoe:FOO
190  % tahoe put bar tahoe:FOO             # same
191  % tahoe put bar MUTABLE-FILE-WRITECAP # modify the mutable file in-place
192 """
193         return t
194
195 class CpOptions(VDriveOptions):
196     optFlags = [
197         ("recursive", "r", "Copy source directory recursively."),
198         ("verbose", "v", "Be noisy about what is happening."),
199         ("caps-only", None,
200          "When copying to local files, write out filecaps instead of actual "
201          "data (only useful for debugging and tree-comparison purposes)."),
202         ]
203     def parseArgs(self, *args):
204         if len(args) < 2:
205             raise usage.UsageError("cp requires at least two arguments")
206         self.sources = map(argv_to_unicode, args[:-1])
207         self.destination = argv_to_unicode(args[-1])
208     def getSynopsis(self):
209         return "Usage: tahoe [options] cp FROM.. TO"
210     longdesc = """
211     Use 'tahoe cp' to copy files between a local filesystem and a Tahoe grid.
212     Any FROM/TO arguments that begin with an alias indicate Tahoe-side
213     files or non-file arguments. Directories will be copied recursively.
214     New Tahoe-side directories will be created when necessary. Assuming that
215     you have previously set up an alias 'home' with 'tahoe create-alias home',
216     here are some examples:
217
218     tahoe cp ~/foo.txt home:  # creates tahoe-side home:foo.txt
219
220     tahoe cp ~/foo.txt /tmp/bar.txt home:  # copies two files to home:
221
222     tahoe cp ~/Pictures home:stuff/my-pictures  # copies directory recursively
223
224     You can also use a dircap as either FROM or TO target:
225
226     tahoe cp URI:DIR2-RO:j74uhg25nwdpjpacl6rkat2yhm:kav7ijeft5h7r7rxdp5bgtlt3viv32yabqajkrdykozia5544jqa/wiki.html ./   # copy Zooko's wiki page to a local file
227
228     This command still has some limitations: symlinks, special files (device
229     nodes, named pipes), and non-ASCII filenames are not handled very well.
230     Arguments should probably not have trailing slashes. 'tahoe cp' does not
231     behave as much like /bin/cp as you would wish, especially with respect to
232     trailing slashes.
233     """
234
235 class RmOptions(VDriveOptions):
236     def parseArgs(self, where):
237         self.where = argv_to_unicode(where)
238
239     def getSynopsis(self):
240         return "%s rm REMOTE_FILE" % (os.path.basename(sys.argv[0]),)
241
242 class MvOptions(VDriveOptions):
243     def parseArgs(self, frompath, topath):
244         self.from_file = argv_to_unicode(frompath)
245         self.to_file = argv_to_unicode(topath)
246
247     def getSynopsis(self):
248         return "%s mv FROM TO" % (os.path.basename(sys.argv[0]),)
249     longdesc = """
250     Use 'tahoe mv' to move files that are already on the grid elsewhere on
251     the grid, e.g., 'tahoe mv alias:some_file alias:new_file'.
252
253     If moving a remote file into a remote directory, you'll need to append a
254     '/' to the name of the remote directory, e.g., 'tahoe mv tahoe:file1
255     tahoe:dir/', not 'tahoe mv tahoe:file1 tahoe:dir'.
256
257     Note that it is not possible to use this command to move local files to
258     the grid -- use 'tahoe cp' for that.
259     """
260
261 class LnOptions(VDriveOptions):
262     def parseArgs(self, frompath, topath):
263         self.from_file = argv_to_unicode(frompath)
264         self.to_file = argv_to_unicode(topath)
265
266     def getSynopsis(self):
267         return "%s ln FROM TO" % (os.path.basename(sys.argv[0]),)
268
269 class BackupConfigurationError(Exception):
270     pass
271
272 class BackupOptions(VDriveOptions):
273     optFlags = [
274         ("verbose", "v", "Be noisy about what is happening."),
275         ("ignore-timestamps", None, "Do not use backupdb timestamps to decide whether a local file is unchanged."),
276         ]
277
278     vcs_patterns = ('CVS', 'RCS', 'SCCS', '.git', '.gitignore', '.cvsignore',
279                     '.svn', '.arch-ids','{arch}', '=RELEASE-ID',
280                     '=meta-update', '=update', '.bzr', '.bzrignore',
281                     '.bzrtags', '.hg', '.hgignore', '_darcs')
282
283     def __init__(self):
284         super(BackupOptions, self).__init__()
285         self['exclude'] = set()
286
287     def parseArgs(self, localdir, topath):
288         self.from_dir = argv_to_unicode(localdir)
289         self.to_dir = argv_to_unicode(topath)
290
291     def getSynopsis(Self):
292         return "%s backup FROM ALIAS:TO" % os.path.basename(sys.argv[0])
293
294     def opt_exclude(self, pattern):
295         """Ignore files matching a glob pattern. You may give multiple
296         '--exclude' options."""
297         g = pattern.strip()
298         if g:
299             exclude = self['exclude']
300             exclude.add(g)
301
302     def opt_exclude_from(self, filepath):
303         """Ignore file matching glob patterns listed in file, one per
304         line."""
305         try:
306             exclude_file = file(filepath)
307         except:
308             raise BackupConfigurationError('Error opening exclude file %r.' % filepath)
309         try:
310             for line in exclude_file:
311                 self.opt_exclude(line)
312         finally:
313             exclude_file.close()
314
315     def opt_exclude_vcs(self):
316         """Exclude files and directories used by following version control
317         systems: CVS, RCS, SCCS, Git, SVN, Arch, Bazaar(bzr), Mercurial,
318         Darcs."""
319         for pattern in self.vcs_patterns:
320             self.opt_exclude(pattern)
321
322     def filter_listdir(self, listdir):
323         """Yields non-excluded childpaths in path."""
324         exclude = self['exclude']
325         exclude_regexps = [re.compile(fnmatch.translate(pat)) for pat in exclude]
326         for filename in listdir:
327             for regexp in exclude_regexps:
328                 if regexp.match(filename):
329                     break
330             else:
331                 yield filename
332
333     longdesc = """
334     Add a versioned backup of the local FROM directory to a timestamped
335     subdirectory of the TO/Archives directory on the grid, sharing as many
336     files and directories as possible with earlier backups. Create TO/Latest
337     as a reference to the latest backup. Behaves somewhat like 'rsync -a
338     --link-dest=TO/Archives/(previous) FROM TO/Archives/(new); ln -sf
339     TO/Archives/(new) TO/Latest'."""
340
341 class WebopenOptions(VDriveOptions):
342     optFlags = [
343         ("info", "i", "Open the t=info page for the file"),
344         ]
345     def parseArgs(self, where=''):
346         self.where = argv_to_unicode(where)
347
348     def getSynopsis(self):
349         return "%s webopen [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
350
351     longdesc = """Open a web browser to the contents of some file or
352     directory on the grid. When run without arguments, open the Welcome
353     page."""
354
355 class ManifestOptions(VDriveOptions):
356     optFlags = [
357         ("storage-index", "s", "Only print storage index strings, not pathname+cap"),
358         ("verify-cap", None, "Only print verifycap, not pathname+cap"),
359         ("repair-cap", None, "Only print repaircap, not pathname+cap"),
360         ("raw", "r", "Display raw JSON data instead of parsed"),
361         ]
362     def parseArgs(self, where=''):
363         self.where = argv_to_unicode(where)
364
365     def getSynopsis(self):
366         return "%s manifest [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
367
368     longdesc = """Print a list of all files and directories reachable from
369     the given starting point."""
370
371 class StatsOptions(VDriveOptions):
372     optFlags = [
373         ("raw", "r", "Display raw JSON data instead of parsed"),
374         ]
375     def parseArgs(self, where=''):
376         self.where = argv_to_unicode(where)
377
378     def getSynopsis(self):
379         return "%s stats [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
380
381     longdesc = """Print statistics about of all files and directories
382     reachable from the given starting point."""
383
384 class CheckOptions(VDriveOptions):
385     optFlags = [
386         ("raw", None, "Display raw JSON data instead of parsed"),
387         ("verify", None, "Verify all hashes, instead of merely querying share presence"),
388         ("repair", None, "Automatically repair any problems found"),
389         ("add-lease", None, "Add/renew lease on all shares"),
390         ]
391     def parseArgs(self, where=''):
392         self.where = argv_to_unicode(where)
393
394     def getSynopsis(self):
395         return "%s check [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
396
397     longdesc = """
398     Check a single file or directory: count how many shares are available and
399     verify their hashes. Optionally repair the file if any problems were
400     found."""
401
402 class DeepCheckOptions(VDriveOptions):
403     optFlags = [
404         ("raw", None, "Display raw JSON data instead of parsed"),
405         ("verify", None, "Verify all hashes, instead of merely querying share presence"),
406         ("repair", None, "Automatically repair any problems found"),
407         ("add-lease", None, "Add/renew lease on all shares"),
408         ("verbose", "v", "Be noisy about what is happening."),
409         ]
410     def parseArgs(self, where=''):
411         self.where = argv_to_unicode(where)
412
413     def getSynopsis(self):
414         return "%s deep-check [ALIAS:PATH]" % (os.path.basename(sys.argv[0]),)
415
416     longdesc = """
417     Check all files and directories reachable from the given starting point
418     (which must be a directory), like 'tahoe check' but for multiple files.
419     Optionally repair any problems found."""
420
421 subCommands = [
422     ["mkdir", None, MakeDirectoryOptions, "Create a new directory"],
423     ["add-alias", None, AddAliasOptions, "Add a new alias cap"],
424     ["create-alias", None, CreateAliasOptions, "Create a new alias cap"],
425     ["list-aliases", None, ListAliasOptions, "List all alias caps"],
426     ["ls", None, ListOptions, "List a directory"],
427     ["get", None, GetOptions, "Retrieve a file from the grid."],
428     ["put", None, PutOptions, "Upload a file into the grid."],
429     ["cp", None, CpOptions, "Copy one or more files."],
430     ["rm", None, RmOptions, "Unlink a file or directory on the grid."],
431     ["mv", None, MvOptions, "Move a file within the grid."],
432     ["ln", None, LnOptions, "Make an additional link to an existing file."],
433     ["backup", None, BackupOptions, "Make target dir look like local dir."],
434     ["webopen", None, WebopenOptions, "Open a web browser to a grid file or directory."],
435     ["manifest", None, ManifestOptions, "List all files/directories in a subtree"],
436     ["stats", None, StatsOptions, "Print statistics about all files/directories in a subtree"],
437     ["check", None, CheckOptions, "Check a single file or directory"],
438     ["deep-check", None, DeepCheckOptions, "Check all files/directories reachable from a starting point"],
439     ]
440
441 def mkdir(options):
442     from allmydata.scripts import tahoe_mkdir
443     rc = tahoe_mkdir.mkdir(options)
444     return rc
445
446 def add_alias(options):
447     from allmydata.scripts import tahoe_add_alias
448     rc = tahoe_add_alias.add_alias(options)
449     return rc
450
451 def create_alias(options):
452     from allmydata.scripts import tahoe_add_alias
453     rc = tahoe_add_alias.create_alias(options)
454     return rc
455
456 def list_aliases(options):
457     from allmydata.scripts import tahoe_add_alias
458     rc = tahoe_add_alias.list_aliases(options)
459     return rc
460
461 def list(options):
462     from allmydata.scripts import tahoe_ls
463     rc = tahoe_ls.list(options)
464     return rc
465
466 def get(options):
467     from allmydata.scripts import tahoe_get
468     rc = tahoe_get.get(options)
469     if rc == 0:
470         if options.to_file is None:
471             # be quiet, since the file being written to stdout should be
472             # proof enough that it worked, unless the user is unlucky
473             # enough to have picked an empty file
474             pass
475         else:
476             print >>options.stderr, "%s retrieved and written to %s" % \
477                   (options.from_file, options.to_file)
478     return rc
479
480 def put(options):
481     from allmydata.scripts import tahoe_put
482     rc = tahoe_put.put(options)
483     return rc
484
485 def cp(options):
486     from allmydata.scripts import tahoe_cp
487     rc = tahoe_cp.copy(options)
488     return rc
489
490 def rm(options):
491     from allmydata.scripts import tahoe_rm
492     rc = tahoe_rm.rm(options)
493     return rc
494
495 def mv(options):
496     from allmydata.scripts import tahoe_mv
497     rc = tahoe_mv.mv(options, mode="move")
498     return rc
499
500 def ln(options):
501     from allmydata.scripts import tahoe_mv
502     rc = tahoe_mv.mv(options, mode="link")
503     return rc
504
505 def backup(options):
506     from allmydata.scripts import tahoe_backup
507     rc = tahoe_backup.backup(options)
508     return rc
509
510 def webopen(options, opener=None):
511     from allmydata.scripts import tahoe_webopen
512     rc = tahoe_webopen.webopen(options, opener=opener)
513     return rc
514
515 def manifest(options):
516     from allmydata.scripts import tahoe_manifest
517     rc = tahoe_manifest.manifest(options)
518     return rc
519
520 def stats(options):
521     from allmydata.scripts import tahoe_manifest
522     rc = tahoe_manifest.stats(options)
523     return rc
524
525 def check(options):
526     from allmydata.scripts import tahoe_check
527     rc = tahoe_check.check(options)
528     return rc
529
530 def deepcheck(options):
531     from allmydata.scripts import tahoe_check
532     rc = tahoe_check.deepcheck(options)
533     return rc
534
535 dispatch = {
536     "mkdir": mkdir,
537     "add-alias": add_alias,
538     "create-alias": create_alias,
539     "list-aliases": list_aliases,
540     "ls": list,
541     "get": get,
542     "put": put,
543     "cp": cp,
544     "rm": rm,
545     "mv": mv,
546     "ln": ln,
547     "backup": backup,
548     "webopen": webopen,
549     "manifest": manifest,
550     "stats": stats,
551     "check": check,
552     "deep-check": deepcheck,
553     }