aboutsummaryrefslogtreecommitdiffstats
path: root/dotfiles/repository.py
blob: c231a55e49428b0788fdc414be0c5c594de8ce82 (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 RepositoryNotFound
from .exceptions import DotfileException, TargetIgnored
from .exceptions import NotRootedInHome, InRepository, IsDirectory


class Repositories(object):
    """An iterable collection of repository objects."""
    def __init__(self, paths, home=Path.home()):
        self.repos = []
        for path in paths:
            self.repos.append(Repository(path, home))

    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."""
    CREATE_REPOSITORY = False
    REMOVE_LEADING_DOT = True
    IGNORE_PATTERNS = ['.git/*', '.gitignore', 'README*', '*~']

    def __init__(self, path, home=Path.home()):
        self.path = Path(path).expanduser().resolve()
        self.home = Path(home).expanduser().resolve()

        if not self.path.exists():
            if self.CREATE_REPOSITORY:
                self.path.mkdir(parents=True, exist_ok=True)
                echo('Created new repository: %s' % self.path)
            else:
                raise RepositoryNotFound(self.path)

        if not self.home.exists():
            raise FileNotFoundError(self.home)


    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):
        """Test whether a dotfile should be ignored."""
        for pattern in self.IGNORE_PATTERNS:
            if fnmatch(str(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.home / ('.%s' % relpath)
        else:
            return self.home / relpath

    def _dotfile_target(self, path):
        """Return the expected repository target for the given symlink."""
        try:
            # is the dotfile within the home directory?
            relpath = str(path.relative_to(self.home))
        except ValueError:
            raise NotRootedInHome(path)

        if self.REMOVE_LEADING_DOT and relpath[0] == '.':
            relpath = relpath[1:]

        return self.path / relpath

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

        if not fnmatch(str(path), '%s/*' % self.home):
            raise NotRootedInHome(path)
        if fnmatch(str(path), '%s/*' % self.path):
            print('oh no')
            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, subdir=None):
        """Return dotfile objects for each file in the repository."""
        def construct(target):
            return Dotfile(self._dotfile_path(target), target)

        path = subdir if subdir else self.path
        path.relative_to(self.path)

        contents = self._contents(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, Dotfile
        objects are constructed for each item in the set.  This set of
        dotfiles is returned to the caller.
        """
        paths = [Path(x).expanduser().absolute() for x in paths]
        dotfiles = []

        # if dir doesn't exist, this breaks
        # need to get entire list and compare each one as a subset

        for path in paths:
            if path.is_dir():
                dotfiles.extend(self.contents(self._dotfile_target(path)))
                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]

        dotfiles.extend([d for d in map(construct, paths) if d])
        return sorted(set(dotfiles))


    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)

        # TODO: this *could* use pathlib instead

        dirs = reversed([dir for dir, subdirs, files in
                         os.walk(str(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)