comparison planemo/lib/python3.7/site-packages/virtualenv/util/path/_sync.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 from __future__ import absolute_import, unicode_literals
2
3 import logging
4 import os
5 import shutil
6 from stat import S_IWUSR
7
8 from six import PY2
9
10 from virtualenv.info import IS_CPYTHON, IS_WIN
11 from virtualenv.util.six import ensure_text
12
13 if PY2 and IS_CPYTHON and IS_WIN: # CPython2 on Windows supports unicode paths if passed as unicode
14
15 def norm(src):
16 return ensure_text(str(src))
17
18
19 else:
20 norm = str
21
22
23 def ensure_dir(path):
24 if not path.exists():
25 logging.debug("create folder %s", ensure_text(str(path)))
26 os.makedirs(norm(path))
27
28
29 def ensure_safe_to_do(src, dest):
30 if src == dest:
31 raise ValueError("source and destination is the same {}".format(src))
32 if not dest.exists():
33 return
34 if dest.is_dir() and not dest.is_symlink():
35 logging.debug("remove directory %s", dest)
36 safe_delete(dest)
37 else:
38 logging.debug("remove file %s", dest)
39 dest.unlink()
40
41
42 def symlink(src, dest):
43 ensure_safe_to_do(src, dest)
44 logging.debug("symlink %s", _Debug(src, dest))
45 dest.symlink_to(src, target_is_directory=src.is_dir())
46
47
48 def copy(src, dest):
49 ensure_safe_to_do(src, dest)
50 is_dir = src.is_dir()
51 method = copytree if is_dir else shutil.copy
52 logging.debug("copy %s", _Debug(src, dest))
53 method(norm(src), norm(dest))
54
55
56 def copytree(src, dest):
57 for root, _, files in os.walk(src):
58 dest_dir = os.path.join(dest, os.path.relpath(root, src))
59 if not os.path.exists(dest_dir):
60 os.makedirs(dest_dir)
61 for name in files:
62 src_f = os.path.join(root, name)
63 dest_f = os.path.join(dest_dir, name)
64 shutil.copy(src_f, dest_f)
65
66
67 def safe_delete(dest):
68 def onerror(func, path, exc_info):
69 if not os.access(path, os.W_OK):
70 os.chmod(path, S_IWUSR)
71 func(path)
72 else:
73 raise
74
75 shutil.rmtree(ensure_text(str(dest)), ignore_errors=True, onerror=onerror)
76
77
78 class _Debug(object):
79 def __init__(self, src, dest):
80 self.src = src
81 self.dest = dest
82
83 def __str__(self):
84 return "{}{} to {}".format(
85 "directory " if self.src.is_dir() else "", ensure_text(str(self.src)), ensure_text(str(self.dest)),
86 )
87
88
89 __all__ = (
90 "ensure_dir",
91 "symlink",
92 "copy",
93 "symlink",
94 "copytree",
95 "safe_delete",
96 )