1 | """ |
---|
2 | A path/directory class. |
---|
3 | """ |
---|
4 | |
---|
5 | import os |
---|
6 | import shutil |
---|
7 | |
---|
8 | from migrate.versioning import exceptions |
---|
9 | from migrate.versioning.base import * |
---|
10 | from migrate.versioning.util import KeyedInstance |
---|
11 | |
---|
12 | |
---|
13 | class Pathed(KeyedInstance): |
---|
14 | """ |
---|
15 | A class associated with a path/directory tree. |
---|
16 | |
---|
17 | Only one instance of this class may exist for a particular file; |
---|
18 | __new__ will return an existing instance if possible |
---|
19 | """ |
---|
20 | parent = None |
---|
21 | |
---|
22 | @classmethod |
---|
23 | def _key(cls, path): |
---|
24 | return str(path) |
---|
25 | |
---|
26 | def __init__(self, path): |
---|
27 | self.path = path |
---|
28 | if self.__class__.parent is not None: |
---|
29 | self._init_parent(path) |
---|
30 | |
---|
31 | def _init_parent(self, path): |
---|
32 | """Try to initialize this object's parent, if it has one""" |
---|
33 | parent_path = self.__class__._parent_path(path) |
---|
34 | self.parent = self.__class__.parent(parent_path) |
---|
35 | log.info("Getting parent %r:%r" % (self.__class__.parent, parent_path)) |
---|
36 | self.parent._init_child(path, self) |
---|
37 | |
---|
38 | def _init_child(self, child, path): |
---|
39 | """Run when a child of this object is initialized. |
---|
40 | |
---|
41 | Parameters: the child object; the path to this object (its |
---|
42 | parent) |
---|
43 | """ |
---|
44 | |
---|
45 | @classmethod |
---|
46 | def _parent_path(cls, path): |
---|
47 | """ |
---|
48 | Fetch the path of this object's parent from this object's path. |
---|
49 | """ |
---|
50 | # os.path.dirname(), but strip directories like files (like |
---|
51 | # unix basename) |
---|
52 | # |
---|
53 | # Treat directories like files... |
---|
54 | if path[-1] == '/': |
---|
55 | path=path[:-1] |
---|
56 | ret = os.path.dirname(path) |
---|
57 | return ret |
---|
58 | |
---|
59 | @classmethod |
---|
60 | def require_notfound(cls, path): |
---|
61 | """Ensures a given path does not already exist""" |
---|
62 | if os.path.exists(path): |
---|
63 | raise exceptions.PathFoundError(path) |
---|
64 | |
---|
65 | @classmethod |
---|
66 | def require_found(cls, path): |
---|
67 | """Ensures a given path already exists""" |
---|
68 | if not os.path.exists(path): |
---|
69 | raise exceptions.PathNotFoundError(path) |
---|
70 | |
---|
71 | def __str__(self): |
---|
72 | return self.path |
---|