-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsetup
More file actions
executable file
·100 lines (77 loc) · 2.62 KB
/
setup
File metadata and controls
executable file
·100 lines (77 loc) · 2.62 KB
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
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import os.path as op
import subprocess as sp
import sys
import time
def execute(args, cwd=None, casual=False):
"""
Execute a command.
"""
p = sp.Popen(args, shell=False, stdout=sp.PIPE, stderr=sp.PIPE, cwd=cwd)
stdo, stde = p.communicate()
code = p.returncode
if not casual:
assert len(stdo) == 0 and len(stde) == 0 and code == 0, \
(stdo, stde, code)
return stdo, stde, code
def locate_bundles(root):
"""
Collect ./_* files and folders.
"""
return [name for name in os.listdir(root) if name.startswith('_')]
def locate_singles(root):
"""
Collect individual files inside ./-* folders.
"""
# symlinks to folders are treated as files
output = []
for path in os.listdir(root):
if path.startswith('-'):
for d, dirnames, filenames in os.walk(path):
output += [op.join(d, filename) for filename in filenames]
output += filter(op.islink,
[op.join(d, dirname) for dirname in dirnames])
return output
def perform_backup(root, home, backup):
"""
Backup files and folders to be overwritten.
"""
print('Creating backup')
tarball = op.join(root, time.strftime('backup-%y%m%d.%H%M%S.tar.bz2'))
stdo, stde, code = execute(['tar', 'jcvf', tarball] + backup,
cwd=home, casual=True)
if len(stde) > 0 or code != 0:
print(stdo)
print(stde)
print('Exit status %d' % code)
sys.exit(code)
print('Removing files to overwrite')
execute(['rm', '-rf'] + backup, cwd=home)
def create_symlinks(root, home, source, target):
"""
Create symlinks in home directory.
"""
print('Creating symlinks')
for raw, symlink in zip(source, target):
print(raw, '⇒', symlink)
original = op.join(root, raw)
dname = op.dirname(symlink)
bname = op.basename(symlink)
if len(dname) > 0:
execute(['mkdir', '-p', dname], cwd=home)
execute(['ln', '-s', original, bname], cwd=op.join(home, dname))
else:
execute(['ln', '-s', original, symlink], cwd=home)
def main():
root = op.dirname(op.abspath(__file__))
home = op.expanduser('~')
source = locate_bundles(root) + locate_singles(root)
target = ['.' + path[1:] for path in source]
backup = [path for path in target if op.exists(op.join(home, path))]
if len(backup) > 0:
perform_backup(root, home, backup)
create_symlinks(root, home, source, target)
if __name__ == '__main__':
main()