-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsetup.py
executable file
·176 lines (138 loc) · 5.36 KB
/
setup.py
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
#!/usr/bin/env python3
"""
This script creates symlinks in your home directory to your dotfiles in the
Git repository.
By default it will delete any file that stands in the way of its mission to
create a better world.
Usage: python setup.py [--nice] [--home=DIRECTORY]
--nice Don't trample existing dot files.
--home=DIRECTORY Place links in DIRECTORY instead of $HOME.
--pretend Don't change anything, just say what would be done.
"""
import os, sys, getopt, socket
import shutil
import string
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
""" Create links to dotfiles """
def makeDots(base, home, nice = False, pretend = False):
# First make a map of dot files to files in the repository.
dotfiles = getMap(base + "/base/")
# Get host specific overrides
hostname = socket.getfqdn().lower().split(".")
for i in range(len(hostname)):
name = '.'.join(hostname[-(i+1):])
directory = base + "/host-overrides/" + name
if os.path.isdir(directory):
mergeDicts(dotfiles, getMap(directory))
if pretend:
print("I would make these links:")
else:
print("I am making these links:")
makeLinks(dotfiles, home + "/.", nice, pretend)
def makeLinks(dotfiles, prefix, nice, pretend):
keys = sorted(dotfiles.keys())
for dst in keys:
src = dotfiles[dst]
realDest = prefix + dst
if type(src) is dict:
try:
if not pretend:
if os.path.islink(realDest):
os.unlink(realDest) # Only remove symlinks. Don't try to replace a file with a directory.
if not os.path.isdir(realDest):
os.mkdir(realDest)
if os.path.lexists(realDest):
print("%50s => <NEW DIRECTORY>" % (realDest))
else:
print("%50s *=> <NEW DIRECTORY>" % (realDest))
makeLinks(src, realDest + "/", nice, pretend)
except OSError as e:
print("Could not mkdir %s. Will not link subitems: %s" % (realDest, str(e)))
else:
try:
fileExists = os.path.lexists(realDest)
if not pretend:
success = makeLink(src, realDest, nice)
if fileExists:
if os.path.realpath(realDest) == os.path.realpath(src):
print("%50s => %s" % (realDest, src))
else:
print("%50s !=> %s" % (realDest, src))
else:
print("%50s *=> %s" % (realDest, src))
except IOError as e:
print("Not linking %s to %s because IOError: %s" % (realDest, src, str(e)))
""" Return a map of dest => source dotfiles """
def getMap(baseDirectory, directory=""):
if baseDirectory[-1] != "/":
baseDirectory = baseDirectory + "/"
if directory != "" and directory[-1] != "/":
directory = directory + "/"
dots = dict()
for filename in os.listdir(baseDirectory + directory):
if filename == ".nolink":
continue
if filename == ".git":
continue # Skip over submodules.
fullPath = baseDirectory + directory + filename
if os.path.isdir(fullPath) and os.path.exists(fullPath + "/.nolink"):
# We will not make a link but will make sure this directory exists.
dots[directory + filename] = getMap(baseDirectory + directory + filename)
else:
dots[directory + filename] = fullPath
return dots
""" Make a link from src to realDest.
If nice is true, don't overwrite realDest.
If src is an empty string, just create a directory. """
def makeLink(src, realDest, nice = False):
if os.path.lexists(realDest):
if nice:
return False
if os.path.isdir(realDest) and not os.path.islink(realDest):
shutil.rmtree(realDest)
else:
os.unlink(realDest)
os.symlink(src, realDest)
return True
""" Recursively merge the second dictionary into the first. The latter takes precedence."""
def mergeDicts(a, b):
for key, value in b.items():
if key in a and type(value) is dict and type(a[key]) is dict:
mergeDicts(a[key], value)
else:
a[key] = value
""" Main Method """
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:],
"hnd:p", ["help", "nice", "home=", "pretend"])
except getopt.error as msg:
raise Usage(msg)
# Settings:
nice = False
pretend = False
home = os.environ.get("HOME")
for o, a in opts:
if o in ("-h", "--help"):
print(__doc__)
return 0
if o in ("-n", "--nice"):
nice = True
elif o in ("-p", "--pretend"):
pretend = True
elif o in ("-d", "--home"):
home = a
if not home:
raise Usage("No home provided")
makeDots(os.getcwd(), home, nice, pretend)
except Usage as err:
eprint(err.msg, file=sys.stderr)
eprint("for help use --help", file=sys.stderr)
return 2
if __name__ == "__main__":
sys.exit(main())