-
Notifications
You must be signed in to change notification settings - Fork 2
/
init
executable file
·196 lines (157 loc) · 5.38 KB
/
init
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
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 filetype=python :
"""Link configs for tools defined here to $HOME.
Why this script?
================
The obvious alternative would be a directory like this::
configs/.bashrc
configs/.vimrc
configs/.vim/
- A simple ls does not work.
- File managers need to display hidden files.
- Need to type dot when navigating on the commandline.
Nested Files
============
Normally tool directories contain an rc file and a directory, e.g.
bash/bash --> ~/.bash
bash/bashrc --> ~/.bashrc
But xfce4 configs are deeply nested in XDG_CONFIG_HOME (`~/.config`), e.g.
_nested/config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml
--> ~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-keyboard-shortcuts.xml
This is a special case, because I only want files very selectively.
"""
import os
from os import listdir, chdir
from os.path import abspath, dirname, isdir, join
import shutil
import subprocess
from optparse import OptionParser
IGNORED_DIRS = ['.git', '_nested', '_tests']
# everything happens relative to this file's parent dir
here = abspath(dirname(__file__))
chdir(here)
checkout_dirname = os.path.basename(here)
OVERRIDE_PREVIOUS = False
HOME = os.environ['HOME']
BACKUP_DIR = join(HOME, 'bak', checkout_dirname)
import logging
log = logging.getLogger('init')
loglevel = os.environ.get('LOGLEVEL', 'WARNING').upper()
logging.basicConfig(level=loglevel, format='%(levelname)-7s %(message)s')
def run(cmd):
"Run command as if in shell. Blocking."
p = subprocess.Popen(cmd, shell=True)
p.wait()
def makelink(src, dest):
"Think ln -s"
log.debug('link %s %s', src, dest)
if OVERRIDE_PREVIOUS:
if os.path.islink(dest):
log.debug('Removing link '+dest)
os.unlink(dest)
elif os.path.isdir(dest) or os.path.isfile(dest):
log.warning("mv %s %s", dest, BACKUP_DIR)
shutil.move(dest, BACKUP_DIR)
src = join(os.getcwd(), src)
try:
os.symlink(src, dest)
log.debug('Linked %s to %s' % (src, dest))
except OSError as e:
if e.strerror != 'File exists':
raise
else:
log.info('%s: %s' % (e.strerror, dest))
def handle_tool(tooldir):
"""
Given:
vim/vimrc
vim/vim/file1
It runs:
ln -s vim/vimrc $HOME/.vimrc
ln -s vim/vim $HOME/.vim
"""
log.info('Initializing ' + tooldir)
files = listdir(tooldir)
for fname in files:
src = join(tooldir, fname)
dest = join(HOME, '.'+fname)
makelink(src, dest)
def get_tool_dirs():
result = filter(isdir, listdir(here))
return set(result) - set(IGNORED_DIRS)
def gen_git_config(email=None, name=None):
path = join(HOME, '.gitconfig.d', 'user')
if email is None:
email = input("git email: ")
if name is None:
name = input("git name: ")
cfg = """\
[user]
email = {email}
name = {name}
""".format(**locals())
if not os.path.exists(path):
with open(path, 'w') as f:
f.write(cfg)
log.info("Wrote {0}".format(path))
def _iter_nested():
for root, dirs, files in os.walk('_nested'):
for f in files:
walkparts = [root] + [f]
src = os.path.join(*walkparts)
log.debug('src: %s', src)
parts = src.split('/')
log.debug('parts: %s', parts)
tmp = os.path.join(*parts[1:])
log.debug('tmp: %s', tmp)
dest = os.path.join(HOME, '.' + tmp)
# _nested/foo/bar --> .foo/bar (note the dot)
log.info('{0} --> {1}'.format(src, dest))
yield src, dest
def handle_nested():
log.info('handling nested files')
# compute up-front
xs = list(_iter_nested())
for src, dest in xs:
# create directory if it does not exist
mkdir_p(os.path.dirname(dest))
makelink(src, dest)
def mkdir_p(dirname):
log.debug('mkdir_p(%s)', dirname)
if not isdir(dirname):
os.makedirs(dirname)
def main():
run('git submodule update --init')
for tool in get_tool_dirs():
handle_tool(tool)
handle_nested()
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-f", "--force",
action="store_true", dest="force", default=False,
help="force overriding old options. Removes links and\
moves dirs/files to $HOME/bak")
parser.add_option("-e", "--email",
action="store", dest="email",
help="email for git")
parser.add_option("-n", "--name",
action="store", dest="name",
help='name for git, e.g. "Felix Hummel"')
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose", default=False,
help="info logging")
parser.add_option("-d", "--debug",
action="store_true", dest="debug", default=False,
help="debug logging")
(options, args) = parser.parse_args()
if options.debug:
log.setLevel(logging.DEBUG)
elif options.verbose:
log.setLevel(logging.INFO)
OVERRIDE_PREVIOUS = options.force
# if we may need backups, create BACKUP_DIR
if OVERRIDE_PREVIOUS:
mkdir_p(BACKUP_DIR)
main()
if options.email or options.name:
gen_git_config(options.email, options.name)