Home | History | Annotate | Download | only in tools
      1 # Copyright (C) 2012 The Android Open Source Project
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License");
      4 # you may not use this file except in compliance with the License.
      5 # You may obtain a copy of the License at
      6 #
      7 #      http://www.apache.org/licenses/LICENSE-2.0
      8 #
      9 # Unless required by applicable law or agreed to in writing, software
     10 # distributed under the License is distributed on an "AS IS" BASIS,
     11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 # See the License for the specific language governing permissions and
     13 # limitations under the License.
     14 
     15 """Common data/functions for the Chromium merging scripts."""
     16 
     17 import logging
     18 import os
     19 import re
     20 import subprocess
     21 
     22 
     23 REPOSITORY_ROOT = os.path.join(os.environ['ANDROID_BUILD_TOP'],
     24                                'external/chromium_org')
     25 
     26 
     27 # Whitelist of projects that need to be merged to build WebView. We don't need
     28 # the other upstream repositories used to build the actual Chrome app.
     29 # Different stages of the merge process need different ways of looking at the
     30 # list, so we construct different combinations below.
     31 
     32 THIRD_PARTY_PROJECTS_WITH_FLAT_HISTORY = [
     33     'third_party/WebKit',
     34 ]
     35 
     36 THIRD_PARTY_PROJECTS_WITH_FULL_HISTORY = [
     37     'sdch/open-vcdiff',
     38     'testing/gtest',
     39     'third_party/angle_dx11',
     40     'third_party/eyesfree/src/android/java/src/com/googlecode/eyesfree/braille',
     41     'third_party/freetype',
     42     'third_party/icu',
     43     'third_party/leveldatabase/src',
     44     'third_party/libjingle/source/talk',
     45     'third_party/libphonenumber/src/phonenumbers',
     46     'third_party/libphonenumber/src/resources',
     47     'third_party/mesa/src',
     48     'third_party/openssl',
     49     'third_party/opus/src',
     50     'third_party/ots',
     51     'third_party/skia/include',
     52     'third_party/skia/gyp',
     53     'third_party/skia/src',
     54     'third_party/smhasher/src',
     55     'third_party/yasm/source/patched-yasm',
     56     'tools/grit',
     57     'tools/gyp',
     58     'v8',
     59 ]
     60 
     61 PROJECTS_WITH_FLAT_HISTORY = ['.'] + THIRD_PARTY_PROJECTS_WITH_FLAT_HISTORY
     62 PROJECTS_WITH_FULL_HISTORY = THIRD_PARTY_PROJECTS_WITH_FULL_HISTORY
     63 
     64 THIRD_PARTY_PROJECTS = (THIRD_PARTY_PROJECTS_WITH_FLAT_HISTORY +
     65                         THIRD_PARTY_PROJECTS_WITH_FULL_HISTORY)
     66 
     67 ALL_PROJECTS = ['.'] + THIRD_PARTY_PROJECTS
     68 
     69 
     70 # Directories to be removed when flattening history.
     71 PRUNE_WHEN_FLATTENING = {
     72     'third_party/WebKit': [
     73         'LayoutTests',
     74     ],
     75 }
     76 
     77 
     78 # Only projects that have their history flattened can have directories pruned.
     79 assert all(p in PROJECTS_WITH_FLAT_HISTORY for p in PRUNE_WHEN_FLATTENING)
     80 
     81 
     82 class MergeError(Exception):
     83   """Used to signal an error that prevents the merge from being completed."""
     84 
     85 
     86 class CommandError(MergeError):
     87   """This exception is raised when a process run by GetCommandStdout fails."""
     88 
     89   def __init__(self, returncode, cmd, cwd, stdout, stderr):
     90     super(CommandError, self).__init__()
     91     self.returncode = returncode
     92     self.cmd = cmd
     93     self.cwd = cwd
     94     self.stdout = stdout
     95     self.stderr = stderr
     96 
     97   def __str__(self):
     98     return ("Command '%s' returned non-zero exit status %d. cwd was '%s'.\n\n"
     99             "===STDOUT===\n%s\n===STDERR===\n%s\n" %
    100             (self.cmd, self.returncode, self.cwd, self.stdout, self.stderr))
    101 
    102 
    103 class TemporaryMergeError(MergeError):
    104   """A merge error that can potentially be resolved by trying again later."""
    105 
    106 
    107 def GetCommandStdout(args, cwd=REPOSITORY_ROOT, ignore_errors=False):
    108   """Gets stdout from runnng the specified shell command.
    109 
    110   Similar to subprocess.check_output() except that it can capture stdout and
    111   stderr separately for better error reporting.
    112 
    113   Args:
    114     args: The command and its arguments as an iterable.
    115     cwd: The working directory to use. Defaults to REPOSITORY_ROOT.
    116     ignore_errors: Ignore the command's return code and stderr.
    117   Returns:
    118     stdout from running the command.
    119   Raises:
    120     CommandError: if the command exited with a nonzero status.
    121   """
    122   p = subprocess.Popen(args=args, cwd=cwd, stdout=subprocess.PIPE,
    123                        stderr=subprocess.PIPE)
    124   stdout, stderr = p.communicate()
    125   if p.returncode == 0 or ignore_errors:
    126     return stdout
    127   else:
    128     raise CommandError(p.returncode, ' '.join(args), cwd, stdout, stderr)
    129 
    130 
    131 def CheckNoConflictsAndCommitMerge(commit_message, unattended=False,
    132                                    cwd=REPOSITORY_ROOT):
    133   """Checks for conflicts and commits once they are resolved.
    134 
    135   Certain conflicts are resolved automatically; if any remain, the user is
    136   prompted to resolve them. The user can specify a custom commit message.
    137 
    138   Args:
    139     commit_message: The default commit message.
    140     unattended: If running unattended, abort on conflicts.
    141     cwd: Working directory to use.
    142   Raises:
    143     TemporaryMergeError: If there are conflicts in unattended mode.
    144   """
    145   status = GetCommandStdout(['git', 'status', '--porcelain'], cwd=cwd)
    146   conflicts_deleted_by_us = re.findall(r'^(?:DD|DU) ([^\n]+)$', status,
    147                                        flags=re.MULTILINE)
    148   if conflicts_deleted_by_us:
    149     logging.info('Keeping ours for the following locally deleted files.\n  %s',
    150                  '\n  '.join(conflicts_deleted_by_us))
    151     GetCommandStdout(['git', 'rm', '-rf', '--ignore-unmatch'] +
    152                      conflicts_deleted_by_us, cwd=cwd)
    153 
    154   # If upstream renames a file we have deleted then it will conflict, but
    155   # we shouldn't just blindly delete these files as they may have been renamed
    156   # into a directory we don't delete. Let them get re-added; they will get
    157   # re-deleted if they are still in a directory we delete.
    158   conflicts_renamed_by_them = re.findall(r'^UA ([^\n]+)$', status,
    159                                          flags=re.MULTILINE)
    160   if conflicts_renamed_by_them:
    161     logging.info('Adding theirs for the following locally deleted files.\n %s',
    162                  '\n  '.join(conflicts_renamed_by_them))
    163     GetCommandStdout(['git', 'add', '-f'] + conflicts_renamed_by_them, cwd=cwd)
    164 
    165   while True:
    166     status = GetCommandStdout(['git', 'status', '--porcelain'], cwd=cwd)
    167     conflicts = re.findall(r'^((DD|AU|UD|UA|DU|AA|UU) [^\n]+)$', status,
    168                            flags=re.MULTILINE)
    169     if not conflicts:
    170       break
    171     if unattended:
    172       GetCommandStdout(['git', 'reset', '--hard'], cwd=cwd)
    173       raise TemporaryMergeError('Cannot resolve merge conflicts.')
    174     conflicts_string = '\n'.join([x[0] for x in conflicts])
    175     new_commit_message = raw_input(
    176         ('The following conflicts exist and must be resolved.\n\n%s\n\nWhen '
    177          'done, enter a commit message or press enter to use the default '
    178          '(\'%s\').\n\n') % (conflicts_string, commit_message))
    179     if new_commit_message:
    180       commit_message = new_commit_message
    181 
    182   GetCommandStdout(['git', 'commit', '-m', commit_message], cwd=cwd)
    183