forked from python/pymanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathutils.py
More file actions
246 lines (199 loc) · 7 KB
/
pathutils.py
File metadata and controls
246 lines (199 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Minimal reimplementations of Path and PurePath.
This is primarily focused on avoiding the expensive imports that come with
pathlib for functionality that we don't need. This module now gets loaded on
every Python launch through PyManager
"""
import os
def _eq(x, y):
return x == y or x.casefold() == y.casefold()
class PurePath:
def __init__(self, *parts):
total = ""
for p in parts:
try:
p = p.__fspath__().replace("/", "\\")
except AttributeError:
p = os.fsdecode(p).replace("/", "\\")
p = p.replace("\\\\", "\\")
if p == ".":
continue
if p.startswith(".\\"):
p = p[2:]
if total:
total += "\\" + p
else:
total += p
drive, root, tail = os.path.splitroot(total)
parent, _, name = tail.rpartition("\\")
self._parent = drive + root + parent
self.name = name
self._p = drive + root + tail.rstrip("\\")
def __fspath__(self):
return self._p
def __repr__(self):
return self._p
def __str__(self):
return self._p
def __bytes__(self):
return os.fsencode(self)
def __hash__(self):
return hash(self._p.casefold())
def __bool__(self):
return bool(self._p)
@property
def stem(self):
stem, dot, suffix = self.name.rpartition(".")
if not dot:
return suffix
return stem
@property
def suffix(self):
stem, dot, suffix = self.name.rpartition(".")
if not dot:
return ""
return dot + suffix
@property
def parent(self):
return type(self)(self._parent)
@property
def parts(self):
drive, root, tail = os.path.splitroot(self._p)
bits = []
if drive or root:
bits.append(drive + root)
if tail:
bits.extend(tail.split("\\"))
while "." in bits:
bits.remove(".")
while ".." in bits:
i = bits.index("..")
bits.pop(i)
bits.pop(i - 1)
return bits
def __truediv__(self, other):
other = str(other)
# Quick hack to hide leading ".\" on paths. We don't fully normalise
# here because it can change the meaning of paths.
while other.startswith(("./", ".\\")):
other = other[2:]
return type(self)(os.path.join(self._p, other))
def __eq__(self, other):
if isinstance(other, PurePath):
return _eq(self._p, other._p)
return _eq(self._p == str(other))
def __ne__(self, other):
if isinstance(other, PurePath):
return not _eq(self._p, other._p)
return not _eq(self._p, str(other))
def with_name(self, name):
return type(self)(os.path.join(self._parent, name))
def with_suffix(self, suffix):
if suffix and suffix[:1] != ".":
suffix = f".{suffix}"
return type(self)(os.path.join(self._parent, self.stem + suffix))
def relative_to(self, base):
base = PurePath(base).parts
parts = self.parts
if not all(_eq(x, y) for x, y in zip(base, parts)):
raise ValueError("path not relative to base")
return type(self)("\\".join(parts[len(base):]))
def as_uri(self):
drive, root, tail = os.path.splitroot(self._p)
if drive[1:2] == ":" and root:
return "file:///" + self._p.replace("\\", "/")
if drive[:2] == "\\\\":
return "file:" + self._p.replace("\\", "/")
return "file://" + self._p.replace("\\", "/")
def full_match(self, pattern):
return self.match(pattern, full_match=True)
def match(self, pattern, full_match=False):
p = str(pattern).casefold().replace("/", "\\")
assert "?" not in p
m = self._p if full_match or "\\" in p else self.name
m = m.casefold()
if "*" not in p:
return m == p or m.casefold() == p
must_start_with = True
for bit in p.split("*"):
if bit:
try:
i = m.index(bit)
except ValueError:
return False
if must_start_with and i != 0:
return False
m = m[i + len(bit):]
must_start_with = False
return not m or p.endswith("*")
class Path(PurePath):
@classmethod
def cwd(cls):
return cls(os.getcwd())
def absolute(self):
return Path.cwd() / self
def exists(self):
return os.path.exists(self._p)
def is_dir(self):
return os.path.isdir(self._p)
def is_file(self):
return os.path.isfile(self._p)
def iterdir(self):
try:
return (self / n for n in os.listdir(self._p))
except FileNotFoundError:
return ()
def glob(self, pattern):
return (f for f in self.iterdir() if f.match(pattern))
def lstat(self):
return os.lstat(self._p)
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
try:
os.mkdir(self._p, mode)
except FileNotFoundError:
if not parents or self.parent == self:
raise
self.parent.mkdir(parents=True, exist_ok=True)
self.mkdir(mode, parents=False, exist_ok=exist_ok)
except OSError:
# Cannot rely on checking for EEXIST, since the operating system
# could give priority to other errors like EACCES or EROFS
if not exist_ok or not self.is_dir():
raise
def rename(self, new_name):
os.rename(self._p, new_name)
return self.parent / PurePath(new_name)
def rmdir(self):
os.rmdir(self._p)
def unlink(self):
os.unlink(self._p)
def open(self, mode="r", encoding=None, errors=None):
if "b" in mode:
return open(self._p, mode)
if not encoding:
encoding = "utf-8-sig" if "r" in mode else "utf-8"
return open(self._p, mode, encoding=encoding, errors=errors or "strict")
def read_bytes(self):
with open(self._p, "rb") as f:
return f.read()
def read_text(self, encoding="utf-8-sig", errors="strict"):
with open(self._p, "r", encoding=encoding, errors=errors) as f:
return f.read()
def write_bytes(self, data):
with open(self._p, "wb") as f:
f.write(data)
def write_text(self, text, encoding="utf-8", errors="strict"):
with open(self._p, "w", encoding=encoding, errors=errors) as f:
f.write(text)
def relative_to(path, root):
if not root:
return path
parts_1 = list(PurePath(path).parts)
parts_2 = list(PurePath(root).parts)
while parts_1 and parts_2 and _eq(parts_1[0], parts_2[0]):
parts_1.pop(0)
parts_2.pop(0)
if parts_1 and not parts_2:
if isinstance(path, PurePath):
return type(path)(*parts_1)
return type(path)(PurePath(*parts_1))
return path