Completed
Push — master ( c3dae1...b09cff )
by Bjorn
01:05
created

Path.parents()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 3
rs 10
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 __iter__(self):
43
        for root, dirs, files in os.walk(self):
44
            dotdirs = [d for d in dirs if d.startswith('.')]
45
            for d in dotdirs:
46
                dirs.remove(d)
47
            dotfiles = [d for d in files if d.startswith('.')]
48
            for d in dotfiles:
49
                files.remove(d)
50
            for fname in files:
51
                yield Path(os.path.join(root, fname))
52
53
    def __contains__(self, item):
54
        if self.isdir():
55
            return item in self.listdir()
56
        super(Path, self).__contains__(item)
57
58
    @doc(shutil.rmtree)
59
    def rmtree(self, subdir=None):
60
        if subdir is not None:
61
            shutil.rmtree(self / subdir)
62
        else:
63
            shutil.rmtree(self)
64
65
    def contents(self):
66
        return [d.relpath(self) for d in self.glob('**/*')]
67
68
    def glob(self, pat):
69
        """`pat` can be an extended glob pattern, e.g. `'**/*.less'`
70
           This code handles negations similarly to node.js' minimatch, i.e.
71
           a leading `!` will negate the entire pattern.
72
        """
73
        r = ""
74
        negate = int(pat.startswith('!'))
75
        i = negate
76
77
        while i < len(pat):
78
            if pat[i:i + 3] == '**/':
79
                r += "(?:.*/)?"
80
                i += 3
81
            elif pat[i] == "*":
82
                r += "[^/]*"
83
                i += 1
84
            elif pat[i] == ".":
85
                r += "[.]"
86
                i += 1
87
            elif pat[i] == "?":
88
                r += "."
89
                i += 1
90
            else:
91
                r += pat[i]
92
                i += 1
93
        r += r'\Z(?ms)'
94
        # print '\n\npat', pat
95
        # print 'regex:', r
96
        # print [s.relpath(self).replace('\\', '/') for s in self]
97
        rx = re.compile(r)
98
99
        def match(d):
100
            m = rx.match(d)
101
            return not m if negate else m
102
103
        return [s for s in self if match(s.relpath(self).replace('\\', '/'))]
104
105
    @doc(os.path.abspath)
106
    def abspath(self):
107
        return Path(os.path.abspath(self))
108
    absolute = abspath  # pathlib
109
110
    def drive(self):
111
        """Return the drive of `self`.
112
        """
113
        return self.splitdrive()[0]
114
115
    def drivepath(self):
116
        """The path local to this drive (i.e. remove drive letter).
117
        """
118
        return self.splitdrive()[1]
119
120
    @doc(os.path.basename)
121
    def basename(self):
122
        return Path(os.path.basename(self))
123
124
    @doc(os.path.commonprefix)
125
    def commonprefix(self, *args):
126
        return os.path.commonprefix([str(self)] + [str(a) for a in args])
127
128
    @doc(os.path.dirname)
129
    def dirname(self):
130
        return Path(os.path.dirname(self))
131
132
    @doc(os.path.exists)
133
    def exists(self):
134
        return os.path.exists(self)
135
136
    @doc(os.path.expanduser)
137
    def expanduser(self):
138
        return Path(os.path.expanduser(self))
139
140
    @doc(os.path.expandvars)
141
    def expandvars(self):
142
        return Path(os.path.expandvars(self))
143
144
    @doc(os.path.getatime)
145
    def getatime(self):
146
        return os.path.getatime(self)
147
148
    @doc(os.path.getctime)
149
    def getctime(self):
150
        return os.path.getctime(self)
151
152
    @doc(os.path.getmtime)
153
    def getmtime(self):
154
        return os.path.getmtime(self)
155
156
    @doc(os.path.getsize)
157
    def getsize(self):
158
        return os.path.getsize(self)
159
160
    @doc(os.path.isabs)
161
    def isabs(self):
162
        return os.path.isabs(self)
163
164
    @doc(os.path.isdir)
165
    def isdir(self, *args, **kw):
166
        return os.path.isdir(self, *args, **kw)
167
168
    @doc(os.path.isfile)
169
    def isfile(self):
170
        return os.path.isfile(self)
171
172
    @doc(os.path.islink)
173
    def islink(self):
174
        return os.path.islink(self)
175
176
    @doc(os.path.ismount)
177
    def ismount(self):
178
        return os.path.ismount(self)
179
180
    @doc(os.path.join)
181
    def join(self, *args):
182
        return Path(os.path.join(self, *args))
183
184
    @doc(os.path.lexists)
185
    def lexists(self):
186
        return os.path.lexists(self)
187
188
    @doc(os.path.normcase)
189
    def normcase(self):
190
        return Path(os.path.normcase(self))
191
192
    @doc(os.path.normpath)
193
    def normpath(self):
194
        return Path(os.path.normpath(str(self)))
195
196
    @doc(os.path.realpath)
197
    def realpath(self):
198
        return Path(os.path.realpath(self))
199
200
    @doc(os.path.relpath)
201
    def relpath(self, other=""):
202
        return Path(os.path.relpath(str(self), str(other)))
203
204
    @doc(os.path.split)
205
    def split(self, sep=None, maxsplit=-1):
206
        # some heuristics to determine if this is a str.split call or
207
        # a os.split call...
208
        sval = str(self)
209
        if sep is not None or ' ' in sval:
210
            return sval.split(sep or ' ', maxsplit)
211
        return os.path.split(self)
212
213
    def parts(self):
214
        res = re.split(r"\\|/", self)
215
        if res and os.path.splitdrive(res[0]) == (res[0], ''):
216
            res[0] += os.path.sep
217
        return res
218
219
    def parent_iter(self):
220
        parts = self.abspath().normpath().normcase().parts()
221
        for i in range(1, len(parts)):
222
            yield Path(os.path.join(*parts[:-i]))
223
224
    @property
225
    def parents(self):
226
        return list(self.parent_iter())
227
228
    @property
229
    def parent(self):
230
        return self.parents[0]
231
232
    @doc(os.path.splitdrive)
233
    def splitdrive(self):
234
        drive, pth = os.path.splitdrive(self)
235
        return drive, Path(pth)
236
237
    @doc(os.path.splitext)
238
    def splitext(self):
239
        return os.path.splitext(self)
240
241
    @property
242
    def ext(self):
243
        return self.splitext()[1]
244
245
    if hasattr(os.path, 'splitunc'):  # pragma: nocover
246
        @doc(os.path.splitunc)
247
        def splitunc(self):
248
            return os.path.splitunc(self)
249
250
    @doc(os.access)
251
    def access(self, *args, **kw):
252
        return os.access(self, *args, **kw)
253
254
    @doc(os.chdir)
255
    def chdir(self):
256
        return os.chdir(self)
257
258
    @contextmanager
259
    def cd(self):
260
        cwd = os.getcwd()
261
        try:
262
            self.chdir()
263
            yield self
264
        finally:
265
            os.chdir(cwd)
266
267
    @doc(os.chmod)
268
    def chmod(self, *args, **kw):
269
        return os.chmod(self, *args, **kw)
270
271
    @doc(os.listdir)
272
    def listdir(self):
273
        return [Path(p) for p in os.listdir(self)]
274
275
    def list(self, filterfn=lambda x: True):
276
        """Return all direct descendands of directory `self` for which
277
           `filterfn` returns True.
278
        """
279
        return [self / p for p in self.listdir() if filterfn(self / p)]
280
281
    def subdirs(self):
282
        """Return all direct sub-directories.
283
        """
284
        return self.list(lambda p: p.isdir())
285
286
    def files(self):
287
        """Return all files in directory.
288
        """
289
        return self.list(lambda p: p.isfile())
290
291
    @doc(os.lstat)
292
    def lstat(self):
293
        return os.lstat(self)
294
295
    @doc(os.makedirs)
296
    def makedirs(self, path=None, mode=0777):
297
        pth = os.path.join(self, path) if path else self
298
        try:
299
            os.makedirs(pth, mode)
300
        except OSError:
301
            pass
302
        return Path(pth)
303
304
    @doc(os.mkdir)
305
    def mkdir(self, path, mode=0777):
306
        pth = os.path.join(self, path)
307
        os.mkdir(pth, mode)
308
        return Path(pth)
309
310
    @doc(os.remove)
311
    def remove(self):
312
        return os.remove(self)
313
314
    @doc(os.removedirs)
315
    def removedirs(self):
316
        return os.removedirs(self)
317
318
    @doc(os.rename)
319
    def rename(self, *args, **kw):
320
        return os.rename(self, *args, **kw)
321
322
    @doc(os.renames)
323
    def renames(self, *args, **kw):
324
        return os.renames(self, *args, **kw)
325
326
    @doc(os.rmdir)
327
    def rmdir(self):
328
        return os.rmdir(self)
329
330
    if hasattr(os, 'startfile'):  # pragma: nocover
331
        @doc(os.startfile)
332
        def startfile(self, *args, **kw):
333
            return os.startfile(self, *args, **kw)
334
335
    @doc(os.stat)
336
    def stat(self, *args, **kw):
337
        return os.stat(self, *args, **kw)
338
339
    @doc(os.utime)
340
    def utime(self, time=None):
341
        os.utime(self, time)
342
        return self.stat()
343
344
    def __add__(self, other):
345
        return Path(str(self) + str(other))
346