-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsetup_tools.py
336 lines (241 loc) · 10.1 KB
/
setup_tools.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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python
import os
import sys
import glob
import stat
import re
from io import BytesIO
from hashlib import sha256
from subprocess import PIPE, call
from itertools import chain
import importlib
class MiniLogger(object):
@staticmethod
def info(txt):
print("INFO: " + txt)
@staticmethod
def warning(txt):
print("WARNING: " + txt)
@staticmethod
def error(txt):
print("ERROR: " + txt)
_logger = MiniLogger()
home_dir = os.path.expanduser("~")
defaltPermission = 0644
installPath = ".scan-o-matic"
defaultSourceBase = "data"
data_files = [
('config', {'calibration.polynomials': False,
'calibration.data': False,
'grayscales.cfg': False,
'rpc.config': False,
'scanners.sane.json': False,
'scan-o-matic.desktop': True}),
(os.path.join('config', 'fixtures'), {}),
('logs', {}),
('locks', {}),
('images', None),
('ui_server', None)
]
_launcher_text = """[Desktop Entry]
Type=Application
Terminal=false
Icon={user_home}/.scan-o-matic/images/scan-o-matic_icon_256_256.png
Name=Scan-o-Matic
Comment=Large-scale high-quality phenomics platform
Exec={executable_path}
Categories=Science;
"""
def get_package_hash(packages, pattern="*.py", **kwargs):
return get_hash((p.replace(".", os.sep) for p in packages), pattern=pattern, **kwargs)
def get_hash_all_files(root, depth=4, **kwargs):
pattern = ["**"] * depth
return get_hash(
("{0}{1}{2}{1}*".format(root, os.sep, os.sep.join(pattern[:d])) for d in range(depth)), **kwargs)
def get_hash(paths, pattern=None, hasher=None, buffsize=65536):
if hasher is None:
hasher = sha256()
files = chain(*(sorted(glob.iglob(os.path.join(path, pattern)) if pattern else path) for path in paths))
for file in files:
try:
# _logger.info("Hashing {0} {1}".format(hasher.hexdigest(), file))
with open(file, 'rb') as f:
buff = f.read(buffsize)
while buff:
hasher.update(buff)
buff = f.read(buffsize)
except IOError:
pass
return hasher
def update_init_file(do_version=True, do_branch=True, release=False):
pass
def _clone_all_files_in(path):
for child in glob.glob(os.path.join(path, "*")):
local_child = child[len(path) + (not path.endswith(os.sep) and 1 or 0):]
if os.path.isdir(child):
for grandchild, _ in _clone_all_files_in(child):
yield os.path.join(local_child, grandchild), True
else:
yield local_child, True
def install_data_files(target_base=None, source_base=None, install_list=None, silent=False):
p = re.compile(r'ver=_-_VERSIONTAG_-_')
cur_dir = os.path.dirname(sys.argv[1])
if not cur_dir:
cur_dir = os.path.curdir
buff_size = 65536
replacement = r'ver={1.0}'
_logger.info("Data gets installed as {0}".format(replacement))
if target_base is None:
target_base = os.path.join(home_dir, installPath)
if source_base is None:
source_base = defaultSourceBase
if install_list is None:
install_list = data_files
if not os.path.isdir(target_base):
os.mkdir(target_base)
os.chmod(target_base, 0755)
for install_instruction in install_list:
relative_directory, files = install_instruction
source_directory = os.path.join(source_base, relative_directory)
target_directory = os.path.join(target_base, relative_directory)
if not os.path.isdir(target_directory):
os.makedirs(target_directory, 0755)
if files is None:
files = dict(_clone_all_files_in(source_directory))
print files
for file_name in files:
source_path = os.path.join(source_directory, file_name)
target_path = os.path.join(target_directory, file_name)
if not os.path.isdir(os.path.dirname(target_path)):
os.makedirs(os.path.dirname(target_path), 0755)
if not os.path.isfile(target_path) and files[file_name] is None:
_logger.info("Creating file {0}".format(target_path))
fh = open(target_path, 'w')
fh.close()
elif (not os.path.isfile(target_path) or files[file_name] or silent or 'y' in raw_input(
"Do you want to overwrite {0} (y/N)".format(target_path)).lower()):
_logger.info(
"Copying file: {0} => {1}".format(
source_path, target_path))
b = BytesIO()
with open(source_path, 'rb') as fh:
buff = fh.read()
b.write(p.sub(replacement, buff))
b.flush()
b.seek(0)
with open(target_path, 'wb') as fh:
fh.write(b.read())
os.chmod(target_path, defaltPermission)
def linux_launcher_install():
user_home = os.path.expanduser("~")
exec_path = os.path.join(user_home, '.local', 'bin', 'scan-o-matic')
if not os.path.isfile(exec_path):
exec_path = os.path.join(os.sep, 'usr', 'local', 'bin', 'scan-o-matic')
text = _launcher_text.format(user_home=user_home, executable_path=exec_path)
target = os.path.join(user_home, '.local', 'share', 'applications', 'scan-o-matic.desktop')
try:
with open(target, 'w') as fh:
fh.write(text)
except IOError:
_logger.error("Could not install desktop launcher automatically, you have an odd linux system.")
_logger.info("""You may want to make a manual 'scan-o-matic.desktop' launcher and place it somewhere nice.
If so, this is what should be its contents:\n\n{0}\n""".format(text))
else:
os.chmod(target, os.stat(target)[stat.ST_MODE] | stat.S_IXUSR)
_logger.info("Installed desktop launcher for linux menu/dash etc.")
def install_launcher():
if sys.platform.startswith('linux'):
linux_launcher_install()
else:
_logger.warning("Don't know how to install launchers for this os...")
def uninstall():
_logger.info("Uninstalling")
uninstall_lib(_logger)
uninstall_executables(_logger)
uninstall_launcher(_logger)
def uninstall_lib(l):
current_location = os.path.abspath(os.curdir)
os.chdir(os.pardir)
import shutil
try:
import scanomatic as som
l.info("Found installation at {0}".format(som.__file__))
if os.path.abspath(som.__file__) != som.__file__ or current_location in som.__file__:
l.error("Trying to uninstall the local folder, just remove it instead if this was intended")
else:
try:
shutil.rmtree(os.path.dirname(som.__file__))
except OSError:
l.error("Not enough permissions to remove {0}".format(os.path.dirname(som.__file__)))
parent_dir = os.path.dirname(os.path.dirname(som.__file__))
for egg in glob.glob(os.path.join(parent_dir, "Scan_o_Matic*.egg-info")):
try:
os.remove(egg)
except OSError:
l.error("Not enough permissions to remove {0}".format(egg))
l.info("Removed installation at {0}".format(som.__file__))
except (ImportError, OSError):
l.info("All install location removed")
l.info("Uninstall complete")
os.chdir(current_location)
def uninstall_executables(l):
for path in os.environ['PATH'].split(":"):
for file_path in glob.glob(os.path.join(path, "scan-o-matic*")):
l.info("Removing {0}".format(file_path))
try:
os.remove(file_path)
except OSError:
l.warning("Not enough permission to remove {0}".format(file_path))
def uninstall_launcher(l):
user_home = os.path.expanduser("~")
if sys.platform.startswith('linux'):
target = os.path.join(user_home, '.local', 'share', 'applications', 'scan-o-matic.desktop')
l.info("Removing desktop-launcher/menu integration at {0}".format(target))
try:
os.remove(target)
except OSError:
l.info("No desktop-launcher/menu integration was found or no permission to remove it")
else:
l.info("Not on linux, no launcher should have been installed.")
def purge():
uninstall()
import shutil
settings = os.path.join(home_dir, ".scan-o-matic")
try:
shutil.rmtree(os.path.join(home_dir, settings))
_logger.info("Setting have been purged")
except IOError:
_logger.info("No settings found")
def test_executable_is_reachable(path='scan-o-matic'):
try:
ret = call([path, '--help'], stdout=PIPE)
except (IOError, OSError):
return False
return ret == 0
def patch_bashrc_if_not_reachable(silent=False):
if not test_executable_is_reachable():
for path in [('~', '.local', 'bin')]:
path = os.path.expanduser(os.path.join(*path))
if test_executable_is_reachable(path) and 'PATH' in os.environ and path not in os.environ['PATH']:
if silent or 'y' in raw_input(
"The installation path is not in your environmental variable PATH"
"Do you wish me to append it in your `.bashrc` file? (Y/n)").lower():
with open(os.path.expanduser(os.path.join("~", ".bashrc")), 'a') as fh:
fh.write("\nexport PATH=$PATH:{0}\n".format(path))
_logger.info("You will need to open a new terminal before you can launch `scan-o-matic`.")
else:
_logger.info("Skipping PATH patching")
#
if __name__ == "__main__":
if len(sys.argv) > 1:
action = sys.argv[1].lower()
if action == 'install-settings':
install_data_files()
elif action == 'uninstall':
uninstall()
elif action == 'purge':
purge()
elif action == 'install-launcher':
install_launcher()
else:
_logger.info("Valid options are 'install-settings', 'install-launcher', 'uninstall', 'purge'")