-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpathlibex.py
267 lines (203 loc) · 5.97 KB
/
pathlibex.py
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
from __future__ import annotations
import os
import pathlib
import re
import shutil
from typing import AnyStr, List, Optional, Tuple, Union
import magic
# ### crude pathlib.Path extension https://github.com/DeadSix27
class Path(pathlib.Path):
'''### Path
##### Path (custom extended)
'''
_flavour = pathlib._windows_flavour if os.name == 'nt' else pathlib._posix_flavour
def __new__(cls, *args):
return super(Path, cls).__new__(cls, *args)
def __init__(self, *args):
super().__init__()
self.stack: List[Path] = []
self.ssuffix = self.suffix.lstrip(".")
self._some_instance_ppath_value = self.exists()
# def ssuffix(self):
# return self.suffix.lstrip(".")
def nexists(self):
if self.exists():
return self
else:
return None
def listfiles(self, extensions=()) -> List[Path]:
'''### listfiles
##### listfiles
### Args:
`extensions` (tuple, optional): List of extensions to limit listing to, with dot prefix. Defaults to ().
### Returns:
List[Path]: List of Paths, matching the optionally specificed extension(s)
'''
lst = None
if len(extensions) > 0:
lst = [self.joinpath(x) for x in self.iterdir() if self.joinpath(x).is_file() and str(x).lower().endswith(extensions)]
else:
lst = [self.joinpath(x) for x in self.iterdir() if self.joinpath(x).is_file()]
def convert(text):
return int(text) if text.isdigit() else text
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', str(key))]
lst = sorted(lst, key=alphanum_key)
return lst
def listall(self, recursive=False) -> List[Path]:
lst = []
if all:
for r, dirs, files in os.walk(self):
for f in files:
lst.append(Path(os.path.join(r, f)))
else:
lst = [self.joinpath(x) for x in self._accessor.listdir(self)]
def convert(text):
return int(text) if text.isdigit() else text
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', str(key))]
lst = sorted(lst, key=alphanum_key)
return lst
def listdirs(self) -> List[Path]:
'''### listdirs
##### Same as listfiles, except for directories only.
### Returns:
List[Path]: List of Path's
'''
# return [self.joinpath(x) for x in self._accessor.listdir(self) if self.joinpath(x).is_dir()]
return [self.joinpath(x) for x in self.iterdir() if self.joinpath(x).is_dir()]
def copy(self, destination: Path) -> Path:
'''### copy
##### Copies the Path to the specificed destination.
### Args:
`destination` (Path): Destination to copy to.
### Returns:
Path: Path of the new copy.
'''
shutil.copy(self, destination)
return destination
@property
def disk_usage(self) -> Path:
return shutil.disk_usage(self)
def change_suffix(self, newSuffix: str) -> Path:
'''### change_name
##### Changes the name, including suffix
### Args:
`newSuffix` (str): The new suffix
### Returns:
Path: Newly named Path.
'''
return Path(self.parent.joinpath(self.stem + newSuffix))
def change_name(self, name: str) -> Path:
'''### change_name
##### Changes the name, including suffix
### Args:
`name` (str): The new name
### Returns:
Path: Newly named Path.
'''
return self.parent.joinpath(name)
def change_stem(self, new_stem: str) -> Path:
'''### append_stem
##### Changes the name, ignoring the suffix.
### Args:
`append_str` (str): String to append.
### Returns:
Path: Newly named Path.
'''
return self.parent.joinpath(new_stem + self.suffix)
'''### append_stem
##### Appends a string to the name, ignoring the suffix.
### Args:
`append_str` (str): String to append.
### Returns:
Path: Newly named Path.
'''
def append_stem(self, append_str: str) -> Path:
'''[summary]
Arguments:
append_str {str} -- [description]
Returns:
Path -- [description]
'''
return self.parent.joinpath(self.stem + append_str + self.suffix)
def prepend_name(self, prepend_str: str):
'''### prepend_name
##### Prepends a string to the name, including the suffix.
### Args:
`prepend_str` (str): String to prepend.
### Returns:
Path: Newly named Path.
'''
return Path(self.parent.joinpath(prepend_str + self.name))
def append_name(self, append_str: str):
'''### append_name
##### Appends a string to the name, including the suffix.
### Args:
`append_str` (str): String to append.
### Returns:
Path: Newly named Path.
'''
return Path(self.parent.joinpath(self.name + append_str))
def rmtree(self) -> None:
shutil.rmtree(self)
def move(self, destination: Path) -> Path:
'''### move
##### Moves the Path to a newly specified Location.
### Args:
`destination` (Path): The destination to move the file to.
### Returns:
Path: The new location of the old Path
'''
shutil.move(self, destination)
return destination
def lower(self):
return Path(str(self))
@property
def mime(self) -> str:
ext = self.suffix.lstrip(".").lower()
custom_types = {
'ttf': 'font/ttf',
'otf': 'font/otf',
}
if ext in custom_types:
return custom_types[ext]
mime = magic.Magic(mime=True)
mime = mime.from_file(str(self))
return mime
def fnmatch(self, match: str) -> bool:
cPath = self.parent
for p in cPath.listall():
if re.search(re.escape(match).replace("\\*", ".*"), p.name):
return True
return False
def executeable(self):
return self.is_file() and self.stat().st_mode & 0o100
def joinpath(self, *other):
return Path(super().joinpath(*other))
def chdir(self):
os.chdir(self)
def pushd(self):
self.stack.append(self)
self.chdir()
def createDate(self):
return self.stat().st_ctime
def modifyDate(self):
return self.stat().st_mtime
def size(self):
return self.stat().st_size
def popd(self):
if len(self.stack) == 0:
return os.getcwd()
directory = self.stack.pop()
directory.chdir()
return directory
@property
def parent(self):
"""The logical parent of the path."""
drv = self._drv
root = self._root
parts = self._parts
if len(parts) == 1 and (drv or root):
return self
return self._from_parsed_parts(drv, root, parts[:-1])