aboutsummaryrefslogtreecommitdiffstats
path: root/dotfiles/repository.py
blob: 9197c2ade04c80e23306b1a3ce0ea8cf4c0c03b3 (plain) (blame)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import os

from click import echo
from pathlib import Path
from fnmatch import fnmatch
from operator import attrgetter

from .dotfile import Dotfile
from .exceptions import DotfileException, TargetIgnored
from .exceptions import NotRootedInHome, InRepository, IsDirectory

PATH = '~/Dotfiles'
HOMEDIR = Path.home()
REMOVE_LEADING_DOT = True
IGNORE_PATTERNS = ['.git', '.gitignore', 'README*', '*~']


class Repositories(object):
    """An iterable collection of repository objects."""

    def __init__(self, paths, dot):
        if not paths:
            paths = [PATH]
        if dot is None:
            dot = REMOVE_LEADING_DOT

        self.repos = []
        for path in paths:
            self.repos.append(Repository(path, remove_leading_dot=dot))

    def __len__(self):
        return len(self.repos)

    def __getitem__(self, index):
        return self.repos[index]


class Repository(object):
    """A repository is a directory that contains dotfiles.

    :param path: the location of the repository directory
    :param homedir: the location of the home directory
    :param remove_leading_dot: whether to remove the target's leading dot
    :param ignore_patterns: a list of glob patterns to ignore
    """

    def __init__(self, path,
                 homedir=HOMEDIR,
                 remove_leading_dot=REMOVE_LEADING_DOT,
                 ignore_patterns=IGNORE_PATTERNS):
        self.path = Path(path).expanduser()
        self.homedir = Path(homedir)
        self.remove_leading_dot = remove_leading_dot
        self.ignore_patterns = ignore_patterns

        # create repository directory if missing
        self.path.mkdir(parents=True, exist_ok=True)

    def __str__(self):
        """Return human-readable repository contents."""
        return ''.join('%s\n' % x for x in self.contents()).rstrip()

    def __repr__(self):
        return '<Repository %r>' % str(self.path)

    def _ignore(self, path):
        for pattern in self.ignore_patterns:
            if fnmatch(path, '*/%s' % pattern):
                return True
        return False

    def _dotfile_path(self, target):
        """Return the expected symlink for the given repository target."""

        relpath = target.relative_to(self.path)
        if self.remove_leading_dot:
            return self.homedir / ('.%s' % relpath)
        else:
            return self.homedir / relpath

    def _dotfile_target(self, path):
        """Return the expected repository target for the given symlink."""

        try:
            relpath = str(path.relative_to(self.homedir))
        except ValueError:
            raise NotRootedInHome(path)

        if self.remove_leading_dot:
            return self.path / relpath[1:]
        else:
            return self.path / relpath

    def _dotfile(self, path):
        """Return a valid dotfile for the given path."""

        target = self._dotfile_target(path)

        if not fnmatch(path, '%s/*' % self.homedir):
            raise NotRootedInHome(path)
        if fnmatch(path, '%s/*' % self.path):
            raise InRepository(path)
        if self._ignore(target):
            raise TargetIgnored(path)
        if path.is_dir():
            raise IsDirectory(path)

        return Dotfile(path, target)

    def _contents(self, dir):
        """Return all unignored files contained below a directory."""

        def skip(path):
            return path.is_dir() or self._ignore(path)

        return [x for x in dir.rglob('*') if not skip(x)]

    def contents(self):
        """Return a list of dotfiles for each file in the repository."""

        def construct(target):
            return Dotfile(self._dotfile_path(target), target)

        contents = self._contents(self.path)
        return sorted(map(construct, contents), key=attrgetter('name'))

    def dotfiles(self, paths):
        """Return a collection of dotfiles given a list of paths.

        This function takes a list of paths where each path can be a file or a
        directory.  Each directory is recursively expaned into file paths.
        Once the list is converted into only files, dotifles are constructed
        for each path in the set.  This set of dotfiles is returned to the
        caller.
        """

        paths = list(set(map(Path, paths)))

        for path in paths:
            if path.is_dir():
                paths.extend(self._contents(path))
                paths.remove(path)

        def construct(path):
            try:
                return self._dotfile(path)
            except DotfileException as err:
                echo(err)
                return None

        return [d for d in map(construct, paths) if d is not None]

    def prune(self, debug=False):
        """Remove any empty directories in the repository.

        After a remove operation, there may be empty directories remaining.
        The Dotfile class has no knowledge of other dotfiles in the repository,
        so pruning must take place explicitly after such operations occur.
        """

        def skip(path):
            return self._ignore(path) or path == str(self.path)

        dirs = reversed([dir for dir, subdirs, files in
                         os.walk(self.path) if not skip(dir)])

        for dir in dirs:
            if not len(os.listdir(dir)):
                if debug:
                    echo('PRUNE  %s' % (dir))
                os.rmdir(dir)