File: path.py

package info (click to toggle)
codeville 0.8.0-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 1,148 kB
  • ctags: 1,088
  • sloc: python: 10,335; ansic: 89; sh: 62; makefile: 25
file content (57 lines) | stat: -rw-r--r-- 1,469 bytes parent folder | download | duplicates (5)
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
# Written by Ross Cohen
# see LICENSE.txt for license information

import os

def preserving_rename(src, dest):
    # preserve whatever permissions the user set
    try:
        statinfo = os.stat(dest)
        os.chmod(src, statinfo.st_mode)
        # windows doesn't allow atomic renames to overwrite
        os.remove(dest)
    except OSError:
        # file may be missing from the filesystem
        pass
    os.rename(src, dest)
    return

def mdir(d):
    try:
        os.makedirs(d)
    except OSError:
        pass

def abspath(rel_path):
    "Because os.path.abspath on Windows drops '...'"
    parent_path, filename = os.path.split(rel_path)
    if filename == '...':
        return os.path.join(os.path.abspath(parent_path), filename)
    return os.path.abspath(rel_path)

def subpath(local, file):
    llocal = breakup(os.path.abspath(local))
    lfile = breakup(abspath(file))
    if lfile[:len(llocal)] != llocal:
        raise ValueError
    fname = ''
    for d in lfile[len(llocal):]:
        fname = os.path.join(fname, d)
    return (lfile, fname)

def breakup(s):
    def _breakup(s):
        if s == '':
            return []
        a, b = os.path.split(s)
        return _breakup(a) + [b]

    drive, s = os.path.splitdrive(s)
    bdrive, bsep = [], []
    if drive != '':
        bdrive = [drive]
        bsep   = [os.sep]
    if s.startswith(os.sep):
        bsep = [os.sep]
        s = s[len(os.sep):]
    return bdrive + bsep + _breakup(s)