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