-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.py
executable file
·70 lines (61 loc) · 2.52 KB
/
install.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
#!/usr/bin/env python3
import os
import os.path
import stat
import sys
def normjoin(*paths):
return os.path.normpath(os.path.join(*paths))
home_abs = os.environ["HOME"]
source_abs = normjoin(os.getcwd(), os.path.dirname(__file__), "homedir")
home_to_source = os.path.relpath(source_abs, start=home_abs)
links = {}
for source_sub, dirs, names in os.walk(source_abs):
sub_rel = os.path.relpath(source_sub, start=source_abs)
home_sub = os.path.join(home_abs, sub_rel)
if not (dirs or names):
sys.exit(f"EMPTY: {source_sub}")
elif ".git" in names:
home_parent = os.path.dirname(home_sub)
links[sub_rel] = os.path.relpath(source_sub, start=home_parent)
dirs[:] = [] # Prune subdirectories
else:
home_to_source_sub = os.path.relpath(source_sub, start=home_sub)
names.extend(d for d in dirs if os.path.islink(normjoin(source_sub, d)))
for name in names:
links[normjoin(sub_rel, name)] = normjoin(home_to_source_sub, name)
os.makedirs(home_abs, exist_ok=True)
for home_sub, dirs, names in os.walk(home_abs):
sub_rel = os.path.relpath(home_sub, start=home_abs)
names.extend(d for d in dirs if os.path.islink(normjoin(home_sub, d)))
for name in names:
existing_abs = normjoin(home_sub, name)
try:
existing_link = os.readlink(existing_abs)
except OSError:
continue
name_rel = normjoin(sub_rel, name)
tilde_rel = normjoin("~", name_rel)
desired_link = links.pop(name_rel, None)
if desired_link == existing_link:
print(f"(keep {tilde_rel} => {existing_link})")
elif not desired_link and "dotfiles" in existing_link:
print(f"*remove* {tilde_rel} (was => {existing_link})")
os.remove(existing_abs)
elif desired_link:
print(
f"*update* {tilde_rel} => {desired_link} "
f"(was {existing_link})")
os.remove(existing_abs)
os.symlink(desired_link, existing_abs)
for new_name, new_link in sorted(links.items()):
tilde_rel = normjoin("~", new_name)
target = normjoin(home_abs, new_name)
if os.path.isdir(target) and not os.listdir(target):
print(f"*rmdir* {new_name}")
os.rmdir(normjoin(home_abs, new_name))
parent = os.path.dirname(target)
if not os.path.isdir(parent):
print(f"*mkdir* {parent}")
os.makedirs(parent, exist_ok=True)
print(f"*link* {tilde_rel} => {new_link}")
os.symlink(new_link, normjoin(home_abs, new_name))