aboutsummaryrefslogtreecommitdiffstats
path: root/dotfiles.py
blob: c8b362c8155560960171802ac3a5d75a2df01648 (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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import py
import os
import click
import errno
from operator import attrgetter


DEFAULT_HOMEDIR = os.path.expanduser('~/')
DEFAULT_REPO_PATH = os.path.expanduser('~/Dotfiles')
DEFAULT_REPO_IGNORE = ['.git', '.gitignore']


class DotfileException(Exception):
    """An exception the CLI can handle and show to the user."""

    def __init__(self, path, message='an unknown error occurred'):
        self.message = '\'%s\' %s' % (path, message)
        Exception.__init__(self, self.message)

    def __str__(self):
        return 'ERROR: %s' % self.message


class TargetIgnored(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'targets an ignored file')


class IsDirectory(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is a directory')


class IsSymlink(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is a symlink')


class NotASymlink(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is not a symlink')


class InRepository(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is within the repository')


class NotRootedInHome(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'not rooted in home directory')


class IsNested(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is nested')


class NotADotfile(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'is not a dotfile')


class DoesNotExist(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'doest not exist')


class TargetExists(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'target already exists')


class TargetMissing(DotfileException):

    def __init__(self, path):
        DotfileException.__init__(self, path, 'target is missing')


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

    :param repodir: the location of the repository directory
    :param homedir: the location of the home directory (primarily for testing)
    :param ignore:  a list of targets to ignore
    """

    def __init__(self, repodir, homedir, ignore=[]):
        self.ignore = ignore
        self.homedir = homedir

        # create repository if needed
        self.repodir = repodir.ensure(dir=1)

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

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

    def _target_to_name(self, target):
        """Return the expected symlink for the given repository target."""
        return self.homedir.join('.%s' % target.basename)

    def _name_to_target(self, name):
        """Return the expected repository target for the given symlink."""
        return self.repodir.join(name.basename[1:])

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

        target = self._name_to_target(name)
        if target.basename in self.ignore:
            raise TargetIgnored(name)

        if name.check(dir=1):
            raise IsDirectory(name)

        for path in name.parts():
            try:
                if self.repodir.samefile(path):
                    raise InRepository(name)
            except py.error.ENOENT:
                # this occurs when the symlink does not yet exist
                continue

        if not self.homedir.samefile(name.dirname):
            raise NotRootedInHome(name)

        if name.dirname != self.homedir:
            raise IsNested(name)

        if name.basename[0] != '.':
            raise NotADotfile(name)

        return Dotfile(name, target)

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

        if path.check(dir=1):
            raise IsDirectory(path)

        return self.dotfile(path)

    def contents(self):
        """Return a list of all dotfiles in the repository path."""
        contents = []
        for target in self.repodir.listdir():
            target = py.path.local(target)
            if target.basename not in self.ignore:
                contents.append(Dotfile(self._target_to_name(target), target))
        return sorted(contents, key=attrgetter('name'))


class Dotfile(object):
    """An 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)
    """

    def __init__(self, name, target):
        self.name = name
        self.target = target

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

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

    def _add(self, verbose):
        if verbose:
            click.echo('MOVE   %s -> %s' % (self.name, self.target))
        self.name.move(self.target)
        self._link(verbose)

    def _remove(self, verbose):
        self._unlink(verbose)
        if verbose:
            click.echo('MOVE   %s -> %s' % (self.target, self.name))
        self.target.move(self.name)

    def _link(self, verbose):
        if verbose:
            click.echo('LINK   %s -> %s' % (self.name, self.target))
        self.name.mksymlinkto(self.target, absolute=0)

    def _unlink(self, verbose):
        if verbose:
            click.echo('UNLINK %s' % self.name)
        self.name.remove()

    @property
    def state(self):
        if self.target.check(exists=0):
            # only for testing, cli should never reach this state
            return 'error'
        elif self.name.check(exists=0):
            # no $HOME symlink
            return 'missing'
        elif self.name.check(link=0) or not self.name.samefile(self.target):
            # if name exists but isn't a link to the target
            return 'conflict'
        return 'ok'

    def add(self, verbose=False):
        if self.name.check(file=0):
            raise DoesNotExist(self.name)
        if self.name.check(dir=1):
            raise IsDirectory(self.name)
        if self.name.check(link=1):
            raise IsSymlink(self.name)
        if self.target.check(exists=1):
            raise TargetExists(self.name)
        self._add(verbose)

    def remove(self, verbose=False):
        if not self.name.check(link=1):
            raise NotASymlink(self.name)
        if self.target.check(exists=0):
            raise TargetMissing(self.name)
        self._remove(verbose)

    # TODO: replace exceptions

    def link(self, verbose=False):
        if self.name.check(exists=1):
            raise OSError(errno.EEXIST, self.name)
        if self.target.check(exists=0):
            raise OSError(errno.ENOENT, self.target)
        self._link(verbose)

    def unlink(self, verbose=False):
        if self.name.check(link=0):
            raise Exception('%s is not a symlink' % self.name.basename)
        if self.target.check(exists=0):
            raise Exception('%s does not exist' % self.target)
        if not self.name.samefile(self.target):
            raise Exception('good lord')
        self._unlink(verbose)


pass_repo = click.make_pass_decorator(Repository)


@click.group(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--repository', type=click.Path(), show_default=True,
              default=DEFAULT_REPO_PATH)
@click.version_option()
@click.pass_context
def cli(ctx, repository):
    """Dotfiles is a tool to make managing your dotfile symlinks in $HOME easy,
    allowing you to keep all your dotfiles in a single directory.
    """
    ctx.obj = Repository(py.path.local(repository),
                         py.path.local(DEFAULT_HOMEDIR),
                         DEFAULT_REPO_IGNORE)


@cli.command()
@click.option('-v', '--verbose', is_flag=True, help='Show executed commands.')
@click.argument('files', nargs=-1, type=click.Path(exists=True))
@pass_repo
def add(repo, verbose, files):
    """Replace file with symlink."""
    for filename in files:
        try:
            repo.dotfile(py.path.local(filename)).add(verbose)
        except DotfileException as err:
            click.echo(err)


@cli.command()
@click.option('-v', '--verbose', is_flag=True, help='Show executed commands.')
@click.argument('files', nargs=-1, type=click.Path(exists=True))
@pass_repo
def remove(repo, verbose, files):
    """Replace symlink with file."""
    for filename in files:
        repo.dotfile(py.path.local(filename)).remove(verbose)


@cli.command()
@click.option('-v', '--verbose', is_flag=True, help='Show all dotfiles.')
@click.option('-c', '--color',   is_flag=True, help='Enable color output.')
@pass_repo
def status(repo, verbose, color):
    """Show all dotfiles in a non-OK state."""

    state_info = {
        'error':    {'char': 'E', 'color': None},
        'conflict': {'char': '!', 'color': None},
        'missing':  {'char': '?', 'color': None},
    }

    if verbose:
        state_info['ok'] = {'char': ' ', 'color': None}

    if color:
        state_info['error']['color'] = 'red'
        state_info['conflict']['color'] = 'magenta'
        state_info['missing']['color'] = 'yellow'

    for dotfile in repo.contents():
        try:
            char = state_info[dotfile.state]['char']
            fg = state_info[dotfile.state]['color']
            click.secho('%c %s' % (char, dotfile), fg=fg)
        except KeyError:
            continue


@cli.command()
@click.option('-v', '--verbose', is_flag=True, help='Show executed commands.')
@click.argument('files', nargs=-1, type=click.Path())
@pass_repo
def link(repo, verbose, files):
    """Create missing symlinks."""
    for filename in files:
        repo.dotfile(py.path.local(filename)).link(verbose)


@cli.command()
@click.option('-v', '--verbose', is_flag=True, help='Show executed commands.')
@click.argument('files', nargs=-1, type=click.Path(exists=True))
@pass_repo
def unlink(repo, verbose, files):
    """Remove existing symlinks."""
    for filename in files:
        repo.dotfile(py.path.local(filename)).unlink(verbose)