You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

208 lines
6.6 KiB

6 years ago
  1. # -*- python -*-
  2. #
  3. # Copyright (c) 2001 - 2017 The SCons Foundation
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining
  6. # a copy of this software and associated documentation files (the
  7. # "Software"), to deal in the Software without restriction, including
  8. # without limitation the rights to use, copy, modify, merge, publish,
  9. # distribute, sublicense, and/or sell copies of the Software, and to
  10. # permit persons to whom the Software is furnished to do so, subject to
  11. # the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included
  14. # in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  17. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  18. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. #
  24. __doc__ = """
  25. Textfile/Substfile builder for SCons.
  26. Create file 'target' which typically is a textfile. The 'source'
  27. may be any combination of strings, Nodes, or lists of same. A
  28. 'linesep' will be put between any part written and defaults to
  29. os.linesep.
  30. The only difference between the Textfile builder and the Substfile
  31. builder is that strings are converted to Value() nodes for the
  32. former and File() nodes for the latter. To insert files in the
  33. former or strings in the latter, wrap them in a File() or Value(),
  34. respectively.
  35. The values of SUBST_DICT first have any construction variables
  36. expanded (its keys are not expanded). If a value of SUBST_DICT is
  37. a python callable function, it is called and the result is expanded
  38. as the value. Values are substituted in a "random" order; if any
  39. substitution could be further expanded by another substitution, it
  40. is unpredictable whether the expansion will occur.
  41. """
  42. __revision__ = "src/engine/SCons/Tool/textfile.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  43. import SCons
  44. import os
  45. import re
  46. from SCons.Node import Node
  47. from SCons.Node.Python import Value
  48. from SCons.Util import is_String, is_Sequence, is_Dict, to_bytes, PY3
  49. if PY3:
  50. TEXTFILE_FILE_WRITE_MODE = 'w'
  51. else:
  52. TEXTFILE_FILE_WRITE_MODE = 'wb'
  53. LINESEP = '\n'
  54. def _do_subst(node, subs):
  55. """
  56. Fetch the node contents and replace all instances of the keys with
  57. their values. For example, if subs is
  58. {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},
  59. then all instances of %VERSION% in the file will be replaced with
  60. 1.2345 and so forth.
  61. """
  62. contents = node.get_text_contents()
  63. if subs:
  64. for (k, val) in subs:
  65. contents = re.sub(k, val, contents)
  66. if 'b' in TEXTFILE_FILE_WRITE_MODE:
  67. try:
  68. contents = bytearray(contents, 'utf-8')
  69. except UnicodeDecodeError:
  70. # contents is already utf-8 encoded python 2 str i.e. a byte array
  71. contents = bytearray(contents)
  72. return contents
  73. def _action(target, source, env):
  74. # prepare the line separator
  75. linesep = env['LINESEPARATOR']
  76. if linesep is None:
  77. linesep = LINESEP # os.linesep
  78. elif is_String(linesep):
  79. pass
  80. elif isinstance(linesep, Value):
  81. linesep = linesep.get_text_contents()
  82. else:
  83. raise SCons.Errors.UserError('unexpected type/class for LINESEPARATOR: %s'
  84. % repr(linesep), None)
  85. if 'b' in TEXTFILE_FILE_WRITE_MODE:
  86. linesep = to_bytes(linesep)
  87. # create a dictionary to use for the substitutions
  88. if 'SUBST_DICT' not in env:
  89. subs = None # no substitutions
  90. else:
  91. subst_dict = env['SUBST_DICT']
  92. if is_Dict(subst_dict):
  93. subst_dict = list(subst_dict.items())
  94. elif is_Sequence(subst_dict):
  95. pass
  96. else:
  97. raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence')
  98. subs = []
  99. for (k, value) in subst_dict:
  100. if callable(value):
  101. value = value()
  102. if is_String(value):
  103. value = env.subst(value)
  104. else:
  105. value = str(value)
  106. subs.append((k, value))
  107. # write the file
  108. try:
  109. if SCons.Util.PY3:
  110. target_file = open(target[0].get_path(), TEXTFILE_FILE_WRITE_MODE, newline='')
  111. else:
  112. target_file = open(target[0].get_path(), TEXTFILE_FILE_WRITE_MODE)
  113. except (OSError, IOError):
  114. raise SCons.Errors.UserError("Can't write target file %s" % target[0])
  115. # separate lines by 'linesep' only if linesep is not empty
  116. lsep = None
  117. for line in source:
  118. if lsep:
  119. target_file.write(lsep)
  120. target_file.write(_do_subst(line, subs))
  121. lsep = linesep
  122. target_file.close()
  123. def _strfunc(target, source, env):
  124. return "Creating '%s'" % target[0]
  125. def _convert_list_R(newlist, sources):
  126. for elem in sources:
  127. if is_Sequence(elem):
  128. _convert_list_R(newlist, elem)
  129. elif isinstance(elem, Node):
  130. newlist.append(elem)
  131. else:
  132. newlist.append(Value(elem))
  133. def _convert_list(target, source, env):
  134. if len(target) != 1:
  135. raise SCons.Errors.UserError("Only one target file allowed")
  136. newlist = []
  137. _convert_list_R(newlist, source)
  138. return target, newlist
  139. _common_varlist = ['SUBST_DICT', 'LINESEPARATOR']
  140. _text_varlist = _common_varlist + ['TEXTFILEPREFIX', 'TEXTFILESUFFIX']
  141. _text_builder = SCons.Builder.Builder(
  142. action=SCons.Action.Action(_action, _strfunc, varlist=_text_varlist),
  143. source_factory=Value,
  144. emitter=_convert_list,
  145. prefix='$TEXTFILEPREFIX',
  146. suffix='$TEXTFILESUFFIX',
  147. )
  148. _subst_varlist = _common_varlist + ['SUBSTFILEPREFIX', 'TEXTFILESUFFIX']
  149. _subst_builder = SCons.Builder.Builder(
  150. action=SCons.Action.Action(_action, _strfunc, varlist=_subst_varlist),
  151. source_factory=SCons.Node.FS.File,
  152. emitter=_convert_list,
  153. prefix='$SUBSTFILEPREFIX',
  154. suffix='$SUBSTFILESUFFIX',
  155. src_suffix=['.in'],
  156. )
  157. def generate(env):
  158. env['LINESEPARATOR'] = LINESEP # os.linesep
  159. env['BUILDERS']['Textfile'] = _text_builder
  160. env['TEXTFILEPREFIX'] = ''
  161. env['TEXTFILESUFFIX'] = '.txt'
  162. env['BUILDERS']['Substfile'] = _subst_builder
  163. env['SUBSTFILEPREFIX'] = ''
  164. env['SUBSTFILESUFFIX'] = ''
  165. def exists(env):
  166. return 1
  167. # Local Variables:
  168. # tab-width:4
  169. # indent-tabs-mode:nil
  170. # End:
  171. # vim: set expandtab tabstop=4 shiftwidth=4: