WebKitTools/Scripts/webkitpy/common/checkout/diff_parser.py
changeset 0 4f2f89ce4247
equal deleted inserted replaced
-1:000000000000 0:4f2f89ce4247
       
     1 # Copyright (C) 2009 Google Inc. All rights reserved.
       
     2 #
       
     3 # Redistribution and use in source and binary forms, with or without
       
     4 # modification, are permitted provided that the following conditions are
       
     5 # met:
       
     6 #
       
     7 #    * Redistributions of source code must retain the above copyright
       
     8 # notice, this list of conditions and the following disclaimer.
       
     9 #    * Redistributions in binary form must reproduce the above
       
    10 # copyright notice, this list of conditions and the following disclaimer
       
    11 # in the documentation and/or other materials provided with the
       
    12 # distribution.
       
    13 #    * Neither the name of Google Inc. nor the names of its
       
    14 # contributors may be used to endorse or promote products derived from
       
    15 # this software without specific prior written permission.
       
    16 #
       
    17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
       
    18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
       
    19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
       
    20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
       
    21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
       
    22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
       
    23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
       
    24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
       
    25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       
    26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
       
    27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    28 
       
    29 """WebKit's Python module for interacting with patches."""
       
    30 
       
    31 import logging
       
    32 import re
       
    33 
       
    34 _log = logging.getLogger("webkitpy.common.checkout.diff_parser")
       
    35 
       
    36 _regexp_compile_cache = {}
       
    37 
       
    38 
       
    39 def match(pattern, string):
       
    40     """Matches the string with the pattern, caching the compiled regexp."""
       
    41     if not pattern in _regexp_compile_cache:
       
    42         _regexp_compile_cache[pattern] = re.compile(pattern)
       
    43     return _regexp_compile_cache[pattern].match(string)
       
    44 
       
    45 
       
    46 def git_diff_to_svn_diff(line):
       
    47     """Converts a git formatted diff line to a svn formatted line.
       
    48 
       
    49     Args:
       
    50       line: A string representing a line of the diff.
       
    51     """
       
    52     conversion_patterns = (("^diff --git \w/(.+) \w/(?P<FilePath>.+)", lambda matched: "Index: " + matched.group('FilePath') + "\n"),
       
    53                            ("^new file.*", lambda matched: "\n"),
       
    54                            ("^index [0-9a-f]{7}\.\.[0-9a-f]{7} [0-9]{6}", lambda matched: "===================================================================\n"),
       
    55                            ("^--- \w/(?P<FilePath>.+)", lambda matched: "--- " + matched.group('FilePath') + "\n"),
       
    56                            ("^\+\+\+ \w/(?P<FilePath>.+)", lambda matched: "+++ " + matched.group('FilePath') + "\n"))
       
    57 
       
    58     for pattern, conversion in conversion_patterns:
       
    59         matched = match(pattern, line)
       
    60         if matched:
       
    61             return conversion(matched)
       
    62     return line
       
    63 
       
    64 
       
    65 def get_diff_converter(first_diff_line):
       
    66     """Gets a converter function of diff lines.
       
    67 
       
    68     Args:
       
    69       first_diff_line: The first filename line of a diff file.
       
    70                        If this line is git formatted, we'll return a
       
    71                        converter from git to SVN.
       
    72     """
       
    73     if match(r"^diff --git \w/", first_diff_line):
       
    74         return git_diff_to_svn_diff
       
    75     return lambda input: input
       
    76 
       
    77 
       
    78 _INITIAL_STATE = 1
       
    79 _DECLARED_FILE_PATH = 2
       
    80 _PROCESSING_CHUNK = 3
       
    81 
       
    82 
       
    83 class DiffFile:
       
    84     """Contains the information for one file in a patch.
       
    85 
       
    86     The field "lines" is a list which contains tuples in this format:
       
    87        (deleted_line_number, new_line_number, line_string)
       
    88     If deleted_line_number is zero, it means this line is newly added.
       
    89     If new_line_number is zero, it means this line is deleted.
       
    90     """
       
    91 
       
    92     def __init__(self, filename):
       
    93         self.filename = filename
       
    94         self.lines = []
       
    95 
       
    96     def add_new_line(self, line_number, line):
       
    97         self.lines.append((0, line_number, line))
       
    98 
       
    99     def add_deleted_line(self, line_number, line):
       
   100         self.lines.append((line_number, 0, line))
       
   101 
       
   102     def add_unchanged_line(self, deleted_line_number, new_line_number, line):
       
   103         self.lines.append((deleted_line_number, new_line_number, line))
       
   104 
       
   105 
       
   106 class DiffParser:
       
   107     """A parser for a patch file.
       
   108 
       
   109     The field "files" is a dict whose key is the filename and value is
       
   110     a DiffFile object.
       
   111     """
       
   112 
       
   113     def __init__(self, diff_input):
       
   114         """Parses a diff.
       
   115 
       
   116         Args:
       
   117           diff_input: An iterable object.
       
   118         """
       
   119         state = _INITIAL_STATE
       
   120 
       
   121         self.files = {}
       
   122         current_file = None
       
   123         old_diff_line = None
       
   124         new_diff_line = None
       
   125         for line in diff_input:
       
   126             line = line.rstrip("\n")
       
   127             if state == _INITIAL_STATE:
       
   128                 transform_line = get_diff_converter(line)
       
   129             line = transform_line(line)
       
   130 
       
   131             file_declaration = match(r"^Index: (?P<FilePath>.+)", line)
       
   132             if file_declaration:
       
   133                 filename = file_declaration.group('FilePath')
       
   134                 current_file = DiffFile(filename)
       
   135                 self.files[filename] = current_file
       
   136                 state = _DECLARED_FILE_PATH
       
   137                 continue
       
   138 
       
   139             lines_changed = match(r"^@@ -(?P<OldStartLine>\d+)(,\d+)? \+(?P<NewStartLine>\d+)(,\d+)? @@", line)
       
   140             if lines_changed:
       
   141                 if state != _DECLARED_FILE_PATH and state != _PROCESSING_CHUNK:
       
   142                     _log.error('Unexpected line change without file path '
       
   143                                'declaration: %r' % line)
       
   144                 old_diff_line = int(lines_changed.group('OldStartLine'))
       
   145                 new_diff_line = int(lines_changed.group('NewStartLine'))
       
   146                 state = _PROCESSING_CHUNK
       
   147                 continue
       
   148 
       
   149             if state == _PROCESSING_CHUNK:
       
   150                 if line.startswith('+'):
       
   151                     current_file.add_new_line(new_diff_line, line[1:])
       
   152                     new_diff_line += 1
       
   153                 elif line.startswith('-'):
       
   154                     current_file.add_deleted_line(old_diff_line, line[1:])
       
   155                     old_diff_line += 1
       
   156                 elif line.startswith(' '):
       
   157                     current_file.add_unchanged_line(old_diff_line, new_diff_line, line[1:])
       
   158                     old_diff_line += 1
       
   159                     new_diff_line += 1
       
   160                 elif line == '\\ No newline at end of file':
       
   161                     # Nothing to do.  We may still have some added lines.
       
   162                     pass
       
   163                 else:
       
   164                     _log.error('Unexpected diff format when parsing a '
       
   165                                'chunk: %r' % line)