ignorePatterns = new ArrayList<>();
42 |
43 | private boolean isEndOfStream = false;
44 |
45 | public ResizingParseWindow(InputStream in) {
46 | Reader unbufferedReader = new InputStreamReader(in);
47 | this.reader = new BufferedReader(unbufferedReader);
48 | }
49 |
50 | public void addIgnorePattern(String ignorePattern) {
51 | this.ignorePatterns.add(Pattern.compile(ignorePattern));
52 | }
53 |
54 | @Override
55 | public String getFutureLine(int distance) {
56 | try {
57 | resizeWindowIfNecessary(distance + 1);
58 | return lineQueue.get(distance);
59 | } catch (IndexOutOfBoundsException e) {
60 | return null;
61 | }
62 | }
63 |
64 | @Override
65 | public void addLine(int pos, String line) {
66 | lineQueue.add(pos, line);
67 | }
68 |
69 | /**
70 | * Resizes the sliding window to the given size, if necessary.
71 | *
72 | * @param newSize the new size of the window (i.e. the number of lines in the
73 | * window).
74 | */
75 | private void resizeWindowIfNecessary(int newSize) {
76 | try {
77 | int numberOfLinesToLoad = newSize - this.lineQueue.size();
78 | for (int i = 0; i < numberOfLinesToLoad; i++) {
79 | String nextLine = getNextLine();
80 | if (nextLine != null) {
81 | lineQueue.addLast(nextLine);
82 | } else {
83 | throw new IndexOutOfBoundsException("End of stream has been reached!");
84 | }
85 | }
86 | } catch (IOException e) {
87 | throw new RuntimeException(e);
88 | }
89 | }
90 |
91 | @Override
92 | public String slideForward() {
93 | try {
94 | lineQueue.pollFirst();
95 | lineNumber++;
96 | if (lineQueue.isEmpty()) {
97 | String nextLine = getNextLine();
98 | if (nextLine != null) {
99 | lineQueue.addLast(nextLine);
100 | }
101 | return nextLine;
102 | } else {
103 | return lineQueue.peekFirst();
104 | }
105 | } catch (IOException e) {
106 | throw new RuntimeException(e);
107 | }
108 | }
109 |
110 | private String getNextLine() throws IOException {
111 | String nextLine = reader.readLine();
112 | while (matchesIgnorePattern(nextLine)) {
113 | nextLine = reader.readLine();
114 | }
115 |
116 | return getNextLineOrVirtualBlankLineAtEndOfStream(nextLine);
117 | }
118 |
119 | /**
120 | * Guarantees that a virtual blank line is injected at the end of the input
121 | * stream to ensure the parser attempts to transition to the {@code END}
122 | * state, if necessary, when the end of stream is reached.
123 | */
124 | private String getNextLineOrVirtualBlankLineAtEndOfStream(String nextLine) {
125 | if ((nextLine == null) && !isEndOfStream) {
126 | isEndOfStream = true;
127 | return "";
128 | }
129 |
130 | return nextLine;
131 | }
132 |
133 | private boolean matchesIgnorePattern(String line) {
134 | if (line == null) {
135 | return false;
136 | } else {
137 | for (Pattern pattern : ignorePatterns) {
138 | Matcher matcher = pattern.matcher(line);
139 | if (matcher.matches()) {
140 | return true;
141 | }
142 | }
143 | return false;
144 | }
145 | }
146 |
147 | @Override
148 | public String getFocusLine() {
149 | return lineQueue.element();
150 | }
151 |
152 | @Override
153 | public int getFocusLineNumber() {
154 | return lineNumber;
155 | }
156 |
157 | }
158 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn ( ) {
37 | echo "$*"
38 | }
39 |
40 | die ( ) {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save ( ) {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/src/main/java/io/reflectoring/diffparser/api/UnifiedDiffParser.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2013-2015 Tom Hombergs (tom.hombergs@gmail.com | http://wickedsource.org)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.reflectoring.diffparser.api;
17 |
18 | import io.reflectoring.diffparser.api.model.Diff;
19 | import io.reflectoring.diffparser.api.model.Hunk;
20 | import io.reflectoring.diffparser.api.model.Line;
21 | import io.reflectoring.diffparser.api.model.Range;
22 | import io.reflectoring.diffparser.unified.ParserState;
23 | import io.reflectoring.diffparser.unified.ResizingParseWindow;
24 |
25 | import java.io.*;
26 | import java.util.ArrayList;
27 | import java.util.List;
28 | import java.util.regex.Matcher;
29 | import java.util.regex.Pattern;
30 |
31 | /**
32 | * A parser that parses a unified diff from text into a {@link Diff} data structure.
33 | *
34 | * An example of a unified diff this parser can handle is the following:
35 | *
36 | * Modified: trunk/test1.txt
37 | * ===================================================================
38 | * --- /trunk/test1.txt 2013-10-23 19:41:56 UTC (rev 46)
39 | * +++ /trunk/test1.txt 2013-10-23 19:44:39 UTC (rev 47)
40 | * @@ -1,4 +1,3 @@
41 | * test1
42 | * -test1
43 | * +test234
44 | * -test1
45 | * \ No newline at end of file
46 | * @@ -5,9 +6,10 @@
47 | * -test1
48 | * -test1
49 | * +test2
50 | * +test2
51 | *
52 | * Note that the TAB character and date after the file names are not being parsed but instead cut off.
53 | */
54 | public class UnifiedDiffParser implements DiffParser {
55 | public static final Pattern LINE_RANGE_PATTERN = Pattern.compile("^.*-([0-9]+)(?:,([0-9]+))? \\+([0-9]+)(?:,([0-9]+))?.*$");
56 |
57 | @Override
58 | public List parse(InputStream in) {
59 | ResizingParseWindow window = new ResizingParseWindow(in);
60 | ParserState state = ParserState.INITIAL;
61 | List parsedDiffs = new ArrayList<>();
62 | Diff currentDiff = new Diff();
63 | String currentLine;
64 | while ((currentLine = window.slideForward()) != null) {
65 | state = state.nextState(window);
66 | switch (state) {
67 | case INITIAL:
68 | // nothing to do
69 | break;
70 | case HEADER:
71 | parseHeader(currentDiff, currentLine);
72 | break;
73 | case FROM_FILE:
74 | parseFromFile(currentDiff, currentLine);
75 | break;
76 | case TO_FILE:
77 | parseToFile(currentDiff, currentLine);
78 | break;
79 | case HUNK_START:
80 | parseHunkStart(currentDiff, currentLine);
81 | break;
82 | case FROM_LINE:
83 | parseFromLine(currentDiff, currentLine);
84 | break;
85 | case TO_LINE:
86 | parseToLine(currentDiff, currentLine);
87 | break;
88 | case NEUTRAL_LINE:
89 | parseNeutralLine(currentDiff, currentLine);
90 | break;
91 | case END:
92 | parsedDiffs.add(currentDiff);
93 | currentDiff = new Diff();
94 | break;
95 | default:
96 | throw new IllegalStateException(String.format("Illegal parser state '%s", state));
97 | }
98 | }
99 |
100 | return parsedDiffs;
101 | }
102 |
103 | private void parseNeutralLine(Diff currentDiff, String currentLine) {
104 | Line line = new Line(Line.LineType.NEUTRAL, currentLine);
105 | currentDiff.getLatestHunk().getLines().add(line);
106 | }
107 |
108 | private void parseToLine(Diff currentDiff, String currentLine) {
109 | Line toLine = new Line(Line.LineType.TO, currentLine.substring(1));
110 | currentDiff.getLatestHunk().getLines().add(toLine);
111 | }
112 |
113 | private void parseFromLine(Diff currentDiff, String currentLine) {
114 | Line fromLine = new Line(Line.LineType.FROM, currentLine.substring(1));
115 | currentDiff.getLatestHunk().getLines().add(fromLine);
116 | }
117 |
118 | private void parseHunkStart(Diff currentDiff, String currentLine) {
119 | Matcher matcher = LINE_RANGE_PATTERN.matcher(currentLine);
120 | if (matcher.matches()) {
121 | String range1Start = matcher.group(1);
122 | String range1Count = (matcher.group(2) != null) ? matcher.group(2) : "1";
123 | Range fromRange = new Range(Integer.valueOf(range1Start), Integer.valueOf(range1Count));
124 |
125 | String range2Start = matcher.group(3);
126 | String range2Count = (matcher.group(4) != null) ? matcher.group(4) : "1";
127 | Range toRange = new Range(Integer.valueOf(range2Start), Integer.valueOf(range2Count));
128 |
129 | Hunk hunk = new Hunk();
130 | hunk.setFromFileRange(fromRange);
131 | hunk.setToFileRange(toRange);
132 | currentDiff.getHunks().add(hunk);
133 | } else {
134 | throw new IllegalStateException(String.format("No line ranges found in the following hunk start line: '%s'. Expected something " +
135 | "like '-1,5 +3,5'.", currentLine));
136 | }
137 | }
138 |
139 | private void parseToFile(Diff currentDiff, String currentLine) {
140 | currentDiff.setToFileName(cutAfterTab(currentLine.substring(4)));
141 | }
142 |
143 | private void parseFromFile(Diff currentDiff, String currentLine) {
144 | currentDiff.setFromFileName(cutAfterTab(currentLine.substring(4)));
145 | }
146 |
147 | /**
148 | * Cuts a TAB and all following characters from a String.
149 | */
150 | private String cutAfterTab(String line) {
151 | Pattern p = Pattern.compile("^(.*)\\t.*$");
152 | Matcher matcher = p.matcher(line);
153 | if (matcher.matches()) {
154 | return matcher.group(1);
155 | } else {
156 | return line;
157 | }
158 | }
159 |
160 | private void parseHeader(Diff currentDiff, String currentLine) {
161 | currentDiff.getHeaderLines().add(currentLine);
162 | }
163 |
164 |
165 | @Override
166 | public List parse(byte[] bytes) {
167 | return parse(new ByteArrayInputStream(bytes));
168 | }
169 |
170 | @Override
171 | public List parse(File file) throws IOException {
172 | FileInputStream in = new FileInputStream(file);
173 | try{
174 | return parse(in);
175 | } finally {
176 | in.close();
177 | }
178 | }
179 |
180 | }
181 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and
10 | distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright
13 | owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all other entities
16 | that control, are controlled by, or are under common control with that entity.
17 | For the purposes of this definition, "control" means (i) the power, direct or
18 | indirect, to cause the direction or management of such entity, whether by
19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20 | outstanding shares, or (iii) beneficial ownership of such entity.
21 |
22 | "You" (or "Your") shall mean an individual or Legal Entity exercising
23 | permissions granted by this License.
24 |
25 | "Source" form shall mean the preferred form for making modifications, including
26 | but not limited to software source code, documentation source, and configuration
27 | files.
28 |
29 | "Object" form shall mean any form resulting from mechanical transformation or
30 | translation of a Source form, including but not limited to compiled object code,
31 | generated documentation, and conversions to other media types.
32 |
33 | "Work" shall mean the work of authorship, whether in Source or Object form, made
34 | available under the License, as indicated by a copyright notice that is included
35 | in or attached to the work (an example is provided in the Appendix below).
36 |
37 | "Derivative Works" shall mean any work, whether in Source or Object form, that
38 | is based on (or derived from) the Work and for which the editorial revisions,
39 | annotations, elaborations, or other modifications represent, as a whole, an
40 | original work of authorship. For the purposes of this License, Derivative Works
41 | shall not include works that remain separable from, or merely link (or bind by
42 | name) to the interfaces of, the Work and Derivative Works thereof.
43 |
44 | "Contribution" shall mean any work of authorship, including the original version
45 | of the Work and any modifications or additions to that Work or Derivative Works
46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work
47 | by the copyright owner or by an individual or Legal Entity authorized to submit
48 | on behalf of the copyright owner. For the purposes of this definition,
49 | "submitted" means any form of electronic, verbal, or written communication sent
50 | to the Licensor or its representatives, including but not limited to
51 | communication on electronic mailing lists, source code control systems, and
52 | issue tracking systems that are managed by, or on behalf of, the Licensor for
53 | the purpose of discussing and improving the Work, but excluding communication
54 | that is conspicuously marked or otherwise designated in writing by the copyright
55 | owner as "Not a Contribution."
56 |
57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58 | of whom a Contribution has been received by Licensor and subsequently
59 | incorporated within the Work.
60 |
61 | 2. Grant of Copyright License.
62 |
63 | Subject to the terms and conditions of this License, each Contributor hereby
64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65 | irrevocable copyright license to reproduce, prepare Derivative Works of,
66 | publicly display, publicly perform, sublicense, and distribute the Work and such
67 | Derivative Works in Source or Object form.
68 |
69 | 3. Grant of Patent License.
70 |
71 | Subject to the terms and conditions of this License, each Contributor hereby
72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73 | irrevocable (except as stated in this section) patent license to make, have
74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75 | such license applies only to those patent claims licensable by such Contributor
76 | that are necessarily infringed by their Contribution(s) alone or by combination
77 | of their Contribution(s) with the Work to which such Contribution(s) was
78 | submitted. If You institute patent litigation against any entity (including a
79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80 | Contribution incorporated within the Work constitutes direct or contributory
81 | patent infringement, then any patent licenses granted to You under this License
82 | for that Work shall terminate as of the date such litigation is filed.
83 |
84 | 4. Redistribution.
85 |
86 | You may reproduce and distribute copies of the Work or Derivative Works thereof
87 | in any medium, with or without modifications, and in Source or Object form,
88 | provided that You meet the following conditions:
89 |
90 | You must give any other recipients of the Work or Derivative Works a copy of
91 | this License; and
92 | You must cause any modified files to carry prominent notices stating that You
93 | changed the files; and
94 | You must retain, in the Source form of any Derivative Works that You distribute,
95 | all copyright, patent, trademark, and attribution notices from the Source form
96 | of the Work, excluding those notices that do not pertain to any part of the
97 | Derivative Works; and
98 | If the Work includes a "NOTICE" text file as part of its distribution, then any
99 | Derivative Works that You distribute must include a readable copy of the
100 | attribution notices contained within such NOTICE file, excluding those notices
101 | that do not pertain to any part of the Derivative Works, in at least one of the
102 | following places: within a NOTICE text file distributed as part of the
103 | Derivative Works; within the Source form or documentation, if provided along
104 | with the Derivative Works; or, within a display generated by the Derivative
105 | Works, if and wherever such third-party notices normally appear. The contents of
106 | the NOTICE file are for informational purposes only and do not modify the
107 | License. You may add Your own attribution notices within Derivative Works that
108 | You distribute, alongside or as an addendum to the NOTICE text from the Work,
109 | provided that such additional attribution notices cannot be construed as
110 | modifying the License.
111 | You may add Your own copyright statement to Your modifications and may provide
112 | additional or different license terms and conditions for use, reproduction, or
113 | distribution of Your modifications, or for any such Derivative Works as a whole,
114 | provided Your use, reproduction, and distribution of the Work otherwise complies
115 | with the conditions stated in this License.
116 |
117 | 5. Submission of Contributions.
118 |
119 | Unless You explicitly state otherwise, any Contribution intentionally submitted
120 | for inclusion in the Work by You to the Licensor shall be under the terms and
121 | conditions of this License, without any additional terms or conditions.
122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of
123 | any separate license agreement you may have executed with Licensor regarding
124 | such Contributions.
125 |
126 | 6. Trademarks.
127 |
128 | This License does not grant permission to use the trade names, trademarks,
129 | service marks, or product names of the Licensor, except as required for
130 | reasonable and customary use in describing the origin of the Work and
131 | reproducing the content of the NOTICE file.
132 |
133 | 7. Disclaimer of Warranty.
134 |
135 | Unless required by applicable law or agreed to in writing, Licensor provides the
136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138 | including, without limitation, any warranties or conditions of TITLE,
139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140 | solely responsible for determining the appropriateness of using or
141 | redistributing the Work and assume any risks associated with Your exercise of
142 | permissions under this License.
143 |
144 | 8. Limitation of Liability.
145 |
146 | In no event and under no legal theory, whether in tort (including negligence),
147 | contract, or otherwise, unless required by applicable law (such as deliberate
148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be
149 | liable to You for damages, including any direct, indirect, special, incidental,
150 | or consequential damages of any character arising as a result of this License or
151 | out of the use or inability to use the Work (including but not limited to
152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153 | any and all other commercial damages or losses), even if such Contributor has
154 | been advised of the possibility of such damages.
155 |
156 | 9. Accepting Warranty or Additional Liability.
157 |
158 | While redistributing the Work or Derivative Works thereof, You may choose to
159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160 | other liability obligations and/or rights consistent with this License. However,
161 | in accepting such obligations, You may act only on Your own behalf and on Your
162 | sole responsibility, not on behalf of any other Contributor, and only if You
163 | agree to indemnify, defend, and hold each Contributor harmless for any liability
164 | incurred by, or claims asserted against, such Contributor by reason of your
165 | accepting any such warranty or additional liability.
166 |
167 | END OF TERMS AND CONDITIONS
168 |
169 | APPENDIX: How to apply the Apache License to your work
170 |
171 | To apply the Apache License to your work, attach the following boilerplate
172 | notice, with the fields enclosed by brackets "[]" replaced with your own
173 | identifying information. (Don't include the brackets!) The text should be
174 | enclosed in the appropriate comment syntax for the file format. We also
175 | recommend that a file or class name and description of purpose be included on
176 | the same "printed page" as the copyright notice for easier identification within
177 | third-party archives.
178 |
179 | Copyright [yyyy] [name of copyright owner]
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | http://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
--------------------------------------------------------------------------------
/src/main/java/io/reflectoring/diffparser/unified/ParserState.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2013-2015 Tom Hombergs (tom.hombergs@gmail.com | http://wickedsource.org)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.reflectoring.diffparser.unified;
17 |
18 | import static io.reflectoring.diffparser.api.UnifiedDiffParser.LINE_RANGE_PATTERN;
19 |
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | /**
24 | * State machine for a parser parsing a unified diff.
25 | *
26 | * @author Tom Hombergs
27 | */
28 | public enum ParserState {
29 |
30 | /**
31 | * This is the initial state of the parser.
32 | */
33 | INITIAL {
34 | @Override
35 | public ParserState nextState(ParseWindow window) {
36 | String line = window.getFocusLine();
37 | if (matchesFromFilePattern(line)) {
38 | logTransition(line, INITIAL, FROM_FILE);
39 | return FROM_FILE;
40 | } else {
41 | logTransition(line, INITIAL, HEADER);
42 | return HEADER;
43 | }
44 | }
45 | },
46 |
47 | /**
48 | * The parser is in this state if it is currently parsing a header line.
49 | */
50 | HEADER {
51 | @Override
52 | public ParserState nextState(ParseWindow window) {
53 | String line = window.getFocusLine();
54 | if (matchesFromFilePattern(line)) {
55 | logTransition(line, HEADER, FROM_FILE);
56 | return FROM_FILE;
57 | } else {
58 | logTransition(line, HEADER, HEADER);
59 | return HEADER;
60 | }
61 | }
62 | },
63 |
64 | /**
65 | * The parser is in this state if it is currently parsing the line containing the "from" file.
66 | *
67 | * Example line:
68 | * {@code --- /path/to/file.txt}
69 | */
70 | FROM_FILE {
71 | @Override
72 | public ParserState nextState(ParseWindow window) {
73 | String line = window.getFocusLine();
74 | if (matchesToFilePattern(line)) {
75 | logTransition(line, FROM_FILE, TO_FILE);
76 | return TO_FILE;
77 | } else {
78 | throw new IllegalStateException("A FROM_FILE line ('---') must be directly followed by a TO_FILE line ('+++')!");
79 | }
80 | }
81 | },
82 |
83 | /**
84 | * The parser is in this state if it is currently parsing the line containing the "to" file.
85 | *
86 | * Example line:
87 | * {@code +++ /path/to/file.txt}
88 | */
89 | TO_FILE {
90 | @Override
91 | public ParserState nextState(ParseWindow window) {
92 | String line = window.getFocusLine();
93 | if (matchesHunkStartPattern(line)) {
94 | logTransition(line, TO_FILE, HUNK_START);
95 | return HUNK_START;
96 | } else {
97 | throw new IllegalStateException("A TO_FILE line ('+++') must be directly followed by a HUNK_START line ('@@')!");
98 | }
99 | }
100 | },
101 |
102 | /**
103 | * The parser is in this state if it is currently parsing a line containing the header of a hunk.
104 | *
105 | * Example line:
106 | * {@code @@ -1,5 +2,6 @@}
107 | */
108 | HUNK_START {
109 | @Override
110 | public ParserState nextState(ParseWindow window) {
111 | String line = window.getFocusLine();
112 | if (matchesFromLinePattern(line)) {
113 | logTransition(line, HUNK_START, FROM_LINE);
114 | return FROM_LINE;
115 | } else if (matchesToLinePattern(line)) {
116 | logTransition(line, HUNK_START, TO_LINE);
117 | return TO_LINE;
118 | } else {
119 | logTransition(line, HUNK_START, NEUTRAL_LINE);
120 | return NEUTRAL_LINE;
121 | }
122 | }
123 | },
124 |
125 | /**
126 | * The parser is in this state if it is currently parsing a line containing a line that is in the first file,
127 | * but not the second (a "from" line).
128 | *
129 | * Example line:
130 | * {@code - only the dash at the start is important}
131 | */
132 | FROM_LINE {
133 | @Override
134 | public ParserState nextState(ParseWindow window) {
135 | String line = window.getFocusLine();
136 | if (matchesFromLinePattern(line)) {
137 | logTransition(line, FROM_LINE, FROM_LINE);
138 | return FROM_LINE;
139 | } else if (matchesToLinePattern(line)) {
140 | logTransition(line, FROM_LINE, TO_LINE);
141 | return TO_LINE;
142 | } else if (matchesEndPattern(line, window)) {
143 | logTransition(line, FROM_LINE, END);
144 | return END;
145 | } else if (matchesHunkStartPattern(line)) {
146 | logTransition(line, FROM_LINE, HUNK_START);
147 | return HUNK_START;
148 | } else {
149 | logTransition(line, FROM_LINE, NEUTRAL_LINE);
150 | return NEUTRAL_LINE;
151 | }
152 | }
153 | },
154 |
155 | /**
156 | * The parser is in this state if it is currently parsing a line containing a line that is in the second file,
157 | * but not the first (a "to" line).
158 | *
159 | * Example line:
160 | * {@code + only the plus at the start is important}
161 | */
162 | TO_LINE {
163 | @Override
164 | public ParserState nextState(ParseWindow window) {
165 | String line = window.getFocusLine();
166 | if (matchesFromLinePattern(line)) {
167 | logTransition(line, TO_LINE, FROM_LINE);
168 | return FROM_LINE;
169 | } else if (matchesToLinePattern(line)) {
170 | logTransition(line, TO_LINE, TO_LINE);
171 | return TO_LINE;
172 | } else if (matchesEndPattern(line, window)) {
173 | logTransition(line, TO_LINE, END);
174 | return END;
175 | } else if (matchesHunkStartPattern(line)) {
176 | logTransition(line, TO_LINE, HUNK_START);
177 | return HUNK_START;
178 | } else {
179 | logTransition(line, TO_LINE, NEUTRAL_LINE);
180 | return NEUTRAL_LINE;
181 | }
182 | }
183 | },
184 |
185 | /**
186 | * The parser is in this state if it is currently parsing a line that is contained in both files (a "neutral" line). This line can
187 | * contain any string.
188 | */
189 | NEUTRAL_LINE {
190 | @Override
191 | public ParserState nextState(ParseWindow window) {
192 | String line = window.getFocusLine();
193 | if (matchesFromLinePattern(line)) {
194 | logTransition(line, NEUTRAL_LINE, FROM_LINE);
195 | return FROM_LINE;
196 | } else if (matchesToLinePattern(line)) {
197 | logTransition(line, NEUTRAL_LINE, TO_LINE);
198 | return TO_LINE;
199 | } else if (matchesEndPattern(line, window)) {
200 | logTransition(line, NEUTRAL_LINE, END);
201 | return END;
202 | } else if (matchesHunkStartPattern(line)) {
203 | logTransition(line, NEUTRAL_LINE, HUNK_START);
204 | return HUNK_START;
205 | } else {
206 | logTransition(line, NEUTRAL_LINE, NEUTRAL_LINE);
207 | return NEUTRAL_LINE;
208 | }
209 | }
210 | },
211 |
212 | /**
213 | * The parser is in this state if it is currently parsing a line that is the delimiter between two Diffs. This line is always a new
214 | * line.
215 | */
216 | END {
217 | @Override
218 | public ParserState nextState(ParseWindow window) {
219 | String line = window.getFocusLine();
220 | logTransition(line, END, INITIAL);
221 | return INITIAL;
222 | }
223 | };
224 |
225 | protected static Logger logger = LoggerFactory.getLogger(ParserState.class);
226 |
227 | /**
228 | * Returns the next state of the state machine depending on the current state and the content of a window of lines around the line
229 | * that is currently being parsed.
230 | *
231 | * @param window the window around the line currently being parsed.
232 | * @return the next state of the state machine.
233 | */
234 | public abstract ParserState nextState(ParseWindow window);
235 |
236 | protected void logTransition(String currentLine, ParserState fromState, ParserState toState) {
237 | logger.debug(String.format("%12s -> %12s: %s", fromState, toState, currentLine));
238 | }
239 |
240 | protected boolean matchesFromFilePattern(String line) {
241 | return line.startsWith("---");
242 | }
243 |
244 | protected boolean matchesToFilePattern(String line) {
245 | return line.startsWith("+++");
246 | }
247 |
248 | protected boolean matchesFromLinePattern(String line) {
249 | return line.startsWith("-");
250 | }
251 |
252 | protected boolean matchesToLinePattern(String line) {
253 | return line.startsWith("+");
254 | }
255 |
256 | protected boolean matchesHunkStartPattern(String line) {
257 | return LINE_RANGE_PATTERN.matcher(line).matches();
258 | }
259 |
260 | protected boolean matchesEndPattern(String line, ParseWindow window) {
261 | if ("".equals(line.trim())) {
262 | // We have a newline which might be the delimiter between two diffs. It may just be an empty line in the current diff or it
263 | // may be the delimiter to the next diff. This has to be disambiguated...
264 | int i = 1;
265 | String futureLine;
266 | while ((futureLine = window.getFutureLine(i)) != null) {
267 | if (matchesFromFilePattern(futureLine)) {
268 | // We found the start of a new diff without another newline in between. That makes the current line the delimiter
269 | // between this diff and the next.
270 | return true;
271 | } else if ("".equals(futureLine.trim())) {
272 | // We found another newline after the current newline without a start of a new diff in between. That makes the
273 | // current line just a newline within the current diff.
274 | return false;
275 | } else {
276 | i++;
277 | }
278 | }
279 | // We reached the end of the stream.
280 | return true;
281 | } else {
282 | // some diff tools like "svn diff" do not put an empty line between two diffs
283 | // we add that empty line and call the method again
284 | String nextFromFileLine = window.getFutureLine(3);
285 | if(nextFromFileLine != null && matchesFromFilePattern(nextFromFileLine)){
286 | window.addLine(1, "");
287 | return matchesEndPattern(line, window);
288 | }else{
289 | return false;
290 | }
291 | }
292 | }
293 |
294 |
295 | }
296 |
--------------------------------------------------------------------------------