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 gclient_utils.IsEnvCog(): 230 return _EMPTY_VERSION_INFO 231 232 git_top_dir = None 233 try: 234 git_top_dir = GetGitTopDirectory(source_dir) 235 except GitError as e: 236 logging.warning("Failed to get git top directory from '%s': %s", source_dir, 237 e) 238 239 merge_base_sha = 'HEAD' 240 if git_top_dir and merge_base_ref: 241 try: 242 merge_base_sha = GetMergeBase(git_top_dir, merge_base_ref) 243 except GitError as e: 244 logging.error( 245 "You requested a --merge-base-ref value of '%s' but no " 246 "merge base could be found between it and HEAD. Git " 247 "reports: %s", merge_base_ref, e) 248 return None 249 250 version_info = None 251 if git_top_dir: 252 try: 253 version_info = FetchGitRevision(git_top_dir, commit_filter, 254 merge_base_sha) 255 except GitError as e: 256 logging.error("Failed to get version info: %s", e) 257 258 if not version_info: 259 logging.warning( 260 "Falling back to a version of 0.0.0 to allow script to " 261 "finish. This is normal if you are bootstrapping a new environment " 262 "or do not have a git repository for any other reason. If not, this " 263 "could represent a serious error.") 264 # Use a dummy revision that has the same length as a Git commit hash, 265 # same as what we use in build/util/LASTCHANGE.dummy. 266 version_info = _EMPTY_VERSION_INFO 267 268 return version_info 269 270 271def main(argv=None): 272 if argv is None: 273 argv = sys.argv 274 275 parser = argparse.ArgumentParser(usage="lastchange.py [options]") 276 parser.add_argument("-m", "--version-macro", 277 help=("Name of C #define when using --header. Defaults to " 278 "LAST_CHANGE.")) 279 parser.add_argument("-o", 280 "--output", 281 metavar="FILE", 282 help=("Write last change to FILE. " 283 "Can be combined with other file-output-related " 284 "options to write multiple files.")) 285 parser.add_argument("--header", 286 metavar="FILE", 287 help=("Write last change to FILE as a C/C++ header. " 288 "Can be combined with other file-output-related " 289 "options to write multiple files.")) 290 parser.add_argument("--revision", 291 metavar="FILE", 292 help=("Write last change to FILE as a one-line revision. " 293 "Can be combined with other file-output-related " 294 "options to write multiple files.")) 295 parser.add_argument("--merge-base-ref", 296 default=None, 297 help=("Only consider changes since the merge " 298 "base between HEAD and the provided ref")) 299 parser.add_argument("--revision-id-only", action='store_true', 300 help=("Output the revision as a VCS revision ID only (in " 301 "Git, a 40-character commit hash, excluding the " 302 "Cr-Commit-Position).")) 303 parser.add_argument("--revision-id-prefix", 304 metavar="PREFIX", 305 help=("Adds a string prefix to the VCS revision ID.")) 306 parser.add_argument("--print-only", action="store_true", 307 help=("Just print the revision string. Overrides any " 308 "file-output-related options.")) 309 parser.add_argument("-s", "--source-dir", metavar="DIR", 310 help="Use repository in the given directory.") 311 parser.add_argument("--filter", metavar="REGEX", 312 help=("Only use log entries where the commit message " 313 "matches the supplied filter regex. Defaults to " 314 "'^Change-Id:' to suppress local commits."), 315 default='^Change-Id:') 316 317 args, extras = parser.parse_known_args(argv[1:]) 318 319 logging.basicConfig(level=logging.WARNING) 320 321 out_file = args.output 322 header = args.header 323 revision = args.revision 324 commit_filter=args.filter 325 326 while len(extras) and out_file is None: 327 if out_file is None: 328 out_file = extras.pop(0) 329 if extras: 330 sys.stderr.write('Unexpected arguments: %r\n\n' % extras) 331 parser.print_help() 332 sys.exit(2) 333 334 source_dir = args.source_dir or os.path.dirname(os.path.abspath(__file__)) 335 336 version_info = GetVersion(source_dir, commit_filter, args.merge_base_ref) 337 338 revision_string = version_info.revision 339 if args.revision_id_only: 340 revision_string = version_info.revision_id 341 342 if args.revision_id_prefix: 343 revision_string = args.revision_id_prefix + revision_string 344 345 if args.print_only: 346 print(revision_string) 347 else: 348 lastchange_year = datetime.datetime.fromtimestamp( 349 version_info.timestamp, datetime.timezone.utc).year 350 contents_lines = [ 351 "LASTCHANGE=%s" % revision_string, 352 "LASTCHANGE_YEAR=%s" % lastchange_year, 353 ] 354 contents = '\n'.join(contents_lines) + '\n' 355 if not out_file and not header and not revision: 356 sys.stdout.write(contents) 357 else: 358 if out_file: 359 committime_file = out_file + '.committime' 360 out_changed = WriteIfChanged(out_file, contents) 361 if out_changed or not os.path.exists(committime_file): 362 with open(committime_file, 'w') as timefile: 363 timefile.write(str(version_info.timestamp)) 364 if header: 365 WriteIfChanged(header, 366 GetHeaderContents(header, args.version_macro, 367 revision_string)) 368 if revision: 369 WriteIfChanged(revision, revision_string) 370 371 return 0 372 373 374if __name__ == '__main__': 375 sys.exit(main()) 376