OLD | NEW |
(Empty) | |
| 1 #!/usr/bin/env python |
| 2 # Copyright (c) 2012 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 """ |
| 7 lastchange.py -- Chromium revision fetching utility. |
| 8 """ |
| 9 |
| 10 import re |
| 11 import optparse |
| 12 import os |
| 13 import subprocess |
| 14 import sys |
| 15 |
| 16 _GIT_SVN_ID_REGEX = re.compile(r'.*git-svn-id:\s*([^@]*)@([0-9]+)', re.DOTALL) |
| 17 |
| 18 class VersionInfo(object): |
| 19 def __init__(self, url, revision): |
| 20 self.url = url |
| 21 self.revision = revision |
| 22 |
| 23 |
| 24 def FetchSVNRevision(directory, svn_url_regex): |
| 25 """ |
| 26 Fetch the Subversion branch and revision for a given directory. |
| 27 |
| 28 Errors are swallowed. |
| 29 |
| 30 Returns: |
| 31 A VersionInfo object or None on error. |
| 32 """ |
| 33 try: |
| 34 proc = subprocess.Popen(['svn', 'info'], |
| 35 stdout=subprocess.PIPE, |
| 36 stderr=subprocess.PIPE, |
| 37 cwd=directory, |
| 38 shell=(sys.platform=='win32')) |
| 39 except OSError: |
| 40 # command is apparently either not installed or not executable. |
| 41 return None |
| 42 if not proc: |
| 43 return None |
| 44 |
| 45 attrs = {} |
| 46 for line in proc.stdout: |
| 47 line = line.strip() |
| 48 if not line: |
| 49 continue |
| 50 key, val = line.split(': ', 1) |
| 51 attrs[key] = val |
| 52 |
| 53 try: |
| 54 match = svn_url_regex.search(attrs['URL']) |
| 55 if match: |
| 56 url = match.group(2) |
| 57 else: |
| 58 url = '' |
| 59 revision = attrs['Revision'] |
| 60 except KeyError: |
| 61 return None |
| 62 |
| 63 return VersionInfo(url, revision) |
| 64 |
| 65 |
| 66 def RunGitCommand(directory, command): |
| 67 """ |
| 68 Launches git subcommand. |
| 69 |
| 70 Errors are swallowed. |
| 71 |
| 72 Returns: |
| 73 A process object or None. |
| 74 """ |
| 75 command = ['git'] + command |
| 76 # Force shell usage under cygwin. This is a workaround for |
| 77 # mysterious loss of cwd while invoking cygwin's git. |
| 78 # We can't just pass shell=True to Popen, as under win32 this will |
| 79 # cause CMD to be used, while we explicitly want a cygwin shell. |
| 80 if sys.platform == 'cygwin': |
| 81 command = ['sh', '-c', ' '.join(command)] |
| 82 try: |
| 83 proc = subprocess.Popen(command, |
| 84 stdout=subprocess.PIPE, |
| 85 stderr=subprocess.PIPE, |
| 86 cwd=directory, |
| 87 shell=(sys.platform=='win32')) |
| 88 return proc |
| 89 except OSError: |
| 90 return None |
| 91 |
| 92 |
| 93 def FetchGitRevision(directory): |
| 94 """ |
| 95 Fetch the Git hash for a given directory. |
| 96 |
| 97 Errors are swallowed. |
| 98 |
| 99 Returns: |
| 100 A VersionInfo object or None on error. |
| 101 """ |
| 102 hsh = '' |
| 103 proc = RunGitCommand(directory, ['rev-parse', 'HEAD']) |
| 104 if proc: |
| 105 output = proc.communicate()[0].strip() |
| 106 if proc.returncode == 0 and output: |
| 107 hsh = output |
| 108 if not hsh: |
| 109 return None |
| 110 pos = '' |
| 111 proc = RunGitCommand(directory, ['cat-file', 'commit', 'HEAD']) |
| 112 if proc: |
| 113 output = proc.communicate()[0] |
| 114 if proc.returncode == 0 and output: |
| 115 for line in reversed(output.splitlines()): |
| 116 if line.startswith('Cr-Commit-Position:'): |
| 117 pos = line.rsplit()[-1].strip() |
| 118 break |
| 119 if not pos: |
| 120 return VersionInfo('git', hsh) |
| 121 return VersionInfo('git', '%s-%s' % (hsh, pos)) |
| 122 |
| 123 |
| 124 def FetchGitSVNURLAndRevision(directory, svn_url_regex): |
| 125 """ |
| 126 Fetch the Subversion URL and revision through Git. |
| 127 |
| 128 Errors are swallowed. |
| 129 |
| 130 Returns: |
| 131 A tuple containing the Subversion URL and revision. |
| 132 """ |
| 133 proc = RunGitCommand(directory, ['log', '-1', '--format=%b']) |
| 134 if proc: |
| 135 output = proc.communicate()[0].strip() |
| 136 if proc.returncode == 0 and output: |
| 137 # Extract the latest SVN revision and the SVN URL. |
| 138 # The target line is the last "git-svn-id: ..." line like this: |
| 139 # git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85528 0039d316.... |
| 140 match = _GIT_SVN_ID_REGEX.search(output) |
| 141 if match: |
| 142 revision = match.group(2) |
| 143 url_match = svn_url_regex.search(match.group(1)) |
| 144 if url_match: |
| 145 url = url_match.group(2) |
| 146 else: |
| 147 url = '' |
| 148 return url, revision |
| 149 return None, None |
| 150 |
| 151 |
| 152 def FetchGitSVNRevision(directory, svn_url_regex): |
| 153 """ |
| 154 Fetch the Git-SVN identifier for the local tree. |
| 155 |
| 156 Errors are swallowed. |
| 157 """ |
| 158 url, revision = FetchGitSVNURLAndRevision(directory, svn_url_regex) |
| 159 if url and revision: |
| 160 return VersionInfo(url, revision) |
| 161 return None |
| 162 |
| 163 |
| 164 def FetchVersionInfo(default_lastchange, directory=None, |
| 165 directory_regex_prior_to_src_url='chrome|blink|svn'): |
| 166 """ |
| 167 Returns the last change (in the form of a branch, revision tuple), |
| 168 from some appropriate revision control system. |
| 169 """ |
| 170 svn_url_regex = re.compile( |
| 171 r'.*/(' + directory_regex_prior_to_src_url + r')(/.*)') |
| 172 |
| 173 version_info = (FetchSVNRevision(directory, svn_url_regex) or |
| 174 FetchGitSVNRevision(directory, svn_url_regex) or |
| 175 FetchGitRevision(directory)) |
| 176 if not version_info: |
| 177 if default_lastchange and os.path.exists(default_lastchange): |
| 178 revision = open(default_lastchange, 'r').read().strip() |
| 179 version_info = VersionInfo(None, revision) |
| 180 else: |
| 181 version_info = VersionInfo(None, None) |
| 182 return version_info |
| 183 |
| 184 def GetHeaderGuard(path): |
| 185 """ |
| 186 Returns the header #define guard for the given file path. |
| 187 This treats everything after the last instance of "src/" as being a |
| 188 relevant part of the guard. If there is no "src/", then the entire path |
| 189 is used. |
| 190 """ |
| 191 src_index = path.rfind('src/') |
| 192 if src_index != -1: |
| 193 guard = path[src_index + 4:] |
| 194 else: |
| 195 guard = path |
| 196 guard = guard.upper() |
| 197 return guard.replace('/', '_').replace('.', '_').replace('\\', '_') + '_' |
| 198 |
| 199 def GetHeaderContents(path, define, version): |
| 200 """ |
| 201 Returns what the contents of the header file should be that indicate the given |
| 202 revision. Note that the #define is specified as a string, even though it's |
| 203 currently always a SVN revision number, in case we need to move to git hashes. |
| 204 """ |
| 205 header_guard = GetHeaderGuard(path) |
| 206 |
| 207 header_contents = """/* Generated by lastchange.py, do not edit.*/ |
| 208 |
| 209 #ifndef %(header_guard)s |
| 210 #define %(header_guard)s |
| 211 |
| 212 #define %(define)s "%(version)s" |
| 213 |
| 214 #endif // %(header_guard)s |
| 215 """ |
| 216 header_contents = header_contents % { 'header_guard': header_guard, |
| 217 'define': define, |
| 218 'version': version } |
| 219 return header_contents |
| 220 |
| 221 def WriteIfChanged(file_name, contents): |
| 222 """ |
| 223 Writes the specified contents to the specified file_name |
| 224 iff the contents are different than the current contents. |
| 225 """ |
| 226 try: |
| 227 old_contents = open(file_name, 'r').read() |
| 228 except EnvironmentError: |
| 229 pass |
| 230 else: |
| 231 if contents == old_contents: |
| 232 return |
| 233 os.unlink(file_name) |
| 234 open(file_name, 'w').write(contents) |
| 235 |
| 236 |
| 237 def main(argv=None): |
| 238 if argv is None: |
| 239 argv = sys.argv |
| 240 |
| 241 parser = optparse.OptionParser(usage="lastchange.py [options]") |
| 242 parser.add_option("-d", "--default-lastchange", metavar="FILE", |
| 243 help="Default last change input FILE.") |
| 244 parser.add_option("-m", "--version-macro", |
| 245 help="Name of C #define when using --header. Defaults to " + |
| 246 "LAST_CHANGE.", |
| 247 default="LAST_CHANGE") |
| 248 parser.add_option("-o", "--output", metavar="FILE", |
| 249 help="Write last change to FILE. " + |
| 250 "Can be combined with --header to write both files.") |
| 251 parser.add_option("", "--header", metavar="FILE", |
| 252 help="Write last change to FILE as a C/C++ header. " + |
| 253 "Can be combined with --output to write both files.") |
| 254 parser.add_option("--revision-only", action='store_true', |
| 255 help="Just print the SVN revision number. Overrides any " + |
| 256 "file-output-related options.") |
| 257 parser.add_option("-s", "--source-dir", metavar="DIR", |
| 258 help="Use repository in the given directory.") |
| 259 opts, args = parser.parse_args(argv[1:]) |
| 260 |
| 261 out_file = opts.output |
| 262 header = opts.header |
| 263 |
| 264 while len(args) and out_file is None: |
| 265 if out_file is None: |
| 266 out_file = args.pop(0) |
| 267 if args: |
| 268 sys.stderr.write('Unexpected arguments: %r\n\n' % args) |
| 269 parser.print_help() |
| 270 sys.exit(2) |
| 271 |
| 272 if opts.source_dir: |
| 273 src_dir = opts.source_dir |
| 274 else: |
| 275 src_dir = os.path.dirname(os.path.abspath(__file__)) |
| 276 |
| 277 version_info = FetchVersionInfo(opts.default_lastchange, src_dir) |
| 278 |
| 279 if version_info.revision == None: |
| 280 version_info.revision = '0' |
| 281 |
| 282 if opts.revision_only: |
| 283 print version_info.revision |
| 284 else: |
| 285 contents = "LASTCHANGE=%s\n" % version_info.revision |
| 286 if not out_file and not opts.header: |
| 287 sys.stdout.write(contents) |
| 288 else: |
| 289 if out_file: |
| 290 WriteIfChanged(out_file, contents) |
| 291 if header: |
| 292 WriteIfChanged(header, |
| 293 GetHeaderContents(header, opts.version_macro, |
| 294 version_info.revision)) |
| 295 |
| 296 return 0 |
| 297 |
| 298 |
| 299 if __name__ == '__main__': |
| 300 sys.exit(main()) |
OLD | NEW |