]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/common.py
CLI: implement the easy part of cp (no -r, only two arguments)
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / common.py
1
2 import os, sys, urllib
3 from twisted.python import usage
4
5
6 class BaseOptions:
7     optFlags = [
8         ["quiet", "q", "Operate silently."],
9         ["version", "V", "Display version numbers and exit."],
10         ]
11
12     def opt_version(self):
13         import allmydata
14         print allmydata.get_package_versions_string()
15         sys.exit(0)
16
17
18 class BasedirMixin:
19     optFlags = [
20         ["multiple", "m", "allow multiple basedirs to be specified at once"],
21         ]
22
23     def postOptions(self):
24         if not self.basedirs:
25             raise usage.UsageError("<basedir> parameter is required")
26         if self['basedir']:
27             del self['basedir']
28         self['basedirs'] = [os.path.abspath(os.path.expanduser(b))
29                             for b in self.basedirs]
30
31     def parseArgs(self, *args):
32         self.basedirs = []
33         if self['basedir']:
34             self.basedirs.append(self['basedir'])
35         if self['multiple']:
36             self.basedirs.extend(args)
37         else:
38             if len(args) == 0 and not self.basedirs:
39                 if sys.platform == 'win32':
40                     from allmydata.windows import registry
41                     self.basedirs.append(registry.get_base_dir_path())
42                 else:
43                     self.basedirs.append(os.path.expanduser("~/.tahoe"))
44             if len(args) > 0:
45                 self.basedirs.append(args[0])
46             if len(args) > 1:
47                 raise usage.UsageError("I wasn't expecting so many arguments")
48
49 class NoDefaultBasedirMixin(BasedirMixin):
50     def parseArgs(self, *args):
51         # create-client won't default to --basedir=~/.tahoe
52         self.basedirs = []
53         if self['basedir']:
54             self.basedirs.append(self['basedir'])
55         if self['multiple']:
56             self.basedirs.extend(args)
57         else:
58             if len(args) > 0:
59                 self.basedirs.append(args[0])
60             if len(args) > 1:
61                 raise usage.UsageError("I wasn't expecting so many arguments")
62         if not self.basedirs:
63             raise usage.UsageError("--basedir must be provided")
64
65 DEFAULT_ALIAS = "tahoe"
66
67
68 def get_aliases(nodedir):
69     from allmydata import uri
70     aliases = {}
71     aliasfile = os.path.join(nodedir, "private", "aliases")
72     rootfile = os.path.join(nodedir, "private", "root_dir.cap")
73     try:
74         f = open(rootfile, "r")
75         rootcap = f.read().strip()
76         if rootcap:
77             aliases["tahoe"] = uri.from_string_dirnode(rootcap).to_string()
78     except EnvironmentError:
79         pass
80     try:
81         f = open(aliasfile, "r")
82         for line in f.readlines():
83             line = line.strip()
84             if line.startswith("#"):
85                 continue
86             name, cap = line.split(":", 1)
87             # normalize it: remove http: prefix, urldecode
88             cap = cap.strip()
89             aliases[name] = uri.from_string_dirnode(cap).to_string()
90     except EnvironmentError:
91         pass
92     return aliases
93
94 class DefaultAliasMarker:
95     pass
96
97 def get_alias(aliases, path, default):
98     # transform "work:path/filename" into (aliases["work"], "path/filename").
99     # If default=None, then an empty alias is indicated by returning
100     # DefaultAliasMarker. We special-case "URI:" to make it easy to access
101     # specific files/directories by their read-cap.
102     if path.startswith("URI:"):
103         # The only way to get a sub-path is to use URI:blah:./foo, and we
104         # strip out the :./ sequence.
105         sep = path.find(":./")
106         if sep != -1:
107             return path[:sep], path[sep+3:]
108         return path, ""
109     colon = path.find(":")
110     if colon == -1:
111         # no alias
112         if default == None:
113             return DefaultAliasMarker, path
114         return aliases[default], path
115     alias = path[:colon]
116     if "/" in alias:
117         # no alias, but there's a colon in a dirname/filename, like
118         # "foo/bar:7"
119         if default == None:
120             return DefaultAliasMarker, path
121         return aliases[default], path
122     return aliases[alias], path[colon+1:]
123
124 def escape_path(path):
125     segments = path.split("/")
126     return "/".join([urllib.quote(s) for s in segments])