blob: 55b6592e5931c48bfd931f5c488f48f72eb2ab24 [file] [log] [blame]
maruel@chromium.org7d654672012-01-05 19:07:23 +00001# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +00005"""SCM-specific utility classes."""
maruel@chromium.orgd5800f12009-11-12 20:03:43 +00006
maruel@chromium.org3c55d982010-05-06 14:25:44 +00007import cStringIO
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +00008import glob
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00009import logging
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000010import os
11import re
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000012import sys
maruel@chromium.orgfd876172010-04-30 14:01:05 +000013import time
maruel@chromium.orgade9c592011-04-07 15:59:11 +000014from xml.etree import ElementTree
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000015
16import gclient_utils
maruel@chromium.org31cb48a2011-04-04 18:01:36 +000017import subprocess2
18
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000019
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000020def ValidateEmail(email):
maruel@chromium.org6e29d572010-06-04 17:32:20 +000021 return (re.match(r"^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$", email)
22 is not None)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +000023
maruel@chromium.orgd5800f12009-11-12 20:03:43 +000024
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +000025def GetCasedPath(path):
26 """Elcheapos way to get the real path case on Windows."""
27 if sys.platform.startswith('win') and os.path.exists(path):
28 # Reconstruct the path.
29 path = os.path.abspath(path)
30 paths = path.split('\\')
31 for i in range(len(paths)):
32 if i == 0:
33 # Skip drive letter.
34 continue
35 subpath = '\\'.join(paths[:i+1])
36 prev = len('\\'.join(paths[:i]))
37 # glob.glob will return the cased path for the last item only. This is why
38 # we are calling it in a loop. Extract the data we want and put it back
39 # into the list.
40 paths[i] = glob.glob(subpath + '*')[0][prev+1:len(subpath)]
41 path = '\\'.join(paths)
42 return path
43
44
maruel@chromium.org3c55d982010-05-06 14:25:44 +000045def GenFakeDiff(filename):
46 """Generates a fake diff from a file."""
47 file_content = gclient_utils.FileRead(filename, 'rb').splitlines(True)
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +000048 filename = filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +000049 nb_lines = len(file_content)
50 # We need to use / since patch on unix will fail otherwise.
51 data = cStringIO.StringIO()
52 data.write("Index: %s\n" % filename)
53 data.write('=' * 67 + '\n')
54 # Note: Should we use /dev/null instead?
55 data.write("--- %s\n" % filename)
56 data.write("+++ %s\n" % filename)
57 data.write("@@ -0,0 +1,%d @@\n" % nb_lines)
58 # Prepend '+' to every lines.
59 for line in file_content:
60 data.write('+')
61 data.write(line)
62 result = data.getvalue()
63 data.close()
64 return result
65
66
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000067def determine_scm(root):
68 """Similar to upload.py's version but much simpler.
69
70 Returns 'svn', 'git' or None.
71 """
72 if os.path.isdir(os.path.join(root, '.svn')):
73 return 'svn'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000074 elif os.path.isdir(os.path.join(root, '.git')):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000075 return 'git'
76 else:
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000077 try:
maruel@chromium.org91def9b2011-09-14 16:28:07 +000078 subprocess2.check_call(
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000079 ['git', 'rev-parse', '--show-cdup'],
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000080 stdout=subprocess2.VOID,
maruel@chromium.org87e6d332011-09-09 19:01:28 +000081 stderr=subprocess2.VOID,
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000082 cwd=root)
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000083 return 'git'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000084 except (OSError, subprocess2.CalledProcessError):
maruel@chromium.org5c8c6de2011-03-18 16:20:18 +000085 return None
86
87
maruel@chromium.org36ac2392011-10-12 16:36:11 +000088def only_int(val):
89 if val.isdigit():
90 return int(val)
91 else:
92 return 0
93
94
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000095class GIT(object):
maruel@chromium.org36ac2392011-10-12 16:36:11 +000096 current_version = None
97
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +000098 @staticmethod
maruel@chromium.org80a9ef12011-12-13 20:44:10 +000099 def Capture(args, cwd, **kwargs):
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000100 return subprocess2.check_output(
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000101 ['git'] + args, cwd=cwd, stderr=subprocess2.PIPE, **kwargs)
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000102
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000103 @staticmethod
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000104 def CaptureStatus(files, cwd, upstream_branch):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000105 """Returns git status.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000106
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000107 @files can be a string (one file) or a list of files.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000108
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000109 Returns an array of (status, file) tuples."""
msb@chromium.org786fb682010-06-02 15:16:23 +0000110 if upstream_branch is None:
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000111 upstream_branch = GIT.GetUpstreamBranch(cwd)
msb@chromium.org786fb682010-06-02 15:16:23 +0000112 if upstream_branch is None:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000113 raise gclient_utils.Error('Cannot determine upstream branch')
114 command = ['diff', '--name-status', '-r', '%s...' % upstream_branch]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000115 if not files:
116 pass
117 elif isinstance(files, basestring):
118 command.append(files)
119 else:
120 command.extend(files)
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000121 status = GIT.Capture(command, cwd).rstrip()
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000122 results = []
123 if status:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000124 for statusline in status.splitlines():
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000125 # 3-way merges can cause the status can be 'MMM' instead of 'M'. This
126 # can happen when the user has 2 local branches and he diffs between
127 # these 2 branches instead diffing to upstream.
128 m = re.match('^(\w)+\t(.+)$', statusline)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000129 if not m:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000130 raise gclient_utils.Error(
131 'status currently unsupported: %s' % statusline)
maruel@chromium.orgcc1614b2010-09-20 17:13:17 +0000132 # Only grab the first letter.
133 results.append(('%s ' % m.group(1)[0], m.group(2)))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000134 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000135
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000136 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000137 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000138 """Retrieves the user email address if known."""
139 # We could want to look at the svn cred when it has a svn remote but it
140 # should be fine for now, users should simply configure their git settings.
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000141 try:
142 return GIT.Capture(['config', 'user.email'], cwd=cwd).strip()
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000143 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000144 return ''
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000145
146 @staticmethod
147 def ShortBranchName(branch):
148 """Converts a name like 'refs/heads/foo' to just 'foo'."""
149 return branch.replace('refs/heads/', '')
150
151 @staticmethod
152 def GetBranchRef(cwd):
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000153 """Returns the full branch reference, e.g. 'refs/heads/master'."""
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000154 return GIT.Capture(['symbolic-ref', 'HEAD'], cwd=cwd).strip()
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000155
156 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000157 def GetBranch(cwd):
158 """Returns the short branch name, e.g. 'master'."""
maruel@chromium.orgc308a742009-12-22 18:29:33 +0000159 return GIT.ShortBranchName(GIT.GetBranchRef(cwd))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000160
161 @staticmethod
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000162 def IsGitSvn(cwd):
163 """Returns true if this repo looks like it's using git-svn."""
164 # If you have any "svn-remote.*" config keys, we think you're using svn.
165 try:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000166 GIT.Capture(['config', '--get-regexp', r'^svn-remote\.'], cwd=cwd)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000167 return True
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000168 except subprocess2.CalledProcessError:
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000169 return False
170
171 @staticmethod
bauerb@chromium.org866276c2011-03-18 20:09:31 +0000172 def MatchSvnGlob(url, base_url, glob_spec, allow_wildcards):
173 """Return the corresponding git ref if |base_url| together with |glob_spec|
174 matches the full |url|.
175
176 If |allow_wildcards| is true, |glob_spec| can contain wildcards (see below).
177 """
178 fetch_suburl, as_ref = glob_spec.split(':')
179 if allow_wildcards:
180 glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl)
181 if glob_match:
182 # Parse specs like "branches/*/src:refs/remotes/svn/*" or
183 # "branches/{472,597,648}/src:refs/remotes/svn/*".
184 branch_re = re.escape(base_url)
185 if glob_match.group(1):
186 branch_re += '/' + re.escape(glob_match.group(1))
187 wildcard = glob_match.group(2)
188 if wildcard == '*':
189 branch_re += '([^/]*)'
190 else:
191 # Escape and replace surrounding braces with parentheses and commas
192 # with pipe symbols.
193 wildcard = re.escape(wildcard)
194 wildcard = re.sub('^\\\\{', '(', wildcard)
195 wildcard = re.sub('\\\\,', '|', wildcard)
196 wildcard = re.sub('\\\\}$', ')', wildcard)
197 branch_re += wildcard
198 if glob_match.group(3):
199 branch_re += re.escape(glob_match.group(3))
200 match = re.match(branch_re, url)
201 if match:
202 return re.sub('\*$', match.group(1), as_ref)
203
204 # Parse specs like "trunk/src:refs/remotes/origin/trunk".
205 if fetch_suburl:
206 full_url = base_url + '/' + fetch_suburl
207 else:
208 full_url = base_url
209 if full_url == url:
210 return as_ref
211 return None
212
213 @staticmethod
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000214 def GetSVNBranch(cwd):
215 """Returns the svn branch name if found."""
216 # Try to figure out which remote branch we're based on.
217 # Strategy:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000218 # 1) iterate through our branch history and find the svn URL.
219 # 2) find the svn-remote that fetches from the URL.
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000220
221 # regexp matching the git-svn line that contains the URL.
222 git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
223
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000224 # We don't want to go through all of history, so read a line from the
225 # pipe at a time.
226 # The -100 is an arbitrary limit so we don't search forever.
227 cmd = ['git', 'log', '-100', '--pretty=medium']
maruel@chromium.orgf94e3f12011-12-13 21:03:46 +0000228 proc = subprocess2.Popen(cmd, cwd=cwd, stdout=subprocess2.PIPE)
maruel@chromium.orge8c28622011-04-05 14:41:44 +0000229 url = None
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000230 for line in proc.stdout:
231 match = git_svn_re.match(line)
232 if match:
233 url = match.group(1)
234 proc.stdout.close() # Cut pipe.
235 break
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000236
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000237 if url:
238 svn_remote_re = re.compile(r'^svn-remote\.([^.]+)\.url (.*)$')
maruel@chromium.org80a9ef12011-12-13 20:44:10 +0000239 remotes = GIT.Capture(
240 ['config', '--get-regexp', r'^svn-remote\..*\.url'],
241 cwd=cwd).splitlines()
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000242 for remote in remotes:
243 match = svn_remote_re.match(remote)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000244 if match:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000245 remote = match.group(1)
246 base_url = match.group(2)
bauerb@chromium.org866276c2011-03-18 20:09:31 +0000247 try:
248 fetch_spec = GIT.Capture(
249 ['config', 'svn-remote.%s.fetch' % remote],
250 cwd=cwd).strip()
251 branch = GIT.MatchSvnGlob(url, base_url, fetch_spec, False)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000252 except subprocess2.CalledProcessError:
bauerb@chromium.org866276c2011-03-18 20:09:31 +0000253 branch = None
254 if branch:
255 return branch
256 try:
257 branch_spec = GIT.Capture(
258 ['config', 'svn-remote.%s.branches' % remote],
259 cwd=cwd).strip()
260 branch = GIT.MatchSvnGlob(url, base_url, branch_spec, True)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000261 except subprocess2.CalledProcessError:
bauerb@chromium.org866276c2011-03-18 20:09:31 +0000262 branch = None
263 if branch:
264 return branch
265 try:
266 tag_spec = GIT.Capture(
267 ['config', 'svn-remote.%s.tags' % remote],
268 cwd=cwd).strip()
269 branch = GIT.MatchSvnGlob(url, base_url, tag_spec, True)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000270 except subprocess2.CalledProcessError:
bauerb@chromium.org866276c2011-03-18 20:09:31 +0000271 branch = None
272 if branch:
273 return branch
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000274
275 @staticmethod
276 def FetchUpstreamTuple(cwd):
277 """Returns a tuple containg remote and remote ref,
278 e.g. 'origin', 'refs/heads/master'
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000279 Tries to be intelligent and understand git-svn.
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000280 """
281 remote = '.'
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000282 branch = GIT.GetBranch(cwd)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000283 try:
284 upstream_branch = GIT.Capture(
285 ['config', 'branch.%s.merge' % branch], cwd=cwd).strip()
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000286 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000287 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000288 if upstream_branch:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000289 try:
290 remote = GIT.Capture(
291 ['config', 'branch.%s.remote' % branch], cwd=cwd).strip()
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000292 except subprocess2.CalledProcessError:
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000293 pass
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000294 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000295 try:
296 upstream_branch = GIT.Capture(
297 ['config', 'rietveld.upstream-branch'], cwd=cwd).strip()
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000298 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000299 upstream_branch = None
300 if upstream_branch:
301 try:
302 remote = GIT.Capture(
303 ['config', 'rietveld.upstream-remote'], cwd=cwd).strip()
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000304 except subprocess2.CalledProcessError:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000305 pass
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000306 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000307 # Fall back on trying a git-svn upstream branch.
308 if GIT.IsGitSvn(cwd):
309 upstream_branch = GIT.GetSVNBranch(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000310 else:
bauerb@chromium.orgade368c2011-03-01 08:57:50 +0000311 # Else, try to guess the origin remote.
312 remote_branches = GIT.Capture(['branch', '-r'], cwd=cwd).split()
313 if 'origin/master' in remote_branches:
314 # Fall back on origin/master if it exits.
315 remote = 'origin'
316 upstream_branch = 'refs/heads/master'
317 elif 'origin/trunk' in remote_branches:
318 # Fall back on origin/trunk if it exists. Generally a shared
319 # git-svn clone
320 remote = 'origin'
321 upstream_branch = 'refs/heads/trunk'
322 else:
323 # Give up.
324 remote = None
325 upstream_branch = None
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000326 return remote, upstream_branch
327
328 @staticmethod
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000329 def GetUpstreamBranch(cwd):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000330 """Gets the current branch's upstream branch."""
331 remote, upstream_branch = GIT.FetchUpstreamTuple(cwd)
maruel@chromium.orga630bd72010-04-29 23:32:34 +0000332 if remote != '.' and upstream_branch:
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000333 upstream_branch = upstream_branch.replace('heads', 'remotes/' + remote)
334 return upstream_branch
335
336 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000337 def GenerateDiff(cwd, branch=None, branch_head='HEAD', full_move=False,
338 files=None):
maruel@chromium.orga9371762009-12-22 18:27:38 +0000339 """Diffs against the upstream branch or optionally another branch.
340
341 full_move means that move or copy operations should completely recreate the
342 files, usually in the prospect to apply the patch for a try job."""
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000343 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000344 branch = GIT.GetUpstreamBranch(cwd)
scottbyer@chromium.org33167332012-02-23 21:15:30 +0000345 command = ['diff', '-p', '--no-color', '--no-prefix', '--no-ext-diff',
evan@chromium.org400f3e72010-05-19 14:23:36 +0000346 branch + "..." + branch_head]
maruel@chromium.orga9371762009-12-22 18:27:38 +0000347 if not full_move:
348 command.append('-C')
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000349 # TODO(maruel): --binary support.
350 if files:
351 command.append('--')
352 command.extend(files)
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000353 diff = GIT.Capture(command, cwd=cwd).splitlines(True)
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000354 for i in range(len(diff)):
355 # In the case of added files, replace /dev/null with the path to the
356 # file being added.
357 if diff[i].startswith('--- /dev/null'):
358 diff[i] = '--- %s' % diff[i+1][4:]
359 return ''.join(diff)
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000360
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000361 @staticmethod
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000362 def GetDifferentFiles(cwd, branch=None, branch_head='HEAD'):
363 """Returns the list of modified files between two branches."""
364 if not branch:
maruel@chromium.org81e012c2010-04-29 16:07:24 +0000365 branch = GIT.GetUpstreamBranch(cwd)
bauerb@chromium.org838f0f22010-04-09 17:02:50 +0000366 command = ['diff', '--name-only', branch + "..." + branch_head]
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000367 return GIT.Capture(command, cwd=cwd).splitlines(False)
maruel@chromium.org8ede00e2010-01-12 14:35:28 +0000368
369 @staticmethod
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000370 def GetPatchName(cwd):
371 """Constructs a name for this patch."""
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000372 short_sha = GIT.Capture(['rev-parse', '--short=4', 'HEAD'], cwd=cwd).strip()
maruel@chromium.org862ff8e2010-08-06 15:29:16 +0000373 return "%s#%s" % (GIT.GetBranch(cwd), short_sha)
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000374
375 @staticmethod
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000376 def GetCheckoutRoot(cwd):
maruel@chromium.org01d8c1d2010-01-07 01:56:59 +0000377 """Returns the top level directory of a git checkout as an absolute path.
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000378 """
maruel@chromium.orgad80e3b2010-09-09 14:18:28 +0000379 root = GIT.Capture(['rev-parse', '--show-cdup'], cwd=cwd).strip()
380 return os.path.abspath(os.path.join(cwd, root))
maruel@chromium.orgb24a8e12009-12-22 13:45:48 +0000381
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000382 @staticmethod
383 def GetGitSvnHeadRev(cwd):
384 """Gets the most recently pulled git-svn revision."""
385 try:
386 output = GIT.Capture(['svn', 'info'], cwd=cwd)
387 match = re.search(r'^Revision: ([0-9]+)$', output, re.MULTILINE)
388 return int(match.group(1)) if match else None
389 except (subprocess2.CalledProcessError, ValueError):
390 return None
391
392 @staticmethod
wittman@chromium.org492a3682012-08-10 00:28:28 +0000393 def ParseGitSvnSha1(output):
394 """Parses git-svn output for the first sha1."""
395 match = re.search(r'[0-9a-fA-F]{40}', output)
396 return match.group(0) if match else None
397
398 @staticmethod
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000399 def GetSha1ForSvnRev(cwd, rev):
400 """Returns a corresponding git sha1 for a SVN revision."""
401 if not GIT.IsGitSvn(cwd=cwd):
402 return None
403 try:
szager@chromium.orgc51def32012-10-15 18:50:37 +0000404 output = GIT.Capture(['svn', 'find-rev', 'r' + str(rev)], cwd=cwd)
405 return GIT.ParseGitSvnSha1(output)
406 except subprocess2.CalledProcessError:
407 return None
408
409 @staticmethod
410 def GetBlessedSha1ForSvnRev(cwd, rev):
411 """Returns a git commit hash from the master branch history that has
412 accurate .DEPS.git and git submodules. To understand why this is more
413 complicated than a simple call to `git svn find-rev`, refer to:
414
415 http://www.chromium.org/developers/how-tos/git-repo
416 """
417 git_svn_rev = GIT.GetSha1ForSvnRev(cwd, rev)
418 if not git_svn_rev:
419 return None
420 try:
szager@google.com312a6a42012-10-11 21:19:42 +0000421 output = GIT.Capture(
422 ['rev-list', '--ancestry-path', '--reverse',
423 '--grep', 'SVN changes up to revision [0-9]*',
424 '%s..refs/remotes/origin/master' % git_svn_rev], cwd=cwd)
425 if not output:
426 return None
427 sha1 = output.splitlines()[0]
428 if not sha1:
429 return None
430 output = GIT.Capture(['rev-list', '-n', '1', '%s^1' % sha1], cwd=cwd)
431 if git_svn_rev != output.rstrip():
432 raise gclient_utils.Error(sha1)
433 return sha1
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000434 except subprocess2.CalledProcessError:
435 return None
436
437 @staticmethod
438 def IsValidRevision(cwd, rev):
439 """Verifies the revision is a proper git revision."""
maruel@chromium.org81473862012-06-27 17:30:56 +0000440 # 'git rev-parse foo' where foo is *any* 40 character hex string will return
441 # the string and return code 0. So strip one character to force 'git
442 # rev-parse' to do a hash table look-up and returns 128 if the hash is not
443 # present.
444 if re.match(r'^[0-9a-fA-F]{40}$', rev):
445 rev = rev[:-1]
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +0000446 try:
447 GIT.Capture(['rev-parse', rev], cwd=cwd)
448 return True
449 except subprocess2.CalledProcessError:
450 return False
451
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000452 @classmethod
453 def AssertVersion(cls, min_version):
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000454 """Asserts git's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000455 if cls.current_version is None:
bashi@chromium.orgfcffd482012-02-24 01:47:00 +0000456 current_version = cls.Capture(['--version'], '.')
457 matched = re.search(r'version ([0-9\.]+)', current_version)
458 cls.current_version = matched.group(1)
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000459 current_version_list = map(only_int, cls.current_version.split('.'))
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000460 for min_ver in map(int, min_version.split('.')):
461 ver = current_version_list.pop(0)
462 if ver < min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000463 return (False, cls.current_version)
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000464 elif ver > min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +0000465 return (True, cls.current_version)
466 return (True, cls.current_version)
maruel@chromium.orgd0f854a2010-03-11 19:35:53 +0000467
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000468
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000469class SVN(object):
tony@chromium.org57564662010-04-14 02:35:12 +0000470 current_version = None
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000471
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000472 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000473 def Capture(args, cwd, **kwargs):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000474 """Always redirect stderr.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000475
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000476 Throws an exception if non-0 is returned.
477 """
maruel@chromium.org904af082011-09-08 22:06:09 +0000478 return subprocess2.check_output(
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000479 ['svn'] + args, stderr=subprocess2.PIPE, cwd=cwd, **kwargs)
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000480
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000481 @staticmethod
maruel@chromium.org2b9aa8e2010-08-25 20:01:42 +0000482 def RunAndGetFileList(verbose, args, cwd, file_list, stdout=None):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000483 """Runs svn checkout, update, or status, output to stdout.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000484
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000485 The first item in args must be either "checkout", "update", or "status".
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000486
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000487 svn's stdout is parsed to collect a list of files checked out or updated.
488 These files are appended to file_list. svn's stdout is also printed to
489 sys.stdout as in Run.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000490
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000491 Args:
maruel@chromium.org03807072010-08-16 17:18:44 +0000492 verbose: If True, uses verbose output
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000493 args: A sequence of command line parameters to be passed to svn.
maruel@chromium.org2b9aa8e2010-08-25 20:01:42 +0000494 cwd: The directory where svn is to be run.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000495
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000496 Raises:
497 Error: An error occurred while running the svn command.
498 """
maruel@chromium.org2b9aa8e2010-08-25 20:01:42 +0000499 stdout = stdout or sys.stdout
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000500
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000501 # svn update and svn checkout use the same pattern: the first three columns
502 # are for file status, property status, and lock status. This is followed
503 # by two spaces, and then the path to the file.
504 update_pattern = '^... (.*)$'
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000505
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000506 # The first three columns of svn status are the same as for svn update and
507 # svn checkout. The next three columns indicate addition-with-history,
508 # switch, and remote lock status. This is followed by one space, and then
509 # the path to the file.
510 status_pattern = '^...... (.*)$'
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000511
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000512 # args[0] must be a supported command. This will blow up if it's something
513 # else, which is good. Note that the patterns are only effective when
514 # these commands are used in their ordinary forms, the patterns are invalid
515 # for "svn status --show-updates", for example.
516 pattern = {
517 'checkout': update_pattern,
518 'status': status_pattern,
519 'update': update_pattern,
520 }[args[0]]
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000521 compiled_pattern = re.compile(pattern)
maruel@chromium.orgb71b67e2009-11-24 20:48:19 +0000522 # Place an upper limit.
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000523 backoff_time = 5
maruel@chromium.orgbec588d2010-10-26 13:50:25 +0000524 retries = 0
maruel@chromium.org03507062010-10-26 00:58:27 +0000525 while True:
maruel@chromium.orgbec588d2010-10-26 13:50:25 +0000526 retries += 1
maruel@chromium.orgb71b67e2009-11-24 20:48:19 +0000527 previous_list_len = len(file_list)
528 failure = []
maruel@chromium.org54d1f1a2010-01-08 19:53:47 +0000529
maruel@chromium.orgb71b67e2009-11-24 20:48:19 +0000530 def CaptureMatchingLines(line):
531 match = compiled_pattern.search(line)
532 if match:
533 file_list.append(match.group(1))
534 if line.startswith('svn: '):
maruel@chromium.org8599aa72010-02-08 20:27:14 +0000535 failure.append(line)
maruel@chromium.org54d1f1a2010-01-08 19:53:47 +0000536
maruel@chromium.orgb71b67e2009-11-24 20:48:19 +0000537 try:
maruel@chromium.org17d01792010-09-01 18:07:10 +0000538 gclient_utils.CheckCallAndFilterAndHeader(
539 ['svn'] + args,
540 cwd=cwd,
541 always=verbose,
542 filter_fn=CaptureMatchingLines,
543 stdout=stdout)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000544 except subprocess2.CalledProcessError:
maruel@chromium.org6133c5b2010-08-18 18:34:48 +0000545 def IsKnownFailure():
546 for x in failure:
547 if (x.startswith('svn: OPTIONS of') or
548 x.startswith('svn: PROPFIND of') or
549 x.startswith('svn: REPORT of') or
maruel@chromium.orgf61fc932010-08-19 13:05:24 +0000550 x.startswith('svn: Unknown hostname') or
maruel@chromium.org7d8b97d2011-10-11 23:32:30 +0000551 x.startswith('svn: Server sent unexpected return value') or
552 x.startswith('svn: Can\'t connect to host')):
maruel@chromium.org6133c5b2010-08-18 18:34:48 +0000553 return True
554 return False
555
maruel@chromium.org953586a2010-06-15 14:22:24 +0000556 # Subversion client is really misbehaving with Google Code.
557 if args[0] == 'checkout':
558 # Ensure at least one file was checked out, otherwise *delete* the
559 # directory.
560 if len(file_list) == previous_list_len:
maruel@chromium.org6133c5b2010-08-18 18:34:48 +0000561 if not IsKnownFailure():
maruel@chromium.org953586a2010-06-15 14:22:24 +0000562 # No known svn error was found, bail out.
563 raise
maruel@chromium.org6133c5b2010-08-18 18:34:48 +0000564 # No file were checked out, so make sure the directory is
565 # deleted in case it's messed up and try again.
566 # Warning: It's bad, it assumes args[2] is the directory
567 # argument.
568 if os.path.isdir(args[2]):
569 gclient_utils.RemoveDirectory(args[2])
maruel@chromium.org953586a2010-06-15 14:22:24 +0000570 else:
571 # Progress was made, convert to update since an aborted checkout
572 # is now an update.
maruel@chromium.org2de10252010-02-08 01:10:39 +0000573 args = ['update'] + args[1:]
maruel@chromium.org953586a2010-06-15 14:22:24 +0000574 else:
575 # It was an update or export.
maruel@chromium.org6133c5b2010-08-18 18:34:48 +0000576 # We enforce that some progress has been made or a known failure.
577 if len(file_list) == previous_list_len and not IsKnownFailure():
578 # No known svn error was found and no progress, bail out.
579 raise
maruel@chromium.orgbec588d2010-10-26 13:50:25 +0000580 if retries == 10:
maruel@chromium.org03507062010-10-26 00:58:27 +0000581 raise
cbentzel@chromium.org2aee2292010-09-03 14:15:25 +0000582 print "Sleeping %.1f seconds and retrying...." % backoff_time
583 time.sleep(backoff_time)
584 backoff_time *= 1.3
maruel@chromium.org953586a2010-06-15 14:22:24 +0000585 continue
maruel@chromium.orgb71b67e2009-11-24 20:48:19 +0000586 break
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000587
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000588 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000589 def CaptureRemoteInfo(url):
590 """Returns a dictionary from the svn info output for the given url.
591
592 Throws an exception if svn info fails.
593 """
594 assert isinstance(url, str)
595 return SVN._CaptureInfo([url], None)
596
597 @staticmethod
598 def CaptureLocalInfo(files, cwd):
599 """Returns a dictionary from the svn info output for the given files.
600
601 Throws an exception if svn info fails.
602 """
603 assert isinstance(files, (list, tuple))
604 return SVN._CaptureInfo(files, cwd)
605
606 @staticmethod
607 def _CaptureInfo(files, cwd):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000608 """Returns a dictionary from the svn info output for the given file.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000609
maruel@chromium.org54019f32010-09-09 13:50:11 +0000610 Throws an exception if svn info fails."""
maruel@chromium.orgd25fb8f2011-04-07 13:40:15 +0000611 result = {}
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000612 info = ElementTree.XML(SVN.Capture(['info', '--xml'] + files, cwd))
maruel@chromium.orgade9c592011-04-07 15:59:11 +0000613 if info is None:
614 return result
615 entry = info.find('entry')
maruel@chromium.org6f323bb2011-04-26 15:42:53 +0000616 if entry is None:
617 return result
maruel@chromium.orgade9c592011-04-07 15:59:11 +0000618
619 # Use .text when the item is not optional.
620 result['Path'] = entry.attrib['path']
maruel@chromium.org7d654672012-01-05 19:07:23 +0000621 rev = entry.attrib['revision']
622 try:
623 result['Revision'] = int(rev)
624 except ValueError:
625 result['Revision'] = None
maruel@chromium.orgade9c592011-04-07 15:59:11 +0000626 result['Node Kind'] = entry.attrib['kind']
627 # Differs across versions.
628 if result['Node Kind'] == 'dir':
629 result['Node Kind'] = 'directory'
630 result['URL'] = entry.find('url').text
631 repository = entry.find('repository')
632 result['Repository Root'] = repository.find('root').text
633 result['UUID'] = repository.find('uuid')
634 wc_info = entry.find('wc-info')
635 if wc_info is not None:
636 result['Schedule'] = wc_info.find('schedule').text
637 result['Copied From URL'] = wc_info.find('copy-from-url')
638 result['Copied From Rev'] = wc_info.find('copy-from-rev')
639 else:
640 result['Schedule'] = None
641 result['Copied From URL'] = None
642 result['Copied From Rev'] = None
643 for key in result.keys():
644 if isinstance(result[key], unicode):
645 # Unicode results interferes with the higher layers matching up things
646 # in the deps dictionary.
647 result[key] = result[key].encode()
648 # Automatic conversion of optional parameters.
649 result[key] = getattr(result[key], 'text', result[key])
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000650 return result
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000651
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000652 @staticmethod
maruel@chromium.org54019f32010-09-09 13:50:11 +0000653 def CaptureRevision(cwd):
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000654 """Get the base revision of a SVN repository.
655
656 Returns:
657 Int base revision
658 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000659 return SVN.CaptureLocalInfo([], cwd).get('Revision')
nasser@codeaurora.org5d63eb82010-03-24 23:22:09 +0000660
661 @staticmethod
maruel@chromium.orgea15cb72012-05-04 14:16:31 +0000662 def CaptureStatus(files, cwd, no_ignore=False):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000663 """Returns the svn 1.5 svn status emulated output.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000664
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000665 @files can be a string (one file) or a list of files.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000666
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000667 Returns an array of (status, file) tuples."""
668 command = ["status", "--xml"]
maruel@chromium.orgea15cb72012-05-04 14:16:31 +0000669 if no_ignore:
670 command.append('--no-ignore')
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000671 if not files:
672 pass
673 elif isinstance(files, basestring):
674 command.append(files)
675 else:
676 command.extend(files)
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000677
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000678 status_letter = {
679 None: ' ',
680 '': ' ',
681 'added': 'A',
682 'conflicted': 'C',
683 'deleted': 'D',
684 'external': 'X',
685 'ignored': 'I',
686 'incomplete': '!',
687 'merged': 'G',
688 'missing': '!',
689 'modified': 'M',
690 'none': ' ',
691 'normal': ' ',
692 'obstructed': '~',
693 'replaced': 'R',
694 'unversioned': '?',
695 }
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000696 dom = ElementTree.XML(SVN.Capture(command, cwd))
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000697 results = []
maruel@chromium.orgade9c592011-04-07 15:59:11 +0000698 if dom is None:
699 return results
700 # /status/target/entry/(wc-status|commit|author|date)
701 for target in dom.findall('target'):
702 for entry in target.findall('entry'):
703 file_path = entry.attrib['path']
704 wc_status = entry.find('wc-status')
705 # Emulate svn 1.5 status ouput...
706 statuses = [' '] * 7
707 # Col 0
708 xml_item_status = wc_status.attrib['item']
709 if xml_item_status in status_letter:
710 statuses[0] = status_letter[xml_item_status]
711 else:
712 raise gclient_utils.Error(
713 'Unknown item status "%s"; please implement me!' %
714 xml_item_status)
715 # Col 1
716 xml_props_status = wc_status.attrib['props']
717 if xml_props_status == 'modified':
718 statuses[1] = 'M'
719 elif xml_props_status == 'conflicted':
720 statuses[1] = 'C'
721 elif (not xml_props_status or xml_props_status == 'none' or
722 xml_props_status == 'normal'):
723 pass
724 else:
725 raise gclient_utils.Error(
726 'Unknown props status "%s"; please implement me!' %
727 xml_props_status)
728 # Col 2
729 if wc_status.attrib.get('wc-locked') == 'true':
730 statuses[2] = 'L'
731 # Col 3
732 if wc_status.attrib.get('copied') == 'true':
733 statuses[3] = '+'
734 # Col 4
735 if wc_status.attrib.get('switched') == 'true':
736 statuses[4] = 'S'
737 # TODO(maruel): Col 5 and 6
738 item = (''.join(statuses), file_path)
739 results.append(item)
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000740 return results
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000741
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000742 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000743 def IsMoved(filename, cwd):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000744 """Determine if a file has been added through svn mv"""
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000745 assert isinstance(filename, basestring)
746 return SVN.IsMovedInfo(SVN.CaptureLocalInfo([filename], cwd))
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000747
748 @staticmethod
749 def IsMovedInfo(info):
750 """Determine if a file has been added through svn mv"""
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000751 return (info.get('Copied From URL') and
752 info.get('Copied From Rev') and
753 info.get('Schedule') == 'add')
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000754
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000755 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000756 def GetFileProperty(filename, property_name, cwd):
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000757 """Returns the value of an SVN property for the given file.
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000758
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000759 Args:
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000760 filename: The file to check
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000761 property_name: The name of the SVN property, e.g. "svn:mime-type"
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000762
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000763 Returns:
764 The value of the property, which will be the empty string if the property
765 is not set on the file. If the file is not under version control, the
766 empty string is also returned.
767 """
maruel@chromium.org54019f32010-09-09 13:50:11 +0000768 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000769 return SVN.Capture(['propget', property_name, filename], cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000770 except subprocess2.CalledProcessError:
maruel@chromium.org54019f32010-09-09 13:50:11 +0000771 return ''
maruel@chromium.orgd5800f12009-11-12 20:03:43 +0000772
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000773 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000774 def DiffItem(filename, cwd, full_move, revision):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000775 """Diffs a single file.
776
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000777 Should be simple, eh? No it isn't.
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000778 Be sure to be in the appropriate directory before calling to have the
maruel@chromium.orga9371762009-12-22 18:27:38 +0000779 expected relative path.
780 full_move means that move or copy operations should completely recreate the
781 files, usually in the prospect to apply the patch for a try job."""
pkasting@chromium.org07258f52013-04-18 20:05:36 +0000782 # Use "svn info" output instead of os.path.isdir because the latter fails
783 # when the file is deleted.
784 return SVN._DiffItemInternal(
785 filename,
786 cwd,
787 SVN.CaptureLocalInfo([filename], cwd),
788 full_move,
789 revision)
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000790
791 @staticmethod
pkasting@chromium.org07258f52013-04-18 20:05:36 +0000792 def _DiffItemInternal(filename, cwd, info, full_move, revision):
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000793 """Grabs the diff data."""
pkasting@chromium.org07258f52013-04-18 20:05:36 +0000794 command = ["diff", "--internal-diff", filename]
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000795 if revision:
796 command.extend(['--revision', revision])
797 data = None
798 if SVN.IsMovedInfo(info):
799 if full_move:
800 if info.get("Node Kind") == "directory":
801 # Things become tricky here. It's a directory copy/move. We need to
802 # diff all the files inside it.
803 # This will put a lot of pressure on the heap. This is why StringIO
804 # is used and converted back into a string at the end. The reason to
805 # return a string instead of a StringIO is that StringIO.write()
806 # doesn't accept a StringIO object. *sigh*.
807 for (dirpath, dirnames, filenames) in os.walk(filename):
808 # Cleanup all files starting with a '.'.
809 for d in dirnames:
810 if d.startswith('.'):
811 dirnames.remove(d)
812 for f in filenames:
813 if f.startswith('.'):
814 filenames.remove(f)
815 for f in filenames:
816 if data is None:
817 data = cStringIO.StringIO()
818 data.write(GenFakeDiff(os.path.join(dirpath, f)))
819 if data:
820 tmp = data.getvalue()
821 data.close()
822 data = tmp
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000823 else:
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000824 data = GenFakeDiff(filename)
825 else:
826 if info.get("Node Kind") != "directory":
maruel@chromium.org0836c562010-01-22 01:10:06 +0000827 # svn diff on a mv/cp'd file outputs nothing if there was no change.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000828 data = SVN.Capture(command, cwd)
maruel@chromium.org0836c562010-01-22 01:10:06 +0000829 if not data:
830 # We put in an empty Index entry so upload.py knows about them.
maruel@chromium.orgc6d170e2010-06-03 00:06:00 +0000831 data = "Index: %s\n" % filename.replace(os.sep, '/')
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000832 # Otherwise silently ignore directories.
833 else:
834 if info.get("Node Kind") != "directory":
835 # Normal simple case.
maruel@chromium.orgf8b3f942011-03-24 17:33:50 +0000836 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000837 data = SVN.Capture(command, cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000838 except subprocess2.CalledProcessError:
maruel@chromium.orgf8b3f942011-03-24 17:33:50 +0000839 if revision:
840 data = GenFakeDiff(filename)
841 else:
842 raise
maruel@chromium.org3c55d982010-05-06 14:25:44 +0000843 # Otherwise silently ignore directories.
maruel@chromium.org5aeb7dd2009-11-17 18:09:01 +0000844 return data
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000845
846 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000847 def GenerateDiff(filenames, cwd, full_move, revision):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000848 """Returns a string containing the diff for the given file list.
849
850 The files in the list should either be absolute paths or relative to the
851 given root. If no root directory is provided, the repository root will be
852 used.
853 The diff will always use relative paths.
854 """
maruel@chromium.org00fdcb32011-02-24 01:41:02 +0000855 assert isinstance(filenames, (list, tuple))
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000856 root = os.path.normcase(os.path.join(cwd, ''))
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000857 def RelativePath(path, root):
858 """We must use relative paths."""
maruel@chromium.orgfd9cbbb2010-01-08 23:04:03 +0000859 if os.path.normcase(path).startswith(root):
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000860 return path[len(root):]
861 return path
pkasting@chromium.org07258f52013-04-18 20:05:36 +0000862 # Cleanup filenames
863 filenames = [RelativePath(f, root) for f in filenames]
864 # Get information about the modified items (files and directories)
865 data = dict([(f, SVN.CaptureLocalInfo([f], root)) for f in filenames])
866 diffs = []
867 if full_move:
868 # Eliminate modified files inside moved/copied directory.
869 for (filename, info) in data.iteritems():
870 if SVN.IsMovedInfo(info) and info.get("Node Kind") == "directory":
871 # Remove files inside the directory.
872 filenames = [f for f in filenames
873 if not f.startswith(filename + os.path.sep)]
874 for filename in data.keys():
875 if not filename in filenames:
876 # Remove filtered out items.
877 del data[filename]
878 else:
879 metaheaders = []
880 for (filename, info) in data.iteritems():
881 if SVN.IsMovedInfo(info):
882 # for now, the most common case is a head copy,
883 # so let's just encode that as a straight up cp.
884 srcurl = info.get('Copied From URL')
885 file_root = info.get('Repository Root')
886 rev = int(info.get('Copied From Rev'))
887 assert srcurl.startswith(file_root)
888 src = srcurl[len(file_root)+1:]
889 try:
890 srcinfo = SVN.CaptureRemoteInfo(srcurl)
891 except subprocess2.CalledProcessError, e:
892 if not 'Not a valid URL' in e.stderr:
893 raise
894 # Assume the file was deleted. No idea how to figure out at which
895 # revision the file was deleted.
896 srcinfo = {'Revision': rev}
897 if (srcinfo.get('Revision') != rev and
898 SVN.Capture(['diff', '--internal-diff', '-r', '%d:head' % rev,
899 srcurl], cwd)):
900 metaheaders.append("#$ svn cp -r %d %s %s "
901 "### WARNING: note non-trunk copy\n" %
902 (rev, src, filename))
903 else:
904 metaheaders.append("#$ cp %s %s\n" % (src, filename))
gavinp@google.com3fda4cc2010-06-29 13:29:27 +0000905
pkasting@chromium.org07258f52013-04-18 20:05:36 +0000906 if metaheaders:
907 diffs.append("### BEGIN SVN COPY METADATA\n")
908 diffs.extend(metaheaders)
909 diffs.append("### END SVN COPY METADATA\n")
910 # Now ready to do the actual diff.
911 for filename in sorted(data.iterkeys()):
912 diffs.append(SVN._DiffItemInternal(filename, cwd, data[filename],
913 full_move, revision))
914 # Use StringIO since it can be messy when diffing a directory move with
915 # full_move=True.
916 buf = cStringIO.StringIO()
917 for d in filter(None, diffs):
918 buf.write(d)
919 result = buf.getvalue()
920 buf.close()
921 return result
maruel@chromium.orgf2f9d552009-12-22 00:12:57 +0000922
923 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000924 def GetEmail(cwd):
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000925 """Retrieves the svn account which we assume is an email address."""
maruel@chromium.org54019f32010-09-09 13:50:11 +0000926 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000927 infos = SVN.CaptureLocalInfo([], cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000928 except subprocess2.CalledProcessError:
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000929 return None
930
931 # Should check for uuid but it is incorrectly saved for https creds.
maruel@chromium.org54019f32010-09-09 13:50:11 +0000932 root = infos['Repository Root']
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000933 realm = root.rsplit('/', 1)[0]
maruel@chromium.org54019f32010-09-09 13:50:11 +0000934 uuid = infos['UUID']
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000935 if root.startswith('https') or not uuid:
936 regexp = re.compile(r'<%s:\d+>.*' % realm)
937 else:
938 regexp = re.compile(r'<%s:\d+> %s' % (realm, uuid))
939 if regexp is None:
940 return None
941 if sys.platform.startswith('win'):
942 if not 'APPDATA' in os.environ:
943 return None
maruel@chromium.org720d9f32009-11-21 17:38:57 +0000944 auth_dir = os.path.join(os.environ['APPDATA'], 'Subversion', 'auth',
945 'svn.simple')
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000946 else:
947 if not 'HOME' in os.environ:
948 return None
949 auth_dir = os.path.join(os.environ['HOME'], '.subversion', 'auth',
950 'svn.simple')
951 for credfile in os.listdir(auth_dir):
952 cred_info = SVN.ReadSimpleAuth(os.path.join(auth_dir, credfile))
953 if regexp.match(cred_info.get('svn:realmstring')):
954 return cred_info.get('username')
955
956 @staticmethod
957 def ReadSimpleAuth(filename):
958 f = open(filename, 'r')
959 values = {}
maruel@chromium.org6e29d572010-06-04 17:32:20 +0000960 def ReadOneItem(item_type):
961 m = re.match(r'%s (\d+)' % item_type, f.readline())
maruel@chromium.orgc78f2462009-11-21 01:20:57 +0000962 if not m:
963 return None
964 data = f.read(int(m.group(1)))
965 if f.read(1) != '\n':
966 return None
967 return data
968
969 while True:
970 key = ReadOneItem('K')
971 if not key:
972 break
973 value = ReadOneItem('V')
974 if not value:
975 break
976 values[key] = value
977 return values
maruel@chromium.org94b1ee92009-12-19 20:27:20 +0000978
979 @staticmethod
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000980 def GetCheckoutRoot(cwd):
maruel@chromium.org94b1ee92009-12-19 20:27:20 +0000981 """Returns the top level directory of the current repository.
982
983 The directory is returned as an absolute path.
984 """
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000985 cwd = os.path.abspath(cwd)
maruel@chromium.org54019f32010-09-09 13:50:11 +0000986 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000987 info = SVN.CaptureLocalInfo([], cwd)
maruel@chromium.org885d6e82011-02-24 20:21:46 +0000988 cur_dir_repo_root = info['Repository Root']
989 url = info['URL']
maruel@chromium.orgda64d632011-09-08 17:41:15 +0000990 except subprocess2.CalledProcessError:
maruel@chromium.org94b1ee92009-12-19 20:27:20 +0000991 return None
maruel@chromium.org94b1ee92009-12-19 20:27:20 +0000992 while True:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000993 parent = os.path.dirname(cwd)
maruel@chromium.org54019f32010-09-09 13:50:11 +0000994 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +0000995 info = SVN.CaptureLocalInfo([], parent)
maruel@chromium.org885d6e82011-02-24 20:21:46 +0000996 if (info['Repository Root'] != cur_dir_repo_root or
997 info['URL'] != os.path.dirname(url)):
maruel@chromium.org54019f32010-09-09 13:50:11 +0000998 break
maruel@chromium.org885d6e82011-02-24 20:21:46 +0000999 url = info['URL']
maruel@chromium.orgda64d632011-09-08 17:41:15 +00001000 except subprocess2.CalledProcessError:
maruel@chromium.org94b1ee92009-12-19 20:27:20 +00001001 break
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001002 cwd = parent
1003 return GetCasedPath(cwd)
tony@chromium.org57564662010-04-14 02:35:12 +00001004
dbeam@chromium.orge5d1e612011-12-19 19:49:19 +00001005 @staticmethod
1006 def IsValidRevision(url):
1007 """Verifies the revision looks like an SVN revision."""
1008 try:
1009 SVN.Capture(['info', url], cwd=None)
1010 return True
1011 except subprocess2.CalledProcessError:
1012 return False
1013
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001014 @classmethod
1015 def AssertVersion(cls, min_version):
tony@chromium.org57564662010-04-14 02:35:12 +00001016 """Asserts svn's version is at least min_version."""
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001017 if cls.current_version is None:
shouqun.liu@intel.com13b522c2012-07-20 17:16:51 +00001018 cls.current_version = cls.Capture(['--version', '--quiet'], None)
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001019 current_version_list = map(only_int, cls.current_version.split('.'))
tony@chromium.org57564662010-04-14 02:35:12 +00001020 for min_ver in map(int, min_version.split('.')):
1021 ver = current_version_list.pop(0)
1022 if ver < min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001023 return (False, cls.current_version)
tony@chromium.org57564662010-04-14 02:35:12 +00001024 elif ver > min_ver:
maruel@chromium.org36ac2392011-10-12 16:36:11 +00001025 return (True, cls.current_version)
1026 return (True, cls.current_version)
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001027
1028 @staticmethod
maruel@chromium.orgea15cb72012-05-04 14:16:31 +00001029 def Revert(cwd, callback=None, ignore_externals=False, no_ignore=False):
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001030 """Reverts all svn modifications in cwd, including properties.
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001031
1032 Deletes any modified files or directory.
1033
1034 A "svn update --revision BASE" call is required after to revive deleted
1035 files.
1036 """
maruel@chromium.orgea15cb72012-05-04 14:16:31 +00001037 for file_status in SVN.CaptureStatus(None, cwd, no_ignore=no_ignore):
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001038 file_path = os.path.join(cwd, file_status[1])
maruel@chromium.org8c415122011-03-15 17:14:27 +00001039 if (ignore_externals and
1040 file_status[0][0] == 'X' and
1041 file_status[0][1:].isspace()):
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001042 # Ignore externals.
1043 logging.info('Ignoring external %s' % file_status[1])
1044 continue
1045
maruel@chromium.org62087572012-04-24 23:16:28 +00001046 # This is the case where '! L .' is returned by 'svn status'. Just
1047 # strip off the '/.'.
1048 if file_path.endswith(os.path.sep + '.'):
1049 file_path = file_path[:-2]
1050
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001051 if callback:
1052 callback(file_status)
1053
maruel@chromium.org8c415122011-03-15 17:14:27 +00001054 if os.path.exists(file_path):
1055 # svn revert is really stupid. It fails on inconsistent line-endings,
1056 # on switched directories, etc. So take no chance and delete everything!
1057 # In theory, it wouldn't be necessary for property-only change but then
1058 # it'd have to look for switched directories, etc so it's not worth
1059 # optimizing this use case.
1060 if os.path.isfile(file_path) or os.path.islink(file_path):
1061 logging.info('os.remove(%s)' % file_path)
1062 os.remove(file_path)
1063 elif os.path.isdir(file_path):
maruel@chromium.orgda64d632011-09-08 17:41:15 +00001064 logging.info('RemoveDirectory(%s)' % file_path)
maruel@chromium.org8c415122011-03-15 17:14:27 +00001065 gclient_utils.RemoveDirectory(file_path)
1066 else:
1067 logging.critical(
1068 ('No idea what is %s.\nYou just found a bug in gclient'
1069 ', please ping maruel@chromium.org ASAP!') % file_path)
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001070
maruel@chromium.org8c415122011-03-15 17:14:27 +00001071 if (file_status[0][0] in ('D', 'A', '!') or
1072 not file_status[0][1:].isspace()):
maruel@chromium.orgaf453492011-03-03 21:04:09 +00001073 # Added, deleted file requires manual intervention and require calling
maruel@chromium.org07ab60e2011-02-08 21:54:00 +00001074 # revert, like for properties.
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001075 if not os.path.isdir(cwd):
maruel@chromium.org8b322b32011-11-01 19:05:50 +00001076 # '.' was deleted. It's not worth continuing.
1077 return
maruel@chromium.orgaf453492011-03-03 21:04:09 +00001078 try:
maruel@chromium.orgd579fcf2011-12-13 20:36:03 +00001079 SVN.Capture(['revert', file_status[1]], cwd=cwd)
maruel@chromium.orgda64d632011-09-08 17:41:15 +00001080 except subprocess2.CalledProcessError:
maruel@chromium.orgaf453492011-03-03 21:04:09 +00001081 if not os.path.exists(file_path):
1082 continue
1083 raise