Temporary allocation of 20Mb before and after call to ServiceProcessControl::GetHisto...
[chromium-blink-merge.git] / build / util / lastchange.py
blobe938c3db70dcab21275520bc9b9e94c71a4ae8c7
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.
6 """
7 lastchange.py -- Chromium revision fetching utility.
8 """
10 import re
11 import optparse
12 import os
13 import subprocess
14 import sys
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):
20 self.url = url
21 self.revision = revision
24 def FetchSVNRevision(directory, svn_url_regex):
25 """
26 Fetch the Subversion branch and revision for a given directory.
28 Errors are swallowed.
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
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
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
63 return VersionInfo(url, revision)
66 def RunGitCommand(directory, command):
67 """
68 Launches git subcommand.
70 Errors are swallowed.
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
93 def FetchGitRevision(directory):
94 """
95 Fetch the Git hash for a given directory.
97 Errors are swallowed.
99 Returns:
100 A VersionInfo object or None on error.
102 # TODO(agable): Re-add the commit position after the lastchange value can
103 # accept strings longer than 64 characters. See crbug.com/406783.
104 hsh = ''
105 proc = RunGitCommand(directory, ['rev-parse', 'HEAD'])
106 if proc:
107 output = proc.communicate()[0].strip()
108 if proc.returncode == 0 and output:
109 hsh = output
110 if not hsh:
111 return None
112 # TODO(agable): Figure out a way to use the full hash instead of just a
113 # 12-character short hash. See crbug.com/406783.
114 return VersionInfo('git', hsh[:12])
117 def FetchGitSVNURLAndRevision(directory, svn_url_regex):
119 Fetch the Subversion URL and revision through Git.
121 Errors are swallowed.
123 Returns:
124 A tuple containing the Subversion URL and revision.
126 proc = RunGitCommand(directory, ['log', '-1', '--format=%b'])
127 if proc:
128 output = proc.communicate()[0].strip()
129 if proc.returncode == 0 and output:
130 # Extract the latest SVN revision and the SVN URL.
131 # The target line is the last "git-svn-id: ..." line like this:
132 # git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85528 0039d316....
133 match = _GIT_SVN_ID_REGEX.search(output)
134 if match:
135 revision = match.group(2)
136 url_match = svn_url_regex.search(match.group(1))
137 if url_match:
138 url = url_match.group(2)
139 else:
140 url = ''
141 return url, revision
142 return None, None
145 def FetchGitSVNRevision(directory, svn_url_regex):
147 Fetch the Git-SVN identifier for the local tree.
149 Errors are swallowed.
151 url, revision = FetchGitSVNURLAndRevision(directory, svn_url_regex)
152 if url and revision:
153 return VersionInfo(url, revision)
154 return None
157 def FetchVersionInfo(default_lastchange, directory=None,
158 directory_regex_prior_to_src_url='chrome|blink|svn'):
160 Returns the last change (in the form of a branch, revision tuple),
161 from some appropriate revision control system.
163 svn_url_regex = re.compile(
164 r'.*/(' + directory_regex_prior_to_src_url + r')(/.*)')
166 version_info = (FetchSVNRevision(directory, svn_url_regex) or
167 FetchGitSVNRevision(directory, svn_url_regex) or
168 FetchGitRevision(directory))
169 if not version_info:
170 if default_lastchange and os.path.exists(default_lastchange):
171 revision = open(default_lastchange, 'r').read().strip()
172 version_info = VersionInfo(None, revision)
173 else:
174 version_info = VersionInfo(None, None)
175 return version_info
177 def GetHeaderGuard(path):
179 Returns the header #define guard for the given file path.
180 This treats everything after the last instance of "src/" as being a
181 relevant part of the guard. If there is no "src/", then the entire path
182 is used.
184 src_index = path.rfind('src/')
185 if src_index != -1:
186 guard = path[src_index + 4:]
187 else:
188 guard = path
189 guard = guard.upper()
190 return guard.replace('/', '_').replace('.', '_').replace('\\', '_') + '_'
192 def GetHeaderContents(path, define, version):
194 Returns what the contents of the header file should be that indicate the given
195 revision. Note that the #define is specified as a string, even though it's
196 currently always a SVN revision number, in case we need to move to git hashes.
198 header_guard = GetHeaderGuard(path)
200 header_contents = """/* Generated by lastchange.py, do not edit.*/
202 #ifndef %(header_guard)s
203 #define %(header_guard)s
205 #define %(define)s "%(version)s"
207 #endif // %(header_guard)s
209 header_contents = header_contents % { 'header_guard': header_guard,
210 'define': define,
211 'version': version }
212 return header_contents
214 def WriteIfChanged(file_name, contents):
216 Writes the specified contents to the specified file_name
217 iff the contents are different than the current contents.
219 try:
220 old_contents = open(file_name, 'r').read()
221 except EnvironmentError:
222 pass
223 else:
224 if contents == old_contents:
225 return
226 os.unlink(file_name)
227 open(file_name, 'w').write(contents)
230 def main(argv=None):
231 if argv is None:
232 argv = sys.argv
234 parser = optparse.OptionParser(usage="lastchange.py [options]")
235 parser.add_option("-d", "--default-lastchange", metavar="FILE",
236 help="Default last change input FILE.")
237 parser.add_option("-m", "--version-macro",
238 help="Name of C #define when using --header. Defaults to " +
239 "LAST_CHANGE.",
240 default="LAST_CHANGE")
241 parser.add_option("-o", "--output", metavar="FILE",
242 help="Write last change to FILE. " +
243 "Can be combined with --header to write both files.")
244 parser.add_option("", "--header", metavar="FILE",
245 help="Write last change to FILE as a C/C++ header. " +
246 "Can be combined with --output to write both files.")
247 parser.add_option("--revision-only", action='store_true',
248 help="Just print the SVN revision number. Overrides any " +
249 "file-output-related options.")
250 parser.add_option("-s", "--source-dir", metavar="DIR",
251 help="Use repository in the given directory.")
252 opts, args = parser.parse_args(argv[1:])
254 out_file = opts.output
255 header = opts.header
257 while len(args) and out_file is None:
258 if out_file is None:
259 out_file = args.pop(0)
260 if args:
261 sys.stderr.write('Unexpected arguments: %r\n\n' % args)
262 parser.print_help()
263 sys.exit(2)
265 if opts.source_dir:
266 src_dir = opts.source_dir
267 else:
268 src_dir = os.path.dirname(os.path.abspath(__file__))
270 version_info = FetchVersionInfo(opts.default_lastchange, src_dir)
272 if version_info.revision == None:
273 version_info.revision = '0'
275 if opts.revision_only:
276 print version_info.revision
277 else:
278 contents = "LASTCHANGE=%s\n" % version_info.revision
279 if not out_file and not opts.header:
280 sys.stdout.write(contents)
281 else:
282 if out_file:
283 WriteIfChanged(out_file, contents)
284 if header:
285 WriteIfChanged(header,
286 GetHeaderContents(header, opts.version_macro,
287 version_info.revision))
289 return 0
292 if __name__ == '__main__':
293 sys.exit(main())