]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/cli.py
CLI: add put --mutable, enhance ls to show mutable vs immutable as rw/r-
[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
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 = self.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     def get_aliases(self, nodedir):
50         from allmydata import uri
51         aliases = {}
52         aliasfile = os.path.join(nodedir, "private", "aliases")
53         rootfile = os.path.join(nodedir, "private", "root_dir.cap")
54         try:
55             f = open(rootfile, "r")
56             rootcap = f.read().strip()
57             if rootcap:
58                 aliases["tahoe"] = uri.from_string_dirnode(rootcap).to_string()
59         except EnvironmentError:
60             pass
61         try:
62             f = open(aliasfile, "r")
63             for line in f.readlines():
64                 line = line.strip()
65                 if line.startswith("#"):
66                     continue
67                 name, cap = line.split(":", 1)
68                 # normalize it: remove http: prefix, urldecode
69                 cap = cap.strip()
70                 aliases[name] = uri.from_string_dirnode(cap).to_string()
71         except EnvironmentError:
72             pass
73         return aliases
74
75 class MakeDirectoryOptions(VDriveOptions):
76     def parseArgs(self, where=""):
77         self.where = where
78     longdesc = """Create a new directory, either unlinked or as a subdirectory."""
79
80 class AddAliasOptions(VDriveOptions):
81     def parseArgs(self, alias, cap):
82         self.alias = alias
83         self.cap = cap
84
85 class ListOptions(VDriveOptions):
86     optFlags = [
87         ("long", "l", "Use long format: show file sizes, and timestamps"),
88         ("uri", "u", "Show file URIs"),
89         ("classify", "F", "Append '/' to directory names, and '*' to mutable"),
90         ("json", None, "Show the raw JSON output"),
91         ]
92     def parseArgs(self, where=""):
93         self.where = where
94
95     longdesc = """List the contents of some portion of the virtual drive."""
96
97 class GetOptions(VDriveOptions):
98     def parseArgs(self, arg1, arg2=None):
99         # tahoe get FOO |less            # write to stdout
100         # tahoe get tahoe:FOO |less      # same
101         # tahoe get FOO bar              # write to local file
102         # tahoe get tahoe:FOO bar        # same
103
104         self.from_file = arg1
105         self.to_file = arg2
106         if self.to_file == "-":
107             self.to_file = None
108
109     def getSynopsis(self):
110         return "%s get VDRIVE_FILE LOCAL_FILE" % (os.path.basename(sys.argv[0]),)
111
112     longdesc = """Retrieve a file from the virtual drive and write it to the
113     local filesystem. If LOCAL_FILE is omitted or '-', the contents of the file
114     will be written to stdout."""
115
116 class PutOptions(VDriveOptions):
117     optFlags = [
118         ("mutable", "m", "Create a mutable file instead of an immutable one."),
119         ]
120
121     def parseArgs(self, arg1=None, arg2=None):
122         # cat FILE > tahoe put           # create unlinked file from stdin
123         # cat FILE > tahoe put FOO       # create tahoe:FOO from stdin
124         # cat FILE > tahoe put tahoe:FOO # same
125         # tahoe put bar FOO              # copy local 'bar' to tahoe:FOO
126         # tahoe put bar tahoe:FOO        # same
127
128         if arg1 is not None and arg2 is not None:
129             self.from_file = arg1
130             self.to_file = arg2
131         elif arg1 is not None and arg2 is None:
132             self.from_file = None
133             self.to_file = arg1
134         else:
135             self.from_file = arg1
136             self.to_file = arg2
137         if self.from_file == "-":
138             self.from_file = None
139
140     def getSynopsis(self):
141         return "%s put LOCAL_FILE VDRIVE_FILE" % (os.path.basename(sys.argv[0]),)
142
143     longdesc = """Put a file into the virtual drive (copying the file's
144     contents from the local filesystem). LOCAL_FILE is required to be a
145     local file (it can't be stdin)."""
146
147 class RmOptions(VDriveOptions):
148     def parseArgs(self, where):
149         self.where = where
150
151     def getSynopsis(self):
152         return "%s rm VE_FILE" % (os.path.basename(sys.argv[0]),)
153
154 class MvOptions(VDriveOptions):
155     def parseArgs(self, frompath, topath):
156         self.from_file = frompath
157         self.to_file = topath
158
159     def getSynopsis(self):
160         return "%s mv FROM TO" % (os.path.basename(sys.argv[0]),)
161
162 class WebopenOptions(VDriveOptions):
163     def parseArgs(self, vdrive_pathname=""):
164         self['vdrive_pathname'] = vdrive_pathname
165
166     longdesc = """Opens a webbrowser to the contents of some portion of the virtual drive."""
167
168 class ReplOptions(usage.Options):
169     pass
170
171 subCommands = [
172     ["mkdir", None, MakeDirectoryOptions, "Create a new directory"],
173     ["add-alias", None, AddAliasOptions, "Add a new alias cap"],
174     ["ls", None, ListOptions, "List a directory"],
175     ["get", None, GetOptions, "Retrieve a file from the virtual drive."],
176     ["put", None, PutOptions, "Upload a file into the virtual drive."],
177     ["rm", None, RmOptions, "Unlink a file or directory in the virtual drive."],
178     ["mv", None, MvOptions, "Move a file within the virtual drive."],
179     ["webopen", None, WebopenOptions, "Open a webbrowser to the root_dir"],
180     ["repl", None, ReplOptions, "Open a python interpreter"],
181     ]
182
183 def mkdir(config, stdout, stderr):
184     from allmydata.scripts import tahoe_mkdir
185     rc = tahoe_mkdir.mkdir(config['node-url'],
186                            config.aliases,
187                            config.where,
188                            stdout, stderr)
189     return rc
190
191 def add_alias(config, stdout, stderr):
192     from allmydata.scripts import tahoe_add_alias
193     rc = tahoe_add_alias.add_alias(config['node-directory'],
194                                    config.alias,
195                                    config.cap,
196                                    stdout, stderr)
197     return rc
198
199 def list(config, stdout, stderr):
200     from allmydata.scripts import tahoe_ls
201     rc = tahoe_ls.list(config['node-url'],
202                        config.aliases,
203                        config.where,
204                        config,
205                        stdout, stderr)
206     return rc
207
208 def get(config, stdout, stderr):
209     from allmydata.scripts import tahoe_get
210     rc = tahoe_get.get(config['node-url'],
211                        config.aliases,
212                        config.from_file,
213                        config.to_file,
214                        stdout, stderr)
215     if rc == 0:
216         if config.to_file is None:
217             # be quiet, since the file being written to stdout should be
218             # proof enough that it worked, unless the user is unlucky
219             # enough to have picked an empty file
220             pass
221         else:
222             print >>stderr, "%s retrieved and written to %s" % \
223                   (config.from_file, config.to_file)
224     return rc
225
226 def put(config, stdout, stderr, stdin=sys.stdin):
227     from allmydata.scripts import tahoe_put
228     if config['quiet']:
229         verbosity = 0
230     else:
231         verbosity = 2
232     rc = tahoe_put.put(config['node-url'],
233                        config.aliases,
234                        config.from_file,
235                        config.to_file,
236                        config['mutable'],
237                        verbosity,
238                        stdin, stdout, stderr)
239     return rc
240
241 def rm(config, stdout, stderr):
242     from allmydata.scripts import tahoe_rm
243     if config['quiet']:
244         verbosity = 0
245     else:
246         verbosity = 2
247     rc = tahoe_rm.rm(config['node-url'],
248                      config.aliases,
249                      config.where,
250                      verbosity,
251                      stdout, stderr)
252     return rc
253
254 def mv(config, stdout, stderr):
255     from allmydata.scripts import tahoe_mv
256     rc = tahoe_mv.mv(config['node-url'],
257                      config.aliases,
258                      config.from_file,
259                      config.to_file,
260                      stdout, stderr)
261     return rc
262
263 def webopen(config, stdout, stderr):
264     import urllib, webbrowser
265     nodeurl = config['node-url']
266     if nodeurl[-1] != "/":
267         nodeurl += "/"
268     url = nodeurl + "uri/%s/" % urllib.quote(config['dir-cap'])
269     if config['vdrive_pathname']:
270         url += urllib.quote(config['vdrive_pathname'])
271     webbrowser.open(url)
272     return 0
273
274 def repl(config, stdout, stderr):
275     import code
276     return code.interact()
277
278 dispatch = {
279     "mkdir": mkdir,
280     "add-alias": add_alias,
281     "ls": list,
282     "get": get,
283     "put": put,
284     "rm": rm,
285     "mv": mv,
286     "webopen": webopen,
287     "repl": repl,
288     }
289