5 from collections import defaultdict
6 from cStringIO import StringIO
7 from twisted.python.failure import Failure
8 from allmydata.scripts.common import get_alias, escape_path, \
9 DefaultAliasMarker, TahoeError
10 from allmydata.scripts.common_http import do_http, HTTPError
11 from allmydata import uri
12 from allmydata.util import fileutil
13 from allmydata.util.fileutil import abspath_expanduser_unicode, precondition_abspath
14 from allmydata.util.encodingutil import unicode_to_url, listdir_unicode, quote_output, \
15 quote_local_unicode_path, to_str
16 from allmydata.util.assertutil import precondition, _assert
19 class MissingSourceError(TahoeError):
20 def __init__(self, name, quotefn=quote_output):
21 TahoeError.__init__(self, "No such file or directory %s" % quotefn(name))
23 class FilenameWithTrailingSlashError(TahoeError):
24 def __init__(self, name, quotefn=quote_output):
25 TahoeError.__init__(self, "source '%s' is not a directory, but ends with a slash" % quotefn(name))
27 class WeirdSourceError(TahoeError):
28 def __init__(self, absname):
29 quoted = quote_local_unicode_path(absname)
30 TahoeError.__init__(self, "source '%s' is neither a file nor a directory, I can't handle it" % quoted)
33 resp = do_http("GET", url)
34 if resp.status == 200:
36 raise HTTPError("Error during GET", resp)
38 def GET_to_string(url):
43 resp = do_http("PUT", url, data)
44 if resp.status in (200, 201):
46 raise HTTPError("Error during PUT", resp)
49 resp = do_http("POST", url, data)
50 if resp.status in (200, 201):
52 raise HTTPError("Error during POST", resp)
55 url = targeturl + "?t=mkdir"
56 resp = do_http("POST", url)
57 if resp.status in (200, 201):
58 return resp.read().strip()
59 raise HTTPError("Error during mkdir", resp)
61 def make_tahoe_subdirectory(nodeurl, parent_writecap, name):
62 url = nodeurl + "/".join(["uri",
63 urllib.quote(parent_writecap),
64 urllib.quote(unicode_to_url(name)),
66 resp = do_http("POST", url)
67 if resp.status in (200, 201):
68 return resp.read().strip()
69 raise HTTPError("Error during mkdir", resp)
72 class LocalFileSource:
73 def __init__(self, pathname, basename):
74 precondition_abspath(pathname)
75 self.pathname = pathname
76 self._basename = basename
81 def need_to_copy_bytes(self):
84 def open(self, caps_only):
85 return open(self.pathname, "rb")
87 class LocalFileTarget:
88 def __init__(self, pathname):
89 precondition_abspath(pathname)
90 self.pathname = pathname
92 def put_file(self, inf):
93 fileutil.put_file(self.pathname, inf)
95 class LocalMissingTarget:
96 def __init__(self, pathname):
97 precondition_abspath(pathname)
98 self.pathname = pathname
100 def put_file(self, inf):
101 fileutil.put_file(self.pathname, inf)
103 class LocalDirectorySource:
104 def __init__(self, progressfunc, pathname, basename):
105 precondition_abspath(pathname)
107 self.progressfunc = progressfunc
108 self.pathname = pathname
110 self._basename = basename
113 return self._basename
115 def populate(self, recurse):
116 if self.children is not None:
119 children = listdir_unicode(self.pathname)
120 for i,n in enumerate(children):
121 self.progressfunc("examining %d of %d" % (i+1, len(children)))
122 pn = os.path.join(self.pathname, n)
123 if os.path.isdir(pn):
124 child = LocalDirectorySource(self.progressfunc, pn, n)
125 self.children[n] = child
127 child.populate(recurse=True)
128 elif os.path.isfile(pn):
129 self.children[n] = LocalFileSource(pn, n)
131 # Could be dangling symlink; probably not copy-able.
132 # TODO: output a warning
135 class LocalDirectoryTarget:
136 def __init__(self, progressfunc, pathname):
137 precondition_abspath(pathname)
139 self.progressfunc = progressfunc
140 self.pathname = pathname
143 def populate(self, recurse):
144 if self.children is not None:
147 children = listdir_unicode(self.pathname)
148 for i,n in enumerate(children):
149 self.progressfunc("examining %d of %d" % (i+1, len(children)))
150 pn = os.path.join(self.pathname, n)
151 if os.path.isdir(pn):
152 child = LocalDirectoryTarget(self.progressfunc, pn)
153 self.children[n] = child
155 child.populate(recurse=True)
157 assert os.path.isfile(pn)
158 self.children[n] = LocalFileTarget(pn)
160 def get_child_target(self, name):
161 precondition(isinstance(name, unicode), name)
162 precondition(len(name), name) # don't want ""
163 if self.children is None:
164 self.populate(recurse=False)
165 if name in self.children:
166 return self.children[name]
167 pathname = os.path.join(self.pathname, name)
168 os.makedirs(pathname)
169 child = LocalDirectoryTarget(self.progressfunc, pathname)
170 self.children[name] = child
173 def put_file(self, name, inf):
174 precondition(isinstance(name, unicode), name)
175 pathname = os.path.join(self.pathname, name)
176 fileutil.put_file(pathname, inf)
178 def set_children(self):
182 class TahoeFileSource:
183 def __init__(self, nodeurl, mutable, writecap, readcap, basename):
184 self.nodeurl = nodeurl
185 self.mutable = mutable
186 self.writecap = writecap
187 self.readcap = readcap
188 self._basename = basename # unicode, or None for raw filecaps
191 return self._basename
193 def need_to_copy_bytes(self):
198 def open(self, caps_only):
200 return StringIO(self.readcap)
201 url = self.nodeurl + "uri/" + urllib.quote(self.readcap)
202 return GET_to_file(url)
205 return self.writecap or self.readcap
207 class TahoeFileTarget:
208 def __init__(self, nodeurl, mutable, writecap, readcap, url):
209 self.nodeurl = nodeurl
210 self.mutable = mutable
211 self.writecap = writecap
212 self.readcap = readcap
215 def put_file(self, inf):
216 # We want to replace this object in-place.
218 # our do_http() call currently requires a string or a filehandle with
220 if not hasattr(inf, "seek"):
223 # TODO: this always creates immutable files. We might want an option
224 # to always create mutable files, or to copy mutable files into new
225 # mutable files. ticket #835
227 class TahoeDirectorySource:
228 def __init__(self, nodeurl, cache, progressfunc, basename):
229 self.nodeurl = nodeurl
231 self.progressfunc = progressfunc
232 self._basename = basename # unicode, or None for raw dircaps
235 return self._basename
237 def init_from_grid(self, writecap, readcap):
238 self.writecap = writecap
239 self.readcap = readcap
240 bestcap = writecap or readcap
241 url = self.nodeurl + "uri/%s" % urllib.quote(bestcap)
242 resp = do_http("GET", url + "?t=json")
243 if resp.status != 200:
244 raise HTTPError("Error examining source directory", resp)
245 parsed = simplejson.loads(resp.read())
247 assert nodetype == "dirnode"
248 self.mutable = d.get("mutable", False) # older nodes don't provide it
249 self.children_d = dict( [(unicode(name),value)
251 in d["children"].iteritems()] )
254 def init_from_parsed(self, parsed):
256 self.writecap = to_str(d.get("rw_uri"))
257 self.readcap = to_str(d.get("ro_uri"))
258 self.mutable = d.get("mutable", False) # older nodes don't provide it
259 self.children_d = dict( [(unicode(name),value)
261 in d["children"].iteritems()] )
264 def populate(self, recurse):
265 if self.children is not None:
268 for i,(name, data) in enumerate(self.children_d.items()):
269 self.progressfunc("examining %d of %d" % (i+1, len(self.children_d)))
270 if data[0] == "filenode":
271 mutable = data[1].get("mutable", False)
272 writecap = to_str(data[1].get("rw_uri"))
273 readcap = to_str(data[1].get("ro_uri"))
274 self.children[name] = TahoeFileSource(self.nodeurl, mutable,
275 writecap, readcap, name)
276 elif data[0] == "dirnode":
277 writecap = to_str(data[1].get("rw_uri"))
278 readcap = to_str(data[1].get("ro_uri"))
279 if writecap and writecap in self.cache:
280 child = self.cache[writecap]
281 elif readcap and readcap in self.cache:
282 child = self.cache[readcap]
284 child = TahoeDirectorySource(self.nodeurl, self.cache,
285 self.progressfunc, name)
286 child.init_from_grid(writecap, readcap)
288 self.cache[writecap] = child
290 self.cache[readcap] = child
292 child.populate(recurse=True)
293 self.children[name] = child
295 # TODO: there should be an option to skip unknown nodes.
296 raise TahoeError("Cannot copy unknown nodes (ticket #839). "
297 "You probably need to use a later version of "
298 "Tahoe-LAFS to copy this directory.")
300 class TahoeMissingTarget:
301 def __init__(self, url):
304 def put_file(self, inf):
305 # We want to replace this object in-place.
306 if not hasattr(inf, "seek"):
309 # TODO: this always creates immutable files. We might want an option
310 # to always create mutable files, or to copy mutable files into new
313 def put_uri(self, filecap):
314 # I'm not sure this will always work
315 return PUT(self.url + "?t=uri", filecap)
317 class TahoeDirectoryTarget:
318 def __init__(self, nodeurl, cache, progressfunc):
319 self.nodeurl = nodeurl
321 self.progressfunc = progressfunc
322 self.new_children = {}
324 def init_from_parsed(self, parsed):
326 self.writecap = to_str(d.get("rw_uri"))
327 self.readcap = to_str(d.get("ro_uri"))
328 self.mutable = d.get("mutable", False) # older nodes don't provide it
329 self.children_d = dict( [(unicode(name),value)
331 in d["children"].iteritems()] )
334 def init_from_grid(self, writecap, readcap):
335 self.writecap = writecap
336 self.readcap = readcap
337 bestcap = writecap or readcap
338 url = self.nodeurl + "uri/%s" % urllib.quote(bestcap)
339 resp = do_http("GET", url + "?t=json")
340 if resp.status != 200:
341 raise HTTPError("Error examining target directory", resp)
342 parsed = simplejson.loads(resp.read())
344 assert nodetype == "dirnode"
345 self.mutable = d.get("mutable", False) # older nodes don't provide it
346 self.children_d = dict( [(unicode(name),value)
348 in d["children"].iteritems()] )
351 def just_created(self, writecap):
352 # TODO: maybe integrate this with the constructor
353 self.writecap = writecap
354 self.readcap = uri.from_string(writecap).get_readonly().to_string()
359 def populate(self, recurse):
360 if self.children is not None:
363 for i,(name, data) in enumerate(self.children_d.items()):
364 self.progressfunc("examining %d of %d" % (i+1, len(self.children_d)))
365 if data[0] == "filenode":
366 mutable = data[1].get("mutable", False)
367 writecap = to_str(data[1].get("rw_uri"))
368 readcap = to_str(data[1].get("ro_uri"))
371 url = self.nodeurl + "/".join(["uri",
372 urllib.quote(self.writecap),
373 urllib.quote(unicode_to_url(name))])
374 self.children[name] = TahoeFileTarget(self.nodeurl, mutable,
375 writecap, readcap, url)
376 elif data[0] == "dirnode":
377 writecap = to_str(data[1].get("rw_uri"))
378 readcap = to_str(data[1].get("ro_uri"))
379 if writecap and writecap in self.cache:
380 child = self.cache[writecap]
381 elif readcap and readcap in self.cache:
382 child = self.cache[readcap]
384 child = TahoeDirectoryTarget(self.nodeurl, self.cache,
386 child.init_from_grid(writecap, readcap)
388 self.cache[writecap] = child
390 self.cache[readcap] = child
392 child.populate(recurse=True)
393 self.children[name] = child
395 # TODO: there should be an option to skip unknown nodes.
396 raise TahoeError("Cannot copy unknown nodes (ticket #839). "
397 "You probably need to use a later version of "
398 "Tahoe-LAFS to copy this directory.")
400 def get_child_target(self, name):
401 # return a new target for a named subdirectory of this dir
402 precondition(isinstance(name, unicode), name)
403 if self.children is None:
404 self.populate(recurse=False)
405 if name in self.children:
406 return self.children[name]
407 writecap = make_tahoe_subdirectory(self.nodeurl, self.writecap, name)
408 child = TahoeDirectoryTarget(self.nodeurl, self.cache,
410 child.just_created(writecap)
411 self.children[name] = child
414 def put_file(self, name, inf):
415 precondition(isinstance(name, unicode), name)
416 url = self.nodeurl + "uri"
417 if not hasattr(inf, "seek"):
420 if self.children is None:
421 self.populate(recurse=False)
423 # Check to see if we already have a mutable file by this name.
424 # If so, overwrite that file in place.
425 if name in self.children and self.children[name].mutable:
426 self.children[name].put_file(inf)
428 filecap = PUT(url, inf)
429 # TODO: this always creates immutable files. We might want an option
430 # to always create mutable files, or to copy mutable files into new
432 self.new_children[name] = filecap
434 def put_uri(self, name, filecap):
435 precondition(isinstance(name, unicode), name)
436 self.new_children[name] = filecap
438 def set_children(self):
439 if not self.new_children:
441 url = (self.nodeurl + "uri/" + urllib.quote(self.writecap)
444 for (name, filecap) in self.new_children.items():
445 # it just so happens that ?t=set_children will accept both file
446 # read-caps and write-caps as ['rw_uri'], and will handle either
447 # correctly. So don't bother trying to figure out whether the one
448 # we have is read-only or read-write.
449 # TODO: think about how this affects forward-compatibility for
451 set_data[name] = ["filenode", {"rw_uri": filecap}]
452 body = simplejson.dumps(set_data)
455 FileSources = (LocalFileSource, TahoeFileSource)
456 DirectorySources = (LocalDirectorySource, TahoeDirectorySource)
457 FileTargets = (LocalFileTarget, TahoeFileTarget)
458 DirectoryTargets = (LocalDirectoryTarget, TahoeDirectoryTarget)
459 MissingTargets = (LocalMissingTarget, TahoeMissingTarget)
463 def do_copy(self, options, progressfunc=None):
466 elif options['verbose']:
471 nodeurl = options['node-url']
472 if nodeurl[-1] != "/":
474 self.nodeurl = nodeurl
475 self.progressfunc = progressfunc
476 self.options = options
477 self.aliases = options.aliases
478 self.verbosity = verbosity
479 self.stdout = options.stdout
480 self.stderr = options.stderr
481 if verbosity >= 2 and not self.progressfunc:
482 def progress(message):
483 print >>self.stderr, message
484 self.progressfunc = progress
485 self.caps_only = options["caps-only"]
488 status = self.try_copy()
490 except TahoeError, te:
492 Failure().printTraceback(self.stderr)
494 te.display(self.stderr)
499 All usage errors are caught here, not in a subroutine. This bottoms
500 out in copy_file_to_file() or copy_things_to_directory().
502 source_specs = self.options.sources
503 destination_spec = self.options.destination
504 recursive = self.options["recursive"]
506 target = self.get_target_info(destination_spec)
507 precondition(isinstance(target, FileTargets + DirectoryTargets + MissingTargets), target)
508 target_has_trailing_slash = destination_spec.endswith("/")
510 sources = [] # list of source objects
511 for ss in source_specs:
513 si = self.get_source_info(ss)
514 except FilenameWithTrailingSlashError as e:
515 self.to_stderr(str(e))
517 precondition(isinstance(si, FileSources + DirectorySources), si)
520 # if any source is a directory, must use -r
521 # if target is missing:
522 # if source is a single file, target will be a file
523 # else target will be a directory, so mkdir it
524 # if there are multiple sources, target must be a dir
525 # if target is a file, source must be a single file
526 # if target is directory, sources must be named or a dir
528 have_source_dirs = any([isinstance(s, DirectorySources)
530 if have_source_dirs and not recursive:
531 # 'cp dir target' without -r: error
532 self.to_stderr("cannot copy directories without --recursive")
534 del recursive # -r is only used for signalling errors
536 if isinstance(target, FileTargets):
537 target_is_file = True
538 elif isinstance(target, DirectoryTargets):
539 target_is_file = False
540 else: # isinstance(target, MissingTargets)
541 if len(sources) == 1 and isinstance(sources[0], FileSources):
542 target_is_file = True
544 target_is_file = False
546 if target_is_file and target_has_trailing_slash:
547 self.to_stderr("target is not a directory, but ends with a slash")
550 if len(sources) > 1 and target_is_file:
551 self.to_stderr("copying multiple things requires target be a directory")
555 _assert(len(sources) == 1, sources)
556 if not isinstance(sources[0], FileSources):
557 # 'cp -r dir existingfile': error
558 self.to_stderr("cannot copy directory into a file")
560 return self.copy_file_to_file(sources[0], target)
562 # else target is a directory, so each source must be one of:
563 # * a named file (copied to a new file under the target)
564 # * a named directory (causes a new directory of the same name to be
565 # created under the target, then the contents of the source are
566 # copied into that directory)
567 # * an unnamed directory (the contents of the source are copied into
568 # the target, without a new directory being made)
570 # If any source is an unnamed file, throw an error, since we have no
571 # way to name the output file.
572 _assert(isinstance(target, DirectoryTargets + MissingTargets), target)
574 for source in sources:
575 if isinstance(source, FileSources) and source.basename() is None:
576 self.to_stderr("when copying into a directory, all source files must have names, but %s is unnamed" % quote_output(source_specs[0]))
578 return self.copy_things_to_directory(sources, target)
580 def to_stderr(self, text):
581 print >>self.stderr, text
583 # FIXME reduce the amount of near-duplicate code between get_target_info
584 # and get_source_info.
586 def get_target_info(self, destination_spec):
587 precondition(isinstance(destination_spec, unicode), destination_spec)
588 rootcap, path_utf8 = get_alias(self.aliases, destination_spec, None)
589 path = path_utf8.decode("utf-8")
590 if rootcap == DefaultAliasMarker:
591 # no alias, so this is a local file
592 pathname = abspath_expanduser_unicode(path)
593 if not os.path.exists(pathname):
594 t = LocalMissingTarget(pathname)
595 elif os.path.isdir(pathname):
596 t = LocalDirectoryTarget(self.progress, pathname)
598 # TODO: should this be _assert? what happens if the target is
600 assert os.path.isfile(pathname), pathname
601 t = LocalFileTarget(pathname) # non-empty
603 # this is a tahoe object
604 url = self.nodeurl + "uri/%s" % urllib.quote(rootcap)
606 url += "/" + escape_path(path)
608 resp = do_http("GET", url + "?t=json")
609 if resp.status == 404:
611 t = TahoeMissingTarget(url)
612 elif resp.status == 200:
613 parsed = simplejson.loads(resp.read())
615 if nodetype == "dirnode":
616 t = TahoeDirectoryTarget(self.nodeurl, self.cache,
618 t.init_from_parsed(parsed)
620 writecap = to_str(d.get("rw_uri"))
621 readcap = to_str(d.get("ro_uri"))
622 mutable = d.get("mutable", False)
623 t = TahoeFileTarget(self.nodeurl, mutable,
624 writecap, readcap, url)
626 raise HTTPError("Error examining target %s"
627 % quote_output(destination_spec), resp)
630 def get_source_info(self, source_spec):
632 This turns an argv string into a (Local|Tahoe)(File|Directory)Source.
634 precondition(isinstance(source_spec, unicode), source_spec)
635 rootcap, path_utf8 = get_alias(self.aliases, source_spec, None)
636 path = path_utf8.decode("utf-8")
637 # any trailing slash is removed in abspath_expanduser_unicode(), so
638 # make a note of it here, to throw an error later
639 had_trailing_slash = path.endswith("/")
640 if rootcap == DefaultAliasMarker:
641 # no alias, so this is a local file
642 pathname = abspath_expanduser_unicode(path)
643 name = os.path.basename(pathname)
644 if not os.path.exists(pathname):
645 raise MissingSourceError(source_spec, quotefn=quote_local_unicode_path)
646 if os.path.isdir(pathname):
647 t = LocalDirectorySource(self.progress, pathname, name)
649 if had_trailing_slash:
650 raise FilenameWithTrailingSlashError(source_spec,
651 quotefn=quote_local_unicode_path)
652 if not os.path.isfile(pathname):
653 raise WeirdSourceError(pathname)
654 t = LocalFileSource(pathname, name) # non-empty
656 # this is a tahoe object
657 url = self.nodeurl + "uri/%s" % urllib.quote(rootcap)
660 if path.endswith("/"):
662 url += "/" + escape_path(path)
663 last_slash = path.rfind(u"/")
666 name = path[last_slash+1:]
668 resp = do_http("GET", url + "?t=json")
669 if resp.status == 404:
670 raise MissingSourceError(source_spec)
671 elif resp.status != 200:
672 raise HTTPError("Error examining source %s" % quote_output(source_spec),
674 parsed = simplejson.loads(resp.read())
676 if nodetype == "dirnode":
677 t = TahoeDirectorySource(self.nodeurl, self.cache,
679 t.init_from_parsed(parsed)
681 if had_trailing_slash:
682 raise FilenameWithTrailingSlashError(source_spec)
683 writecap = to_str(d.get("rw_uri"))
684 readcap = to_str(d.get("ro_uri"))
685 mutable = d.get("mutable", False) # older nodes don't provide it
686 t = TahoeFileSource(self.nodeurl, mutable, writecap, readcap, name)
690 def need_to_copy_bytes(self, source, target):
691 if source.need_to_copy_bytes:
692 # mutable tahoe files, and local files
694 if isinstance(target, (LocalFileTarget, LocalDirectoryTarget)):
698 def announce_success(self, msg):
699 if self.verbosity >= 1:
700 print >>self.stdout, "Success: %s" % msg
703 def copy_file_to_file(self, source, target):
704 precondition(isinstance(source, FileSources), source)
705 precondition(isinstance(target, FileTargets + MissingTargets), target)
706 if self.need_to_copy_bytes(source, target):
707 # if the target is a local directory, this will just write the
708 # bytes to disk. If it is a tahoe directory, it will upload the
709 # data, and stash the new filecap for a later set_children call.
710 f = source.open(self.caps_only)
712 return self.announce_success("file copied")
713 # otherwise we're copying tahoe to tahoe, and using immutable files,
714 # so we can just make a link. TODO: this probably won't always work:
715 # need to enumerate the cases and analyze them.
716 target.put_uri(source.bestcap())
717 return self.announce_success("file linked")
719 def copy_things_to_directory(self, sources, target):
720 # step one: if the target is missing, we should mkdir it
721 target = self.maybe_create_target(target)
722 target.populate(recurse=False)
724 # step two: scan any source dirs, recursively, to find children
726 if isinstance(s, DirectorySources):
727 s.populate(recurse=True)
728 if isinstance(s, FileSources):
729 # each source must have a name, or be a directory
730 _assert(s.basename() is not None, s)
732 # step three: find a target for each source node, creating
733 # directories as necessary. 'targetmap' is a dictionary that uses
734 # target Directory instances as keys, and has values of (name:
735 # sourceobject) dicts for all the files that need to wind up there.
736 targetmap = self.build_targetmap(sources, target)
738 # step four: walk through the list of targets. For each one, copy all
739 # the files. If the target is a TahoeDirectory, upload and create
740 # read-caps, then do a set_children to the target directory.
741 self.copy_to_targetmap(targetmap)
743 return self.announce_success("files copied")
745 def maybe_create_target(self, target):
746 if isinstance(target, LocalMissingTarget):
747 os.makedirs(target.pathname)
748 target = LocalDirectoryTarget(self.progress, target.pathname)
749 elif isinstance(target, TahoeMissingTarget):
750 writecap = mkdir(target.url)
751 target = TahoeDirectoryTarget(self.nodeurl, self.cache,
753 target.just_created(writecap)
754 # afterwards, or otherwise, it will be a directory
755 precondition(isinstance(target, DirectoryTargets), target)
758 def build_targetmap(self, sources, target):
759 num_source_files = len([s for s in sources
760 if isinstance(s, FileSources)])
761 num_source_dirs = len([s for s in sources
762 if isinstance(s, DirectorySources)])
763 self.progress("attaching sources to targets, "
764 "%d files / %d dirs in root" %
765 (num_source_files, num_source_dirs))
767 # this maps each target directory to a list of source files that need
768 # to be copied into it. All source files have names.
769 targetmap = defaultdict(list)
772 if isinstance(s, FileSources):
773 targetmap[target].append(s)
775 _assert(isinstance(s, DirectorySources), s)
778 # named sources get a new directory. see #2329
779 new_target = target.get_child_target(name)
781 # unnamed sources have their contents copied directly
783 self.assign_targets(targetmap, s, new_target)
785 self.progress("targets assigned, %s dirs, %s files" %
786 (len(targetmap), self.count_files_to_copy(targetmap)))
789 def assign_targets(self, targetmap, source, target):
790 # copy everything in the source into the target
791 precondition(isinstance(source, DirectorySources), source)
792 for name, child in source.children.items():
793 if isinstance(child, DirectorySources):
794 # we will need a target directory for this one
795 subtarget = target.get_child_target(name)
796 self.assign_targets(targetmap, child, subtarget)
798 _assert(isinstance(child, FileSources), child)
799 targetmap[target].append(child)
801 def copy_to_targetmap(self, targetmap):
802 files_to_copy = self.count_files_to_copy(targetmap)
803 self.progress("starting copy, %d files, %d directories" %
804 (files_to_copy, len(targetmap)))
808 for target, sources in targetmap.items():
809 _assert(isinstance(target, DirectoryTargets), target)
810 for source in sources:
811 _assert(isinstance(source, FileSources), source)
812 self.copy_file_into_dir(source, source.basename(), target)
814 self.progress("%d/%d files, %d/%d directories" %
815 (files_copied, files_to_copy,
816 targets_finished, len(targetmap)))
817 target.set_children()
818 targets_finished += 1
819 self.progress("%d/%d directories" %
820 (targets_finished, len(targetmap)))
822 def count_files_to_copy(self, targetmap):
823 return sum([len(sources) for sources in targetmap.values()])
825 def copy_file_into_dir(self, source, name, target):
826 precondition(isinstance(source, FileSources), source)
827 precondition(isinstance(target, DirectoryTargets), target)
828 precondition(isinstance(name, unicode), name)
829 if self.need_to_copy_bytes(source, target):
830 # if the target is a local directory, this will just write the
831 # bytes to disk. If it is a tahoe directory, it will upload the
832 # data, and stash the new filecap for a later set_children call.
833 f = source.open(self.caps_only)
834 target.put_file(name, f)
836 # otherwise we're copying tahoe to tahoe, and using immutable files,
837 # so we can just make a link
838 target.put_uri(name, source.bestcap())
841 def progress(self, message):
843 if self.progressfunc:
844 self.progressfunc(message)
848 return Copier().do_copy(options)
850 # error cases that need improvement:
851 # local-file-in-the-way
853 # tahoe cp -r my:docs/proposed/denver.txt proposed/denver.txt
854 # handling of unknown nodes
856 # things that maybe should be errors but aren't
857 # local-dir-in-the-way
859 # tahoe cp -r my:docs/proposed/denver.txt denver.txt
860 # (creates denver.txt/denver.txt)
862 # error cases that look good:
863 # tahoe cp -r my:docs/missing missing
865 # tahoe cp -r my:docs/missing missing -> No JSON object could be decoded
866 # tahoe-file-in-the-way (when we want to make a directory)
867 # tahoe put README my:docs
868 # tahoe cp -r docs/proposed my:docs/proposed