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.
7 lastchange.py -- Chromium revision fetching utility.
16 _GIT_SVN_ID_REGEX
= re
.compile(r
'.*git-svn-id:\s*([^@]*)@([0-9]+)', re
.DOTALL
)
18 class VersionInfo(object):
19 def __init__(self
, url
, revision
):
21 self
.revision
= revision
24 def FetchSVNRevision(directory
, svn_url_regex
):
26 Fetch the Subversion branch and revision for a given directory.
31 A VersionInfo object or None on error.
34 proc
= subprocess
.Popen(['svn', 'info'],
35 stdout
=subprocess
.PIPE
,
36 stderr
=subprocess
.PIPE
,
38 shell
=(sys
.platform
=='win32'))
40 # command is apparently either not installed or not executable.
46 for line
in proc
.stdout
:
50 key
, val
= line
.split(': ', 1)
54 match
= svn_url_regex
.search(attrs
['URL'])
59 revision
= attrs
['Revision']
63 return VersionInfo(url
, revision
)
66 def RunGitCommand(directory
, command
):
68 Launches git subcommand.
73 A process object or None.
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
)]
83 proc
= subprocess
.Popen(command
,
84 stdout
=subprocess
.PIPE
,
85 stderr
=subprocess
.PIPE
,
87 shell
=(sys
.platform
=='win32'))
93 def FetchGitRevision(directory
):
95 Fetch the Git hash for a given directory.
100 A VersionInfo object or None on error.
103 proc
= RunGitCommand(directory
, ['rev-parse', 'HEAD'])
105 output
= proc
.communicate()[0].strip()
106 if proc
.returncode
== 0 and output
:
111 proc
= RunGitCommand(directory
, ['cat-file', 'commit', 'HEAD'])
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()
120 return VersionInfo('git', hsh
)
121 return VersionInfo('git', '%s-%s' % (hsh
, pos
))
124 def FetchGitSVNURLAndRevision(directory
, svn_url_regex
, go_deeper
):
126 Fetch the Subversion URL and revision through Git.
128 Errors are swallowed.
131 A tuple containing the Subversion URL and revision.
133 git_args
= ['log', '-1', '--format=%b']
135 git_args
.append('--grep=git-svn-id')
136 proc
= RunGitCommand(directory
, git_args
)
138 output
= proc
.communicate()[0].strip()
139 if proc
.returncode
== 0 and output
:
140 # Extract the latest SVN revision and the SVN URL.
141 # The target line is the last "git-svn-id: ..." line like this:
142 # git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85528 0039d316....
143 match
= _GIT_SVN_ID_REGEX
.search(output
)
145 revision
= match
.group(2)
146 url_match
= svn_url_regex
.search(match
.group(1))
148 url
= url_match
.group(2)
155 def FetchGitSVNRevision(directory
, svn_url_regex
, go_deeper
):
157 Fetch the Git-SVN identifier for the local tree.
159 Errors are swallowed.
161 url
, revision
= FetchGitSVNURLAndRevision(directory
, svn_url_regex
, go_deeper
)
163 return VersionInfo(url
, revision
)
167 def FetchVersionInfo(default_lastchange
, directory
=None,
168 directory_regex_prior_to_src_url
='chrome|blink|svn',
171 Returns the last change (in the form of a branch, revision tuple),
172 from some appropriate revision control system.
174 svn_url_regex
= re
.compile(
175 r
'.*/(' + directory_regex_prior_to_src_url
+ r
')(/.*)')
177 version_info
= (FetchSVNRevision(directory
, svn_url_regex
) or
178 FetchGitSVNRevision(directory
, svn_url_regex
, go_deeper
) or
179 FetchGitRevision(directory
))
181 if default_lastchange
and os
.path
.exists(default_lastchange
):
182 revision
= open(default_lastchange
, 'r').read().strip()
183 version_info
= VersionInfo(None, revision
)
185 version_info
= VersionInfo(None, None)
188 def GetHeaderGuard(path
):
190 Returns the header #define guard for the given file path.
191 This treats everything after the last instance of "src/" as being a
192 relevant part of the guard. If there is no "src/", then the entire path
195 src_index
= path
.rfind('src/')
197 guard
= path
[src_index
+ 4:]
200 guard
= guard
.upper()
201 return guard
.replace('/', '_').replace('.', '_').replace('\\', '_') + '_'
203 def GetHeaderContents(path
, define
, version
):
205 Returns what the contents of the header file should be that indicate the given
206 revision. Note that the #define is specified as a string, even though it's
207 currently always a SVN revision number, in case we need to move to git hashes.
209 header_guard
= GetHeaderGuard(path
)
211 header_contents
= """/* Generated by lastchange.py, do not edit.*/
213 #ifndef %(header_guard)s
214 #define %(header_guard)s
216 #define %(define)s "%(version)s"
218 #endif // %(header_guard)s
220 header_contents
= header_contents
% { 'header_guard': header_guard
,
223 return header_contents
225 def WriteIfChanged(file_name
, contents
):
227 Writes the specified contents to the specified file_name
228 iff the contents are different than the current contents.
231 old_contents
= open(file_name
, 'r').read()
232 except EnvironmentError:
235 if contents
== old_contents
:
238 open(file_name
, 'w').write(contents
)
245 parser
= optparse
.OptionParser(usage
="lastchange.py [options]")
246 parser
.add_option("-d", "--default-lastchange", metavar
="FILE",
247 help="Default last change input FILE.")
248 parser
.add_option("-m", "--version-macro",
249 help="Name of C #define when using --header. Defaults to " +
251 default
="LAST_CHANGE")
252 parser
.add_option("-o", "--output", metavar
="FILE",
253 help="Write last change to FILE. " +
254 "Can be combined with --header to write both files.")
255 parser
.add_option("", "--header", metavar
="FILE",
256 help="Write last change to FILE as a C/C++ header. " +
257 "Can be combined with --output to write both files.")
258 parser
.add_option("--revision-only", action
='store_true',
259 help="Just print the SVN revision number. Overrides any " +
260 "file-output-related options.")
261 parser
.add_option("-s", "--source-dir", metavar
="DIR",
262 help="Use repository in the given directory.")
263 parser
.add_option("--git-svn-go-deeper", action
='store_true',
264 help="In a Git-SVN repo, dig down to the last committed " +
265 "SVN change (historic behaviour).")
266 opts
, args
= parser
.parse_args(argv
[1:])
268 out_file
= opts
.output
271 while len(args
) and out_file
is None:
273 out_file
= args
.pop(0)
275 sys
.stderr
.write('Unexpected arguments: %r\n\n' % args
)
280 src_dir
= opts
.source_dir
282 src_dir
= os
.path
.dirname(os
.path
.abspath(__file__
))
284 version_info
= FetchVersionInfo(opts
.default_lastchange
,
286 go_deeper
=opts
.git_svn_go_deeper
)
288 if version_info
.revision
== None:
289 version_info
.revision
= '0'
291 if opts
.revision_only
:
292 print version_info
.revision
294 contents
= "LASTCHANGE=%s\n" % version_info
.revision
295 if not out_file
and not opts
.header
:
296 sys
.stdout
.write(contents
)
299 WriteIfChanged(out_file
, contents
)
301 WriteIfChanged(header
,
302 GetHeaderContents(header
, opts
.version_macro
,
303 version_info
.revision
))
308 if __name__
== '__main__':