aboutsummaryrefslogtreecommitdiffstats
path: root/dotfiles/dotfile.py
blob: 64bfabb294965c1edb5c01a73fa5992da56031a9 (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
172
173
174
175
176
import os

from click import echo
from hashlib import md5
from pathlib import Path

from .exceptions import \
    IsSymlink, NotASymlink, Exists, NotFound, Dangling, \
    TargetExists, TargetMissing

UNUSED = False


class Dotfile(object):
    """A configuration file managed within a repository.

    :param name:   name of the symlink in the home directory (~/.vimrc)
    :param target: where the symlink should point to (~/Dotfiles/vimrc)
    """
    RELATIVE_SYMLINKS = True

    def __init__(self, name, target):
        # if not name.is_file() and not name.is_symlink():
        #     raise NotFound(name)
        self.name = Path(name)
        self.target = Path(target)

    def __str__(self):
        return str(self.name)

    def __repr__(self):
        return '<Dotfile %r>' % self.name

    def __hash__(self):
        return hash((self.name, self.target))

    def __eq__(self, othr):
        return ((self.name, self.target) ==
                (othr.name, othr.target))

    def __lt__(self, othr):
        return self.name < othr.name

    def _ensure_dirs(self, debug):
        """Ensure the directories for both name and target are in place.

        This is needed for the 'add' and 'link' operations where the
        directory structure is expected to exist.
        """
        def ensure(dir, debug):
            if not dir.is_dir():
                if debug:
                    echo('MKDIR  %s' % dir)
                else:
                    dir.mkdir(parents=True)

        ensure(self.name.parent, debug)
        ensure(self.target.parent, debug)

    def _prune_dirs(self, debug):
        # TODO
        if debug:
            echo('PRUNE  <TODO>')

    def _link(self, debug, home):
        """Create a symlink from name to target, no error checking."""
        source = self.name
        target = self.target

        if self.name.is_symlink():
            source = self.target
            target = self.name.resolve()
        elif self.RELATIVE_SYMLINKS:
            target = os.path.relpath(target, source.parent)

        if debug:
            echo('LINK   %s -> %s' % (source, target))
        else:
            source.symlink_to(target)

    def _unlink(self, debug):
        """Remove a symlink in the home directory, no error checking."""
        if debug:
            echo('UNLINK %s' % self.name)
        else:
            self.name.unlink()

    def short_name(self, home):
        """A shorter, more readable name given a home directory."""
        return self.name.relative_to(home)

    def _is_present(self):
        """Is this dotfile present in the repository?"""
        return self.name.is_symlink() and (self.name.resolve() == self.target)

    def _same_contents(self):
        return (md5(self.name.read_bytes()).hexdigest() == \
                md5(self.target.read_bytes()).hexdigest())

    @property
    def state(self):
        """The current state of this dotfile."""
        if self.target.is_symlink():
            return 'external'

        if not self.name.exists():
            # no $HOME file or symlink
            return 'missing'

        if self.name.is_symlink():
            # name exists, is a link, but isn't a link to the target
            if not self.name.samefile(self.target):
                return 'conflict'
            return 'link'

        if not self._same_contents():
            # name exists, is a file, but differs from the target
            return 'conflict'

        return 'copy'

    def add(self, copy=False, debug=False, home=Path.home()):
        """Move a dotfile to its target and create a link.

        The link is either a symlink or a copy.
        """
        if copy:
            raise NotImplementedError()
        if self._is_present():
            raise IsSymlink(self.name)
        if self.target.exists():
            raise TargetExists(self.name)
        self._ensure_dirs(debug)
        if not self.name.is_symlink():
            if debug:
                echo('MOVE   %s -> %s' % (self.name, self.target))
            else:
                self.name.replace(self.target)
        self._link(debug, home)

    def remove(self, copy=UNUSED, debug=False):
        """Remove a dotfile and move target to its original location."""
        if not self.name.is_symlink():
            raise NotASymlink(self.name)
        if not self.target.is_file():
            raise TargetMissing(self.name)
        self._unlink(debug)
        if debug:
            echo('MOVE   %s -> %s' % (self.target, self.name))
        else:
            self.target.replace(self.name)

    def enable(self, copy=False, debug=False, home=Path.home()):
        """Create a symlink or copy from name to target."""
        if copy:
            raise NotImplementedError()
        if self.name.exists():
            # nothing to do
            return
        if not self.target.exists():
            raise TargetMissing(self.name)
        import pdb; pdb.set_trace()
        self._ensure_dirs(debug)
        self._link(debug, home)

    def disable(self, copy=UNUSED, debug=False):
        """Remove a dotfile from name to target."""
        if not self.name.is_symlink():
            raise NotASymlink(self.name)
        if self.name.exists():
            if not self.target.exists():
                raise TargetMissing(self.name)
            if not self.name.samefile(self.target):
                raise RuntimeError
        self._unlink(debug)
        self._prune_dirs(debug)