2
from SCons.Script import * # the usual scons stuff you get in a SConscript
6
Add builders and construction variables for the
9
Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
10
from the source to the target.
11
The values of SUBST_DICT first have any construction variables expanded
12
(its keys are not expanded).
13
If a value of SUBST_DICT is a python callable function, it is called and
14
the result is expanded as the value.
15
If there's more than one source and more than one target, each target gets
16
substituted from the corresponding source.
18
def do_subst_in_file(targetfile, sourcefile, dict):
19
"""Replace all instances of the keys of dict with their values.
20
For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},
21
then all instances of %VERSION% in the file will be replaced with 1.2345 etc.
24
f = open(sourcefile, 'rb')
28
raise SCons.Errors.UserError, "Can't read source file %s"%sourcefile
29
for (k,v) in dict.items():
30
contents = re.sub(k, v, contents)
32
f = open(targetfile, 'wb')
36
raise SCons.Errors.UserError, "Can't write target file %s"%targetfile
39
def subst_in_file(target, source, env):
40
if not env.has_key('SUBST_DICT'):
41
raise SCons.Errors.UserError, "SubstInFile requires SUBST_DICT to be set."
42
d = dict(env['SUBST_DICT']) # copy it
43
for (k,v) in d.items():
45
d[k] = env.subst(v()).replace('\\','\\\\')
46
elif SCons.Util.is_String(v):
47
d[k] = env.subst(v).replace('\\','\\\\')
49
raise SCons.Errors.UserError, "SubstInFile: key %s: %s must be a string or callable"%(k, repr(v))
50
for (t,s) in zip(target, source):
51
return do_subst_in_file(str(t), str(s), d)
53
def subst_in_file_string(target, source, env):
54
"""This is what gets printed on the console."""
55
return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t))
56
for (t,s) in zip(target, source)])
58
def subst_emitter(target, source, env):
59
"""Add dependency from substituted SUBST_DICT to target.
60
Returns original target, source tuple unchanged.
62
d = env['SUBST_DICT'].copy() # copy it
63
for (k,v) in d.items():
66
elif SCons.Util.is_String(v):
68
Depends(target, SCons.Node.Python.Value(d))
71
## env.Append(TOOLS = 'substinfile') # this should be automaticaly done by Scons ?!?
72
subst_action = SCons.Action.Action( subst_in_file, subst_in_file_string )
73
env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter)
77
Make sure tool exists.