forked from devcurmudgeon/ybd
/
app.py
148 lines (118 loc) · 4.42 KB
/
app.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
# Copyright (C) 2014-2015 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# =*= License: GPL-2 =*=
import contextlib
import datetime
import os
import shutil
import sys
import warnings
import yaml
from multiprocessing import cpu_count
from subprocess import call, check_output
from repos import get_version
xdg_cache_home = os.environ.get('XDG_CACHE_HOME') or \
os.path.join(os.path.expanduser('~'), '.cache')
settings = {}
def log(component, message='', data=''):
''' Print a timestamped log. '''
if os.getpid() != settings.get('pid'):
return
name = component
try:
name = component['name']
except:
pass
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = '%s [%s] %s %s\n' % (timestamp, name, message, data)
if 'ERROR' in log_entry:
log_entry = '\n\n%s\n\n' % log_entry
print(log_entry),
def log_env(log, env, message=''):
with open(log, "a") as logfile:
for key in sorted(env):
msg = env[key] if 'PASSWORD' not in key else '(hidden)'
logfile.write('%s=%s\n' % (key, msg))
logfile.write(message + '\n')
logfile.flush()
def exit(component, message, data):
log(component, message, data)
sys.exit(1)
def warning_handler(message, category, filename, lineno, file=None, line=None):
'''Output messages from warnings.warn().
The default output is a bit ugly.
'''
return 'WARNING: %s\n' % (message)
@contextlib.contextmanager
def setup(target, arch):
warnings.formatwarning = warning_handler
try:
settings_file = './ybd.def'
if not os.path.exists(settings_file):
settings_file = os.path.join(os.path.dirname(__file__), 'ybd.def')
with open(settings_file) as f:
text = f.read()
for key, value in yaml.safe_load(text).items():
settings[key] = value
settings['pid'] = os.getpid()
with open(os.devnull, "w") as fnull:
if call(['git', 'describe', '--all'], stdout=fnull, stderr=fnull):
exit(target, 'ERROR: not a git repo', os.getcwd())
settings['ybd-version'] = get_version(os.path.dirname(__file__))
settings['defdir'] = os.getcwd()
settings['extsdir'] = os.path.join(settings['defdir'], 'extensions')
settings['def-ver'] = get_version('.')
settings['target'] = target
settings['arch'] = arch
for directory in ['base', 'caches', 'artifacts', 'gits', 'tmp',
'ccache_dir', 'deployment']:
try:
os.makedirs(settings[directory])
except OSError:
if not os.path.isdir(settings[directory]):
exit(target, 'ERROR: Can not find or create',
settings[directory])
# git replace means we can't trust that just the sha1 of a branch
# is enough to say what it contains, so we turn it off by setting
# the right flag in an environment variable.
os.environ['GIT_NO_REPLACE_OBJECTS'] = '1'
settings['max-jobs'] = max(int(cpu_count() * 1.5 + 0.5), 1)
yield
finally:
log(target, 'Finished')
@contextlib.contextmanager
def chdir(dirname=None):
currentdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(currentdir)
@contextlib.contextmanager
def timer(this, start_message=''):
starttime = datetime.datetime.now()
log(this, start_message)
if type(this) is dict:
this['start-time'] = starttime
try:
yield
finally:
log(this, 'Elapsed time', elapsed(starttime))
def elapsed(starttime):
td = datetime.datetime.now() - starttime
hours, remainder = divmod(int(td.total_seconds()), 60*60)
minutes, seconds = divmod(remainder, 60)
return "%02d:%02d:%02d" % (hours, minutes, seconds)