-
Notifications
You must be signed in to change notification settings - Fork 0
/
hwaf-runtime.py
525 lines (454 loc) · 15.2 KB
/
hwaf-runtime.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# -*- python -*-
### imports -------------------------------------------------------------------
# stdlib imports ---
import os
import os.path as osp
import platform
import subprocess
import sys
# waf imports ---
from waflib.Configure import conf
import waflib.Context
import waflib.Logs as msg
import waflib.Task
import waflib.TaskGen
import waflib.Utils
_heptooldir = osp.dirname(osp.abspath(__file__))
### ---------------------------------------------------------------------------
class hwaf_runtime_tsk(waflib.Task.Task):
"""
A task to properly configure runtime environment
"""
color = 'PINK'
reentrant = False
always = True
def run(self):
return
pass # class hwaf_runtime_tsk
### ---------------------------------------------------------------------------
@conf
def hwaf_setup_runtime(self):
feats = waflib.TaskGen.feats['hwaf_runtime_tsk']
for fctname in feats:
#msg.info("triggering [%s]..." % fctname)
fct = getattr(waflib.TaskGen.task_gen, fctname, None)
if fct:
# extract un-decorated function...
fct = getattr(fct, '__func__', fct)
fct(self)
pass
#msg.info("triggering [%s]... [done]" % fctname)
return
### ---------------------------------------------------------------------------
import waflib.Utils
from waflib.TaskGen import feature, before_method, after_method
@feature('hwaf_runtime_tsk', '*')
@before_method('process_rule')
def insert_project_level_bindir(self):
'''
insert_project_level_bindir adds ${INSTALL_AREA}/bin into the
${PATH} environment variable.
'''
_get = getattr(self, 'hwaf_get_install_path', None)
if not _get: _get = getattr(self.bld, 'hwaf_get_install_path')
d = _get('${INSTALL_AREA}/bin')
self.env.prepend_value('PATH', d)
return
### ---------------------------------------------------------------------------
import waflib.Utils
from waflib.TaskGen import feature, before_method, after_method
@feature('hwaf_runtime_tsk', '*')
@before_method('process_rule')
def insert_project_level_libdir(self):
'''
insert_project_level_bindir adds ${INSTALL_AREA}/lib into the
${LD_LIBRARY_PATH} and ${DYLD_LIBRARY_PATH} environment variables.
'''
_get = getattr(self, 'hwaf_get_install_path', None)
if not _get: _get = getattr(self.bld, 'hwaf_get_install_path')
d = _get('${INSTALL_AREA}/lib')
self.env.prepend_value('LD_LIBRARY_PATH', d)
self.env.prepend_value('DYLD_LIBRARY_PATH', d)
return
### ---------------------------------------------------------------------------
import waflib.Utils
from waflib.TaskGen import feature, before_method, after_method
@feature('*')
@after_method('insert_project_level_bindir','insert_project_level_libdir')
def hwaf_setup_runtime_env(self):
'''
hwaf_setup_runtime_env crafts a correct os.environ from the ctx.env.
'''
env = _hwaf_get_runtime_env(self.bld)
for k in self.env.HWAF_RUNTIME_ENVVARS:
v = env.get(k, None)
if v is None: continue
os.environ[k] = v
return
### ---------------------------------------------------------------------------
import waflib.Build
import waflib.Scripting
import waflib.Utils
class RunCmdContext(waflib.Build.BuildContext):
"""run a command within the correct runtime environment"""
cmd = 'run'
def execute_build(self):
self.logger = msg
lvl = msg.log.level
if lvl < msg.logging.ERROR:
msg.log.setLevel(msg.logging.ERROR)
pass
try:
ret = super(RunCmdContext, self).execute_build()
finally:
msg.log.setLevel(lvl)
#msg.info("args: %s" % waflib.Options.commands)
if not waflib.Options.commands:
self.fatal('%s expects at least one package name. got: %s' %
(self.cmd, waflib.Options.commands))
args = []
while waflib.Options.commands:
arg = waflib.Options.commands.pop(0)
#msg.info("arg: %r" % arg)
args.append(arg)
pass
#msg.info("args: %s" % args)
self.hwaf_setup_runtime()
ret = hwaf_run_cmd_with_runtime_env(self, args)
return ret
pass # RunCmdContext
def _hwaf_get_runtime_env(ctx):
"""return an environment suitably modified to run locally built programs
"""
import os
cwd = os.getcwd()
root = os.path.realpath(ctx.env.PREFIX)
root = os.path.abspath(os.path.realpath(ctx.env.INSTALL_AREA))
#msg.info(":::root:::"+root)
if ctx.env.DESTDIR:
root = ctx.env.DESTDIR + os.sep + ctx.env.INSTALL_AREA
pass
bindir = os.path.join(root, 'bin')
libdir = os.path.join(root, 'lib')
pydir = os.path.join(root, 'python')
env = dict(os.environ)
def _env_prepend(k, args):
old_v = env.get(k, '').split(os.pathsep)
if isinstance(args, (list,tuple)):
env[k] = os.pathsep.join(args)
else:
env[k] = args
pass
if old_v:
env[k] = os.pathsep.join([env[k]]+old_v)
pass
return
def _clean_env_path(env, k):
paths = env.get(k, '').split(os.pathsep)
o = []
for p in paths:
if osp.exists(p):
o.append(p)
pass
#else: msg.info("discarding: %s" % p)
pass
env[k] = os.pathsep.join(o)
return
for k in ctx.env.keys():
v = ctx.env[k]
if k in ctx.env.HWAF_RUNTIME_ENVVARS:
if isinstance(v, (list,tuple)):
if len(v) == 1: v = v[0]
else:
if k.endswith('PATH'): v = os.pathsep.join(v)
else: v = " ".join(v)
pass
# FIXME: we should have an API to decide...
if k.endswith('PATH'): _env_prepend(k, osp.abspath(v))
else: env[k]=v
continue
# reject invalid values (for an environment)
if isinstance(v, (list,tuple)):
continue
env[k] = str(v)
pass
## handle the shell flavours...
if ctx.is_linux():
shell = os.environ.get("SHELL", "/bin/sh")
elif ctx.is_darwin():
shell = os.environ.get("SHELL", "/bin/sh")
shell = shell.strip()
if shell.startswith('-'):
shell = shell[1:]
elif ctx.is_windows():
## FIXME: ???
shell = None
else:
shell = None
pass
# catch-all
if not shell or "(deleted)" in shell:
# fallback on the *login* shell
shell = os.environ.get("SHELL", "/bin/sh")
pass
env['SHELL'] = shell
for k in env:
v = env[k]
if not isinstance(v, str):
msg.warning('env[%s]=%r (%s)' % (k,v,type(v)))
del env[k]
for k in (
'PATH',
'LD_LIBRARY_PATH',
'DYLD_LIBRARY_PATH',
'PYTHONPATH',
):
_clean_env_path(env, k)
pass
return env
def hwaf_run_cmd_with_runtime_env(ctx, cmds):
# make sure we build first"
# waflib.Scripting.run_command('install')
import os
import tempfile
import textwrap
#env = ctx.env
cwd = os.getcwd()
# get the runtime...
env = _hwaf_get_runtime_env(ctx)
# retrieve the directory from which to run the command
ishell_cwd = os.environ.get('HWAF_WAF_SHELL_CWD', cwd)
for k in env:
v = env[k]
if not isinstance(v, str):
ctx.fatal('env[%s]=%r (%s)' % (k,v,type(v)))
pass
pass
shell_cmd = cmds[:]
import pipes # FIXME: use shlex.quote when available ?
from string import Template as str_template
cmds=' '.join(pipes.quote(str_template(s).safe_substitute(env)) for s in cmds)
retval = subprocess.Popen(
cmds,
env=env,
cwd=ishell_cwd,
shell=True,
).wait()
if retval:
signame = None
if retval < 0: # signal?
import signal
for name, val in vars(signal).items():
if len(name) > 3 and name[:3] == 'SIG' and name[3] != '_':
if val == -retval:
signame = name
break
if signame:
raise waflib.Errors.WafError(
"Command '%s' terminated with signal %s." % (cmds, signame))
else:
raise waflib.Errors.WafError(
"Command '%s' exited with code %i" % (cmds, retval))
pass
return retval
### ---------------------------------------------------------------------------
import waflib.Build
import waflib.Scripting
import waflib.Utils
class IShellContext(waflib.Build.BuildContext):
"""run an interactive shell with an environment suitably modified to run locally built programs"""
cmd = 'shell'
#fun = 'shell'
def execute_build(self):
self.logger = msg
lvl = msg.log.level
if lvl < msg.logging.ERROR:
msg.log.setLevel(msg.logging.ERROR)
pass
try:
ret = super(IShellContext, self).execute_build()
finally:
msg.log.setLevel(lvl)
self.hwaf_setup_runtime()
ret = hwaf_ishell(self)
return ret
def hwaf_ishell(ctx):
# make sure we build first"
# waflib.Scripting.run_command('install')
import os
import tempfile
import textwrap
#env = ctx.env
cwd = os.getcwd()
root = os.path.realpath(ctx.options.prefix)
root = os.path.abspath(os.path.realpath(ctx.env['INSTALL_AREA']))
bindir = os.path.join(root, 'bin')
libdir = os.path.join(root, 'lib')
pydir = os.path.join(root, 'python')
# get the runtime...
env = _hwaf_get_runtime_env(ctx)
# retrieve the directory from which to run the shell
ishell_cwd = os.environ.get('HWAF_WAF_SHELL_CWD', cwd)
## handle the shell flavours...
if ctx.is_linux():
shell = os.environ.get("SHELL", "/bin/sh")
elif ctx.is_darwin():
shell = os.environ.get("SHELL", "/bin/sh")
shell = shell.strip()
if shell.startswith('-'):
shell = shell[1:]
elif ctx.is_windows():
## FIXME: ???
shell = None
else:
shell = None
pass
# catch-all
if not shell or "(deleted)" in shell:
# fallback on the *login* shell
shell = os.environ.get("SHELL", "/bin/sh")
tmpdir = tempfile.mkdtemp(prefix='hwaf-env-')
dotrc = None
dotrc_fname = None
shell_cmd = [shell,]
msg.info("---> shell: %s" % shell)
shell_alias = '='
if 'zsh' in os.path.basename(shell):
env['ZDOTDIR'] = tmpdir
dotrc_fname = os.path.join(tmpdir, '.zshrc')
shell_cmd.append('-i')
elif 'bash' in os.path.basename(shell):
dotrc_fname = os.path.join(tmpdir, '.bashrc')
shell_cmd += [
'--init-file',
dotrc_fname,
'-i',
]
elif 'csh' in os.path.basename(shell):
msg.info('sorry, c-shells not handled at the moment: fallback to bash')
dotrc_fname = os.path.join(tmpdir, '.bashrc')
shell_cmd += [
'--init-file',
dotrc_fname,
'-i',
]
# FIXME: when c-shells are supported...
# c-shells use a space as an alias separation token
# in c-shell:
# alias ll 'ls -l'
# in s-shell:
# alias ll='ls -l'
#shell_alias = ' '
else:
# default to dash...
dotrc_fname = os.path.join(tmpdir, '.bashrc')
shell_cmd += [
#'--init-file',
#dotrc_fname,
'-i',
]
env['ENV'] = dotrc_fname
pass
###
hwaf_runtime_aliases = ";\n".join([
"alias %s%s'%s'" % (alias[0], shell_alias, alias[1])
for alias in ctx.env.HWAF_RUNTIME_ALIASES
])
dotrc = open(dotrc_fname, 'w')
dotrc.write(textwrap.dedent(
'''
## automatically generated by hwaf-shell
echo ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
echo ":: launching a sub-shell with the correct environment..."
echo ":: sourcing ${HOME}/%(dotrc_fname)s..."
source ${HOME}/%(dotrc_fname)s
echo ":: sourcing ${HOME}/%(dotrc_fname)s... [done]"
# adjust env. variables
export PATH=%(hwaf_path)s
export LD_LIBRARY_PATH=%(hwaf_ld_library_path)s
export DYLD_LIBRARY_PATH=%(hwaf_dyld_library_path)s
export PYTHONPATH=%(hwaf_pythonpath)s
# customize PS1 so we know we are in a hwaf subshell
export PS1="[hwaf] ${PS1}"
# setup aliases
%(hwaf_runtime_aliases)s
echo ":: hwaf environment... [setup]"
echo ":: hit ^D or exit to go back to the parent shell"
echo ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
''' % {
'dotrc_fname' : os.path.basename(dotrc_fname),
'hwaf_path': env['PATH'],
'hwaf_ld_library_path': env['LD_LIBRARY_PATH'],
'hwaf_dyld_library_path': env['DYLD_LIBRARY_PATH'],
'hwaf_pythonpath': env['PYTHONPATH'],
'hwaf_runtime_aliases': hwaf_runtime_aliases,
}
))
dotrc.flush()
dotrc.close()
for k in env:
v = env[k]
if not isinstance(v, str):
ctx.fatal('env[%s]=%r (%s)' % (k,v,type(v)))
pass
pass
retval = subprocess.Popen(
shell_cmd,
env=env,
cwd=ishell_cwd,
shell=True,
).wait()
try:
import shutil
shutil.rmtree(tmpdir)
except Exception:
msg.verbose('could not remove directory [%s]' % tmpdir)
pass
if retval:
signame = None
if retval < 0: # signal?
import signal
for name, val in vars(signal).items():
if len(name) > 3 and name[:3] == 'SIG' and name[3] != '_':
if val == -retval:
signame = name
break
if signame:
raise waflib.Errors.WafError(
"Command %s terminated with signal %s." % (shell_cmd, signame))
else:
raise waflib.Errors.WafError(
"Command %s exited with code %i" % (shell_cmd, retval))
return retval
### ---------------------------------------------------------------------------
import waflib.Build
import waflib.Scripting
import waflib.Utils
class DumpEnvCmdContext(waflib.Build.BuildContext):
"""print the runtime environment in a json format"""
cmd = 'dump-env'
def execute_build(self):
self.logger = msg
lvl = msg.log.level
if lvl < msg.logging.ERROR:
msg.log.setLevel(msg.logging.ERROR)
pass
try:
ret = super(DumpEnvCmdContext, self).execute_build()
finally:
msg.log.setLevel(lvl)
py_exe = self.env.PYTHON
if isinstance(py_exe, (list, tuple)):
if len(py_exe) > 0: py_exe = str(py_exe[0])
else: py_exe = "python"
pass
if py_exe == "": py_exe = "python"
# get the runtime...
env = _hwaf_get_runtime_env(self)
import json
import sys
sys.stdout.write("%s\n" % json.dumps(env))
sys.stdout.flush()
return 0
pass # RunCmdContext
## EOF ##