version.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/env python3
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """
  6. version.py -- Chromium version string substitution utility.
  7. """
  8. from __future__ import print_function
  9. import argparse
  10. import os
  11. import sys
  12. import android_chrome_version
  13. def FetchValuesFromFile(values_dict, file_name):
  14. """
  15. Fetches KEYWORD=VALUE settings from the specified file.
  16. Everything to the left of the first '=' is the keyword,
  17. everything to the right is the value. No stripping of
  18. white space, so beware.
  19. The file must exist, otherwise you get the Python exception from open().
  20. """
  21. with open(file_name, 'r') as f:
  22. for line in f.readlines():
  23. key, val = line.rstrip('\r\n').split('=', 1)
  24. values_dict[key] = val
  25. def FetchValues(file_list, is_official_build=None):
  26. """
  27. Returns a dictionary of values to be used for substitution.
  28. Populates the dictionary with KEYWORD=VALUE settings from the files in
  29. 'file_list'.
  30. Explicitly adds the following value from internal calculations:
  31. OFFICIAL_BUILD
  32. """
  33. CHROME_BUILD_TYPE = os.environ.get('CHROME_BUILD_TYPE')
  34. if CHROME_BUILD_TYPE == '_official' or is_official_build:
  35. official_build = '1'
  36. else:
  37. official_build = '0'
  38. values = dict(
  39. OFFICIAL_BUILD = official_build,
  40. )
  41. for file_name in file_list:
  42. FetchValuesFromFile(values, file_name)
  43. script_dirname = os.path.dirname(os.path.realpath(__file__))
  44. lastchange_filename = os.path.join(script_dirname, "LASTCHANGE")
  45. lastchange_values = {}
  46. FetchValuesFromFile(lastchange_values, lastchange_filename)
  47. for placeholder_key, placeholder_value in values.items():
  48. values[placeholder_key] = SubstTemplate(placeholder_value,
  49. lastchange_values)
  50. return values
  51. def SubstTemplate(contents, values):
  52. """
  53. Returns the template with substituted values from the specified dictionary.
  54. Keywords to be substituted are surrounded by '@': @KEYWORD@.
  55. No attempt is made to avoid recursive substitution. The order
  56. of evaluation is random based on the order of the keywords returned
  57. by the Python dictionary. So do NOT substitute a value that
  58. contains any @KEYWORD@ strings expecting them to be recursively
  59. substituted, okay?
  60. """
  61. for key, val in values.items():
  62. try:
  63. contents = contents.replace('@' + key + '@', val)
  64. except TypeError:
  65. print(repr(key), repr(val))
  66. return contents
  67. def SubstFile(file_name, values):
  68. """
  69. Returns the contents of the specified file_name with substituted values.
  70. Substituted values come from the specified dictionary.
  71. This is like SubstTemplate, except it operates on a file.
  72. """
  73. template = open(file_name, 'r').read()
  74. return SubstTemplate(template, values)
  75. def WriteIfChanged(file_name, contents):
  76. """
  77. Writes the specified contents to the specified file_name.
  78. Does nothing if the contents aren't different than the current contents.
  79. """
  80. try:
  81. old_contents = open(file_name, 'r').read()
  82. except EnvironmentError:
  83. pass
  84. else:
  85. if contents == old_contents:
  86. return
  87. os.unlink(file_name)
  88. open(file_name, 'w').write(contents)
  89. def BuildParser():
  90. """Build argparse parser, with added arguments."""
  91. parser = argparse.ArgumentParser()
  92. parser.add_argument('-f', '--file', action='append', default=[],
  93. help='Read variables from FILE.')
  94. parser.add_argument('-i', '--input', default=None,
  95. help='Read strings to substitute from FILE.')
  96. parser.add_argument('-o', '--output', default=None,
  97. help='Write substituted strings to FILE.')
  98. parser.add_argument('-t', '--template', default=None,
  99. help='Use TEMPLATE as the strings to substitute.')
  100. parser.add_argument(
  101. '-e',
  102. '--eval',
  103. action='append',
  104. default=[],
  105. help='Evaluate VAL after reading variables. Can be used '
  106. 'to synthesize variables. e.g. -e \'PATCH_HI=int('
  107. 'PATCH)//256.')
  108. parser.add_argument(
  109. '-a',
  110. '--arch',
  111. default=None,
  112. choices=android_chrome_version.ARCH_CHOICES,
  113. help='Set which cpu architecture the build is for.')
  114. parser.add_argument('--os', default=None, help='Set the target os.')
  115. parser.add_argument('--official', action='store_true',
  116. help='Whether the current build should be an official '
  117. 'build, used in addition to the environment '
  118. 'variable.')
  119. parser.add_argument(
  120. '--next',
  121. action='store_true',
  122. help='Whether the current build should be a "next" '
  123. 'build, which targets pre-release versions of '
  124. 'Android')
  125. parser.add_argument('args', nargs=argparse.REMAINDER,
  126. help='For compatibility: INPUT and OUTPUT can be '
  127. 'passed as positional arguments.')
  128. return parser
  129. def BuildEvals(options, parser):
  130. """Construct a dict of passed '-e' arguments for evaluating."""
  131. evals = {}
  132. for expression in options.eval:
  133. try:
  134. evals.update(dict([expression.split('=', 1)]))
  135. except ValueError:
  136. parser.error('-e requires VAR=VAL')
  137. return evals
  138. def ModifyOptionsCompat(options, parser):
  139. """Support compatibility with old versions.
  140. Specifically, for old versions that considered the first two
  141. positional arguments shorthands for --input and --output.
  142. """
  143. while len(options.args) and (options.input is None or options.output is None):
  144. if options.input is None:
  145. options.input = options.args.pop(0)
  146. elif options.output is None:
  147. options.output = options.args.pop(0)
  148. if options.args:
  149. parser.error('Unexpected arguments: %r' % options.args)
  150. def GenerateValues(options, evals):
  151. """Construct a dict of raw values used to generate output.
  152. e.g. this could return a dict like
  153. {
  154. 'BUILD': 74,
  155. }
  156. which would be used to resolve a template like
  157. 'build = "@BUILD@"' into 'build = "74"'
  158. """
  159. values = FetchValues(options.file, options.official)
  160. for key, val in evals.items():
  161. values[key] = str(eval(val, globals(), values))
  162. if options.os == 'android':
  163. android_chrome_version_codes = android_chrome_version.GenerateVersionCodes(
  164. values, options.arch, options.next)
  165. values.update(android_chrome_version_codes)
  166. return values
  167. def GenerateOutputContents(options, values):
  168. """Construct output string (e.g. from template).
  169. Arguments:
  170. options -- argparse parsed arguments
  171. values -- dict with raw values used to resolve the keywords in a template
  172. string
  173. """
  174. if options.template is not None:
  175. return SubstTemplate(options.template, values)
  176. elif options.input:
  177. return SubstFile(options.input, values)
  178. else:
  179. # Generate a default set of version information.
  180. return """MAJOR=%(MAJOR)s
  181. MINOR=%(MINOR)s
  182. BUILD=%(BUILD)s
  183. PATCH=%(PATCH)s
  184. LASTCHANGE=%(LASTCHANGE)s
  185. OFFICIAL_BUILD=%(OFFICIAL_BUILD)s
  186. """ % values
  187. def BuildOutput(args):
  188. """Gets all input and output values needed for writing output."""
  189. # Build argparse parser with arguments
  190. parser = BuildParser()
  191. options = parser.parse_args(args)
  192. # Get dict of passed '-e' arguments for evaluating
  193. evals = BuildEvals(options, parser)
  194. # For compatibility with interface that considered first two positional
  195. # arguments shorthands for --input and --output.
  196. ModifyOptionsCompat(options, parser)
  197. # Get the raw values that will be used the generate the output
  198. values = GenerateValues(options, evals)
  199. # Get the output string
  200. contents = GenerateOutputContents(options, values)
  201. return {'options': options, 'contents': contents}
  202. def main():
  203. output = BuildOutput(sys.argv[1:])
  204. if output['options'].output is not None:
  205. WriteIfChanged(output['options'].output, output['contents'])
  206. else:
  207. print(output['contents'])
  208. return 0
  209. if __name__ == '__main__':
  210. sys.exit(main())