-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdotty
executable file
·205 lines (182 loc) · 6.52 KB
/
dotty
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
#!/usr/bin/env python
import argparse
import glob
import sys
import os
import subprocess
import logging
logging.basicConfig()
logger = logging.getLogger('dotty')
logger.setLevel(logging.INFO)
class DottyException(Exception):
def __init__(self, msg):
super(Exception, self).__init__(msg)
class FileStatus(object):
IS_MISSING = 1
IS_DIRECTORY = 2
IS_FILE = 3
IS_LINK = 4
class LinkStatus(object):
# destination is already something, not a link to the right place
DST_WRONG = 1
# source file doesn't exist
SRC_MISSING = 2
# installed correctly
INSTALLED = 3
# not installed
UNINSTALLED = 4
class DotFile(object):
def __init__(self, dotty_dir, src_path, dst_path=None):
if src_path[:len(dotty_dir)] != dotty_dir:
raise DottyException(
"""
Internal error:
%s did not start with %s
""" % (src_path, dotty_dir)
)
self.dotty_dir = dotty_dir
self.src_path = src_path
self.name = src_path[len(dotty_dir)+1:]
if dst_path is None:
dst_path = os.path.join('~', '.' + self.name)
dst_path = os.path.expanduser(dst_path)
self.dst_path = dst_path
def read_rcfile(dotty_dir):
dotty_rc = os.path.join(dotty_dir, "dotty.rc")
if not os.path.exists(dotty_rc):
logger.warn(
"""
No dotty.rc file found!
Please place a file containing a pattern on each line at %s
""" % dotty_rc
)
lines = (line.strip() for line in open(dotty_rc))
dotfiles = []
for line in lines:
if line == "":
continue
if line.startswith("#"): # a comment
continue
if ' ' in line:
pattern, dst = line.split(' ')
else:
pattern, dst = line, None
full_pattern = os.path.join(dotty_dir, pattern)
filepaths = glob.glob(full_pattern)
if len(filepaths) == 0:
logger.warn(
"""
dotty.rc contained line with invalid pattern %s.
Expected a file matching %s. Ignoring line.
""" % (pattern, full_pattern)
)
dotfiles.extend([
DotFile(dotty_dir, filepath, dst_path=dst)
for filepath in filepaths
])
return dotfiles
def check_file(filepath):
# NOTE: we do the link check before existence so that
# broken links are IS_LINK
if os.path.islink(filepath):
return FileStatus.IS_LINK
elif os.path.isdir(filepath):
return FileStatus.IS_DIRECTORY
elif os.path.exists(filepath):
return FileStatus.IS_FILE
else:
return FileStatus.IS_MISSING
def get_link_status(dotfile):
src_status = check_file(dotfile.src_path)
if src_status == FileStatus.IS_MISSING:
return LinkStatus.SRC_MISSING
dst_status = check_file(dotfile.dst_path)
if dst_status == FileStatus.IS_MISSING:
return LinkStatus.UNINSTALLED
elif dst_status == FileStatus.IS_DIRECTORY or \
dst_status == FileStatus.IS_FILE:
return LinkStatus.DST_WRONG
else:
assert dst_status == FileStatus.IS_LINK
source = os.readlink(dotfile.dst_path)
if source != dotfile.src_path:
return LinkStatus.DST_WRONG
else:
return LinkStatus.INSTALLED
def get_statuses(dotty_dir):
dotfiles = read_rcfile(dotty_dir)
return [
(dotfile, get_link_status(dotfile))
for dotfile in dotfiles
]
argp = argparse.ArgumentParser(description='manage your dotfiles.')
argp_sub = argp.add_subparsers(title='dotty commands')
argp_status = argp_sub.add_parser('status', help="get status")
def status(args):
statuses = get_statuses(args.dotty_dir)
lcol = max(len(pair[0].name) for pair in statuses)
for (dotfile, status) in statuses:
if status == LinkStatus.SRC_MISSING:
msg = 'UNINSTALLED (source file is missing)'
elif status == LinkStatus.DST_WRONG:
msg = 'UNINSTALLED (destination %s already exists)' % dotfile.dst_path
elif status == LinkStatus.UNINSTALLED:
msg = 'UNINSTALLED'
else:
assert status == LinkStatus.INSTALLED
msg = 'INSTALLED'
print ('%s : %s' % (dotfile.name.ljust(lcol), msg))
argp_status.set_defaults(func=status)
argp_install = argp_sub.add_parser('install', help="install symlinks")
argp_install.add_argument('-f', '--force', help='overwrite existing files', action='store_true')
def install(args):
statuses = get_statuses(args.dotty_dir)
lcol = max(len(pair[0].name) for pair in statuses)
for (dotfile, status) in statuses:
if status == LinkStatus.SRC_MISSING:
msg = 'ERROR (source file is missing)'
elif status == LinkStatus.DST_WRONG:
if args.force:
os.unlink(dotfile.dst_path)
# os.remove? os.rmdir?
os.symlink(dotfile.src_path, dotfile.dst_path)
msg = 'SUCCESS'
else:
msg = 'ERROR (destination %s already exists)' % dotfile.dst_path
elif status == LinkStatus.INSTALLED:
msg = 'SUCCESS (already installed)'
else:
assert status == LinkStatus.UNINSTALLED
os.makedirs(os.path.dirname(dotfile.dst_path), exist_ok=True)
os.symlink(dotfile.src_path, dotfile.dst_path)
msg = 'SUCCESS'
print ('%s : %s' % (dotfile.name.ljust(lcol), msg))
argp_install.set_defaults(func=install)
argp_uninstall = argp_sub.add_parser('uninstall', help="uninstall symlinks")
def uninstall(args):
statuses = get_statuses(args.dotty_dir)
lcol = max(len(pair[0].name) for pair in statuses)
for (dotfile, status) in statuses:
if status == LinkStatus.SRC_MISSING or \
status == LinkStatus.DST_WRONG or \
status == LinkStatus.UNINSTALLED:
msg = 'SUCCESS (already uninstalled)'
else:
assert status == LinkStatus.INSTALLED
os.unlink(dotfile.dst_path)
msg = 'SUCCESS'
print ('%s : %s' % (dotfile.name.ljust(lcol), msg))
argp_uninstall.set_defaults(func=uninstall)
if __name__ == "__main__":
args = argp.parse_args()
args.dotty_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
# Python3 doesn't error on parse_args with no subcommand.
try:
if 'func' in args:
args.func(args)
else:
argp.print_help()
except DottyException as e:
logger.error(e)
sys.exit(1)
sys.exit(0)