This repository has been archived by the owner on Sep 23, 2019. It is now read-only.
forked from ffnord/mesh-announce
-
Notifications
You must be signed in to change notification settings - Fork 4
/
gather.py
68 lines (56 loc) · 1.83 KB
/
gather.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
import os
import subprocess
import traceback
from importlib import import_module
def _set_value(node, path, value):
''' Sets a value inside a complex data dictionary.
The path Array must have at least one element.
'''
key = path[0]
if len(path) == 1:
node[key] = value
elif key in node:
_set_value(node[key], path[1:], value)
else:
node[path[0]] = {}
_set_value(node[key], path[1:], value)
def _eval_snippet(f, env):
# definitions of functions used in the snippets go here
def call(cmdnargs):
output = subprocess.check_output(cmdnargs)
lines = output.splitlines()
lines = [line.decode("utf-8") for line in lines]
return lines
real_env = dict(env)
real_env.update({
'call': call,
'import_module': import_module
})
# compile file
with open(f) as fh:
code = compile(fh.read(), os.path.abspath(f), 'eval')
# ensure that files are opened as UTF-8
import locale
encoding_backup = locale.getpreferredencoding
locale.getpreferredencoding = lambda _=None: 'UTF-8'
try:
ret = eval(code, real_env)
finally:
locale.getpreferredencoding = encoding_backup
return ret
def gather_data(directory, env={}):
data = {}
if not os.path.isdir(directory):
return
for dirname, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename[0] != '.':
path = os.path.join(dirname, filename)
relPath = os.path.relpath(path, directory)
try:
value = _eval_snippet(path, env)
_set_value(data, relPath.rsplit(os.sep), value)
except:
# print but don't abort
traceback.print_exc()
return data