1#!/usr/bin/env python3 2# Copyright 2012 The Chromium Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6""" 7lastchange.py -- Chromium revision fetching utility. 8""" 9 10import argparse 11import collections 12import datetime 13import logging 14import os 15import subprocess 16import sys 17 18_THIS_DIR = os.path.abspath(os.path.dirname(__file__)) 19_ROOT_DIR = os.path.abspath( 20 os.path.join(_THIS_DIR, "..", "..", "third_party/depot_tools")) 21 22sys.path.insert(0, _ROOT_DIR) 23 24import gclient_utils 25 26VersionInfo = collections.namedtuple("VersionInfo", 27 ("revision_id", "revision", "timestamp")) 28_EMPTY_VERSION_INFO = VersionInfo('0' * 40, '0' * 40, 0) 29 30class GitError(Exception): 31 pass 32 33# This function exists for compatibility with logic outside this 34# repository that uses this file as a library. 35# TODO(eliribble) remove this function after it has been ported into 36# the repositories that depend on it 37def RunGitCommand(directory, command): 38 """ 39 Launches git subcommand. 40 41 Errors are swallowed. 42 43 Returns: 44 A process object or None. 45 """ 46 command = ['git'] + command 47 # Force shell usage under cygwin. This is a workaround for 48 # mysterious loss of cwd while invoking cygwin's git. 49 # We can't just pass shell=True to Popen, as under win32 this will 50 # cause CMD to be used, while we explicitly want a cygwin shell. 51 if sys.platform == 'cygwin': 52 command = ['sh', '-c', ' '.join(command)] 53 try: 54 proc = subprocess.Popen(command, 55 stdout=subprocess.PIPE, 56 stderr=subprocess.PIPE, 57 cwd=directory, 58 shell=(sys.platform=='win32')) 59 return proc 60 except OSError as e: 61 logging.error('Command %r failed: %s' % (' '.join(command), e)) 62 return None 63 64 65def _RunGitCommand(directory, command): 66 """Launches git subcommand. 67 68 Returns: 69 The stripped stdout of the git command. 70 Raises: 71 GitError on failure, including a nonzero return code. 72 """ 73 command = ['git'] + command 74 # Force shell usage under cygwin. This is a workaround for 75 # mysterious loss of cwd while invoking cygwin's git. 76 # We can't just pass shell=True to Popen, as under win32 this will 77 # cause CMD to be used, while we explicitly want a cygwin shell. 78 if sys.platform == 'cygwin': 79 command = ['sh', '-c', ' '.join(command)] 80 try: 81 logging.info("Executing '%s' in %s", ' '.join(command), directory) 82 proc = subprocess.Popen(command, 83 stdout=subprocess.PIPE, 84 stderr=subprocess.PIPE, 85 cwd=directory, 86 shell=(sys.platform=='win32')) 87 stdout, stderr = tuple(x.decode(encoding='utf_8') 88 for x in proc.communicate()) 89 stdout = stdout.strip() 90 stderr = stderr.strip() 91 logging.debug("returncode: %d", proc.returncode) 92 logging.debug("stdout: %s", stdout) 93 logging.debug("stderr: %s", stderr) 94 if proc.returncode != 0 or not stdout: 95 raise GitError(( 96 "Git command '{}' in {} failed: " 97 "rc={}, stdout='{}' stderr='{}'").format( 98 " ".join(command), directory, proc.returncode, stdout, stderr)) 99 return stdout 100 except OSError as e: 101 raise GitError("Git command 'git {}' in {} failed: {}".format( 102 " ".join(command), directory, e)) 103 104 105def GetMergeBase(directory, ref): 106 """ 107 Return the merge-base of HEAD and ref. 108 109 Args: 110 directory: The directory containing the .git directory. 111 ref: The ref to use to find the merge base. 112 Returns: 113 The git commit SHA of the merge-base as a string. 114 """ 115 logging.debug("Calculating merge base between HEAD and %s in %s", 116 ref, directory) 117 command = ['merge-base', 'HEAD', ref] 118 return _RunGitCommand(directory, command) 119 120 121def FetchGitRevision(directory, commit_filter, start_commit="HEAD"): 122 """ 123 Fetch the Git hash (and Cr-Commit-Position if any) for a given directory. 124 125 Args: 126 directory: The directory containing the .git directory. 127 commit_filter: A filter to supply to grep to filter commits 128 start_commit: A commit identifier. The result of this function 129 will be limited to only consider commits before the provided 130 commit. 131 Returns: 132 A VersionInfo object. On error all values will be 0. 133 """ 134 hash_ = '' 135 136 git_args = ['log', '-1', '--format=%H %ct'] 137 if commit_filter is not None: 138 git_args.append('--grep=' + commit_filter) 139 140 git_args.append(start_commit) 141 142 output = _RunGitCommand(directory, git_args) 143 hash_, commit_timestamp = output.split() 144 if not hash_: 145 return VersionInfo('0', '0', 0) 146 147 revision = hash_ 148 output = _RunGitCommand(directory, ['cat-file', 'commit', hash_]) 149 for line in reversed(output.splitlines()): 150 if line.startswith('Cr-Commit-Position:'): 151 pos = line.rsplit()[-1].strip() 152 logging.debug("Found Cr-Commit-Position '%s'", pos) 153 revision = "{}-{}".format(hash_, pos) 154 break 155 return VersionInfo(hash_, revision, int(commit_timestamp)) 156 157 158def GetHeaderGuard(path): 159 """ 160 Returns the header #define guard for the given file path. 161 This treats everything after the last instance of "src/" as being a 162 relevant part of the guard. If there is no "src/", then the entire path 163 is used. 164 """ 165 src_index = path.rfind('src/') 166 if src_index != -1: 167 guard = path[src_index + 4:] 168 else: 169 guard = path 170 guard = guard.upper() 171 return guard.replace('/', '_').replace('.', '_').replace('\\', '_') + '_' 172 173 174def GetHeaderContents(path, define, version): 175 """ 176 Returns what the contents of the header file should be that indicate the given 177 revision. 178 """ 179 header_guard = GetHeaderGuard(path) 180 181 header_contents = """/* Generated by lastchange.py, do not edit.*/ 182 183#ifndef %(header_guard)s 184#define %(header_guard)s 185 186#define %(define)s "%(version)s" 187 188#endif // %(header_guard)s 189""" 190 header_contents = header_contents % { 'header_guard': header_guard, 191 'define': define, 192 'version': version } 193 return header_contents 194 195 196def GetGitTopDirectory(source_dir): 197 """Get the top git directory - the directory that contains the .git directory. 198 199 Args: 200 source_dir: The directory to search. 201 Returns: 202 The output of "git rev-parse --show-toplevel" as a string 203 """ 204 return _RunGitCommand(source_dir, ['rev-parse', '--show-toplevel']) 205 206 207def WriteIfChanged(file_name, contents): 208 """ 209 Writes the specified contents to the specified file_name 210 iff the contents are different than the current contents. 211 Returns if new data was written. 212 """ 213 try: 214 old_contents = open(file_name, 'r').read() 215 except EnvironmentError: 216 pass 217 else: 218 if contents == old_contents: 219 return False 220 os.unlink(file_name) 221 open(file_name, 'w').write(contents) 222 return True 223 224 225def GetVersion(source_dir, commit_filter, merge_base_ref): 226 """ 227 Returns the version information for the given source directory. 228 """ 229 if 'BASE_COMMIT_SUBMISSION_MS' in os.environ: 230 return GetVersionInfoFromEnv() 231 232 if gclient_utils.IsEnvCog(): 233 return _EMPTY_VERSION_INFO 234 235 git_top_dir = None 236 try: 237 git_top_dir = GetGitTopDirectory(source_dir) 238 except GitError as e: 239 logging.warning("Failed to get git top directory from '%s': %s", source_dir, 240 e) 241 242 merge_base_sha = 'HEAD' 243 if git_top_dir and merge_base_ref: 244 try: 245 merge_base_sha = GetMergeBase(git_top_dir, merge_base_ref) 246 except GitError as e: 247 logging.error( 248 "You requested a --merge-base-ref value of '%s' but no " 249 "merge base could be found between it and HEAD. Git " 250 "reports: %s", merge_base_ref, e) 251 return None 252 253 version_info = None 254 if git_top_dir: 255 try: 256 version_info = FetchGitRevision(git_top_dir, commit_filter, 257 merge_base_sha) 258 except GitError as e: 259 logging.error("Failed to get version info: %s", e) 260 261 if not version_info: 262 logging.warning( 263 "Falling back to a version of 0.0.0 to allow script to " 264 "finish. This is normal if you are bootstrapping a new environment " 265 "or do not have a git repository for any other reason. If not, this " 266 "could represent a serious error.") 267 # Use a dummy revision that has the same length as a Git commit hash, 268 # same as what we use in build/util/LASTCHANGE.dummy. 269 version_info = _EMPTY_VERSION_INFO 270 271 return version_info 272 273 274def GetVersionInfoFromEnv(): 275 """ 276 Returns the version information from the environment. 277 """ 278 hash = os.environ.get('BASE_COMMIT_HASH', _EMPTY_VERSION_INFO.revision) 279 timestamp = int( 280 os.environ.get('BASE_COMMIT_SUBMISSION_MS', 281 _EMPTY_VERSION_INFO.timestamp)) / 1000 282 return VersionInfo(hash, hash, int(timestamp)) 283 284 285def main(argv=None): 286 if argv is None: 287 argv = sys.argv 288 289 parser = argparse.ArgumentParser(usage="lastchange.py [options]") 290 parser.add_argument("-m", "--version-macro", 291 help=("Name of C #define when using --header. Defaults to " 292 "LAST_CHANGE.")) 293 parser.add_argument("-o", 294 "--output", 295 metavar="FILE", 296 help=("Write last change to FILE. " 297 "Can be combined with other file-output-related " 298 "options to write multiple files.")) 299 parser.add_argument("--header", 300 metavar="FILE", 301 help=("Write last change to FILE as a C/C++ header. " 302 "Can be combined with other file-output-related " 303 "options to write multiple files.")) 304 parser.add_argument("--revision", 305 metavar="FILE", 306 help=("Write last change to FILE as a one-line revision. " 307 "Can be combined with other file-output-related " 308 "options to write multiple files.")) 309 parser.add_argument("--merge-base-ref", 310 default=None, 311 help=("Only consider changes since the merge " 312 "base between HEAD and the provided ref")) 313 parser.add_argument("--revision-id-only", action='store_true', 314 help=("Output the revision as a VCS revision ID only (in " 315 "Git, a 40-character commit hash, excluding the " 316 "Cr-Commit-Position).")) 317 parser.add_argument("--print-only", action="store_true", 318 help=("Just print the revision string. Overrides any " 319 "file-output-related options.")) 320 parser.add_argument("-s", "--source-dir", metavar="DIR", 321 help="Use repository in the given directory.") 322 parser.add_argument("--filter", metavar="REGEX", 323 help=("Only use log entries where the commit message " 324 "matches the supplied filter regex. Defaults to " 325 "'^Change-Id:' to suppress local commits."), 326 default='^Change-Id:') 327 328 args, extras = parser.parse_known_args(argv[1:]) 329 330 logging.basicConfig(level=logging.WARNING) 331 332 out_file = args.output 333 header = args.header 334 revision = args.revision 335 commit_filter=args.filter 336 337 while len(extras) and out_file is None: 338 if out_file is None: 339 out_file = extras.pop(0) 340 if extras: 341 sys.stderr.write('Unexpected arguments: %r\n\n' % extras) 342 parser.print_help() 343 sys.exit(2) 344 345 source_dir = args.source_dir or os.path.dirname(os.path.abspath(__file__)) 346 347 version_info = GetVersion(source_dir, commit_filter, args.merge_base_ref) 348 349 revision_string = version_info.revision 350 if args.revision_id_only: 351 revision_string = version_info.revision_id 352 353 if args.print_only: 354 print(revision_string) 355 else: 356 lastchange_year = datetime.datetime.fromtimestamp( 357 version_info.timestamp, datetime.timezone.utc).year 358 contents_lines = [ 359 "LASTCHANGE=%s" % revision_string, 360 "LASTCHANGE_YEAR=%s" % lastchange_year, 361 ] 362 contents = '\n'.join(contents_lines) + '\n' 363 if not out_file and not header and not revision: 364 sys.stdout.write(contents) 365 else: 366 if out_file: 367 committime_file = out_file + '.committime' 368 out_changed = WriteIfChanged(out_file, contents) 369 if out_changed or not os.path.exists(committime_file): 370 with open(committime_file, 'w') as timefile: 371 timefile.write(str(version_info.timestamp)) 372 if header: 373 WriteIfChanged(header, 374 GetHeaderContents(header, args.version_macro, 375 revision_string)) 376 if revision: 377 WriteIfChanged(revision, revision_string) 378 379 return 0 380 381 382if __name__ == '__main__': 383 sys.exit(main()) 384