]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/tahoe_mv.py
208b720eaefd1e1b876c1b73ad7b99898551be05
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / scripts / tahoe_mv.py
1
2 import re
3 import urllib
4 import simplejson
5 from allmydata.scripts.common import get_alias, DEFAULT_ALIAS, escape_path, \
6                                      UnknownAliasError
7 from allmydata.scripts.common_http import do_http
8
9 # this script is used for both 'mv' and 'ln'
10
11 def mv(options, mode="move"):
12     nodeurl = options['node-url']
13     aliases = options.aliases
14     from_file = options.from_file
15     to_file = options.to_file
16     stdout = options.stdout
17     stderr = options.stderr
18
19     if nodeurl[-1] != "/":
20         nodeurl += "/"
21     try:
22         rootcap, from_path = get_alias(aliases, from_file, DEFAULT_ALIAS)
23     except UnknownAliasError, e:
24         print >>stderr, "error: %s" % e.args[0]
25         return 1
26     from_url = nodeurl + "uri/%s" % urllib.quote(rootcap)
27     if from_path:
28         from_url += "/" + escape_path(from_path)
29     # figure out the source cap
30     data = urllib.urlopen(from_url + "?t=json").read()
31     nodetype, attrs = simplejson.loads(data)
32     cap = attrs.get("rw_uri") or attrs["ro_uri"]
33     # simplejson sometimes returns unicode, but we know that it's really just
34     # an ASCII file-cap.
35     cap = str(cap)
36
37     # now get the target
38     try:
39         rootcap, path = get_alias(aliases, to_file, DEFAULT_ALIAS)
40     except UnknownAliasError, e:
41         print >>stderr, "error: %s" % e.args[0]
42         return 1
43     to_url = nodeurl + "uri/%s" % urllib.quote(rootcap)
44     if path:
45         to_url += "/" + escape_path(path)
46
47     if to_url.endswith("/"):
48         # "mv foo.txt bar/" == "mv foo.txt bar/foo.txt"
49         to_url += escape_path(from_path[from_path.rfind("/")+1:])
50
51     to_url += "?t=uri&replace=only-files"
52
53     resp = do_http("PUT", to_url, cap)
54     status = resp.status
55     if not re.search(r'^2\d\d$', str(status)):
56         if status == 409:
57             print >>stderr, "Error: You can't overwrite a directory with a file"
58         else:
59             print >>stderr, "error, got %s %s" % (resp.status, resp.reason)
60             print >>stderr, resp.read()
61             if mode == "move":
62                 print >>stderr, "NOT removing the original"
63         return
64
65     if mode == "move":
66         # now remove the original
67         resp = do_http("DELETE", from_url)
68         if not re.search(r'^2\d\d$', str(status)):
69             print >>stderr, "error, got %s %s" % (resp.status, resp.reason)
70             print >>stderr, resp.read()
71
72     print >>stdout, "OK"
73     return