blob: ef18b4edbcb6a9ad7dec9fe602ab486eb0d2376d [file] [log] [blame]
Christopher Dunnf9864232007-06-14 21:01:26 +00001import re
2from SCons.Script import * # the usual scons stuff you get in a SConscript
Christopher Dunnbd1e8952014-11-19 23:30:47 -06003import collections
Christopher Dunnf9864232007-06-14 21:01:26 +00004
5def generate(env):
6 """
7 Add builders and construction variables for the
8 SubstInFile tool.
9
10 Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
11 from the source to the target.
12 The values of SUBST_DICT first have any construction variables expanded
13 (its keys are not expanded).
14 If a value of SUBST_DICT is a python callable function, it is called and
15 the result is expanded as the value.
16 If there's more than one source and more than one target, each target gets
17 substituted from the corresponding source.
18 """
19 def do_subst_in_file(targetfile, sourcefile, dict):
20 """Replace all instances of the keys of dict with their values.
21 For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},
22 then all instances of %VERSION% in the file will be replaced with 1.2345 etc.
23 """
24 try:
25 f = open(sourcefile, 'rb')
26 contents = f.read()
27 f.close()
28 except:
Christopher Dunnbd1e8952014-11-19 23:30:47 -060029 raise SCons.Errors.UserError("Can't read source file %s"%sourcefile)
30 for (k,v) in list(dict.items()):
Christopher Dunnf9864232007-06-14 21:01:26 +000031 contents = re.sub(k, v, contents)
32 try:
33 f = open(targetfile, 'wb')
34 f.write(contents)
35 f.close()
36 except:
Christopher Dunnbd1e8952014-11-19 23:30:47 -060037 raise SCons.Errors.UserError("Can't write target file %s"%targetfile)
Christopher Dunnf9864232007-06-14 21:01:26 +000038 return 0 # success
39
40 def subst_in_file(target, source, env):
Christopher Dunnbd1e8952014-11-19 23:30:47 -060041 if 'SUBST_DICT' not in env:
42 raise SCons.Errors.UserError("SubstInFile requires SUBST_DICT to be set.")
Christopher Dunnf9864232007-06-14 21:01:26 +000043 d = dict(env['SUBST_DICT']) # copy it
Christopher Dunnbd1e8952014-11-19 23:30:47 -060044 for (k,v) in list(d.items()):
45 if isinstance(v, collections.Callable):
Christopher Dunnf9864232007-06-14 21:01:26 +000046 d[k] = env.subst(v()).replace('\\','\\\\')
47 elif SCons.Util.is_String(v):
48 d[k] = env.subst(v).replace('\\','\\\\')
49 else:
Christopher Dunnbd1e8952014-11-19 23:30:47 -060050 raise SCons.Errors.UserError("SubstInFile: key %s: %s must be a string or callable"%(k, repr(v)))
Christopher Dunnf9864232007-06-14 21:01:26 +000051 for (t,s) in zip(target, source):
52 return do_subst_in_file(str(t), str(s), d)
53
54 def subst_in_file_string(target, source, env):
55 """This is what gets printed on the console."""
56 return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t))
57 for (t,s) in zip(target, source)])
58
59 def subst_emitter(target, source, env):
60 """Add dependency from substituted SUBST_DICT to target.
61 Returns original target, source tuple unchanged.
62 """
63 d = env['SUBST_DICT'].copy() # copy it
Christopher Dunnbd1e8952014-11-19 23:30:47 -060064 for (k,v) in list(d.items()):
65 if isinstance(v, collections.Callable):
Christopher Dunnf9864232007-06-14 21:01:26 +000066 d[k] = env.subst(v())
67 elif SCons.Util.is_String(v):
68 d[k]=env.subst(v)
69 Depends(target, SCons.Node.Python.Value(d))
70 return target, source
71
72## env.Append(TOOLS = 'substinfile') # this should be automaticaly done by Scons ?!?
73 subst_action = SCons.Action.Action( subst_in_file, subst_in_file_string )
74 env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter)
75
76def exists(env):
77 """
78 Make sure tool exists.
79 """
80 return True