]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/common.py
CLI: add 'list-aliases', factor out get_aliases
[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 def get_alias(aliases, path, default):
95     # transform "work:path/filename" into (aliases["work"], "path/filename")
96     # We special-case URI:
97     if path.startswith("URI:"):
98         # The only way to get a sub-path is to use URI:blah:./foo, and we
99         # strip out the :./ sequence.
100         sep = path.find(":./")
101         if sep != -1:
102             return path[:sep], path[sep+3:]
103         return path, ""
104     colon = path.find(":")
105     if colon == -1:
106         # no alias
107         return aliases[default], path
108     alias = path[:colon]
109     if "/" in alias:
110         # no alias, but there's a colon in a dirname/filename, like
111         # "foo/bar:7"
112         return aliases[default], path
113     return aliases[alias], path[colon+1:]
114
115 def escape_path(path):
116     segments = path.split("/")
117     return "/".join([urllib.quote(s) for s in segments])