[Tizen] Add prelauncher
[platform/framework/web/crosswalk-tizen.git] / vendor / depot_tools / gclient_scm.py
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 """Gclient-specific SCM-specific operations."""
6
7 from __future__ import print_function
8
9 import errno
10 import logging
11 import os
12 import posixpath
13 import re
14 import sys
15 import tempfile
16 import traceback
17 import urlparse
18
19 import download_from_google_storage
20 import gclient_utils
21 import git_cache
22 import scm
23 import shutil
24 import subprocess2
25
26
27 THIS_FILE_PATH = os.path.abspath(__file__)
28
29 GSUTIL_DEFAULT_PATH = os.path.join(
30     os.path.dirname(os.path.abspath(__file__)),
31     'third_party', 'gsutil', 'gsutil')
32
33 CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git'
34 class DiffFiltererWrapper(object):
35   """Simple base class which tracks which file is being diffed and
36   replaces instances of its file name in the original and
37   working copy lines of the svn/git diff output."""
38   index_string = None
39   original_prefix = "--- "
40   working_prefix = "+++ "
41
42   def __init__(self, relpath, print_func):
43     # Note that we always use '/' as the path separator to be
44     # consistent with svn's cygwin-style output on Windows
45     self._relpath = relpath.replace("\\", "/")
46     self._current_file = None
47     self._print_func = print_func
48
49   def SetCurrentFile(self, current_file):
50     self._current_file = current_file
51
52   @property
53   def _replacement_file(self):
54     return posixpath.join(self._relpath, self._current_file)
55
56   def _Replace(self, line):
57     return line.replace(self._current_file, self._replacement_file)
58
59   def Filter(self, line):
60     if (line.startswith(self.index_string)):
61       self.SetCurrentFile(line[len(self.index_string):])
62       line = self._Replace(line)
63     else:
64       if (line.startswith(self.original_prefix) or
65           line.startswith(self.working_prefix)):
66         line = self._Replace(line)
67     self._print_func(line)
68
69
70 class SvnDiffFilterer(DiffFiltererWrapper):
71   index_string = "Index: "
72
73
74 class GitDiffFilterer(DiffFiltererWrapper):
75   index_string = "diff --git "
76
77   def SetCurrentFile(self, current_file):
78     # Get filename by parsing "a/<filename> b/<filename>"
79     self._current_file = current_file[:(len(current_file)/2)][2:]
80
81   def _Replace(self, line):
82     return re.sub("[a|b]/" + self._current_file, self._replacement_file, line)
83
84
85 ### SCM abstraction layer
86
87 # Factory Method for SCM wrapper creation
88
89 def GetScmName(url):
90   if url:
91     url, _ = gclient_utils.SplitUrlRevision(url)
92     if (url.startswith('git://') or url.startswith('ssh://') or
93         url.startswith('git+http://') or url.startswith('git+https://') or
94         url.endswith('.git') or url.startswith('sso://') or
95         'googlesource' in url):
96       return 'git'
97     elif (url.startswith('http://') or url.startswith('https://') or
98           url.startswith('svn://') or url.startswith('svn+ssh://')):
99       return 'svn'
100     elif url.startswith('file://'):
101       if url.endswith('.git'):
102         return 'git'
103       return 'svn'
104   return None
105
106
107 def CreateSCM(url, root_dir=None, relpath=None, out_fh=None, out_cb=None):
108   SCM_MAP = {
109     'svn' : SVNWrapper,
110     'git' : GitWrapper,
111   }
112
113   scm_name = GetScmName(url)
114   if not scm_name in SCM_MAP:
115     raise gclient_utils.Error('No SCM found for url %s' % url)
116   scm_class = SCM_MAP[scm_name]
117   if not scm_class.BinaryExists():
118     raise gclient_utils.Error('%s command not found' % scm_name)
119   return scm_class(url, root_dir, relpath, out_fh, out_cb)
120
121
122 # SCMWrapper base class
123
124 class SCMWrapper(object):
125   """Add necessary glue between all the supported SCM.
126
127   This is the abstraction layer to bind to different SCM.
128   """
129
130   def __init__(self, url=None, root_dir=None, relpath=None, out_fh=None,
131                out_cb=None):
132     self.url = url
133     self._root_dir = root_dir
134     if self._root_dir:
135       self._root_dir = self._root_dir.replace('/', os.sep)
136     self.relpath = relpath
137     if self.relpath:
138       self.relpath = self.relpath.replace('/', os.sep)
139     if self.relpath and self._root_dir:
140       self.checkout_path = os.path.join(self._root_dir, self.relpath)
141     if out_fh is None:
142       out_fh = sys.stdout
143     self.out_fh = out_fh
144     self.out_cb = out_cb
145
146   def Print(self, *args, **kwargs):
147     kwargs.setdefault('file', self.out_fh)
148     if kwargs.pop('timestamp', True):
149       self.out_fh.write('[%s] ' % gclient_utils.Elapsed())
150     print(*args, **kwargs)
151
152   def RunCommand(self, command, options, args, file_list=None):
153     commands = ['cleanup', 'update', 'updatesingle', 'revert',
154                 'revinfo', 'status', 'diff', 'pack', 'runhooks']
155
156     if not command in commands:
157       raise gclient_utils.Error('Unknown command %s' % command)
158
159     if not command in dir(self):
160       raise gclient_utils.Error('Command %s not implemented in %s wrapper' % (
161           command, self.__class__.__name__))
162
163     return getattr(self, command)(options, args, file_list)
164
165   @staticmethod
166   def _get_first_remote_url(checkout_path):
167     log = scm.GIT.Capture(
168         ['config', '--local', '--get-regexp', r'remote.*.url'],
169         cwd=checkout_path)
170     # Get the second token of the first line of the log.
171     return log.splitlines()[0].split(' ', 1)[1]
172
173   def GetActualRemoteURL(self, options):
174     """Attempt to determine the remote URL for this SCMWrapper."""
175     # Git
176     if os.path.exists(os.path.join(self.checkout_path, '.git')):
177       actual_remote_url = self._get_first_remote_url(self.checkout_path)
178
179       # If a cache_dir is used, obtain the actual remote URL from the cache.
180       if getattr(self, 'cache_dir', None):
181         url, _ = gclient_utils.SplitUrlRevision(self.url)
182         mirror = git_cache.Mirror(url)
183         if (mirror.exists() and mirror.mirror_path.replace('\\', '/') ==
184             actual_remote_url.replace('\\', '/')):
185           actual_remote_url = self._get_first_remote_url(mirror.mirror_path)
186       return actual_remote_url
187
188     # Svn
189     if os.path.exists(os.path.join(self.checkout_path, '.svn')):
190       return scm.SVN.CaptureLocalInfo([], self.checkout_path)['URL']
191     return None
192
193   def DoesRemoteURLMatch(self, options):
194     """Determine whether the remote URL of this checkout is the expected URL."""
195     if not os.path.exists(self.checkout_path):
196       # A checkout which doesn't exist can't be broken.
197       return True
198
199     actual_remote_url = self.GetActualRemoteURL(options)
200     if actual_remote_url:
201       return (gclient_utils.SplitUrlRevision(actual_remote_url)[0].rstrip('/')
202               == gclient_utils.SplitUrlRevision(self.url)[0].rstrip('/'))
203     else:
204       # This may occur if the self.checkout_path exists but does not contain a
205       # valid git or svn checkout.
206       return False
207
208   def _DeleteOrMove(self, force):
209     """Delete the checkout directory or move it out of the way.
210
211     Args:
212         force: bool; if True, delete the directory. Otherwise, just move it.
213     """
214     if force and os.environ.get('CHROME_HEADLESS') == '1':
215       self.Print('_____ Conflicting directory found in %s. Removing.'
216                  % self.checkout_path)
217       gclient_utils.AddWarning('Conflicting directory %s deleted.'
218                                % self.checkout_path)
219       gclient_utils.rmtree(self.checkout_path)
220     else:
221       bad_scm_dir = os.path.join(self._root_dir, '_bad_scm',
222                                  os.path.dirname(self.relpath))
223
224       try:
225         os.makedirs(bad_scm_dir)
226       except OSError as e:
227         if e.errno != errno.EEXIST:
228           raise
229
230       dest_path = tempfile.mkdtemp(
231           prefix=os.path.basename(self.relpath),
232           dir=bad_scm_dir)
233       self.Print('_____ Conflicting directory found in %s. Moving to %s.'
234                  % (self.checkout_path, dest_path))
235       gclient_utils.AddWarning('Conflicting directory %s moved to %s.'
236                                % (self.checkout_path, dest_path))
237       shutil.move(self.checkout_path, dest_path)
238
239
240 class GitWrapper(SCMWrapper):
241   """Wrapper for Git"""
242   name = 'git'
243   remote = 'origin'
244
245   cache_dir = None
246
247   def __init__(self, url=None, *args):
248     """Removes 'git+' fake prefix from git URL."""
249     if url.startswith('git+http://') or url.startswith('git+https://'):
250       url = url[4:]
251     SCMWrapper.__init__(self, url, *args)
252     filter_kwargs = { 'time_throttle': 1, 'out_fh': self.out_fh }
253     if self.out_cb:
254       filter_kwargs['predicate'] = self.out_cb
255     self.filter = gclient_utils.GitFilter(**filter_kwargs)
256
257   @staticmethod
258   def BinaryExists():
259     """Returns true if the command exists."""
260     try:
261       # We assume git is newer than 1.7.  See: crbug.com/114483
262       result, version = scm.GIT.AssertVersion('1.7')
263       if not result:
264         raise gclient_utils.Error('Git version is older than 1.7: %s' % version)
265       return result
266     except OSError:
267       return False
268
269   def GetCheckoutRoot(self):
270     return scm.GIT.GetCheckoutRoot(self.checkout_path)
271
272   def GetRevisionDate(self, _revision):
273     """Returns the given revision's date in ISO-8601 format (which contains the
274     time zone)."""
275     # TODO(floitsch): get the time-stamp of the given revision and not just the
276     # time-stamp of the currently checked out revision.
277     return self._Capture(['log', '-n', '1', '--format=%ai'])
278
279   @staticmethod
280   def cleanup(options, args, file_list):
281     """'Cleanup' the repo.
282
283     There's no real git equivalent for the svn cleanup command, do a no-op.
284     """
285
286   def diff(self, options, _args, _file_list):
287     merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
288     self._Run(['diff', merge_base], options)
289
290   def pack(self, _options, _args, _file_list):
291     """Generates a patch file which can be applied to the root of the
292     repository.
293
294     The patch file is generated from a diff of the merge base of HEAD and
295     its upstream branch.
296     """
297     merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
298     gclient_utils.CheckCallAndFilter(
299         ['git', 'diff', merge_base],
300         cwd=self.checkout_path,
301         filter_fn=GitDiffFilterer(self.relpath, print_func=self.Print).Filter)
302
303   def _FetchAndReset(self, revision, file_list, options):
304     """Equivalent to git fetch; git reset."""
305     quiet = []
306     if not options.verbose:
307       quiet = ['--quiet']
308     self._UpdateBranchHeads(options, fetch=False)
309
310     self._Fetch(options, prune=True, quiet=options.verbose)
311     self._Run(['reset', '--hard', revision] + quiet, options)
312     if file_list is not None:
313       files = self._Capture(['ls-files']).splitlines()
314       file_list.extend([os.path.join(self.checkout_path, f) for f in files])
315
316   def _DisableHooks(self):
317     hook_dir = os.path.join(self.checkout_path, '.git', 'hooks')
318     if not os.path.isdir(hook_dir):
319       return
320     for f in os.listdir(hook_dir):
321       if not f.endswith('.sample') and not f.endswith('.disabled'):
322         os.rename(os.path.join(hook_dir, f),
323                   os.path.join(hook_dir, f + '.disabled'))
324
325   def update(self, options, args, file_list):
326     """Runs git to update or transparently checkout the working copy.
327
328     All updated files will be appended to file_list.
329
330     Raises:
331       Error: if can't get URL for relative path.
332     """
333     if args:
334       raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
335
336     self._CheckMinVersion("1.6.6")
337
338     # If a dependency is not pinned, track the default remote branch.
339     default_rev = 'refs/remotes/%s/master' % self.remote
340     url, deps_revision = gclient_utils.SplitUrlRevision(self.url)
341     rev_str = ""
342     revision = deps_revision
343     managed = True
344     if options.revision:
345       # Override the revision number.
346       revision = str(options.revision)
347     if revision == 'unmanaged':
348       # Check again for a revision in case an initial ref was specified
349       # in the url, for example bla.git@refs/heads/custombranch
350       revision = deps_revision
351       managed = False
352     if not revision:
353       revision = default_rev
354
355     if managed:
356       self._DisableHooks()
357
358     if gclient_utils.IsDateRevision(revision):
359       # Date-revisions only work on git-repositories if the reflog hasn't
360       # expired yet. Use rev-list to get the corresponding revision.
361       #  git rev-list -n 1 --before='time-stamp' branchname
362       if options.transitive:
363         self.Print('Warning: --transitive only works for SVN repositories.')
364         revision = default_rev
365
366     rev_str = ' at %s' % revision
367     files = [] if file_list is not None else None
368
369     printed_path = False
370     verbose = []
371     if options.verbose:
372       self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
373       verbose = ['--verbose']
374       printed_path = True
375
376     remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
377     if remote_ref:
378       # Rewrite remote refs to their local equivalents.
379       revision = ''.join(remote_ref)
380       rev_type = "branch"
381     elif revision.startswith('refs/'):
382       # Local branch? We probably don't want to support, since DEPS should
383       # always specify branches as they are in the upstream repo.
384       rev_type = "branch"
385     else:
386       # hash is also a tag, only make a distinction at checkout
387       rev_type = "hash"
388
389     mirror = self._GetMirror(url, options)
390     if mirror:
391       url = mirror.mirror_path
392
393     if (not os.path.exists(self.checkout_path) or
394         (os.path.isdir(self.checkout_path) and
395          not os.path.exists(os.path.join(self.checkout_path, '.git')))):
396       if mirror:
397         self._UpdateMirror(mirror, options)
398       try:
399         self._Clone(revision, url, options)
400       except subprocess2.CalledProcessError:
401         self._DeleteOrMove(options.force)
402         self._Clone(revision, url, options)
403       if file_list is not None:
404         files = self._Capture(['ls-files']).splitlines()
405         file_list.extend([os.path.join(self.checkout_path, f) for f in files])
406       if not verbose:
407         # Make the output a little prettier. It's nice to have some whitespace
408         # between projects when cloning.
409         self.Print('')
410       return self._Capture(['rev-parse', '--verify', 'HEAD'])
411
412     if not managed:
413       self._UpdateBranchHeads(options, fetch=False)
414       self.Print('________ unmanaged solution; skipping %s' % self.relpath)
415       return self._Capture(['rev-parse', '--verify', 'HEAD'])
416
417     if mirror:
418       self._UpdateMirror(mirror, options)
419
420     # See if the url has changed (the unittests use git://foo for the url, let
421     # that through).
422     current_url = self._Capture(['config', 'remote.%s.url' % self.remote])
423     return_early = False
424     # TODO(maruel): Delete url != 'git://foo' since it's just to make the
425     # unit test pass. (and update the comment above)
426     # Skip url auto-correction if remote.origin.gclient-auto-fix-url is set.
427     # This allows devs to use experimental repos which have a different url
428     # but whose branch(s) are the same as official repos.
429     if (current_url.rstrip('/') != url.rstrip('/') and
430         url != 'git://foo' and
431         subprocess2.capture(
432             ['git', 'config', 'remote.%s.gclient-auto-fix-url' % self.remote],
433             cwd=self.checkout_path).strip() != 'False'):
434       self.Print('_____ switching %s to a new upstream' % self.relpath)
435       if not (options.force or options.reset):
436         # Make sure it's clean
437         self._CheckClean(rev_str)
438       # Switch over to the new upstream
439       self._Run(['remote', 'set-url', self.remote, url], options)
440       self._FetchAndReset(revision, file_list, options)
441       return_early = True
442
443     if return_early:
444       return self._Capture(['rev-parse', '--verify', 'HEAD'])
445
446     cur_branch = self._GetCurrentBranch()
447
448     # Cases:
449     # 0) HEAD is detached. Probably from our initial clone.
450     #   - make sure HEAD is contained by a named ref, then update.
451     # Cases 1-4. HEAD is a branch.
452     # 1) current branch is not tracking a remote branch (could be git-svn)
453     #   - try to rebase onto the new hash or branch
454     # 2) current branch is tracking a remote branch with local committed
455     #    changes, but the DEPS file switched to point to a hash
456     #   - rebase those changes on top of the hash
457     # 3) current branch is tracking a remote branch w/or w/out changes, and
458     #    no DEPS switch
459     #   - see if we can FF, if not, prompt the user for rebase, merge, or stop
460     # 4) current branch is tracking a remote branch, but DEPS switches to a
461     #    different remote branch, and
462     #   a) current branch has no local changes, and --force:
463     #      - checkout new branch
464     #   b) current branch has local changes, and --force and --reset:
465     #      - checkout new branch
466     #   c) otherwise exit
467
468     # GetUpstreamBranch returns something like 'refs/remotes/origin/master' for
469     # a tracking branch
470     # or 'master' if not a tracking branch (it's based on a specific rev/hash)
471     # or it returns None if it couldn't find an upstream
472     if cur_branch is None:
473       upstream_branch = None
474       current_type = "detached"
475       logging.debug("Detached HEAD")
476     else:
477       upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
478       if not upstream_branch or not upstream_branch.startswith('refs/remotes'):
479         current_type = "hash"
480         logging.debug("Current branch is not tracking an upstream (remote)"
481                       " branch.")
482       elif upstream_branch.startswith('refs/remotes'):
483         current_type = "branch"
484       else:
485         raise gclient_utils.Error('Invalid Upstream: %s' % upstream_branch)
486
487     if not scm.GIT.IsValidRevision(self.checkout_path, revision, sha_only=True):
488       # Update the remotes first so we have all the refs.
489       remote_output = scm.GIT.Capture(['remote'] + verbose + ['update'],
490               cwd=self.checkout_path)
491       if verbose:
492         self.Print(remote_output)
493
494       self._UpdateBranchHeads(options, fetch=True)
495
496     # This is a big hammer, debatable if it should even be here...
497     if options.force or options.reset:
498       target = 'HEAD'
499       if options.upstream and upstream_branch:
500         target = upstream_branch
501       self._Run(['reset', '--hard', target], options)
502
503     if current_type == 'detached':
504       # case 0
505       self._CheckClean(rev_str)
506       self._CheckDetachedHead(rev_str, options)
507       if self._Capture(['rev-list', '-n', '1', 'HEAD']) == revision:
508         self.Print('Up-to-date; skipping checkout.')
509       else:
510         # 'git checkout' may need to overwrite existing untracked files. Allow
511         # it only when nuclear options are enabled.
512         self._Checkout(
513             options,
514             revision,
515             force=(options.force and options.delete_unversioned_trees),
516             quiet=True,
517         )
518       if not printed_path:
519         self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
520     elif current_type == 'hash':
521       # case 1
522       if scm.GIT.IsGitSvn(self.checkout_path) and upstream_branch is not None:
523         # Our git-svn branch (upstream_branch) is our upstream
524         self._AttemptRebase(upstream_branch, files, options,
525                             newbase=revision, printed_path=printed_path,
526                             merge=options.merge)
527         printed_path = True
528       else:
529         # Can't find a merge-base since we don't know our upstream. That makes
530         # this command VERY likely to produce a rebase failure. For now we
531         # assume origin is our upstream since that's what the old behavior was.
532         upstream_branch = self.remote
533         if options.revision or deps_revision:
534           upstream_branch = revision
535         self._AttemptRebase(upstream_branch, files, options,
536                             printed_path=printed_path, merge=options.merge)
537         printed_path = True
538     elif rev_type == 'hash':
539       # case 2
540       self._AttemptRebase(upstream_branch, files, options,
541                           newbase=revision, printed_path=printed_path,
542                           merge=options.merge)
543       printed_path = True
544     elif remote_ref and ''.join(remote_ref) != upstream_branch:
545       # case 4
546       new_base = ''.join(remote_ref)
547       if not printed_path:
548         self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
549       switch_error = ("Could not switch upstream branch from %s to %s\n"
550                      % (upstream_branch, new_base) +
551                      "Please use --force or merge or rebase manually:\n" +
552                      "cd %s; git rebase %s\n" % (self.checkout_path, new_base) +
553                      "OR git checkout -b <some new branch> %s" % new_base)
554       force_switch = False
555       if options.force:
556         try:
557           self._CheckClean(rev_str)
558           # case 4a
559           force_switch = True
560         except gclient_utils.Error as e:
561           if options.reset:
562             # case 4b
563             force_switch = True
564           else:
565             switch_error = '%s\n%s' % (e.message, switch_error)
566       if force_switch:
567         self.Print("Switching upstream branch from %s to %s" %
568                    (upstream_branch, new_base))
569         switch_branch = 'gclient_' + remote_ref[1]
570         self._Capture(['branch', '-f', switch_branch, new_base])
571         self._Checkout(options, switch_branch, force=True, quiet=True)
572       else:
573         # case 4c
574         raise gclient_utils.Error(switch_error)
575     else:
576       # case 3 - the default case
577       if files is not None:
578         files = self._Capture(['diff', upstream_branch, '--name-only']).split()
579       if verbose:
580         self.Print('Trying fast-forward merge to branch : %s' % upstream_branch)
581       try:
582         merge_args = ['merge']
583         if options.merge:
584           merge_args.append('--ff')
585         else:
586           merge_args.append('--ff-only')
587         merge_args.append(upstream_branch)
588         merge_output = self._Capture(merge_args)
589       except subprocess2.CalledProcessError as e:
590         if re.match('fatal: Not possible to fast-forward, aborting.', e.stderr):
591           files = []
592           if not printed_path:
593             self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
594             printed_path = True
595           while True:
596             try:
597               action = self._AskForData(
598                   'Cannot %s, attempt to rebase? '
599                   '(y)es / (q)uit / (s)kip : ' %
600                       ('merge' if options.merge else 'fast-forward merge'),
601                   options)
602             except ValueError:
603               raise gclient_utils.Error('Invalid Character')
604             if re.match(r'yes|y', action, re.I):
605               self._AttemptRebase(upstream_branch, files, options,
606                                   printed_path=printed_path, merge=False)
607               printed_path = True
608               break
609             elif re.match(r'quit|q', action, re.I):
610               raise gclient_utils.Error("Can't fast-forward, please merge or "
611                                         "rebase manually.\n"
612                                         "cd %s && git " % self.checkout_path
613                                         + "rebase %s" % upstream_branch)
614             elif re.match(r'skip|s', action, re.I):
615               self.Print('Skipping %s' % self.relpath)
616               return
617             else:
618               self.Print('Input not recognized')
619         elif re.match("error: Your local changes to '.*' would be "
620                       "overwritten by merge.  Aborting.\nPlease, commit your "
621                       "changes or stash them before you can merge.\n",
622                       e.stderr):
623           if not printed_path:
624             self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
625             printed_path = True
626           raise gclient_utils.Error(e.stderr)
627         else:
628           # Some other problem happened with the merge
629           logging.error("Error during fast-forward merge in %s!" % self.relpath)
630           self.Print(e.stderr)
631           raise
632       else:
633         # Fast-forward merge was successful
634         if not re.match('Already up-to-date.', merge_output) or verbose:
635           if not printed_path:
636             self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
637             printed_path = True
638           self.Print(merge_output.strip())
639           if not verbose:
640             # Make the output a little prettier. It's nice to have some
641             # whitespace between projects when syncing.
642             self.Print('')
643
644     if file_list is not None:
645       file_list.extend([os.path.join(self.checkout_path, f) for f in files])
646
647     # If the rebase generated a conflict, abort and ask user to fix
648     if self._IsRebasing():
649       raise gclient_utils.Error('\n____ %s%s\n'
650                                 '\nConflict while rebasing this branch.\n'
651                                 'Fix the conflict and run gclient again.\n'
652                                 'See man git-rebase for details.\n'
653                                 % (self.relpath, rev_str))
654
655     if verbose:
656       self.Print('Checked out revision %s' % self.revinfo(options, (), None),
657                  timestamp=False)
658
659     # If --reset and --delete_unversioned_trees are specified, remove any
660     # untracked directories.
661     if options.reset and options.delete_unversioned_trees:
662       # GIT.CaptureStatus() uses 'dit diff' to compare to a specific SHA1 (the
663       # merge-base by default), so doesn't include untracked files. So we use
664       # 'git ls-files --directory --others --exclude-standard' here directly.
665       paths = scm.GIT.Capture(
666           ['ls-files', '--directory', '--others', '--exclude-standard'],
667           self.checkout_path)
668       for path in (p for p in paths.splitlines() if p.endswith('/')):
669         full_path = os.path.join(self.checkout_path, path)
670         if not os.path.islink(full_path):
671           self.Print('_____ removing unversioned directory %s' % path)
672           gclient_utils.rmtree(full_path)
673
674     return self._Capture(['rev-parse', '--verify', 'HEAD'])
675
676
677   def revert(self, options, _args, file_list):
678     """Reverts local modifications.
679
680     All reverted files will be appended to file_list.
681     """
682     if not os.path.isdir(self.checkout_path):
683       # revert won't work if the directory doesn't exist. It needs to
684       # checkout instead.
685       self.Print('_____ %s is missing, synching instead' % self.relpath)
686       # Don't reuse the args.
687       return self.update(options, [], file_list)
688
689     default_rev = "refs/heads/master"
690     if options.upstream:
691       if self._GetCurrentBranch():
692         upstream_branch = scm.GIT.GetUpstreamBranch(self.checkout_path)
693         default_rev = upstream_branch or default_rev
694     _, deps_revision = gclient_utils.SplitUrlRevision(self.url)
695     if not deps_revision:
696       deps_revision = default_rev
697     if deps_revision.startswith('refs/heads/'):
698       deps_revision = deps_revision.replace('refs/heads/', self.remote + '/')
699     deps_revision = self.GetUsableRev(deps_revision, options)
700
701     if file_list is not None:
702       files = self._Capture(['diff', deps_revision, '--name-only']).split()
703
704     self._Run(['reset', '--hard', deps_revision], options)
705     self._Run(['clean', '-f', '-d'], options)
706
707     if file_list is not None:
708       file_list.extend([os.path.join(self.checkout_path, f) for f in files])
709
710   def revinfo(self, _options, _args, _file_list):
711     """Returns revision"""
712     return self._Capture(['rev-parse', 'HEAD'])
713
714   def runhooks(self, options, args, file_list):
715     self.status(options, args, file_list)
716
717   def status(self, options, _args, file_list):
718     """Display status information."""
719     if not os.path.isdir(self.checkout_path):
720       self.Print('________ couldn\'t run status in %s:\n'
721                  'The directory does not exist.' % self.checkout_path)
722     else:
723       merge_base = self._Capture(['merge-base', 'HEAD', self.remote])
724       self._Run(['diff', '--name-status', merge_base], options,
725                 stdout=self.out_fh)
726       if file_list is not None:
727         files = self._Capture(['diff', '--name-only', merge_base]).split()
728         file_list.extend([os.path.join(self.checkout_path, f) for f in files])
729
730   def GetUsableRev(self, rev, options):
731     """Finds a useful revision for this repository.
732
733     If SCM is git-svn and the head revision is less than |rev|, git svn fetch
734     will be called on the source."""
735     sha1 = None
736     if not os.path.isdir(self.checkout_path):
737       raise gclient_utils.Error(
738           ( 'We could not find a valid hash for safesync_url response "%s".\n'
739             'Safesync URLs with a git checkout currently require the repo to\n'
740             'be cloned without a safesync_url before adding the safesync_url.\n'
741             'For more info, see: '
742             'http://code.google.com/p/chromium/wiki/UsingNewGit'
743             '#Initial_checkout' ) % rev)
744     elif rev.isdigit() and len(rev) < 7:
745       # Handles an SVN rev.  As an optimization, only verify an SVN revision as
746       # [0-9]{1,6} for now to avoid making a network request.
747       if scm.GIT.IsGitSvn(cwd=self.checkout_path):
748         local_head = scm.GIT.GetGitSvnHeadRev(cwd=self.checkout_path)
749         if not local_head or local_head < int(rev):
750           try:
751             logging.debug('Looking for git-svn configuration optimizations.')
752             if scm.GIT.Capture(['config', '--get', 'svn-remote.svn.fetch'],
753                              cwd=self.checkout_path):
754               self._Fetch(options)
755           except subprocess2.CalledProcessError:
756             logging.debug('git config --get svn-remote.svn.fetch failed, '
757                           'ignoring possible optimization.')
758           if options.verbose:
759             self.Print('Running git svn fetch. This might take a while.\n')
760           scm.GIT.Capture(['svn', 'fetch'], cwd=self.checkout_path)
761         try:
762           sha1 = scm.GIT.GetBlessedSha1ForSvnRev(
763               cwd=self.checkout_path, rev=rev)
764         except gclient_utils.Error, e:
765           sha1 = e.message
766           self.Print('Warning: Could not find a git revision with accurate\n'
767                  '.DEPS.git that maps to SVN revision %s.  Sync-ing to\n'
768                  'the closest sane git revision, which is:\n'
769                  '  %s\n' % (rev, e.message))
770         if not sha1:
771           raise gclient_utils.Error(
772               ( 'It appears that either your git-svn remote is incorrectly\n'
773                 'configured or the revision in your safesync_url is\n'
774                 'higher than git-svn remote\'s HEAD as we couldn\'t find a\n'
775                 'corresponding git hash for SVN rev %s.' ) % rev)
776     else:
777       if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
778         sha1 = rev
779       else:
780         # May exist in origin, but we don't have it yet, so fetch and look
781         # again.
782         self._Fetch(options)
783         if scm.GIT.IsValidRevision(cwd=self.checkout_path, rev=rev):
784           sha1 = rev
785
786     if not sha1:
787       raise gclient_utils.Error(
788           ( 'We could not find a valid hash for safesync_url response "%s".\n'
789             'Safesync URLs with a git checkout currently require a git-svn\n'
790             'remote or a safesync_url that provides git sha1s. Please add a\n'
791             'git-svn remote or change your safesync_url. For more info, see:\n'
792             'http://code.google.com/p/chromium/wiki/UsingNewGit'
793             '#Initial_checkout' ) % rev)
794
795     return sha1
796
797   def FullUrlForRelativeUrl(self, url):
798     # Strip from last '/'
799     # Equivalent to unix basename
800     base_url = self.url
801     return base_url[:base_url.rfind('/')] + url
802
803   def _GetMirror(self, url, options):
804     """Get a git_cache.Mirror object for the argument url."""
805     if not git_cache.Mirror.GetCachePath():
806       return None
807     mirror_kwargs = {
808         'print_func': self.filter,
809         'refs': []
810     }
811     # TODO(hinoka): This currently just fails because lkcr/lkgr are branches
812     #               not tags. This also adds 20 seconds to every bot_update
813     #               run, so I'm commenting this out until lkcr/lkgr become
814     #               tags.  (2014/4/24)
815     # if url == CHROMIUM_SRC_URL or url + '.git' == CHROMIUM_SRC_URL:
816     #  mirror_kwargs['refs'].extend(['refs/tags/lkgr', 'refs/tags/lkcr'])
817     if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
818       mirror_kwargs['refs'].append('refs/branch-heads/*')
819     if hasattr(options, 'with_tags') and options.with_tags:
820       mirror_kwargs['refs'].append('refs/tags/*')
821     return git_cache.Mirror(url, **mirror_kwargs)
822
823   @staticmethod
824   def _UpdateMirror(mirror, options):
825     """Update a git mirror by fetching the latest commits from the remote."""
826     if getattr(options, 'shallow', False):
827       # HACK(hinoka): These repositories should be super shallow.
828       if 'flash' in mirror.url:
829         depth = 10
830       else:
831         depth = 10000
832     else:
833       depth = None
834     mirror.populate(verbose=options.verbose, bootstrap=True, depth=depth,
835                     ignore_lock=getattr(options, 'ignore_locks', False))
836     mirror.unlock()
837
838   def _Clone(self, revision, url, options):
839     """Clone a git repository from the given URL.
840
841     Once we've cloned the repo, we checkout a working branch if the specified
842     revision is a branch head. If it is a tag or a specific commit, then we
843     leave HEAD detached as it makes future updates simpler -- in this case the
844     user should first create a new branch or switch to an existing branch before
845     making changes in the repo."""
846     if not options.verbose:
847       # git clone doesn't seem to insert a newline properly before printing
848       # to stdout
849       self.Print('')
850     cfg = gclient_utils.DefaultIndexPackConfig(url)
851     clone_cmd = cfg + ['clone', '--no-checkout', '--progress']
852     if self.cache_dir:
853       clone_cmd.append('--shared')
854     if options.verbose:
855       clone_cmd.append('--verbose')
856     clone_cmd.append(url)
857     # If the parent directory does not exist, Git clone on Windows will not
858     # create it, so we need to do it manually.
859     parent_dir = os.path.dirname(self.checkout_path)
860     gclient_utils.safe_makedirs(parent_dir)
861
862     template_dir = None
863     if hasattr(options, 'no_history') and options.no_history:
864       if gclient_utils.IsGitSha(revision):
865         # In the case of a subproject, the pinned sha is not necessarily the
866         # head of the remote branch (so we can't just use --depth=N). Instead,
867         # we tell git to fetch all the remote objects from SHA..HEAD by means of
868         # a template git dir which has a 'shallow' file pointing to the sha.
869         template_dir = tempfile.mkdtemp(
870             prefix='_gclient_gittmp_%s' % os.path.basename(self.checkout_path),
871             dir=parent_dir)
872         self._Run(['init', '--bare', template_dir], options, cwd=self._root_dir)
873         with open(os.path.join(template_dir, 'shallow'), 'w') as template_file:
874           template_file.write(revision)
875         clone_cmd.append('--template=' + template_dir)
876       else:
877         # Otherwise, we're just interested in the HEAD. Just use --depth.
878         clone_cmd.append('--depth=1')
879
880     tmp_dir = tempfile.mkdtemp(
881         prefix='_gclient_%s_' % os.path.basename(self.checkout_path),
882         dir=parent_dir)
883     try:
884       clone_cmd.append(tmp_dir)
885       self._Run(clone_cmd, options, cwd=self._root_dir, retry=True)
886       gclient_utils.safe_makedirs(self.checkout_path)
887       gclient_utils.safe_rename(os.path.join(tmp_dir, '.git'),
888                                 os.path.join(self.checkout_path, '.git'))
889     except:
890       traceback.print_exc(file=self.out_fh)
891       raise
892     finally:
893       if os.listdir(tmp_dir):
894         self.Print('_____ removing non-empty tmp dir %s' % tmp_dir)
895       gclient_utils.rmtree(tmp_dir)
896       if template_dir:
897         gclient_utils.rmtree(template_dir)
898     self._UpdateBranchHeads(options, fetch=True)
899     remote_ref = scm.GIT.RefToRemoteRef(revision, self.remote)
900     self._Checkout(options, ''.join(remote_ref or revision), quiet=True)
901     if self._GetCurrentBranch() is None:
902       # Squelch git's very verbose detached HEAD warning and use our own
903       self.Print(
904         ('Checked out %s to a detached HEAD. Before making any commits\n'
905          'in this repo, you should use \'git checkout <branch>\' to switch to\n'
906          'an existing branch or use \'git checkout %s -b <branch>\' to\n'
907          'create a new branch for your work.') % (revision, self.remote))
908
909   def _AskForData(self, prompt, options):
910     if options.jobs > 1:
911       self.Print(prompt)
912       raise gclient_utils.Error("Background task requires input. Rerun "
913                                 "gclient with --jobs=1 so that\n"
914                                 "interaction is possible.")
915     try:
916       return raw_input(prompt)
917     except KeyboardInterrupt:
918       # Hide the exception.
919       sys.exit(1)
920
921
922   def _AttemptRebase(self, upstream, files, options, newbase=None,
923                      branch=None, printed_path=False, merge=False):
924     """Attempt to rebase onto either upstream or, if specified, newbase."""
925     if files is not None:
926       files.extend(self._Capture(['diff', upstream, '--name-only']).split())
927     revision = upstream
928     if newbase:
929       revision = newbase
930     action = 'merge' if merge else 'rebase'
931     if not printed_path:
932       self.Print('_____ %s : Attempting %s onto %s...' % (
933           self.relpath, action, revision))
934       printed_path = True
935     else:
936       self.Print('Attempting %s onto %s...' % (action, revision))
937
938     if merge:
939       merge_output = self._Capture(['merge', revision])
940       if options.verbose:
941         self.Print(merge_output)
942       return
943
944     # Build the rebase command here using the args
945     # git rebase [options] [--onto <newbase>] <upstream> [<branch>]
946     rebase_cmd = ['rebase']
947     if options.verbose:
948       rebase_cmd.append('--verbose')
949     if newbase:
950       rebase_cmd.extend(['--onto', newbase])
951     rebase_cmd.append(upstream)
952     if branch:
953       rebase_cmd.append(branch)
954
955     try:
956       rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
957     except subprocess2.CalledProcessError, e:
958       if (re.match(r'cannot rebase: you have unstaged changes', e.stderr) or
959           re.match(r'cannot rebase: your index contains uncommitted changes',
960                    e.stderr)):
961         while True:
962           rebase_action = self._AskForData(
963               'Cannot rebase because of unstaged changes.\n'
964               '\'git reset --hard HEAD\' ?\n'
965               'WARNING: destroys any uncommitted work in your current branch!'
966               ' (y)es / (q)uit / (s)how : ', options)
967           if re.match(r'yes|y', rebase_action, re.I):
968             self._Run(['reset', '--hard', 'HEAD'], options)
969             # Should this be recursive?
970             rebase_output = scm.GIT.Capture(rebase_cmd, cwd=self.checkout_path)
971             break
972           elif re.match(r'quit|q', rebase_action, re.I):
973             raise gclient_utils.Error("Please merge or rebase manually\n"
974                                       "cd %s && git " % self.checkout_path
975                                       + "%s" % ' '.join(rebase_cmd))
976           elif re.match(r'show|s', rebase_action, re.I):
977             self.Print('%s' % e.stderr.strip())
978             continue
979           else:
980             gclient_utils.Error("Input not recognized")
981             continue
982       elif re.search(r'^CONFLICT', e.stdout, re.M):
983         raise gclient_utils.Error("Conflict while rebasing this branch.\n"
984                                   "Fix the conflict and run gclient again.\n"
985                                   "See 'man git-rebase' for details.\n")
986       else:
987         self.Print(e.stdout.strip())
988         self.Print('Rebase produced error output:\n%s' % e.stderr.strip())
989         raise gclient_utils.Error("Unrecognized error, please merge or rebase "
990                                   "manually.\ncd %s && git " %
991                                   self.checkout_path
992                                   + "%s" % ' '.join(rebase_cmd))
993
994     self.Print(rebase_output.strip())
995     if not options.verbose:
996       # Make the output a little prettier. It's nice to have some
997       # whitespace between projects when syncing.
998       self.Print('')
999
1000   @staticmethod
1001   def _CheckMinVersion(min_version):
1002     (ok, current_version) = scm.GIT.AssertVersion(min_version)
1003     if not ok:
1004       raise gclient_utils.Error('git version %s < minimum required %s' %
1005                                 (current_version, min_version))
1006
1007   def _IsRebasing(self):
1008     # Check for any of REBASE-i/REBASE-m/REBASE/AM. Unfortunately git doesn't
1009     # have a plumbing command to determine whether a rebase is in progress, so
1010     # for now emualate (more-or-less) git-rebase.sh / git-completion.bash
1011     g = os.path.join(self.checkout_path, '.git')
1012     return (
1013       os.path.isdir(os.path.join(g, "rebase-merge")) or
1014       os.path.isdir(os.path.join(g, "rebase-apply")))
1015
1016   def _CheckClean(self, rev_str):
1017     # Make sure the tree is clean; see git-rebase.sh for reference
1018     try:
1019       scm.GIT.Capture(['update-index', '--ignore-submodules', '--refresh'],
1020                       cwd=self.checkout_path)
1021     except subprocess2.CalledProcessError:
1022       raise gclient_utils.Error('\n____ %s%s\n'
1023                                 '\tYou have unstaged changes.\n'
1024                                 '\tPlease commit, stash, or reset.\n'
1025                                   % (self.relpath, rev_str))
1026     try:
1027       scm.GIT.Capture(['diff-index', '--cached', '--name-status', '-r',
1028                        '--ignore-submodules', 'HEAD', '--'],
1029                        cwd=self.checkout_path)
1030     except subprocess2.CalledProcessError:
1031       raise gclient_utils.Error('\n____ %s%s\n'
1032                                 '\tYour index contains uncommitted changes\n'
1033                                 '\tPlease commit, stash, or reset.\n'
1034                                   % (self.relpath, rev_str))
1035
1036   def _CheckDetachedHead(self, rev_str, _options):
1037     # HEAD is detached. Make sure it is safe to move away from (i.e., it is
1038     # reference by a commit). If not, error out -- most likely a rebase is
1039     # in progress, try to detect so we can give a better error.
1040     try:
1041       scm.GIT.Capture(['name-rev', '--no-undefined', 'HEAD'],
1042           cwd=self.checkout_path)
1043     except subprocess2.CalledProcessError:
1044       # Commit is not contained by any rev. See if the user is rebasing:
1045       if self._IsRebasing():
1046         # Punt to the user
1047         raise gclient_utils.Error('\n____ %s%s\n'
1048                                   '\tAlready in a conflict, i.e. (no branch).\n'
1049                                   '\tFix the conflict and run gclient again.\n'
1050                                   '\tOr to abort run:\n\t\tgit-rebase --abort\n'
1051                                   '\tSee man git-rebase for details.\n'
1052                                    % (self.relpath, rev_str))
1053       # Let's just save off the commit so we can proceed.
1054       name = ('saved-by-gclient-' +
1055               self._Capture(['rev-parse', '--short', 'HEAD']))
1056       self._Capture(['branch', '-f', name])
1057       self.Print('_____ found an unreferenced commit and saved it as \'%s\'' %
1058           name)
1059
1060   def _GetCurrentBranch(self):
1061     # Returns name of current branch or None for detached HEAD
1062     branch = self._Capture(['rev-parse', '--abbrev-ref=strict', 'HEAD'])
1063     if branch == 'HEAD':
1064       return None
1065     return branch
1066
1067   def _Capture(self, args, **kwargs):
1068     kwargs.setdefault('cwd', self.checkout_path)
1069     kwargs.setdefault('stderr', subprocess2.PIPE)
1070     env = scm.GIT.ApplyEnvVars(kwargs)
1071     return subprocess2.check_output(['git'] + args, env=env, **kwargs).strip()
1072
1073   def _Checkout(self, options, ref, force=False, quiet=None):
1074     """Performs a 'git-checkout' operation.
1075
1076     Args:
1077       options: The configured option set
1078       ref: (str) The branch/commit to checkout
1079       quiet: (bool/None) Whether or not the checkout shoud pass '--quiet'; if
1080           'None', the behavior is inferred from 'options.verbose'.
1081     Returns: (str) The output of the checkout operation
1082     """
1083     if quiet is None:
1084       quiet = (not options.verbose)
1085     checkout_args = ['checkout']
1086     if force:
1087       checkout_args.append('--force')
1088     if quiet:
1089       checkout_args.append('--quiet')
1090     checkout_args.append(ref)
1091     return self._Capture(checkout_args)
1092
1093   def _Fetch(self, options, remote=None, prune=False, quiet=False):
1094     cfg = gclient_utils.DefaultIndexPackConfig(self.url)
1095     fetch_cmd =  cfg + [
1096         'fetch',
1097         remote or self.remote,
1098     ]
1099
1100     if prune:
1101       fetch_cmd.append('--prune')
1102     if options.verbose:
1103       fetch_cmd.append('--verbose')
1104     elif quiet:
1105       fetch_cmd.append('--quiet')
1106     self._Run(fetch_cmd, options, show_header=options.verbose, retry=True)
1107
1108     # Return the revision that was fetched; this will be stored in 'FETCH_HEAD'
1109     return self._Capture(['rev-parse', '--verify', 'FETCH_HEAD'])
1110
1111   def _UpdateBranchHeads(self, options, fetch=False):
1112     """Adds, and optionally fetches, "branch-heads" and "tags" refspecs
1113     if requested."""
1114     need_fetch = fetch
1115     if hasattr(options, 'with_branch_heads') and options.with_branch_heads:
1116       config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1117                     '+refs/branch-heads/*:refs/remotes/branch-heads/*',
1118                     '^\\+refs/branch-heads/\\*:.*$']
1119       self._Run(config_cmd, options)
1120       need_fetch = True
1121     if hasattr(options, 'with_tags') and options.with_tags:
1122       config_cmd = ['config', 'remote.%s.fetch' % self.remote,
1123                     '+refs/tags/*:refs/tags/*',
1124                     '^\\+refs/tags/\\*:.*$']
1125       self._Run(config_cmd, options)
1126       need_fetch = True
1127     if fetch and need_fetch:
1128       self._Fetch(options)
1129
1130   def _Run(self, args, options, show_header=True, **kwargs):
1131     # Disable 'unused options' warning | pylint: disable=W0613
1132     kwargs.setdefault('cwd', self.checkout_path)
1133     kwargs.setdefault('stdout', self.out_fh)
1134     kwargs['filter_fn'] = self.filter
1135     kwargs.setdefault('print_stdout', False)
1136     env = scm.GIT.ApplyEnvVars(kwargs)
1137     cmd = ['git'] + args
1138     if show_header:
1139       gclient_utils.CheckCallAndFilterAndHeader(cmd, env=env, **kwargs)
1140     else:
1141       gclient_utils.CheckCallAndFilter(cmd, env=env, **kwargs)
1142
1143
1144 class SVNWrapper(SCMWrapper):
1145   """ Wrapper for SVN """
1146   name = 'svn'
1147
1148   @staticmethod
1149   def BinaryExists():
1150     """Returns true if the command exists."""
1151     try:
1152       result, version = scm.SVN.AssertVersion('1.4')
1153       if not result:
1154         raise gclient_utils.Error('SVN version is older than 1.4: %s' % version)
1155       return result
1156     except OSError:
1157       return False
1158
1159   def GetCheckoutRoot(self):
1160     return scm.SVN.GetCheckoutRoot(self.checkout_path)
1161
1162   def GetRevisionDate(self, revision):
1163     """Returns the given revision's date in ISO-8601 format (which contains the
1164     time zone)."""
1165     date = scm.SVN.Capture(
1166         ['propget', '--revprop', 'svn:date', '-r', revision],
1167         os.path.join(self.checkout_path, '.'))
1168     return date.strip()
1169
1170   def cleanup(self, options, args, _file_list):
1171     """Cleanup working copy."""
1172     self._Run(['cleanup'] + args, options)
1173
1174   def diff(self, options, args, _file_list):
1175     # NOTE: This function does not currently modify file_list.
1176     if not os.path.isdir(self.checkout_path):
1177       raise gclient_utils.Error('Directory %s is not present.' %
1178           self.checkout_path)
1179     self._Run(['diff'] + args, options)
1180
1181   def pack(self, _options, args, _file_list):
1182     """Generates a patch file which can be applied to the root of the
1183     repository."""
1184     if not os.path.isdir(self.checkout_path):
1185       raise gclient_utils.Error('Directory %s is not present.' %
1186           self.checkout_path)
1187     gclient_utils.CheckCallAndFilter(
1188         ['svn', 'diff', '-x', '--ignore-eol-style'] + args,
1189         cwd=self.checkout_path,
1190         print_stdout=False,
1191         filter_fn=SvnDiffFilterer(self.relpath, print_func=self.Print).Filter)
1192
1193   def update(self, options, args, file_list):
1194     """Runs svn to update or transparently checkout the working copy.
1195
1196     All updated files will be appended to file_list.
1197
1198     Raises:
1199       Error: if can't get URL for relative path.
1200     """
1201     # Only update if hg is not controlling the directory.
1202     hg_path = os.path.join(self.checkout_path, '.hg')
1203     if os.path.exists(hg_path):
1204       self.Print('________ found .hg directory; skipping %s' % self.relpath)
1205       return
1206
1207     if args:
1208       raise gclient_utils.Error("Unsupported argument(s): %s" % ",".join(args))
1209
1210     # revision is the revision to match. It is None if no revision is specified,
1211     # i.e. the 'deps ain't pinned'.
1212     url, revision = gclient_utils.SplitUrlRevision(self.url)
1213     # Keep the original unpinned url for reference in case the repo is switched.
1214     base_url = url
1215     managed = True
1216     if options.revision:
1217       # Override the revision number.
1218       revision = str(options.revision)
1219     if revision:
1220       if revision != 'unmanaged':
1221         forced_revision = True
1222         # Reconstruct the url.
1223         url = '%s@%s' % (url, revision)
1224         rev_str = ' at %s' % revision
1225       else:
1226         managed = False
1227         revision = None
1228     else:
1229       forced_revision = False
1230       rev_str = ''
1231
1232     exists = os.path.exists(self.checkout_path)
1233     if exists and managed:
1234       # Git is only okay if it's a git-svn checkout of the right repo.
1235       if scm.GIT.IsGitSvn(self.checkout_path):
1236         remote_url = scm.GIT.Capture(['config', '--local', '--get',
1237                                       'svn-remote.svn.url'],
1238                                      cwd=self.checkout_path).rstrip()
1239         if remote_url.rstrip('/') == base_url.rstrip('/'):
1240           self.Print('\n_____ %s looks like a git-svn checkout. Skipping.'
1241                      % self.relpath)
1242           return # TODO(borenet): Get the svn revision number?
1243
1244     # Get the existing scm url and the revision number of the current checkout.
1245     if exists and managed:
1246       try:
1247         from_info = scm.SVN.CaptureLocalInfo(
1248             [], os.path.join(self.checkout_path, '.'))
1249       except (gclient_utils.Error, subprocess2.CalledProcessError):
1250         self._DeleteOrMove(options.force)
1251         exists = False
1252
1253     BASE_URLS = {
1254         '/chrome/trunk/src': 'gs://chromium-svn-checkout/chrome/',
1255         '/blink/trunk': 'gs://chromium-svn-checkout/blink/',
1256     }
1257     WHITELISTED_ROOTS = [
1258         'svn://svn.chromium.org',
1259         'svn://svn-mirror.golo.chromium.org',
1260     ]
1261     if not exists:
1262       try:
1263         # Split out the revision number since it's not useful for us.
1264         base_path = urlparse.urlparse(url).path.split('@')[0]
1265         # Check to see if we're on a whitelisted root.  We do this because
1266         # only some svn servers have matching UUIDs.
1267         local_parsed = urlparse.urlparse(url)
1268         local_root = '%s://%s' % (local_parsed.scheme, local_parsed.netloc)
1269         if ('CHROME_HEADLESS' in os.environ
1270             and sys.platform == 'linux2'  # TODO(hinoka): Enable for win/mac.
1271             and base_path in BASE_URLS
1272             and local_root in WHITELISTED_ROOTS):
1273
1274           # Use a tarball for initial sync if we are on a bot.
1275           # Get an unauthenticated gsutil instance.
1276           gsutil = download_from_google_storage.Gsutil(
1277               GSUTIL_DEFAULT_PATH, boto_path=os.devnull)
1278
1279           gs_path = BASE_URLS[base_path]
1280           _, out, _ = gsutil.check_call('ls', gs_path)
1281           # So that we can get the most recent revision.
1282           sorted_items = sorted(out.splitlines())
1283           latest_checkout = sorted_items[-1]
1284
1285           tempdir = tempfile.mkdtemp()
1286           self.Print('Downloading %s...' % latest_checkout)
1287           code, out, err = gsutil.check_call('cp', latest_checkout, tempdir)
1288           if code:
1289             self.Print('%s\n%s' % (out, err))
1290             raise Exception()
1291           filename = latest_checkout.split('/')[-1]
1292           tarball = os.path.join(tempdir, filename)
1293           self.Print('Unpacking into %s...' % self.checkout_path)
1294           gclient_utils.safe_makedirs(self.checkout_path)
1295           # TODO(hinoka): Use 7z for windows.
1296           cmd = ['tar', '--extract', '--ungzip',
1297                   '--directory', self.checkout_path,
1298                   '--file', tarball]
1299           gclient_utils.CheckCallAndFilter(
1300               cmd, stdout=sys.stdout, print_stdout=True)
1301
1302           self.Print('Deleting temp file')
1303           gclient_utils.rmtree(tempdir)
1304
1305           # Rewrite the repository root to match.
1306           tarball_url = scm.SVN.CaptureLocalInfo(
1307               ['.'], self.checkout_path)['Repository Root']
1308           tarball_parsed = urlparse.urlparse(tarball_url)
1309           tarball_root = '%s://%s' % (tarball_parsed.scheme,
1310                                       tarball_parsed.netloc)
1311
1312           if tarball_root != local_root:
1313             self.Print('Switching repository root to %s' % local_root)
1314             self._Run(['switch', '--relocate', tarball_root,
1315                        local_root, self.checkout_path],
1316                       options)
1317       except Exception as e:
1318         self.Print('We tried to get a source tarball but failed.')
1319         self.Print('Resuming normal operations.')
1320         self.Print(str(e))
1321
1322       gclient_utils.safe_makedirs(os.path.dirname(self.checkout_path))
1323       # We need to checkout.
1324       command = ['checkout', url, self.checkout_path]
1325       command = self._AddAdditionalUpdateFlags(command, options, revision)
1326       self._RunAndGetFileList(command, options, file_list, self._root_dir)
1327       return self.Svnversion()
1328
1329     if not managed:
1330       self.Print(('________ unmanaged solution; skipping %s' % self.relpath))
1331       if os.path.exists(os.path.join(self.checkout_path, '.svn')):
1332         return self.Svnversion()
1333       return
1334
1335     if 'URL' not in from_info:
1336       raise gclient_utils.Error(
1337           ('gclient is confused. Couldn\'t get the url for %s.\n'
1338            'Try using @unmanaged.\n%s') % (
1339             self.checkout_path, from_info))
1340
1341     # Look for locked directories.
1342     dir_info = scm.SVN.CaptureStatus(
1343         None, os.path.join(self.checkout_path, '.'))
1344     if any(d[0][2] == 'L' for d in dir_info):
1345       try:
1346         self._Run(['cleanup', self.checkout_path], options)
1347       except subprocess2.CalledProcessError, e:
1348         # Get the status again, svn cleanup may have cleaned up at least
1349         # something.
1350         dir_info = scm.SVN.CaptureStatus(
1351             None, os.path.join(self.checkout_path, '.'))
1352
1353         # Try to fix the failures by removing troublesome files.
1354         for d in dir_info:
1355           if d[0][2] == 'L':
1356             if d[0][0] == '!' and options.force:
1357               # We don't pass any files/directories to CaptureStatus and set
1358               # cwd=self.checkout_path, so we should get relative paths here.
1359               assert not os.path.isabs(d[1])
1360               path_to_remove = os.path.normpath(
1361                   os.path.join(self.checkout_path, d[1]))
1362               self.Print('Removing troublesome path %s' % path_to_remove)
1363               gclient_utils.rmtree(path_to_remove)
1364             else:
1365               self.Print(
1366                   'Not removing troublesome path %s automatically.' % d[1])
1367               if d[0][0] == '!':
1368                 self.Print('You can pass --force to enable automatic removal.')
1369               raise e
1370
1371     # Retrieve the current HEAD version because svn is slow at null updates.
1372     if options.manually_grab_svn_rev and not revision:
1373       from_info_live = scm.SVN.CaptureRemoteInfo(from_info['URL'])
1374       revision = str(from_info_live['Revision'])
1375       rev_str = ' at %s' % revision
1376
1377     if from_info['URL'].rstrip('/') != base_url.rstrip('/'):
1378       # The repository url changed, need to switch.
1379       try:
1380         to_info = scm.SVN.CaptureRemoteInfo(url)
1381       except (gclient_utils.Error, subprocess2.CalledProcessError):
1382         # The url is invalid or the server is not accessible, it's safer to bail
1383         # out right now.
1384         raise gclient_utils.Error('This url is unreachable: %s' % url)
1385       can_switch = ((from_info['Repository Root'] != to_info['Repository Root'])
1386                     and (from_info['UUID'] == to_info['UUID']))
1387       if can_switch:
1388         self.Print('_____ relocating %s to a new checkout' % self.relpath)
1389         # We have different roots, so check if we can switch --relocate.
1390         # Subversion only permits this if the repository UUIDs match.
1391         # Perform the switch --relocate, then rewrite the from_url
1392         # to reflect where we "are now."  (This is the same way that
1393         # Subversion itself handles the metadata when switch --relocate
1394         # is used.)  This makes the checks below for whether we
1395         # can update to a revision or have to switch to a different
1396         # branch work as expected.
1397         # TODO(maruel):  TEST ME !
1398         command = ['switch', '--relocate',
1399                    from_info['Repository Root'],
1400                    to_info['Repository Root'],
1401                    self.relpath]
1402         self._Run(command, options, cwd=self._root_dir)
1403         from_info['URL'] = from_info['URL'].replace(
1404             from_info['Repository Root'],
1405             to_info['Repository Root'])
1406       else:
1407         if not options.force and not options.reset:
1408           # Look for local modifications but ignore unversioned files.
1409           for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1410             if status[0][0] != '?':
1411               raise gclient_utils.Error(
1412                   ('Can\'t switch the checkout to %s; UUID don\'t match and '
1413                    'there is local changes in %s. Delete the directory and '
1414                    'try again.') % (url, self.checkout_path))
1415         # Ok delete it.
1416         self.Print('_____ switching %s to a new checkout' % self.relpath)
1417         gclient_utils.rmtree(self.checkout_path)
1418         # We need to checkout.
1419         command = ['checkout', url, self.checkout_path]
1420         command = self._AddAdditionalUpdateFlags(command, options, revision)
1421         self._RunAndGetFileList(command, options, file_list, self._root_dir)
1422         return self.Svnversion()
1423
1424     # If the provided url has a revision number that matches the revision
1425     # number of the existing directory, then we don't need to bother updating.
1426     if not options.force and str(from_info['Revision']) == revision:
1427       if options.verbose or not forced_revision:
1428         self.Print('_____ %s%s' % (self.relpath, rev_str), timestamp=False)
1429     else:
1430       command = ['update', self.checkout_path]
1431       command = self._AddAdditionalUpdateFlags(command, options, revision)
1432       self._RunAndGetFileList(command, options, file_list, self._root_dir)
1433
1434     # If --reset and --delete_unversioned_trees are specified, remove any
1435     # untracked files and directories.
1436     if options.reset and options.delete_unversioned_trees:
1437       for status in scm.SVN.CaptureStatus(None, self.checkout_path):
1438         full_path = os.path.join(self.checkout_path, status[1])
1439         if (status[0][0] == '?'
1440             and os.path.isdir(full_path)
1441             and not os.path.islink(full_path)):
1442           self.Print('_____ removing unversioned directory %s' % status[1])
1443           gclient_utils.rmtree(full_path)
1444     return self.Svnversion()
1445
1446   def updatesingle(self, options, args, file_list):
1447     filename = args.pop()
1448     if scm.SVN.AssertVersion("1.5")[0]:
1449       if not os.path.exists(os.path.join(self.checkout_path, '.svn')):
1450         # Create an empty checkout and then update the one file we want.  Future
1451         # operations will only apply to the one file we checked out.
1452         command = ["checkout", "--depth", "empty", self.url, self.checkout_path]
1453         self._Run(command, options, cwd=self._root_dir)
1454         if os.path.exists(os.path.join(self.checkout_path, filename)):
1455           os.remove(os.path.join(self.checkout_path, filename))
1456         command = ["update", filename]
1457         self._RunAndGetFileList(command, options, file_list)
1458       # After the initial checkout, we can use update as if it were any other
1459       # dep.
1460       self.update(options, args, file_list)
1461     else:
1462       # If the installed version of SVN doesn't support --depth, fallback to
1463       # just exporting the file.  This has the downside that revision
1464       # information is not stored next to the file, so we will have to
1465       # re-export the file every time we sync.
1466       if not os.path.exists(self.checkout_path):
1467         gclient_utils.safe_makedirs(self.checkout_path)
1468       command = ["export", os.path.join(self.url, filename),
1469                  os.path.join(self.checkout_path, filename)]
1470       command = self._AddAdditionalUpdateFlags(command, options,
1471           options.revision)
1472       self._Run(command, options, cwd=self._root_dir)
1473
1474   def revert(self, options, _args, file_list):
1475     """Reverts local modifications. Subversion specific.
1476
1477     All reverted files will be appended to file_list, even if Subversion
1478     doesn't know about them.
1479     """
1480     if not os.path.isdir(self.checkout_path):
1481       if os.path.exists(self.checkout_path):
1482         gclient_utils.rmtree(self.checkout_path)
1483       # svn revert won't work if the directory doesn't exist. It needs to
1484       # checkout instead.
1485       self.Print('_____ %s is missing, synching instead' % self.relpath)
1486       # Don't reuse the args.
1487       return self.update(options, [], file_list)
1488
1489     if not os.path.isdir(os.path.join(self.checkout_path, '.svn')):
1490       if os.path.isdir(os.path.join(self.checkout_path, '.git')):
1491         self.Print('________ found .git directory; skipping %s' % self.relpath)
1492         return
1493       if os.path.isdir(os.path.join(self.checkout_path, '.hg')):
1494         self.Print('________ found .hg directory; skipping %s' % self.relpath)
1495         return
1496       if not options.force:
1497         raise gclient_utils.Error('Invalid checkout path, aborting')
1498       self.Print(
1499           '\n_____ %s is not a valid svn checkout, synching instead' %
1500           self.relpath)
1501       gclient_utils.rmtree(self.checkout_path)
1502       # Don't reuse the args.
1503       return self.update(options, [], file_list)
1504
1505     def printcb(file_status):
1506       if file_list is not None:
1507         file_list.append(file_status[1])
1508       if logging.getLogger().isEnabledFor(logging.INFO):
1509         logging.info('%s%s' % (file_status[0], file_status[1]))
1510       else:
1511         self.Print(os.path.join(self.checkout_path, file_status[1]))
1512     scm.SVN.Revert(self.checkout_path, callback=printcb)
1513
1514     # Revert() may delete the directory altogether.
1515     if not os.path.isdir(self.checkout_path):
1516       # Don't reuse the args.
1517       return self.update(options, [], file_list)
1518
1519     try:
1520       # svn revert is so broken we don't even use it. Using
1521       # "svn up --revision BASE" achieve the same effect.
1522       # file_list will contain duplicates.
1523       self._RunAndGetFileList(['update', '--revision', 'BASE'], options,
1524           file_list)
1525     except OSError, e:
1526       # Maybe the directory disapeared meanwhile. Do not throw an exception.
1527       logging.error('Failed to update:\n%s' % str(e))
1528
1529   def revinfo(self, _options, _args, _file_list):
1530     """Display revision"""
1531     try:
1532       return scm.SVN.CaptureRevision(self.checkout_path)
1533     except (gclient_utils.Error, subprocess2.CalledProcessError):
1534       return None
1535
1536   def runhooks(self, options, args, file_list):
1537     self.status(options, args, file_list)
1538
1539   def status(self, options, args, file_list):
1540     """Display status information."""
1541     command = ['status'] + args
1542     if not os.path.isdir(self.checkout_path):
1543       # svn status won't work if the directory doesn't exist.
1544       self.Print(('\n________ couldn\'t run \'%s\' in \'%s\':\n'
1545              'The directory does not exist.') %
1546                 (' '.join(command), self.checkout_path))
1547       # There's no file list to retrieve.
1548     else:
1549       self._RunAndGetFileList(command, options, file_list)
1550
1551   def GetUsableRev(self, rev, _options):
1552     """Verifies the validity of the revision for this repository."""
1553     if not scm.SVN.IsValidRevision(url='%s@%s' % (self.url, rev)):
1554       raise gclient_utils.Error(
1555         ( '%s isn\'t a valid revision. Please check that your safesync_url is\n'
1556           'correct.') % rev)
1557     return rev
1558
1559   def FullUrlForRelativeUrl(self, url):
1560     # Find the forth '/' and strip from there. A bit hackish.
1561     return '/'.join(self.url.split('/')[:4]) + url
1562
1563   def _Run(self, args, options, **kwargs):
1564     """Runs a commands that goes to stdout."""
1565     kwargs.setdefault('cwd', self.checkout_path)
1566     gclient_utils.CheckCallAndFilterAndHeader(['svn'] + args,
1567         always=options.verbose, **kwargs)
1568
1569   def Svnversion(self):
1570     """Runs the lowest checked out revision in the current project."""
1571     info = scm.SVN.CaptureLocalInfo([], os.path.join(self.checkout_path, '.'))
1572     return info['Revision']
1573
1574   def _RunAndGetFileList(self, args, options, file_list, cwd=None):
1575     """Runs a commands that goes to stdout and grabs the file listed."""
1576     cwd = cwd or self.checkout_path
1577     scm.SVN.RunAndGetFileList(
1578         options.verbose,
1579         args + ['--ignore-externals'],
1580         cwd=cwd,
1581         file_list=file_list)
1582
1583   @staticmethod
1584   def _AddAdditionalUpdateFlags(command, options, revision):
1585     """Add additional flags to command depending on what options are set.
1586     command should be a list of strings that represents an svn command.
1587
1588     This method returns a new list to be used as a command."""
1589     new_command = command[:]
1590     if revision:
1591       new_command.extend(['--revision', str(revision).strip()])
1592     # We don't want interaction when jobs are used.
1593     if options.jobs > 1:
1594       new_command.append('--non-interactive')
1595     # --force was added to 'svn update' in svn 1.5.
1596     # --accept was added to 'svn update' in svn 1.6.
1597     if not scm.SVN.AssertVersion('1.5')[0]:
1598       return new_command
1599
1600     # It's annoying to have it block in the middle of a sync, just sensible
1601     # defaults.
1602     if options.force:
1603       new_command.append('--force')
1604       if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1605         new_command.extend(('--accept', 'theirs-conflict'))
1606     elif options.manually_grab_svn_rev:
1607       new_command.append('--force')
1608       if command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1609         new_command.extend(('--accept', 'postpone'))
1610     elif command[0] != 'checkout' and scm.SVN.AssertVersion('1.6')[0]:
1611       new_command.extend(('--accept', 'postpone'))
1612     return new_command