update_build_version.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python
  2. # Copyright (c) 2016 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # Updates an output file with version info unless the new content is the same
  16. # as the existing content.
  17. #
  18. # Args: <spirv-tools_dir> <output-file>
  19. #
  20. # The output file will contain a line of text consisting of two C source syntax
  21. # string literals separated by a comma:
  22. # - The software version deduced from the CHANGES file in the given directory.
  23. # - A longer string with the project name, the software version number, and
  24. # git commit information for the directory. The commit information
  25. # is the output of "git describe" if that succeeds, or "git rev-parse HEAD"
  26. # if that succeeds, or otherwise a message containing the phrase
  27. # "unknown hash".
  28. # The string contents are escaped as necessary.
  29. import datetime
  30. import errno
  31. import os
  32. import os.path
  33. import re
  34. import subprocess
  35. import sys
  36. import time
  37. def mkdir_p(directory):
  38. """Make the directory, and all its ancestors as required. Any of the
  39. directories are allowed to already exist."""
  40. if directory == "":
  41. # We're being asked to make the current directory.
  42. return
  43. try:
  44. os.makedirs(directory)
  45. except OSError as e:
  46. if e.errno == errno.EEXIST and os.path.isdir(directory):
  47. pass
  48. else:
  49. raise
  50. def command_output(cmd, directory):
  51. """Runs a command in a directory and returns its standard output stream.
  52. Captures the standard error stream.
  53. Raises a RuntimeError if the command fails to launch or otherwise fails.
  54. """
  55. p = subprocess.Popen(cmd,
  56. cwd=directory,
  57. stdout=subprocess.PIPE,
  58. stderr=subprocess.PIPE)
  59. (stdout, _) = p.communicate()
  60. if p.returncode != 0:
  61. raise RuntimeError('Failed to run %s in %s' % (cmd, directory))
  62. return stdout
  63. def deduce_software_version(directory):
  64. """Returns a software version number parsed from the CHANGES file
  65. in the given directory.
  66. The CHANGES file describes most recent versions first.
  67. """
  68. # Match the first well-formed version-and-date line.
  69. # Allow trailing whitespace in the checked-out source code has
  70. # unexpected carriage returns on a linefeed-only system such as
  71. # Linux.
  72. pattern = re.compile(r'^(v\d+\.\d+(-dev)?) \d\d\d\d-\d\d-\d\d\s*$')
  73. changes_file = os.path.join(directory, 'CHANGES')
  74. with open(changes_file, mode='r') as f:
  75. for line in f.readlines():
  76. match = pattern.match(line)
  77. if match:
  78. return match.group(1)
  79. raise Exception('No version number found in {}'.format(changes_file))
  80. def describe(directory):
  81. """Returns a string describing the current Git HEAD version as descriptively
  82. as possible.
  83. Runs 'git describe', or alternately 'git rev-parse HEAD', in directory. If
  84. successful, returns the output; otherwise returns 'unknown hash, <date>'."""
  85. try:
  86. # decode() is needed here for Python3 compatibility. In Python2,
  87. # str and bytes are the same type, but not in Python3.
  88. # Popen.communicate() returns a bytes instance, which needs to be
  89. # decoded into text data first in Python3. And this decode() won't
  90. # hurt Python2.
  91. return command_output(['git', 'describe'], directory).rstrip().decode()
  92. except:
  93. try:
  94. return command_output(
  95. ['git', 'rev-parse', 'HEAD'], directory).rstrip().decode()
  96. except:
  97. # This is the fallback case where git gives us no information,
  98. # e.g. because the source tree might not be in a git tree.
  99. # In this case, usually use a timestamp. However, to ensure
  100. # reproducible builds, allow the builder to override the wall
  101. # clock time with environment variable SOURCE_DATE_EPOCH
  102. # containing a (presumably) fixed timestamp.
  103. timestamp = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
  104. formatted = datetime.datetime.utcfromtimestamp(timestamp).isoformat()
  105. return 'unknown hash, {}'.format(formatted)
  106. def main():
  107. if len(sys.argv) != 3:
  108. print('usage: {} <spirv-tools-dir> <output-file>'.format(sys.argv[0]))
  109. sys.exit(1)
  110. output_file = sys.argv[2]
  111. mkdir_p(os.path.dirname(output_file))
  112. software_version = deduce_software_version(sys.argv[1])
  113. new_content = '"{}", "SPIRV-Tools {} {}"\n'.format(
  114. software_version, software_version,
  115. describe(sys.argv[1]).replace('"', '\\"'))
  116. if os.path.isfile(output_file):
  117. with open(output_file, 'r') as f:
  118. if new_content == f.read():
  119. return
  120. with open(output_file, 'w') as f:
  121. f.write(new_content)
  122. if __name__ == '__main__':
  123. main()