Completed
Push — master ( c8d5b2...ff259f )
by Bjorn
01:41
created

Path.curdir()   A

Complexity

Conditions 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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