• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3# Copyright (c) 2016 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Updates an output file with version info unless the new content is the same
18# as the existing content.
19#
20# Args: <changes-file> <output-file>
21#
22# The output file will contain a line of text consisting of two C source syntax
23# string literals separated by a comma:
24#  - The software version deduced from the given CHANGES file.
25#  - A longer string with the project name, the software version number, and
26#    git commit information for the CHANGES file's directory.  The commit
27#    information is the content of the FORCED_BUILD_VERSION_DESCRIPTION
28#    environement variable is it exists, else the output of "git describe" if
29#    that succeeds, or "git rev-parse HEAD" if that succeeds, or otherwise a
30#    message containing the phrase "unknown hash".
31# The string contents are escaped as necessary.
32
33import datetime
34import errno
35import os
36import os.path
37import re
38import subprocess
39import logging
40import sys
41import time
42
43# Format of the output generated by this script. Example:
44# "v2023.1", "SPIRV-Tools v2023.1 0fc5526f2b01a0cc89192c10cf8bef77f1007a62, 2023-01-18T14:51:49"
45OUTPUT_FORMAT = '"{version_tag}", "SPIRV-Tools {version_tag} {description}"\n'
46
47def mkdir_p(directory):
48    """Make the directory, and all its ancestors as required.  Any of the
49    directories are allowed to already exist."""
50
51    if directory == "":
52        # We're being asked to make the current directory.
53        return
54
55    try:
56        os.makedirs(directory)
57    except OSError as e:
58        if e.errno == errno.EEXIST and os.path.isdir(directory):
59            pass
60        else:
61            raise
62
63def command_output(cmd, directory):
64    """Runs a command in a directory and returns its standard output stream.
65
66    Returns (False, None) if the command fails to launch or otherwise fails.
67    """
68    try:
69      # Set shell=True on Windows so that Chromium's git.bat can be found when
70      # 'git' is invoked.
71      p = subprocess.Popen(cmd,
72                           cwd=directory,
73                           stdout=subprocess.PIPE,
74                           stderr=subprocess.PIPE,
75                           shell=os.name == 'nt')
76      (stdout, _) = p.communicate()
77      if p.returncode != 0:
78        return False, None
79    except Exception as e:
80        return False, None
81    return p.returncode == 0, stdout
82
83def deduce_software_version(changes_file):
84    """Returns a tuple (success, software version number) parsed from the
85    given CHANGES file.
86
87    Success is set to True if the software version could be deduced.
88    Software version is undefined if success if False.
89    Function expects the CHANGES file to describes most recent versions first.
90    """
91
92    # Match the first well-formed version-and-date line
93    # Allow trailing whitespace in the checked-out source code has
94    # unexpected carriage returns on a linefeed-only system such as
95    # Linux.
96    pattern = re.compile(r'^(v\d+\.\d+(-dev)?) \d\d\d\d-\d\d-\d\d\s*$')
97    with open(changes_file, mode='r') as f:
98        for line in f.readlines():
99            match = pattern.match(line)
100            if match:
101                return True, match.group(1)
102    return False, None
103
104
105def describe(repo_path):
106    """Returns a string describing the current Git HEAD version as descriptively
107    as possible.
108
109    Runs 'git describe', or alternately 'git rev-parse HEAD', in directory.  If
110    successful, returns the output; otherwise returns 'unknown hash, <date>'."""
111
112    # if we're in a git repository, attempt to extract version info
113    success, output = command_output(["git", "rev-parse", "--show-toplevel"], repo_path)
114    if success:
115        success, output = command_output(["git", "describe", "--tags", "--match=v*", "--long"], repo_path)
116        if not success:
117            success, output = command_output(["git", "rev-parse", "HEAD"], repo_path)
118
119        if success:
120            # decode() is needed here for Python3 compatibility. In Python2,
121            # str and bytes are the same type, but not in Python3.
122            # Popen.communicate() returns a bytes instance, which needs to be
123            # decoded into text data first in Python3. And this decode() won't
124            # hurt Python2.
125            return output.rstrip().decode()
126
127    # This is the fallback case where git gives us no information,
128    # e.g. because the source tree might not be in a git tree or
129    # git is not available on the system.
130    # In this case, usually use a timestamp.  However, to ensure
131    # reproducible builds, allow the builder to override the wall
132    # clock time with environment variable SOURCE_DATE_EPOCH
133    # containing a (presumably) fixed timestamp.
134    timestamp = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
135    iso_date = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc).isoformat()
136    return "unknown hash, {}".format(iso_date)
137
138def main():
139    FORMAT = '%(asctime)s %(message)s'
140    logging.basicConfig(format="[%(asctime)s][%(levelname)-8s] %(message)s", datefmt="%H:%M:%S")
141    if len(sys.argv) != 3:
142        logging.error("usage: {} <repo-path> <output-file>".format(sys.argv[0]))
143        sys.exit(1)
144
145    changes_file_path = os.path.realpath(sys.argv[1])
146    output_file_path = sys.argv[2]
147
148    success, version = deduce_software_version(changes_file_path)
149    if not success:
150      logging.error("Could not deduce latest release version from {}.".format(changes_file_path))
151      sys.exit(1)
152
153    repo_path = os.path.dirname(changes_file_path)
154    description = os.getenv("FORCED_BUILD_VERSION_DESCRIPTION", describe(repo_path))
155    content = OUTPUT_FORMAT.format(version_tag=version, description=description)
156
157    # Escape file content.
158    content.replace('"', '\\"')
159
160    if os.path.isfile(output_file_path):
161      with open(output_file_path, 'r') as f:
162        if content == f.read():
163          return
164
165    mkdir_p(os.path.dirname(output_file_path))
166    with open(output_file_path, 'w') as f:
167        f.write(content)
168
169if __name__ == '__main__':
170    main()
171