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