File: urn.py

package info (click to toggle)
python-webdavclient 3.14.6-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 644 kB
  • sloc: python: 2,241; xml: 535; makefile: 5; sh: 3
file content (59 lines) | stat: -rw-r--r-- 1,917 bytes parent folder | download | duplicates (2)
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
from re import sub
from urllib.parse import unquote, quote, urlsplit


class Urn(object):
    separate = "/"

    def __init__(self, path, directory=False):

        self._path = quote(path)
        expressions = (r"/\.+/", "/+")
        for expression in expressions:
            self._path = sub(expression, Urn.separate, self._path)

        if not self._path.startswith(Urn.separate):
            self._path = "{begin}{end}".format(begin=Urn.separate, end=self._path)

        if directory and not self._path.endswith(Urn.separate):
            self._path = "{begin}{end}".format(begin=self._path, end=Urn.separate)

    def __str__(self):
        return self.path()

    def path(self):
        return unquote(self._path)

    def quote(self):
        return self._path

    def filename(self):
        path_split = self._path.split(Urn.separate)
        name = path_split[-2] + Urn.separate if path_split[-1] == '' else path_split[-1]
        return unquote(name)

    def parent(self):
        path_split = self._path.split(Urn.separate)
        nesting_level = self.nesting_level()
        parent_path_split = path_split[:nesting_level]
        parent = self.separate.join(parent_path_split) if nesting_level != 1 else Urn.separate
        if not parent.endswith(Urn.separate):
            return unquote(parent + Urn.separate)
        else:
            return unquote(parent)

    def nesting_level(self):
        return self._path.count(Urn.separate, 0, -1)

    def is_dir(self):
        return self._path[-1] == Urn.separate

    @staticmethod
    def normalize_path(path):
        result = sub('/{2,}', '/', path)
        return result if len(result) < 1 or result[-1] != Urn.separate else result[:-1]

    @staticmethod
    def compare_path(path_a, href):
        unqouted_path = Urn.separate + unquote(urlsplit(href).path)
        return Urn.normalize_path(path_a) == Urn.normalize_path(unqouted_path)