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