Completed
Push — master ( fab5c0...2ffa8b )
by Bjorn
01:35
created

Path.rm()   A

Complexity

Conditions 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
1
# -*- coding: utf-8 -*-
2
"""Poor man's pathlib.
3
4
   (Path instances are subclasses of str, so interoperability with existing
5
   os.path code is greater than with Python 3's pathlib.)
6
"""
7
# pylint:disable=C0111,R0904
8
# R0904: too many public methods in Path
9
import os
10
import re
11
from contextlib import contextmanager
12
import shutil
13
14
15
def doc(srcfn):
16
    def decorator(fn):
17
        fn.__doc__ = srcfn.__doc__.replace(srcfn.__name__, fn.__name__)
18
        return fn
19
    return decorator
20
21
22
class Path(str):
23
    """Poor man's pathlib.
24
    """
25
26
    def __div__(self, other):
27
        return Path(
28
            os.path.normcase(
29
                os.path.normpath(
30
                    os.path.join(self, other)
31
                )
32
            )
33
        )
34
35
    @doc(os.unlink)
36
    def unlink(self):
37
        os.unlink(self)
38
39
    def open(self, mode='r'):
40
        return open(self, mode)
41
42
    def read(self, mode='r'):
43
        with self.open(mode) as fp:
44
            return fp.read()
45
46
    def __iter__(self):
47
        for root, dirs, files in os.walk(self):
48
            dotdirs = [d for d in dirs if d.startswith('.')]
49
            for d in dotdirs:
50
                dirs.remove(d)
51
            dotfiles = [d for d in files if d.startswith('.')]
52
            for d in dotfiles:
53
                files.remove(d)
54
            for fname in files:
55
                yield Path(os.path.join(root, fname))
56
57
    def __contains__(self, item):
58
        if self.isdir():
59
            return item in self.listdir()
60
        super(Path, self).__contains__(item)
61
62
    @doc(shutil.rmtree)
63
    def rmtree(self, subdir=None):
64
        if subdir is not None:
65
            shutil.rmtree(self / subdir, ignore_errors=True)
66
        else:
67
            shutil.rmtree(self, ignore_errors=True)
68
69
    def contents(self):
70
        res = [d.relpath(self) for d in self.glob('**/*')]
71
        res.sort()
72
        return res
73
74
    @classmethod
75
    def curdir(cls):
76
        """Initialize a Path object on the current directory.
77
        """
78
        return cls(os.getcwd())
79
80
    def touch(self, mode=0o666, exist_ok=True):
81
        """Create this file with the given access mode, if it doesn't exist.
82
           (based on https://github.com/python/cpython/blob/master/Lib/pathlib.py)
83
        """
84
        if exist_ok:
85
            # First try to bump modification time
86
            # Implementation note: GNU touch uses the UTIME_NOW option of
87
            # the utimensat() / futimens() functions.
88
            try:
89
                os.utime(self, None)
90
            except OSError:
91
                # Avoid exception chaining
92
                pass
93
            else:
94
                return
95
        flags = os.O_CREAT | os.O_WRONLY
96
        if not exist_ok:
97
            flags |= os.O_EXCL
98
        fd = os.open(self, flags, mode)
99
        os.close(fd)
100
101
    def glob(self, pat):
102
        """`pat` can be an extended glob pattern, e.g. `'**/*.less'`
103
           This code handles negations similarly to node.js' minimatch, i.e.
104
           a leading `!` will negate the entire pattern.
105
        """
106
        r = ""
107
        negate = int(pat.startswith('!'))
108
        i = negate
109
110
        while i < len(pat):
111
            if pat[i:i + 3] == '**/':
112
                r += "(?:.*/)?"
113
                i += 3
114
            elif pat[i] == "*":
115
                r += "[^/]*"
116
                i += 1
117
            elif pat[i] == ".":
118
                r += "[.]"
119
                i += 1
120
            elif pat[i] == "?":
121
                r += "."
122
                i += 1
123
            else:
124
                r += pat[i]
125
                i += 1
126
        r += r'\Z(?ms)'
127
        # print '\n\npat', pat
128
        # print 'regex:', r
129
        # print [s.relpath(self).replace('\\', '/') for s in self]
130
        rx = re.compile(r)
131
132
        def match(d):
133
            m = rx.match(d)
134
            return not m if negate else m
135
136
        return [s for s in self if match(s.relpath(self).replace('\\', '/'))]
137
138
    @doc(os.path.abspath)
139
    def abspath(self):
140
        return Path(os.path.abspath(self))
141
    absolute = abspath  # pathlib
142
143
    def drive(self):
144
        """Return the drive of `self`.
145
        """
146
        return self.splitdrive()[0]
147
148
    def drivepath(self):
149
        """The path local to this drive (i.e. remove drive letter).
150
        """
151
        return self.splitdrive()[1]
152
153
    @doc(os.path.basename)
154
    def basename(self):
155
        return Path(os.path.basename(self))
156
157
    @doc(os.path.commonprefix)
158
    def commonprefix(self, *args):
159
        return os.path.commonprefix([str(self)] + [str(a) for a in args])
160
161
    @doc(os.path.dirname)
162
    def dirname(self):
163
        return Path(os.path.dirname(self))
164
165
    @doc(os.path.exists)
166
    def exists(self):
167
        return os.path.exists(self)
168
169
    @doc(os.path.expanduser)
170
    def expanduser(self):
171
        return Path(os.path.expanduser(self))
172
173
    @doc(os.path.expandvars)
174
    def expandvars(self):
175
        return Path(os.path.expandvars(self))
176
177
    @doc(os.path.getatime)
178
    def getatime(self):
179
        return os.path.getatime(self)
180
181
    @doc(os.path.getctime)
182
    def getctime(self):
183
        return os.path.getctime(self)
184
185
    @doc(os.path.getmtime)
186
    def getmtime(self):
187
        return os.path.getmtime(self)
188
189
    @doc(os.path.getsize)
190
    def getsize(self):
191
        return os.path.getsize(self)
192
193
    @doc(os.path.isabs)
194
    def isabs(self):
195
        return os.path.isabs(self)
196
197
    @doc(os.path.isdir)
198
    def isdir(self, *args, **kw):
199
        return os.path.isdir(self, *args, **kw)
200
201
    @doc(os.path.isfile)
202
    def isfile(self):
203
        return os.path.isfile(self)
204
205
    @doc(os.path.islink)
206
    def islink(self):
207
        return os.path.islink(self)
208
209
    @doc(os.path.ismount)
210
    def ismount(self):
211
        return os.path.ismount(self)
212
213
    @doc(os.path.join)
214
    def join(self, *args):
215
        return Path(os.path.join(self, *args))
216
217
    @doc(os.path.lexists)
218
    def lexists(self):
219
        return os.path.lexists(self)
220
221
    @doc(os.path.normcase)
222
    def normcase(self):
223
        return Path(os.path.normcase(self))
224
225
    @doc(os.path.normpath)
226
    def normpath(self):
227
        return Path(os.path.normpath(str(self)))
228
229
    @doc(os.path.realpath)
230
    def realpath(self):
231
        return Path(os.path.realpath(self))
232
233
    @doc(os.path.relpath)
234
    def relpath(self, other=""):
235
        return Path(os.path.relpath(str(self), str(other)))
236
237
    @doc(os.path.split)
238
    def split(self, sep=None, maxsplit=-1):
239
        # some heuristics to determine if this is a str.split call or
240
        # a os.split call...
241
        sval = str(self)
242
        if sep is not None or ' ' in sval:
243
            return sval.split(sep or ' ', maxsplit)
244
        return os.path.split(self)
245
246
    def parts(self):
247
        res = re.split(r"\\|/", self)
248
        if res and os.path.splitdrive(res[0]) == (res[0], ''):
249
            res[0] += os.path.sep
250
        return res
251
252
    def parent_iter(self):
253
        parts = self.abspath().normpath().normcase().parts()
254
        for i in range(1, len(parts)):
255
            yield Path(os.path.join(*parts[:-i]))
256
257
    @property
258
    def parents(self):
259
        return list(self.parent_iter())
260
261
    @property
262
    def parent(self):
263
        return self.parents[0]
264
265
    @doc(os.path.splitdrive)
266
    def splitdrive(self):
267
        drive, pth = os.path.splitdrive(self)
268
        return drive, Path(pth)
269
270
    @doc(os.path.splitext)
271
    def splitext(self):
272
        return os.path.splitext(self)
273
274
    @property
275
    def ext(self):
276
        return self.splitext()[1]
277
278
    if hasattr(os.path, 'splitunc'):  # pragma: nocover
279
        @doc(os.path.splitunc)
280
        def splitunc(self):
281
            return os.path.splitunc(self)
282
283
    @doc(os.access)
284
    def access(self, *args, **kw):
285
        return os.access(self, *args, **kw)
286
287
    @doc(os.chdir)
288
    def chdir(self):
289
        return os.chdir(self)
290
291
    @contextmanager
292
    def cd(self):
293
        cwd = os.getcwd()
294
        try:
295
            self.chdir()
296
            yield self
297
        finally:
298
            os.chdir(cwd)
299
300
    @doc(os.chmod)
301
    def chmod(self, *args, **kw):
302
        return os.chmod(self, *args, **kw)
303
304
    @doc(os.listdir)
305
    def listdir(self):
306
        return [Path(p) for p in os.listdir(self)]
307
308
    def list(self, filterfn=lambda x: True):
309
        """Return all direct descendands of directory `self` for which
310
           `filterfn` returns True.
311
        """
312
        return [self / p for p in self.listdir() if filterfn(self / p)]
313
314
    def subdirs(self):
315
        """Return all direct sub-directories.
316
        """
317
        return self.list(lambda p: p.isdir())
318
319
    def files(self):
320
        """Return all files in directory.
321
        """
322
        return self.list(lambda p: p.isfile())
323
324
    @doc(os.lstat)
325
    def lstat(self):
326
        return os.lstat(self)
327
328
    @doc(os.makedirs)
329
    def makedirs(self, path=None, mode=0777):
330
        pth = os.path.join(self, path) if path else self
331
        try:
332
            os.makedirs(pth, mode)
333
        except OSError:
334
            pass
335
        return Path(pth)
336
337
    @doc(os.mkdir)
338
    def mkdir(self, path, mode=0777):
339
        pth = os.path.join(self, path)
340
        os.mkdir(pth, mode)
341
        return Path(pth)
342
343
    @doc(os.remove)
344
    def remove(self):
345
        return os.remove(self)
346
347
    def rm(self, fname=None):
348
        "Remove a file, don't raise exception if file does not exist."
349
        if fname is not None:
350
            return (self / fname).rm()
351
        try:
352
            self.remove()
353
        except OSError:
354
            pass
355
356
    @doc(os.removedirs)
357
    def removedirs(self):
358
        return os.removedirs(self)
359
360
    @doc(os.rename)
361
    def rename(self, *args, **kw):
362
        return os.rename(self, *args, **kw)
363
364
    @doc(os.renames)
365
    def renames(self, *args, **kw):
366
        return os.renames(self, *args, **kw)
367
368
    @doc(os.rmdir)
369
    def rmdir(self):
370
        return os.rmdir(self)
371
372
    if hasattr(os, 'startfile'):  # pragma: nocover
373
        @doc(os.startfile)
374
        def startfile(self, *args, **kw):
375
            return os.startfile(self, *args, **kw)
376
377
    @doc(os.stat)
378
    def stat(self, *args, **kw):
379
        return os.stat(self, *args, **kw)
380
381
    @doc(os.utime)
382
    def utime(self, time=None):
383
        os.utime(self, time)
384
        return self.stat()
385
386
    def __add__(self, other):
387
        return Path(str(self) + str(other))
388
389
390
@contextmanager
391
def cd(pth):
392
    cwd = os.getcwd()
393
    try:
394
        os.chdir(pth)
395
        yield
396
    finally:
397
        os.chdir(cwd)
398