]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/scripts/tahoe_mv.py
Merge pull request #236 from daira/2725.timezone-test.0
[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.encodingutil 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     resp = do_http("GET", from_url + "?t=json")
32     if not re.search(r'^2\d\d$', str(resp.status)):
33         print >>stderr, format_http_error("Error", resp)
34         return 1
35     data = resp.read()
36     nodetype, attrs = simplejson.loads(data)
37     cap = to_str(attrs.get("rw_uri") or attrs["ro_uri"])
38
39     # now get the target
40     try:
41         rootcap, path = get_alias(aliases, to_file, DEFAULT_ALIAS)
42     except UnknownAliasError, e:
43         e.display(stderr)
44         return 1
45     to_url = nodeurl + "uri/%s" % urllib.quote(rootcap)
46     if path:
47         to_url += "/" + escape_path(path)
48
49     if to_url.endswith("/"):
50         # "mv foo.txt bar/" == "mv foo.txt bar/foo.txt"
51         to_url += escape_path(from_path[from_path.rfind("/")+1:])
52
53     to_url += "?t=uri&replace=only-files"
54
55     resp = do_http("PUT", to_url, cap)
56     status = resp.status
57     if not re.search(r'^2\d\d$', str(status)):
58         if status == 409:
59             print >>stderr, "Error: You can't overwrite a directory with a file"
60         else:
61             print >>stderr, format_http_error("Error", resp)
62             if mode == "move":
63                 print >>stderr, "NOT removing the original"
64         return 1
65
66     if mode == "move":
67         # now remove the original
68         resp = do_http("DELETE", from_url)
69         if not re.search(r'^2\d\d$', str(resp.status)):
70             print >>stderr, format_http_error("Error deleting original after move", resp)
71             return 2
72
73     print >>stdout, "OK"
74     return 0