diff --git a/.idea/ant.xml b/.idea/ant.xml deleted file mode 100644 index 6ddee46..0000000 --- a/.idea/ant.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/.idea/compiler.xml b/.idea/compiler.xml deleted file mode 100644 index 5267941..0000000 --- a/.idea/compiler.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index b385f01..0000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml deleted file mode 100644 index 7c62b52..0000000 --- a/.idea/encodings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/.idea/libraries/Maven__junit_junit_4_8_1.xml b/.idea/libraries/Maven__junit_junit_4_8_1.xml deleted file mode 100644 index 21ab8f0..0000000 --- a/.idea/libraries/Maven__junit_junit_4_8_1.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 9835fae..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index fd2ff8f..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index 1e7cce4..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index cce6fd9..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 0000000..1649ac3 --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,49 @@ +Diff Utils library is an OpenSource library for performing the comparison operations between texts: computing diffs, applying patches, generating unified diffs or parsing them, generating diff output for easy future displaying (like side-by-side view) and so on. + +Main reason to build this library was the lack of easy-to-use libraries with all the usual stuff you need while working with diff files. Originally it was inspired by JRCS library and it's nice design of diff module. + +## Main Features ## + + * computing the difference between two texts. + * capable to hand more than plain ascci. Arrays or List of any type that implements hashCode() and equals() correctly can be subject to differencing using this library + * patch and unpatch the text with the given patch + * parsing the unified diff format + * producing human-readable differences + +### Algoritms ### + +This library implements Myer's diff algorithm. But it can easily replaced by any other which is better for handing your texts. I have plan to add implementation of some in future. + +### Changelog ### + + * Version 1.2 + * JDK 1.5 compatibility + * Ant build script + * Generate output in unified diff format (thanks for Bill James) + +### To Install ### + +Just add the code below to your maven dependencies: +``` + + com.googlecode.java-diff-utils + diffutils + 1.2.1 + +``` + +And for Ivy: +``` + +``` + +## Coming eventually ## + + * support for inline diffs in output + * helpers for showing side-by-side, line-by-line diffs or text with inter-line and intra-line change highlights + * customization of diff algorithm for better experience while computing diffs between strings (ignoring blank lines or spaces, etc) + * generating output in other formats (not only unified). E.g. CVS. + +### Tutorials ### + +http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=CompararFicherosJavaDiffUtils (in Spanish). Thanks Miguel \ No newline at end of file diff --git a/References.md b/References.md new file mode 100644 index 0000000..b6a93a0 --- /dev/null +++ b/References.md @@ -0,0 +1 @@ +About diff utility and the format of diff files: http://en.wikipedia.org/wiki/Diff_utility diff --git a/SampleUsage.md b/SampleUsage.md new file mode 100644 index 0000000..d554b86 --- /dev/null +++ b/SampleUsage.md @@ -0,0 +1,93 @@ +# Introduction # + +The all common operation of this library is available through static methods of DiffUtils object. These methods are: + + * `DiffUtils.diff(List original, List revised): Patch patch` + * `DiffUtils.patch(List original, Patch patch): List revised` + * `DiffUtils.unpatch(List revised, Patch patch): List original` + * `DiffUtils.parseUnifiedDiff(List diff): Patch patch` + * `DiffUtils.getDiffRows(List original, List revised): List diffRows` + +NOTE: All up-to-date examples can be found [here](http://code.google.com/p/java-diff-utils/source/browse/#svn%2Ftrunk%2Ftest%2Fexamples%2Fdiffutils). + +### Basic use in a Java App ### + +## Task 1: Compute the difference between to files and print its deltas ## + +**Solution:** + +``` +import difflib.*; + +public class BasicJavaApp_Task1 { + // Helper method for get the file content + private static List fileToLines(String filename) { + List lines = new LinkedList(); + String line = ""; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + while ((line = in.readLine()) != null) { + lines.add(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + return lines; + } + + public static void main(String[] args) { + List original = fileToLines("originalFile.txt"); + List revised = fileToLines("revisedFile.xt"); + + // Compute diff. Get the Patch object. Patch is the container for computed deltas. + Patch patch = DiffUtils.diff(original, revised); + + for (Delta delta: patch.getDeltas()) { + System.out.println(delta); + } + } +} +``` + + +## Task 2: Get the file in unified format and apply it as the patch to given text ## + +**Solution:** + +``` +import difflib.*; + +public class BasicJavaApp_Task2 { + private List originalList = Arrays.asList("aaa", "bbb", "ccc"); + + // Helper method for get the file content + private List fileToLines(String filename) { + List lines = new LinkedList(); + String line = ""; + try { + BufferedReader in = new BufferedReader(new FileReader(filename)); + while ((line = in.readLine()) != null) { + lines.add(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + return lines; + } + + public static void main(String[] args) { + // At first, parse the unified diff file and get the patch + Patch patch = DiffUtils.parseUnifiedDiff(fileToLines("example.diff")); + + // Then apply the computed patch to the given text + List result = DiffUtils.patch(original, patch); + /// Or we can call patch.applyTo(original). There is no difference. + } +} +``` + +## Task 3: Compute the difference between to texts and print it in human-readable side-by-side view ## + +**Solution:** + +_Coming soon..._ \ No newline at end of file diff --git a/build.xml b/build.xml deleted file mode 100644 index 621d364..0000000 --- a/build.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/java-diff-utils.iml b/java-diff-utils.iml deleted file mode 100644 index 5f6b53a..0000000 --- a/java-diff-utils.iml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 15a78b2..0000000 --- a/pom.xml +++ /dev/null @@ -1,92 +0,0 @@ - - 4.0.0 - com.googlecode.java-diff-utils - diffutils - jar - 1.4.0-SNAPSHOT - - java-diff-utils - The DiffUtils library for computing diffs, applying patches, generationg side-by-side view in Java. - http://code.google.com/p/java-diff-utils/ - 2009 - - org.sonatype.oss - oss-parent - 7 - - - scm:svn:http://java-diff-utils.googlecode.com/svn/trunk/ - scm:svn:https://java-diff-utils.googlecode.com/svn/trunk/ - http://code.google.com/p/java-diff-utils/source/browse/ - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - A business-friendly OSS license - - - - - UTF-8 - - - - - junit - junit - 4.11 - jar - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.5 - 1.5 - UTF-8 - - - - - - - maven-jar-plugin - 2.4 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - - - bundle-manifest - process-classes - - manifest - - - - - - - - - - diff --git a/src/main/java/difflib/ChangeDelta.java b/src/main/java/difflib/ChangeDelta.java deleted file mode 100644 index 759bc54..0000000 --- a/src/main/java/difflib/ChangeDelta.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.List; - -/** - * Describes the change-delta between original and revised texts. - * - * @author Dmitry Naumenko - * @param T The type of the compared elements in the 'lines'. - */ -public class ChangeDelta extends Delta { - - /** - * Creates a change delta with the two given chunks. - * @param original The original chunk. Must not be {@code null}. - * @param revised The original chunk. Must not be {@code null}. - */ - public ChangeDelta(Chunk original, Chunkrevised) { - super(original, revised); - } - - /** - * {@inheritDoc} - * - * @throws PatchFailedException - */ - @Override - public void applyTo(List target) throws PatchFailedException { - verify(target); - int position = getOriginal().getPosition(); - int size = getOriginal().size(); - for (int i = 0; i < size; i++) { - target.remove(position); - } - int i = 0; - for (T line : getRevised().getLines()) { - target.add(position + i, line); - i++; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void restore(List target) { - int position = getRevised().getPosition(); - int size = getRevised().size(); - for (int i = 0; i < size; i++) { - target.remove(position); - } - int i = 0; - for (T line : getOriginal().getLines()) { - target.add(position + i, line); - i++; - } - } - - /** - * {@inheritDoc} - */ - public void verify(List target) throws PatchFailedException { - getOriginal().verify(target); - if (getOriginal().getPosition() > target.size()) { - throw new PatchFailedException("Incorrect patch for delta: " - + "delta original position > target size"); - } - } - - @Override - public String toString() { - return "[ChangeDelta, position: " + getOriginal().getPosition() + ", lines: " - + getOriginal().getLines() + " to " + getRevised().getLines() + "]"; - } - - @Override - public TYPE getType() { - return Delta.TYPE.CHANGE; - } -} diff --git a/src/main/java/difflib/Chunk.java b/src/main/java/difflib/Chunk.java deleted file mode 100644 index bbc332c..0000000 --- a/src/main/java/difflib/Chunk.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.Arrays; -import java.util.List; - -/** - * Holds the information about the part of text involved in the diff process - * - *

- * Text is represented as Object[] because the diff engine is - * capable of handling more than plain ascci. In fact, arrays or lists of any - * type that implements {@link java.lang.Object#hashCode hashCode()} and - * {@link java.lang.Object#equals equals()} correctly can be subject to - * differencing using this library. - *

- * - * @author target size"); - } - for (int i = 0; i < size(); i++) { - if (!target.get(position + i).equals(lines.get(i))) { - throw new PatchFailedException( - "Incorrect Chunk: the chunk content doesn't match the target"); - } - } - } - - /** - * @return the start position of chunk in the text - */ - public int getPosition() { - return position; - } - - public void setLines(List lines) { - this.lines = lines; - } - - /** - * @return the affected lines - */ - public List getLines() { - return lines; - } - - public int size() { - return lines.size(); - } - - /** - * Returns the index of the last line of the chunk. - */ - public int last() { - return getPosition() + size() - 1; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((lines == null) ? 0 : lines.hashCode()); - result = prime * result + position; - result = prime * result + size(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Chunk other = (Chunk) obj; - if (lines == null) { - if (other.lines != null) - return false; - } else if (!lines.equals(other.lines)) - return false; - if (position != other.position) - return false; - return true; - } - - @Override - public String toString() { - return "[position: " + position + ", size: " + size() + ", lines: " + lines + "]"; - } - -} diff --git a/src/main/java/difflib/DeleteDelta.java b/src/main/java/difflib/DeleteDelta.java deleted file mode 100644 index 44dcecc..0000000 --- a/src/main/java/difflib/DeleteDelta.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.List; - -/** - * Describes the delete-delta between original and revised texts. - * - * @author Dmitry Naumenko - * @param T The type of the compared elements in the 'lines'. - */ -public class DeleteDelta extends Delta { - - /** - * Creates a change delta with the two given chunks. - * - * @param original - * The original chunk. Must not be {@code null}. - * @param revised - * The original chunk. Must not be {@code null}. - */ - public DeleteDelta(Chunk original, Chunk revised) { - super(original, revised); - } - - /** - * {@inheritDoc} - * - * @throws PatchFailedException - */ - @Override - public void applyTo(List target) throws PatchFailedException { - verify(target); - int position = getOriginal().getPosition(); - int size = getOriginal().size(); - for (int i = 0; i < size; i++) { - target.remove(position); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void restore(List target) { - int position = this.getRevised().getPosition(); - List lines = this.getOriginal().getLines(); - for (int i = 0; i < lines.size(); i++) { - target.add(position + i, lines.get(i)); - } - } - - @Override - public TYPE getType() { - return Delta.TYPE.DELETE; - } - - @Override - public void verify(List target) throws PatchFailedException { - getOriginal().verify(target); - } - - @Override - public String toString() { - return "[DeleteDelta, position: " + getOriginal().getPosition() + ", lines: " - + getOriginal().getLines() + "]"; - } -} diff --git a/src/main/java/difflib/Delta.java b/src/main/java/difflib/Delta.java deleted file mode 100644 index 2a0a8d1..0000000 --- a/src/main/java/difflib/Delta.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.*; - -/** - * Describes the delta between original and revised texts. - * - * @author Dmitry Naumenko - * @param T The type of the compared elements in the 'lines'. - */ -public abstract class Delta { - - /** The original chunk. */ - private Chunk original; - - /** The revised chunk. */ - private Chunk revised; - - /** - * Specifies the type of the delta. - * - */ - public enum TYPE { - /** A change in the original. */ - CHANGE, - /** A delete from the original. */ - DELETE, - /** An insert into the original. */ - INSERT - } - - /** - * Construct the delta for original and revised chunks - * - * @param original Chunk describing the original text. Must not be {@code null}. - * @param revised Chunk describing the revised text. Must not be {@code null}. - */ - public Delta(Chunk original, Chunk revised) { - if (original == null) { - throw new IllegalArgumentException("original must not be null"); - } - if (revised == null) { - throw new IllegalArgumentException("revised must not be null"); - } - this.original = original; - this.revised = revised; - } - - /** - * Verifies that this delta can be used to patch the given text. - * - * @param target the text to patch. - * @throws PatchFailedException if the patch cannot be applied. - */ - public abstract void verify(List target) throws PatchFailedException; - - /** - * Applies this delta as the patch for a given target - * - * @param target the given target - * @throws PatchFailedException - */ - public abstract void applyTo(List target) throws PatchFailedException; - - /** - * Cancel this delta for a given revised text. The action is opposite to - * patch. - * - * @param target the given revised text - */ - public abstract void restore(List target); - - /** - * Returns the type of delta - * @return the type enum - */ - public abstract TYPE getType(); - - /** - * @return The Chunk describing the original text. - */ - public Chunk getOriginal() { - return original; - } - - /** - * @param original The Chunk describing the original text to set. - */ - public void setOriginal(Chunk original) { - this.original = original; - } - - /** - * @return The Chunk describing the revised text. - */ - public Chunk getRevised() { - return revised; - } - - /** - * @param revised The Chunk describing the revised text to set. - */ - public void setRevised(Chunk revised) { - this.revised = revised; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((original == null) ? 0 : original.hashCode()); - result = prime * result + ((revised == null) ? 0 : revised.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Delta other = (Delta) obj; - if (original == null) { - if (other.original != null) - return false; - } else if (!original.equals(other.original)) - return false; - if (revised == null) { - if (other.revised != null) - return false; - } else if (!revised.equals(other.revised)) - return false; - return true; - } - -} diff --git a/src/main/java/difflib/DeltaComparator.java b/src/main/java/difflib/DeltaComparator.java deleted file mode 100644 index 98b7ab3..0000000 --- a/src/main/java/difflib/DeltaComparator.java +++ /dev/null @@ -1,27 +0,0 @@ -package difflib; - -import java.io.Serializable; -import java.util.Comparator; - -/** - * @author mksenzov - * @param T The type of the compared elements in the 'lines'. - */ -public class DeltaComparator implements Comparator>, Serializable { - private static final long serialVersionUID = 1L; - public static final Comparator> INSTANCE = new DeltaComparator(); - - private DeltaComparator() { - } - - public int compare(final Delta a, final Delta b) { - final int posA = a.getOriginal().getPosition(); - final int posB = b.getOriginal().getPosition(); - if (posA > posB) { - return 1; - } else if (posA < posB) { - return -1; - } - return 0; - } -} \ No newline at end of file diff --git a/src/main/java/difflib/DiffAlgorithm.java b/src/main/java/difflib/DiffAlgorithm.java deleted file mode 100644 index 21ccd16..0000000 --- a/src/main/java/difflib/DiffAlgorithm.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.*; - -/** - * The general interface for computing diffs between two lists of elements of type T. - * - * @author Dmitry Naumenko - * @param T The type of the compared elements in the 'lines'. - */ -public interface DiffAlgorithm { - - /** - * Computes the difference between the original sequence and the revised - * sequence and returns it as a {@link Patch} object. - * - * @param original The original sequence. Must not be {@code null}. - * @param revised The revised sequence. Must not be {@code null}. - * @return The patch representing the diff of the given sequences. Never {@code null}. - */ - public Patch diff(T[] original, T[] revised); - - /** - * Computes the difference between the original sequence and the revised - * sequence and returns it as a {@link Patch} object. - * - * @param original The original sequence. Must not be {@code null}. - * @param revised The revised sequence. Must not be {@code null}. - * @return The patch representing the diff of the given sequences. Never {@code null}. - */ - public Patch diff(List original, List revised); -} diff --git a/src/main/java/difflib/DiffException.java b/src/main/java/difflib/DiffException.java deleted file mode 100644 index 6ad3dd4..0000000 --- a/src/main/java/difflib/DiffException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -/** - * Base class for all exceptions emanating from this package. - * - * @author Juanco Anez - */ -public class DiffException extends Exception { - - private static final long serialVersionUID = 1L; - - public DiffException() { - } - - public DiffException(String msg) { - super(msg); - } -} diff --git a/src/main/java/difflib/DiffRow.java b/src/main/java/difflib/DiffRow.java deleted file mode 100644 index 6f8234b..0000000 --- a/src/main/java/difflib/DiffRow.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -/** - * Describes the diff row in form [tag, oldLine, newLine) for showing the - * difference between two texts - * - * @author Dmitry Naumenko - */ -public class DiffRow { - private Tag tag; - private String oldLine; - private String newLine; - - public DiffRow(Tag tag, String oldLine, String newLine) { - this.tag = tag; - this.oldLine = oldLine; - this.newLine = newLine; - } - - public enum Tag { - INSERT, DELETE, CHANGE, EQUAL - } - - /** - * @return the tag - */ - public Tag getTag() { - return tag; - } - - /** - * @param tag the tag to set - */ - public void setTag(Tag tag) { - this.tag = tag; - } - - /** - * @return the oldLine - */ - public String getOldLine() { - return oldLine; - } - - /** - * @param oldLine the oldLine to set - */ - public void setOldLine(String oldLine) { - this.oldLine = oldLine; - } - - /** - * @return the newLine - */ - public String getNewLine() { - return newLine; - } - - /** - * @param newLine the newLine to set - */ - public void setNewLine(String newLine) { - this.newLine = newLine; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((newLine == null) ? 0 : newLine.hashCode()); - result = prime * result + ((oldLine == null) ? 0 : oldLine.hashCode()); - result = prime * result + ((tag == null) ? 0 : tag.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DiffRow other = (DiffRow) obj; - if (newLine == null) { - if (other.newLine != null) - return false; - } else if (!newLine.equals(other.newLine)) - return false; - if (oldLine == null) { - if (other.oldLine != null) - return false; - } else if (!oldLine.equals(other.oldLine)) - return false; - if (tag == null) { - if (other.tag != null) - return false; - } else if (!tag.equals(other.tag)) - return false; - return true; - } - - public String toString() { - return "[" + this.tag + "," + this.oldLine + "," + this.newLine + "]"; - } -} diff --git a/src/main/java/difflib/DiffRowGenerator.java b/src/main/java/difflib/DiffRowGenerator.java deleted file mode 100644 index d6ffb6b..0000000 --- a/src/main/java/difflib/DiffRowGenerator.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import difflib.DiffRow.Tag; -import difflib.myers.Equalizer; - -import java.util.*; - -/** - * This class for generating DiffRows for side-by-sidy view. - * You can customize the way of generating. For example, show inline diffs on not, ignoring - * white spaces or/and blank lines and so on. All parameters for generating are optional. If you do - * not specify them, the class will use the default values. - * - * These values are: - * showInlineDiffs = false; - * ignoreWhiteSpaces = true; - * ignoreBlankLines = true; - * ... - * - * For instantiating the DiffRowGenerator you should use the its builder. Like in example - * - * DiffRowGenerator generator = new DiffRowGenerator.Builder().showInlineDiffs(true). - * ignoreWhiteSpaces(true).columnWidth(100).build(); - * - * - * @author Dmitry Naumenko - */ -public class DiffRowGenerator { - private final boolean showInlineDiffs; - private final boolean ignoreWhiteSpaces; - private final boolean ignoreBlankLines; - private final String InlineOldTag; - private final String InlineNewTag; - private final String InlineOldCssClass; - private final String InlineNewCssClass; - private final int columnWidth; - private final Equalizer equalizer; - - /** - * This class used for building the DiffRowGenerator. - * @author dmitry - * - */ - public static class Builder { - private boolean showInlineDiffs = false; - private boolean ignoreWhiteSpaces = false; - private boolean ignoreBlankLines = false; - private String InlineOldTag = "span"; - private String InlineNewTag = "span"; - private String InlineOldCssClass = "editOldInline"; - private String InlineNewCssClass = "editNewInline"; - private int columnWidth = 80; - - /** - * Show inline diffs in generating diff rows or not. - * @param val the value to set. Default: false. - * @return builder with configured showInlineDiff parameter - */ - public Builder showInlineDiffs(boolean val) { - showInlineDiffs = val; - return this; - } - - /** - * Ignore white spaces in generating diff rows or not. - * @param val the value to set. Default: true. - * @return builder with configured ignoreWhiteSpaces parameter - */ - public Builder ignoreWhiteSpaces(boolean val) { - ignoreWhiteSpaces = val; - return this; - } - - /** - * Ignore blank lines in generating diff rows or not. - * @param val the value to set. Default: true. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder ignoreBlankLines(boolean val) { - ignoreBlankLines = val; - return this; - } - - /** - * Set the tag used for displaying changes in the original text. - * @param tag the tag to set. Without angle brackets. Default: span. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder InlineOldTag(String tag) { - InlineOldTag = tag; - return this; - } - - /** - * Set the tag used for displaying changes in the revised text. - * @param tag the tag to set. Without angle brackets. Default: span. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder InlineNewTag(String tag) { - InlineNewTag = tag; - return this; - } - - /** - * Set the css class used for displaying changes in the original text. - * @param cssClass the tag to set. Without any quotes, just word. Default: editOldInline. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder InlineOldCssClass(String cssClass) { - InlineOldCssClass = cssClass; - return this; - } - - /** - * Set the css class used for displaying changes in the revised text. - * @param cssClass the tag to set. Without any quotes, just word. Default: editNewInline. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder InlineNewCssClass(String cssClass) { - InlineNewCssClass = cssClass; - return this; - } - - /** - * Set the column with of generated lines of original and revised texts. - * @param width the width to set. Making it < 0 doesn't have any sense. Default 80. - * @return builder with configured ignoreBlankLines parameter - */ - public Builder columnWidth(int width) { - if (width > 0) { - columnWidth = width; - } - return this; - } - - /** - * Build the DiffRowGenerator. If some parameters is not set, the default values are used. - * @return the customized DiffRowGenerator - */ - public DiffRowGenerator build() { - return new DiffRowGenerator(this); - } - } - - private DiffRowGenerator(Builder builder) { - showInlineDiffs = builder.showInlineDiffs; - ignoreWhiteSpaces = builder.ignoreWhiteSpaces; // - ignoreBlankLines = builder.ignoreBlankLines; // - InlineOldTag = builder.InlineOldTag; - InlineNewTag = builder.InlineNewTag; - InlineOldCssClass = builder.InlineOldCssClass; - InlineNewCssClass = builder.InlineNewCssClass; - columnWidth = builder.columnWidth; // - equalizer = new Equalizer() { - public boolean equals(String original, String revised) { - if (ignoreWhiteSpaces) { - original = original.trim().replaceAll("\\s+", " "); - revised = revised.trim().replaceAll("\\s+", " "); - } - return original.equals(revised); - } - }; - } - - /** - * Get the DiffRows describing the difference between original and revised texts using the - * given patch. Useful for displaying side-by-side diff. - * - * @param original the original text - * @param revised the revised text - * @return the DiffRows between original and revised texts - */ - public List generateDiffRows(List original, List revised) { - return generateDiffRows(original, revised, DiffUtils.diff(original, revised, equalizer)); - } - - private List removeBlankLines(List lines) { - List result = new ArrayList(); - for (String line: lines) { - if (line.trim().length() == 0) { - result.add(""); - } - result.add(line); - } - return result; - } - - /** - * Generates the DiffRows describing the difference between original and revised texts using the - * given patch. Useful for displaying side-by-side diff. - * - * @param original the original text - * @param revised the revised text - * @param patch the given patch - * @return the DiffRows between original and revised texts - */ - public List generateDiffRows(List original, List revised, Patch patch) { - // normalize the lines (expand tabs, escape html entities) - original = StringUtills.normalize(original); - revised = StringUtills.normalize(revised); - - // wrap to the column width - original = StringUtills.wrapText(original, this.columnWidth); - revised = StringUtills.wrapText(revised, this.columnWidth); - - List diffRows = new ArrayList(); - int endPos = 0; - final List> deltaList = patch.getDeltas(); - for (int i = 0; i < deltaList.size(); i++) { - Delta delta = deltaList.get(i); - Chunk orig = delta.getOriginal(); - Chunk rev = delta.getRevised(); - - // We should normalize and wrap lines in deltas too. - orig.setLines(StringUtills.normalize((List) orig.getLines())); - rev.setLines(StringUtills.normalize((List) rev.getLines())); - - orig.setLines(StringUtills.wrapText((List) orig.getLines(), this.columnWidth)); - rev.setLines(StringUtills.wrapText((List) rev.getLines(), this.columnWidth)); - - // catch the equal prefix for each chunk - for (String line : original.subList(endPos, orig.getPosition())) { - diffRows.add(new DiffRow(Tag.EQUAL, line, line)); - } - - // Inserted DiffRow - if (delta.getClass().equals(InsertDelta.class)) { - endPos = orig.last() + 1; - for (String line : (List) rev.getLines()) { - diffRows.add(new DiffRow(Tag.INSERT, "", line)); - } - continue; - } - - // Deleted DiffRow - if (delta.getClass().equals(DeleteDelta.class)) { - endPos = orig.last() + 1; - for (String line : (List) orig.getLines()) { - diffRows.add(new DiffRow(Tag.DELETE, line, "")); - } - continue; - } - - if (showInlineDiffs) { - addInlineDiffs(delta); - } - // the changed size is match - if (orig.size() == rev.size()) { - for (int j = 0; j < orig.size(); j++) { - diffRows.add(new DiffRow(Tag.CHANGE, (String) orig.getLines().get(j), - (String) rev.getLines().get(j))); - } - } else if (orig.size() > rev.size()) { - for (int j = 0; j < orig.size(); j++) { - diffRows.add(new DiffRow(Tag.CHANGE, (String) orig.getLines().get(j), rev - .getLines().size() > j ? (String) rev.getLines().get(j) : "")); - } - } else { - for (int j = 0; j < rev.size(); j++) { - diffRows.add(new DiffRow(Tag.CHANGE, orig.getLines().size() > j ? (String) orig - .getLines().get(j) : "", (String) rev.getLines().get(j))); - } - } - endPos = orig.last() + 1; - } - - // Copy the final matching chunk if any. - for (String line : original.subList(endPos, original.size())) { - diffRows.add(new DiffRow(Tag.EQUAL, line, line)); - } - return diffRows; - } - - /** - * Add the inline diffs for given delta - * @param delta the given delta - */ - private void addInlineDiffs(Delta delta) { - List orig = (List) delta.getOriginal().getLines(); - List rev = (List) delta.getRevised().getLines(); - LinkedList origList = new LinkedList(); - for (Character character : join(orig, "\n").toCharArray()) { - origList.add(character.toString()); - } - LinkedList revList = new LinkedList(); - for (Character character : join(rev, "\n").toCharArray()) { - revList.add(character.toString()); - } - List> inlineDeltas = DiffUtils.diff(origList, revList).getDeltas(); - if (inlineDeltas.size() < 3) { - Collections.reverse(inlineDeltas); - for (Delta inlineDelta : inlineDeltas) { - Chunk inlineOrig = inlineDelta.getOriginal(); - Chunk inlineRev = inlineDelta.getRevised(); - if (inlineDelta.getClass().equals(DeleteDelta.class)) { - origList = wrapInTag(origList, inlineOrig.getPosition(), inlineOrig - .getPosition() - + inlineOrig.size() + 1, this.InlineOldTag, this.InlineOldCssClass); - } else if (inlineDelta.getClass().equals(InsertDelta.class)) { - revList = wrapInTag(revList, inlineRev.getPosition(), inlineRev.getPosition() - + inlineRev.size() + 1, this.InlineNewTag, this.InlineNewCssClass); - } else if (inlineDelta.getClass().equals(ChangeDelta.class)) { - origList = wrapInTag(origList, inlineOrig.getPosition(), inlineOrig - .getPosition() - + inlineOrig.size() + 1, this.InlineOldTag, this.InlineOldCssClass); - revList = wrapInTag(revList, inlineRev.getPosition(), inlineRev.getPosition() - + inlineRev.size() + 1, this.InlineNewTag, this.InlineNewCssClass); - } - } - StringBuilder origResult = new StringBuilder(), revResult = new StringBuilder(); - for (String character : origList) { - origResult.append(character); - } - for (String character : revList) { - revResult.append(character); - } - delta.getOriginal().setLines(Arrays.asList(origResult.toString().split("\n"))); - delta.getRevised().setLines(Arrays.asList(revResult.toString().split("\n"))); - } - } - - /** - * Wrap the elements in the sequence with the given tag - * @param startPosition the position from which tag should start. The counting start from a zero. - * @param endPosition the position before which tag should should be closed. - * @param tag the tag name without angle brackets, just a word - * @param cssClass the optional css class - */ - public static LinkedList wrapInTag(LinkedList sequence, int startPosition, - int endPosition, String tag, String cssClass) { - LinkedList result = (LinkedList) sequence.clone(); - StringBuilder tagBuilder = new StringBuilder(); - tagBuilder.append("<"); - tagBuilder.append(tag); - if (cssClass != null) { - tagBuilder.append(" class=\""); - tagBuilder.append(cssClass); - tagBuilder.append("\""); - } - tagBuilder.append(">"); - String startTag = tagBuilder.toString(); - - tagBuilder.delete(0, tagBuilder.length()); - - tagBuilder.append(""); - String endTag = tagBuilder.toString(); - - result.add(startPosition, startTag); - result.add(endPosition, endTag); - return result; - } - - /** - * Wrap the given line with the given tag - * @param line the given line - * @param tag the tag name without angle brackets, just a word - * @param cssClass the optional css class - * @return the wrapped string - */ - public static String wrapInTag(String line, String tag, String cssClass) { - StringBuilder tagBuilder = new StringBuilder(); - tagBuilder.append("<"); - tagBuilder.append(tag); - if (cssClass != null) { - tagBuilder.append(" class=\""); - tagBuilder.append(cssClass); - tagBuilder.append("\""); - } - tagBuilder.append(">"); - String startTag = tagBuilder.toString(); - - tagBuilder.delete(0, tagBuilder.length()); - - tagBuilder.append(""); - String endTag = tagBuilder.toString(); - - return startTag + line + endTag; - } - - /** - * The helper method for joining collections - * @param - * @param objs the collection to join - * @param delimiter the delimiter to use - * @return the joined string - */ - private static String join(final Iterable objs, final String delimiter) { - Iterator iter = objs.iterator(); - if (!iter.hasNext()) { - return ""; - } - StringBuffer buffer = new StringBuffer(String.valueOf(iter.next())); - while (iter.hasNext()) { - buffer.append(delimiter).append(String.valueOf(iter.next())); - } - return buffer.toString(); - } -} diff --git a/src/main/java/difflib/DiffUtils.java b/src/main/java/difflib/DiffUtils.java deleted file mode 100644 index 62247b3..0000000 --- a/src/main/java/difflib/DiffUtils.java +++ /dev/null @@ -1,424 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import difflib.myers.Equalizer; -import difflib.myers.MyersDiff; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Implements the difference and patching engine - * - * @author Dmitry Naumenko - * @version 0.4.1 - * @param T - * The type of the compared elements in the 'lines'. - */ -public class DiffUtils { - - private static Pattern unifiedDiffChunkRe = Pattern - .compile("^@@\\s+-(?:(\\d+)(?:,(\\d+))?)\\s+\\+(?:(\\d+)(?:,(\\d+))?)\\s+@@$"); - - /** - * Computes the difference between the original and revised list of elements - * with default diff algorithm - * - * @param original - * The original text. Must not be {@code null}. - * @param revised - * The revised text. Must not be {@code null}. - * @return The patch describing the difference between the original and - * revised sequences. Never {@code null}. - */ - public static Patch diff(List original, List revised) { - return DiffUtils.diff(original, revised, new MyersDiff()); - } - - /** - * Computes the difference between the original and revised list of elements - * with default diff algorithm - * - * @param original - * The original text. Must not be {@code null}. - * @param revised - * The revised text. Must not be {@code null}. - * - * @param equalizer - * the equalizer object to replace the default compare algorithm - * (Object.equals). If {@code null} the default equalizer of the - * default algorithm is used.. - * @return The patch describing the difference between the original and - * revised sequences. Never {@code null}. - */ - public static Patch diff(List original, List revised, - Equalizer equalizer) { - if (equalizer != null) { - return DiffUtils.diff(original, revised, - new MyersDiff(equalizer)); - } - return DiffUtils.diff(original, revised, new MyersDiff()); - } - - /** - * Computes the difference between the original and revised list of elements - * with default diff algorithm - * - * @param original - * The original text. Must not be {@code null}. - * @param revised - * The revised text. Must not be {@code null}. - * @param algorithm - * The diff algorithm. Must not be {@code null}. - * @return The patch describing the difference between the original and - * revised sequences. Never {@code null}. - */ - public static Patch diff(List original, List revised, - DiffAlgorithm algorithm) { - if (original == null) { - throw new IllegalArgumentException("original must not be null"); - } - if (revised == null) { - throw new IllegalArgumentException("revised must not be null"); - } - if (algorithm == null) { - throw new IllegalArgumentException("algorithm must not be null"); - } - return algorithm.diff(original, revised); - } - - /** - * Patch the original text with given patch - * - * @param original - * the original text - * @param patch - * the given patch - * @return the revised text - * @throws PatchFailedException - * if can't apply patch - */ - public static List patch(List original, Patch patch) - throws PatchFailedException { - return patch.applyTo(original); - } - - /** - * Unpatch the revised text for a given patch - * - * @param revised - * the revised text - * @param patch - * the given patch - * @return the original text - */ - public static List unpatch(List revised, Patch patch) { - return patch.restore(revised); - } - - /** - * Parse the given text in unified format and creates the list of deltas for - * it. - * - * @param diff - * the text in unified format - * @return the patch with deltas. - */ - public static Patch parseUnifiedDiff(List diff) { - boolean inPrelude = true; - List rawChunk = new ArrayList(); - Patch patch = new Patch(); - - int old_ln = 0, new_ln = 0; - String tag; - String rest; - for (String line : diff) { - // Skip leading lines until after we've seen one starting with '+++' - if (inPrelude) { - if (line.startsWith("+++")) { - inPrelude = false; - } - continue; - } - Matcher m = unifiedDiffChunkRe.matcher(line); - if (m.find()) { - // Process the lines in the previous chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (String[] raw_line : rawChunk) { - tag = raw_line[0]; - rest = raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) { - newChunkLines.add(rest); - } - } - patch.addDelta(new ChangeDelta(new Chunk( - old_ln - 1, oldChunkLines), new Chunk( - new_ln - 1, newChunkLines))); - rawChunk.clear(); - } - // Parse the @@ header - old_ln = m.group(1) == null ? 1 : Integer.parseInt(m.group(1)); - new_ln = m.group(3) == null ? 1 : Integer.parseInt(m.group(3)); - - if (old_ln == 0) { - old_ln += 1; - } - if (new_ln == 0) { - new_ln += 1; - } - } else { - if (line.length() > 0) { - tag = line.substring(0, 1); - rest = line.substring(1); - if (tag.equals(" ") || tag.equals("+") || tag.equals("-")) { - rawChunk.add(new String[] { tag, rest }); - } - } else { - rawChunk.add(new String[] { " ", "" }); - } - } - } - - // Process the lines in the last chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (String[] raw_line : rawChunk) { - tag = raw_line[0]; - rest = raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) { - newChunkLines.add(rest); - } - } - - patch.addDelta(new ChangeDelta(new Chunk( - old_ln - 1, oldChunkLines), new Chunk(new_ln - 1, - newChunkLines))); - rawChunk.clear(); - } - - return patch; - } - - /** - * generateUnifiedDiff takes a Patch and some other arguments, returning the - * Unified Diff format text representing the Patch. - * - * @param original - * - Filename of the original (unrevised file) - * @param revised - * - Filename of the revised file - * @param originalLines - * - Lines of the original file - * @param patch - * - Patch created by the diff() function - * @param contextSize - * - number of lines of context output around each difference in - * the file. - * @return List of strings representing the Unified Diff representation of - * the Patch argument. - * @author Bill James (tankerbay@gmail.com) - */ - public static List generateUnifiedDiff(String original, - String revised, List originalLines, Patch patch, - int contextSize) { - if (!patch.getDeltas().isEmpty()) { - List ret = new ArrayList(); - ret.add("--- " + original); - ret.add("+++ " + revised); - - List> patchDeltas = new ArrayList>( - patch.getDeltas()); - - // code outside the if block also works for single-delta issues. - List> deltas = new ArrayList>(); // current - // list - // of - // Delta's to - // process - Delta delta = patchDeltas.get(0); - deltas.add(delta); // add the first Delta to the current set - // if there's more than 1 Delta, we may need to output them together - if (patchDeltas.size() > 1) { - for (int i = 1; i < patchDeltas.size(); i++) { - int position = delta.getOriginal().getPosition(); // store - // the - // current - // position - // of - // the first Delta - - // Check if the next Delta is too close to the current - // position. - // And if it is, add it to the current set - Delta nextDelta = patchDeltas.get(i); - if ((position + delta.getOriginal().size() + contextSize) >= (nextDelta - .getOriginal().getPosition() - contextSize)) { - deltas.add(nextDelta); - } else { - // if it isn't, output the current set, - // then create a new set and add the current Delta to - // it. - List curBlock = processDeltas(originalLines, - deltas, contextSize); - ret.addAll(curBlock); - deltas.clear(); - deltas.add(nextDelta); - } - delta = nextDelta; - } - - } - // don't forget to process the last set of Deltas - List curBlock = processDeltas(originalLines, deltas, - contextSize); - ret.addAll(curBlock); - return ret; - } - return new ArrayList(); - } - - /** - * processDeltas takes a list of Deltas and outputs them together in a - * single block of Unified-Diff-format text. - * - * @param origLines - * - the lines of the original file - * @param deltas - * - the Deltas to be output as a single block - * @param contextSize - * - the number of lines of context to place around block - * @return - * @author Bill James (tankerbay@gmail.com) - */ - private static List processDeltas(List origLines, - List> deltas, int contextSize) { - List buffer = new ArrayList(); - int origTotal = 0; // counter for total lines output from Original - int revTotal = 0; // counter for total lines output from Original - int line; - - Delta curDelta = deltas.get(0); - - // NOTE: +1 to overcome the 0-offset Position - int origStart = curDelta.getOriginal().getPosition() + 1 - contextSize; - if (origStart < 1) { - origStart = 1; - } - - int revStart = curDelta.getRevised().getPosition() + 1 - contextSize; - if (revStart < 1) { - revStart = 1; - } - - // find the start of the wrapper context code - int contextStart = curDelta.getOriginal().getPosition() - contextSize; - if (contextStart < 0) { - contextStart = 0; // clamp to the start of the file - } - - // output the context before the first Delta - for (line = contextStart; line < curDelta.getOriginal().getPosition(); line++) { // - buffer.add(" " + origLines.get(line)); - origTotal++; - revTotal++; - } - - // output the first Delta - buffer.addAll(getDeltaText(curDelta)); - origTotal += curDelta.getOriginal().getLines().size(); - revTotal += curDelta.getRevised().getLines().size(); - - int deltaIndex = 1; - while (deltaIndex < deltas.size()) { // for each of the other Deltas - Delta nextDelta = deltas.get(deltaIndex); - int intermediateStart = curDelta.getOriginal().getPosition() - + curDelta.getOriginal().getLines().size(); - for (line = intermediateStart; line < nextDelta.getOriginal() - .getPosition(); line++) { - // output the code between the last Delta and this one - buffer.add(" " + origLines.get(line)); - origTotal++; - revTotal++; - } - buffer.addAll(getDeltaText(nextDelta)); // output the Delta - origTotal += nextDelta.getOriginal().getLines().size(); - revTotal += nextDelta.getRevised().getLines().size(); - curDelta = nextDelta; - deltaIndex++; - } - - // Now output the post-Delta context code, clamping the end of the file - contextStart = curDelta.getOriginal().getPosition() - + curDelta.getOriginal().getLines().size(); - for (line = contextStart; (line < (contextStart + contextSize)) - && (line < origLines.size()); line++) { - buffer.add(" " + origLines.get(line)); - origTotal++; - revTotal++; - } - - // Create and insert the block header, conforming to the Unified Diff - // standard - StringBuffer header = new StringBuffer(); - header.append("@@ -"); - header.append(origStart); - header.append(","); - header.append(origTotal); - header.append(" +"); - header.append(revStart); - header.append(","); - header.append(revTotal); - header.append(" @@"); - buffer.add(0, header.toString()); - - return buffer; - } - - /** - * getDeltaText returns the lines to be added to the Unified Diff text from - * the Delta parameter - * - * @param delta - * - the Delta to output - * @return list of String lines of code. - * @author Bill James (tankerbay@gmail.com) - */ - private static List getDeltaText(Delta delta) { - List buffer = new ArrayList(); - for (String line : delta.getOriginal().getLines()) { - buffer.add("-" + line); - } - for (String line : delta.getRevised().getLines()) { - buffer.add("+" + line); - } - return buffer; - } - -} diff --git a/src/main/java/difflib/InsertDelta.java b/src/main/java/difflib/InsertDelta.java deleted file mode 100644 index 23914a9..0000000 --- a/src/main/java/difflib/InsertDelta.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.List; - -/** - * Describes the add-delta between original and revised texts. - * - * @author Dmitry Naumenko - * @param T - * The type of the compared elements in the 'lines'. - */ -public class InsertDelta extends Delta { - - /** - * Creates an insert delta with the two given chunks. - * - * @param original - * The original chunk. Must not be {@code null}. - * @param revised - * The original chunk. Must not be {@code null}. - */ - public InsertDelta(Chunk original, Chunk revised) { - super(original, revised); - } - - /** - * {@inheritDoc} - * - * @throws PatchFailedException - */ - @Override - public void applyTo(List target) throws PatchFailedException { - verify(target); - int position = this.getOriginal().getPosition(); - List lines = this.getRevised().getLines(); - for (int i = 0; i < lines.size(); i++) { - target.add(position + i, lines.get(i)); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void restore(List target) { - int position = getRevised().getPosition(); - int size = getRevised().size(); - for (int i = 0; i < size; i++) { - target.remove(position); - } - } - - @Override - public void verify(List target) throws PatchFailedException { - if (getOriginal().getPosition() > target.size()) { - throw new PatchFailedException("Incorrect patch for delta: " - + "delta original position > target size"); - } - - } - - public TYPE getType() { - return Delta.TYPE.INSERT; - } - - @Override - public String toString() { - return "[InsertDelta, position: " + getOriginal().getPosition() - + ", lines: " + getRevised().getLines() + "]"; - } -} diff --git a/src/main/java/difflib/Patch.java b/src/main/java/difflib/Patch.java deleted file mode 100644 index b93a5f1..0000000 --- a/src/main/java/difflib/Patch.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.ListIterator; - -/** - * Describes the patch holding all deltas between the original and revised texts. - * - * @author Dmitry Naumenko - * @param T The type of the compared elements in the 'lines'. - */ -public class Patch { - private List> deltas = new LinkedList>(); - - /** - * Apply this patch to the given target - * @return the patched text - * @throws PatchFailedException if can't apply patch - */ - public List applyTo(List target) throws PatchFailedException { - List result = new LinkedList(target); - ListIterator> it = getDeltas().listIterator(deltas.size()); - while (it.hasPrevious()) { - Delta delta = (Delta) it.previous(); - delta.applyTo(result); - } - return result; - } - - /** - * Restore the text to original. Opposite to applyTo() method. - * @param target the given target - * @return the restored text - */ - public List restore(List target) { - List result = new LinkedList(target); - ListIterator> it = getDeltas().listIterator(deltas.size()); - while (it.hasPrevious()) { - Delta delta = (Delta) it.previous(); - delta.restore(result); - } - return result; - } - - /** - * Add the given delta to this patch - * @param delta the given delta - */ - public void addDelta(Delta delta) { - deltas.add(delta); - } - - /** - * Get the list of computed deltas - * @return the deltas - */ - public List> getDeltas() { - Collections.sort(deltas, DeltaComparator.INSTANCE); - return deltas; - } -} diff --git a/src/main/java/difflib/PatchFailedException.java b/src/main/java/difflib/PatchFailedException.java deleted file mode 100644 index 5fb77d2..0000000 --- a/src/main/java/difflib/PatchFailedException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -/** - * Thrown whenever a delta cannot be applied as a patch to a given text. - * - * @author Juanco Anez - */ -public class PatchFailedException extends DiffException { - - private static final long serialVersionUID = 1L; - - public PatchFailedException() { - } - - public PatchFailedException(String msg) { - super(msg); - } -} \ No newline at end of file diff --git a/src/main/java/difflib/StringUtills.java b/src/main/java/difflib/StringUtills.java deleted file mode 100644 index 6917036..0000000 --- a/src/main/java/difflib/StringUtills.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright 2010 Dmitry Naumenko (dm.naumenko@gmail.com) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -package difflib; - -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - -public class StringUtills { - - public static String join(final Iterable objs, final String delimiter) { - Iterator iter = objs.iterator(); - if (!iter.hasNext()) { - return ""; - } - StringBuffer buffer = new StringBuffer(String.valueOf(iter.next())); - while (iter.hasNext()) { - buffer.append(delimiter).append(String.valueOf(iter.next())); - } - return buffer.toString(); - } - - /** - * Replaces all tabs with 4 spaces. - * @param str The string. - * @return - */ - public static String expandTabs(String str) { - return str.replace("\t", " "); - } - - /** - * Replaces all opening an closing tags with < or >. - * @param str - * @return - */ - public static String htmlEntites(String str) { - return str.replace("<", "<").replace(">", ">"); - } - - public static String normalize(String str) { - return expandTabs(htmlEntites(str)); - } - - public static List normalize(List list) { - List result = new LinkedList(); - for (String line : list) { - result.add(normalize(line)); - } - return result; - } - - public static List wrapText(List list, int columnWidth) { - List result = new LinkedList(); - for (String line : list) { - result.add(wrapText(line, columnWidth)); - } - return result; - } - - /** - * Wrap the text with the given column width - * @param line the text - * @param columnWidth the given column - * @return the wrapped text - */ - public static String wrapText(String line, int columnWidth) { - int lenght = line.length(); - int delimiter = "
".length(); - int widthIndex = columnWidth; - - for (int count = 0; lenght > widthIndex; count++) { - line = line.subSequence(0, widthIndex + delimiter * count) + "
" - + line.substring(widthIndex + delimiter * count); - widthIndex += columnWidth; - } - - return line; - } -} diff --git a/src/main/java/difflib/myers/DiffException.java b/src/main/java/difflib/myers/DiffException.java deleted file mode 100644 index d3802ff..0000000 --- a/src/main/java/difflib/myers/DiffException.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ==================================================================== - * - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999-2003 The Apache Software Foundation. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowledgement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgement may appear in the software itself, - * if and wherever such third-party acknowledgements normally appear. - * - * 4. The names "The Jakarta Project", "Commons", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package difflib.myers; - -/** - * Base class for all exceptions emanating from this package. - * - * @version $Revision: 69 $ $Date: 2003-10-13 11:00:44 +0300 (Пнд, 13 Окт 2003) $ - * - * @author Juanco Anez - */ -public class DiffException extends Exception { - - private static final long serialVersionUID = 1L; - - public DiffException() { - } - - public DiffException(String msg) { - super(msg); - } -} diff --git a/src/main/java/difflib/myers/DiffNode.java b/src/main/java/difflib/myers/DiffNode.java deleted file mode 100644 index a2fb071..0000000 --- a/src/main/java/difflib/myers/DiffNode.java +++ /dev/null @@ -1,53 +0,0 @@ -package difflib.myers; - -/** - *

Title:

- *

Description:

- *

Copyright: Copyright (c) 2002

- *

Company:

- * @author not attributable - * @version 1.0 - */ - -/** - * A diffnode in a diffpath. - *

- * A DiffNode and its previous node mark a delta between - * two input sequences, that is, two differing subsequences - * between (possibly zero length) matching sequences. - * - * {@link DiffNode DiffNodes} and {@link Snake Snakes} allow for compression - * of diffpaths, as each snake is represented by a single {@link Snake Snake} - * node and each contiguous series of insertions and deletions is represented - * by a single {@link DiffNode DiffNodes}. - * - * @version $Revision: 60 $ $Date: 2003-05-10 21:56:10 +0300 (Суб, 10 Май 2003) $ - * @author Juanco Anez - * - */ -public final class DiffNode extends PathNode { - /** - * Constructs a DiffNode. - *

- * DiffNodes are compressed. That means that - * the path pointed to by the prev parameter - * will be followed using {@link PathNode#previousSnake} - * until a non-diff node is found. - * - * @param the position in the original sequence - * @param the position in the revised sequence - * @param prev the previous node in the path. - */ - public DiffNode(int i, int j, PathNode prev) { - super(i, j, (prev == null ? null : prev.previousSnake())); - } - - /** - * {@inheritDoc} - * @return false, always - */ - public boolean isSnake() { - return false; - } - -} \ No newline at end of file diff --git a/src/main/java/difflib/myers/DifferentiationFailedException.java b/src/main/java/difflib/myers/DifferentiationFailedException.java deleted file mode 100644 index c25c081..0000000 --- a/src/main/java/difflib/myers/DifferentiationFailedException.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * ==================================================================== - * - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999-2003 The Apache Software Foundation. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowledgement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgement may appear in the software itself, - * if and wherever such third-party acknowledgements normally appear. - * - * 4. The names "The Jakarta Project", "Commons", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package difflib.myers; - -/** - * Thrown whenever the differencing engine cannot produce the differences - * between two revisions of ta text. - * - * @version $Revision: 69 $ $Date: 2003-10-13 11:00:44 +0300 (Пнд, 13 Окт 2003) $ - * - * @author Juanco Anez - * @see MyersDiff - * @see difflib.DiffAlgorithm - */ -public class DifferentiationFailedException extends DiffException { - private static final long serialVersionUID = 1L; - - public DifferentiationFailedException() { - } - - public DifferentiationFailedException(String msg) { - super(msg); - } -} diff --git a/src/main/java/difflib/myers/Equalizer.java b/src/main/java/difflib/myers/Equalizer.java deleted file mode 100644 index f644019..0000000 --- a/src/main/java/difflib/myers/Equalizer.java +++ /dev/null @@ -1,17 +0,0 @@ -package difflib.myers; - -/** - * Specifies when two compared elements in the Myers algorithm are equal. - * - * @param T The type of the compared elements in the 'lines'. - */ -public interface Equalizer { - - /** - * Indicates if two elements are equal according to the diff mechanism. - * @param original The original element. Must not be {@code null}. - * @param revised The revised element. Must not be {@code null}. - * @return Returns true if the elements are equal. - */ - public boolean equals(T original, T revised); -} diff --git a/src/main/java/difflib/myers/MyersDiff.java b/src/main/java/difflib/myers/MyersDiff.java deleted file mode 100644 index 40be478..0000000 --- a/src/main/java/difflib/myers/MyersDiff.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * ==================================================================== - * - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999-2003 The Apache Software Foundation. All rights - * reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowledgement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgement may appear in the software itself, - * if and wherever such third-party acknowledgements normally appear. - * - * 4. The names "The Jakarta Project", "Commons", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package difflib.myers; - -import difflib.*; - -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * A clean-room implementation of - * Eugene Myers differencing algorithm. - * - *

See the paper at - * http://www.cs.arizona.edu/people/gene/PAPERS/diff.ps

- * - * @author Juanco Anez - * @param T The type of the compared elements in the 'lines'. - */ -public class MyersDiff implements DiffAlgorithm { - - /** Default equalizer. */ - private final Equalizer DEFAULT_EQUALIZER = new Equalizer() { - public boolean equals(final T original, final T revised) { - return original.equals(revised); - } - }; - - /** The equalizer. */ - private final Equalizer equalizer; - - - /** - * Constructs an instance of the Myers differencing algorithm. - */ - public MyersDiff() { - equalizer = DEFAULT_EQUALIZER; - } - - /** - * Constructs an instance of the Myers differencing algorithm. - * @param equalizer Must not be {@code null}. - */ - public MyersDiff(final Equalizer equalizer) { - if (equalizer == null) { - throw new IllegalArgumentException("equalizer must not be null"); - } - this.equalizer = equalizer; - } - - /** - * {@inheritDoc} - * - * @return Returns an empty diff if get the error while procession the difference. - */ - public Patch diff(final T[] original, final T[] revised) { - return diff(Arrays.asList(original), Arrays.asList(revised)); - } - - /** - * {@inheritDoc} - * - * Return empty diff if get the error while procession the difference. - */ - public Patch diff(final List original, final List revised) { - if (original == null) { - throw new IllegalArgumentException("original list must not be null"); - } - if (revised == null) { - throw new IllegalArgumentException("revised list must not be null"); - } - PathNode path; - try { - path = buildPath(original, revised); - return buildRevision(path, original, revised); - } catch (DifferentiationFailedException e) { - e.printStackTrace(); - } - return new Patch(); - } - - /** - * Computes the minimum diffpath that expresses de differences - * between the original and revised sequences, according - * to Gene Myers differencing algorithm. - * - * @param orig The original sequence. - * @param rev The revised sequence. - * @return A minimum {@link PathNode Path} accross the differences graph. - * @throws DifferentiationFailedException if a diff path could not be found. - */ - public PathNode buildPath(final List orig, final List rev) - throws DifferentiationFailedException { - if (orig == null) - throw new IllegalArgumentException("original sequence is null"); - if (rev == null) - throw new IllegalArgumentException("revised sequence is null"); - - // these are local constants - final int N = orig.size(); - final int M = rev.size(); - - final int MAX = N + M + 1; - final int size = 1 + 2 * MAX; - final int middle = size / 2; - final PathNode diagonal[] = new PathNode[size]; - - diagonal[middle + 1] = new Snake(0, -1, null); - for (int d = 0; d < MAX; d++) { - for (int k = -d; k <= d; k += 2) { - final int kmiddle = middle + k; - final int kplus = kmiddle + 1; - final int kminus = kmiddle - 1; - PathNode prev = null; - - int i; - if ((k == -d) || (k != d && diagonal[kminus].i < diagonal[kplus].i)) { - i = diagonal[kplus].i; - prev = diagonal[kplus]; - } else { - i = diagonal[kminus].i + 1; - prev = diagonal[kminus]; - } - - diagonal[kminus] = null; // no longer used - - int j = i - k; - - PathNode node = new DiffNode(i, j, prev); - - // orig and rev are zero-based - // but the algorithm is one-based - // that's why there's no +1 when indexing the sequences - while (i < N && j < M && equals(orig.get(i), rev.get(j))) { - i++; - j++; - } - if (i > node.i) - node = new Snake(i, j, node); - - diagonal[kmiddle] = node; - - if (i >= N && j >= M) { - return diagonal[kmiddle]; - } - } - diagonal[middle + d - 1] = null; - - } - // According to Myers, this cannot happen - throw new DifferentiationFailedException("could not find a diff path"); - } - - private boolean equals(T orig, T rev) { - return equalizer.equals(orig, rev); - } - - /** - * Constructs a {@link Patch} from a difference path. - * - * @param path The path. - * @param orig The original sequence. - * @param rev The revised sequence. - * @return A {@link Patch} script corresponding to the path. - * @throws DifferentiationFailedException if a {@link Patch} could - * not be built from the given path. - */ - public Patch buildRevision(PathNode path, List orig, List rev) { - if (path == null) - throw new IllegalArgumentException("path is null"); - if (orig == null) - throw new IllegalArgumentException("original sequence is null"); - if (rev == null) - throw new IllegalArgumentException("revised sequence is null"); - - Patch patch = new Patch(); - if (path.isSnake()) - path = path.prev; - while (path != null && path.prev != null && path.prev.j >= 0) { - if (path.isSnake()) - throw new IllegalStateException("bad diffpath: found snake when looking for diff"); - int i = path.i; - int j = path.j; - - path = path.prev; - int ianchor = path.i; - int janchor = path.j; - - Chunk original = new Chunk(ianchor, copyOfRange(orig, ianchor, i)); - Chunk revised = new Chunk(janchor, copyOfRange(rev, janchor, j)); - Delta delta = null; - if (original.size() == 0 && revised.size() != 0) { - delta = new InsertDelta(original, revised); - } else if (original.size() > 0 && revised.size() == 0) { - delta = new DeleteDelta(original, revised); - } else { - delta = new ChangeDelta(original, revised); - } - - patch.addDelta(delta); - if (path.isSnake()) - path = path.prev; - } - return patch; - } - - /** - * Creates a new list containing the elements returned by {@link List#subList(int, int)}. - * @param original The original sequence. Must not be {@code null}. - * @param fromIndex low endpoint (inclusive) of the subList. - * @param to high endpoint (exclusive) of the subList. - * @return A new list of the specified range within the original list. - - */ - private List copyOfRange( final List original, final int fromIndex, final int to ) { - return new ArrayList( original.subList( fromIndex, to ) ); - } - - /** - * Copied here from JDK 1.6 - */ - @SuppressWarnings("unchecked") - public static T[] copyOfRange2(T[] original, int from, int to) { - return copyOfRange2(original, from, to, (Class) original.getClass()); - } - - /** - * Copied here from JDK 1.6 - */ - @SuppressWarnings("unchecked") - public static T[] copyOfRange2(U[] original, int from, int to, - Class newType) { - int newLength = to - from; - if (newLength < 0) - throw new IllegalArgumentException(from + " > " + to); - T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength] - : (T[]) Array.newInstance(newType.getComponentType(), newLength); - System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); - return copy; - } - -} diff --git a/src/main/java/difflib/myers/PathNode.java b/src/main/java/difflib/myers/PathNode.java deleted file mode 100644 index 4ead5f2..0000000 --- a/src/main/java/difflib/myers/PathNode.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * ==================================================================== - * - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999-2003 The Apache Software Foundation. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowledgement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgement may appear in the software itself, - * if and wherever such third-party acknowledgements normally appear. - * - * 4. The names "The Jakarta Project", "Commons", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package difflib.myers; - -/** - * A node in a diffpath. - * - * @version $Revision: 69 $ $Date: 2003-10-13 11:00:44 +0300 (Пнд, 13 Окт 2003) $ - * @author Juanco Anez - * - * @see DiffNode - * @see Snake - * - */ -public abstract class PathNode { - /** Position in the original sequence. */ - public final int i; - /** Position in the revised sequence. */ - public final int j; - /** The previous node in the path. */ - public final PathNode prev; - - /** - * Concatenates a new path node with an existing diffpath. - * @param i The position in the original sequence for the new node. - * @param j The position in the revised sequence for the new node. - * @param prev The previous node in the path. - */ - public PathNode(int i, int j, PathNode prev) { - this.i = i; - this.j = j; - this.prev = prev; - } - - /** - * Is this node a {@link Snake Snake node}? - * @return true if this is a {@link Snake Snake node} - */ - public abstract boolean isSnake(); - - /** - * Is this a bootstrap node? - *

- * In bottstrap nodes one of the two corrdinates is - * less than zero. - * @return tru if this is a bootstrap node. - */ - public boolean isBootstrap() { - return i < 0 || j < 0; - } - - /** - * Skips sequences of {@link DiffNode DiffNodes} until a - * {@link Snake} or bootstrap node is found, or the end - * of the path is reached. - * @return The next first {@link Snake} or bootstrap node in the path, or - * null - * if none found. - */ - public final PathNode previousSnake() { - if (isBootstrap()) - return null; - if (!isSnake() && prev != null) - return prev.previousSnake(); - return this; - } - - /** - * {@inheritDoc} - */ - public String toString() { - StringBuffer buf = new StringBuffer("["); - PathNode node = this; - while (node != null) { - buf.append("("); - buf.append(Integer.toString(node.i)); - buf.append(","); - buf.append(Integer.toString(node.j)); - buf.append(")"); - node = node.prev; - } - buf.append("]"); - return buf.toString(); - } -} \ No newline at end of file diff --git a/src/main/java/difflib/myers/Snake.java b/src/main/java/difflib/myers/Snake.java deleted file mode 100644 index 452829b..0000000 --- a/src/main/java/difflib/myers/Snake.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ==================================================================== - * - * The Apache Software License, Version 1.1 - * - * Copyright (c) 1999-2003 The Apache Software Foundation. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in - * the documentation and/or other materials provided with the - * distribution. - * - * 3. The end-user documentation included with the redistribution, if - * any, must include the following acknowledgement: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgement may appear in the software itself, - * if and wherever such third-party acknowledgements normally appear. - * - * 4. The names "The Jakarta Project", "Commons", and "Apache Software - * Foundation" must not be used to endorse or promote products derived - * from this software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache" - * nor may "Apache" appear in their names without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package difflib.myers; - -/** - * Represents a snake in a diffpath. - *

- * - * {@link DiffNode DiffNodes} and {@link Snake Snakes} allow for compression - * of diffpaths, as each snake is represented by a single {@link Snake Snake} - * node and each contiguous series of insertions and deletions is represented - * by a single {@link DiffNode DiffNodes}. - * - * @version $Revision: 69 $ $Date: 2003-10-13 11:00:44 +0300 (Пнд, 13 Окт 2003) $ - * @author Juanco Anez - * - */ -public final class Snake extends PathNode { - /** - * Constructs a snake node. - * - * @param the position in the original sequence - * @param the position in the revised sequence - * @param prev the previous node in the path. - */ - public Snake(int i, int j, PathNode prev) { - super(i, j, prev); - } - - /** - * {@inheritDoc} - * @return true always - */ - public boolean isSnake() { - return true; - } - -} \ No newline at end of file diff --git a/src/main/java/difflib/myers/package.html b/src/main/java/difflib/myers/package.html deleted file mode 100644 index 3ccec66..0000000 --- a/src/main/java/difflib/myers/package.html +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - -

- The {@link difflib.myers diff.myers} package - implements Gene Myers' - differencing algorithm. -

-

- Myer's algorithm produces optimum results (minimum diffs), but - consumes considerably more memory than SimpleDiff, so its not - suitable for very large files. -

-@author Juanco Anez - - diff --git a/src/main/java/difflib/package.html b/src/main/java/difflib/package.html deleted file mode 100644 index 0f82244..0000000 --- a/src/main/java/difflib/package.html +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - -

- The {@link difflib difflib} package - implements general operation with diff files. -

-@author Dmitry Naumenko - - diff --git a/src/test/java/diffutils/DiffRowGeneratorTest.java b/src/test/java/diffutils/DiffRowGeneratorTest.java deleted file mode 100644 index de209d4..0000000 --- a/src/test/java/diffutils/DiffRowGeneratorTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package diffutils; - -import java.util.Arrays; -import java.util.List; - -import difflib.DiffRow; -import difflib.DiffRowGenerator; - -import junit.framework.TestCase; - -public class DiffRowGeneratorTest extends TestCase { - - public void testGenerator_Default() { - String first = "anything \n \nother"; - String second ="anything\n\nother"; - - DiffRowGenerator generator = new DiffRowGenerator.Builder() - .columnWidth(Integer.MAX_VALUE) // do not wrap - .build(); - List rows = generator.generateDiffRows(split(first), split(second)); - print(rows); - - assertEquals(3, rows.size()); - } - - public void testGenerator_InlineDiff() { - String first = "anything \n \nother"; - String second ="anything\n\nother"; - - DiffRowGenerator generator = new DiffRowGenerator.Builder() - .showInlineDiffs(true) - .columnWidth(Integer.MAX_VALUE) // do not wrap - .build(); - List rows = generator.generateDiffRows(split(first), split(second)); - print(rows); - - assertEquals(3, rows.size()); - assertTrue(rows.get(0).getOldLine().indexOf(" 0); - } - - public void testGenerator_IgnoreWhitespaces() { - String first = "anything \n \nother\nmore lines"; - String second ="anything\n\nother\nsome more lines"; - - DiffRowGenerator generator = new DiffRowGenerator.Builder() - .ignoreWhiteSpaces(true) - .columnWidth(Integer.MAX_VALUE) // do not wrap - .build(); - List rows = generator.generateDiffRows(split(first), split(second)); - print(rows); - - assertEquals(4, rows.size()); - assertEquals(rows.get(0).getTag(), DiffRow.Tag.EQUAL); - assertEquals(rows.get(1).getTag(), DiffRow.Tag.EQUAL); - assertEquals(rows.get(2).getTag(), DiffRow.Tag.EQUAL); - assertEquals(rows.get(3).getTag(), DiffRow.Tag.CHANGE); - } - - private List split(String content) { - return Arrays.asList(content.split("\n")); - } - - private void print(List diffRows) { - for (DiffRow row: diffRows) { - System.out.println(row); - } - } -} diff --git a/src/test/java/diffutils/DiffTest.java b/src/test/java/diffutils/DiffTest.java deleted file mode 100644 index 6d1ef31..0000000 --- a/src/test/java/diffutils/DiffTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package diffutils; - -import difflib.*; -import junit.framework.TestCase; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class DiffTest extends TestCase { - - public void testDiff_Insert() { - final Patch patch = DiffUtils.diff(Arrays.asList("hhh"), Arrays.asList("hhh", "jjj", "kkk")); - assertNotNull(patch); - assertEquals(1, patch.getDeltas().size()); - final Delta delta = patch.getDeltas().get(0); - assertEquals(InsertDelta.class, delta.getClass()); - assertEquals(new Chunk(1, Collections. emptyList()), delta.getOriginal()); - assertEquals(new Chunk(1, Arrays.asList("jjj", "kkk")), delta.getRevised()); - } - - public void testDiff_Delete() { - final Patch patch = DiffUtils.diff(Arrays.asList("ddd", "fff", "ggg"), Arrays.asList("ggg")); - assertNotNull(patch); - assertEquals(1, patch.getDeltas().size()); - final Delta delta = patch.getDeltas().get(0); - assertEquals(DeleteDelta.class, delta.getClass()); - assertEquals(new Chunk(0, Arrays.asList("ddd", "fff")), delta.getOriginal()); - assertEquals(new Chunk(0, Collections. emptyList()), delta.getRevised()); - } - - public void testDiff_Change() { - final List changeTest_from = Arrays.asList("aaa", "bbb", "ccc"); - final List changeTest_to = Arrays.asList("aaa", "zzz", "ccc"); - - final Patch patch = DiffUtils.diff(changeTest_from, changeTest_to); - assertNotNull(patch); - assertEquals(1, patch.getDeltas().size()); - final Delta delta = patch.getDeltas().get(0); - assertEquals(ChangeDelta.class, delta.getClass()); - assertEquals(new Chunk(1, Arrays.asList("bbb")), delta.getOriginal()); - assertEquals(new Chunk(1, Arrays.asList("zzz")), delta.getRevised()); - } - - public void testDiff_EmptyList() { - final Patch patch = DiffUtils.diff(new ArrayList(), new ArrayList()); - assertNotNull(patch); - assertEquals(0, patch.getDeltas().size()); - } - - public void testDiff_EmptyListWithNonEmpty() { - final Patch patch = DiffUtils.diff(new ArrayList(), Arrays.asList("aaa")); - assertNotNull(patch); - assertEquals(1, patch.getDeltas().size()); - final Delta delta = patch.getDeltas().get(0); - assertEquals(InsertDelta.class, delta.getClass()); - } -} diff --git a/src/test/java/diffutils/GenerateUnifiedDiffTest.java b/src/test/java/diffutils/GenerateUnifiedDiffTest.java deleted file mode 100644 index 64432db..0000000 --- a/src/test/java/diffutils/GenerateUnifiedDiffTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package diffutils; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import junit.framework.TestCase; -import difflib.DiffUtils; -import difflib.Patch; -import difflib.PatchFailedException; - -public class GenerateUnifiedDiffTest extends TestCase { - - - public List fileToLines(String filename) { - List lines = new LinkedList(); - String line = ""; - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(filename)); - while ((line = in.readLine()) != null) { - lines.add(line); - } - } catch (IOException e) { - e.printStackTrace(); - fail(e.getMessage()); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - // ignore ... any errors should already have been - // reported via an IOException from the final flush. - } - } - } - return lines; - } - - public void testGenerateUnified() { - List origLines = fileToLines(TestConstants.MOCK_FOLDER + "original.txt"); - List revLines = fileToLines(TestConstants.MOCK_FOLDER + "revised.txt"); - - verify(origLines, revLines, "original.txt", "revised.txt"); - } - - public void testGenerateUnifiedWithOneDelta() { - List origLines = fileToLines(TestConstants.MOCK_FOLDER + "one_delta_test_original.txt"); - List revLines = fileToLines(TestConstants.MOCK_FOLDER + "one_delta_test_revised.txt"); - - verify(origLines, revLines, "one_delta_test_original.txt", "one_delta_test_revised.txt"); - } - - public void testGenerateUnifiedDiffWithoutAnyDeltas() { - List test = Arrays.asList("abc"); - Patch patch = DiffUtils.diff(test, test); - DiffUtils.generateUnifiedDiff("abc", "abc", test, patch, 0); - } - - public void testDiff_Issue10() { - final List baseLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_base.txt"); - final List patchLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_patch.txt"); - final Patch p = DiffUtils.parseUnifiedDiff(patchLines); - try { - DiffUtils.patch(baseLines, p); - } catch (PatchFailedException e) { - fail(e.getMessage()); - } - } - - /** - * Issue 12 - */ - public void testPatchWithNoDeltas() { - final List lines1 = fileToLines(TestConstants.MOCK_FOLDER + "issue11_1.txt"); - final List lines2 = fileToLines(TestConstants.MOCK_FOLDER + "issue11_2.txt"); - verify(lines1, lines2, "issue11_1.txt", "issue11_2.txt"); - } - - public void testDiff5() { - final List lines1 = fileToLines(TestConstants.MOCK_FOLDER + "5A.txt"); - final List lines2 = fileToLines(TestConstants.MOCK_FOLDER + "5B.txt"); - verify(lines1, lines2, "5A.txt", "5B.txt"); - } - - /** - * Issue 19 - */ - public void testDiffWithHeaderLineInText() { - List original = new ArrayList(); - List revised = new ArrayList(); - - original.add("test line1"); - original.add("test line2"); - original.add("test line 4"); - original.add("test line 5"); - - revised.add("test line1"); - revised.add("test line2"); - revised.add("@@ -2,6 +2,7 @@"); - revised.add("test line 4"); - revised.add("test line 5"); - - Patch patch = DiffUtils.diff(original, revised); - List udiff = DiffUtils.generateUnifiedDiff("original", "revised", - original, patch, 10); - DiffUtils.parseUnifiedDiff(udiff); - } - - private void verify(List origLines, List revLines, - String originalFile, String revisedFile) { - Patch patch = DiffUtils.diff(origLines, revLines); - List unifiedDiff = DiffUtils.generateUnifiedDiff(originalFile, revisedFile, - origLines, patch, 10); - - Patch fromUnifiedPatch = DiffUtils.parseUnifiedDiff(unifiedDiff); - List patchedLines; - try { - patchedLines = (List) fromUnifiedPatch.applyTo(origLines); - assertTrue(revLines.size() == patchedLines.size()); - for (int i = 0; i < revLines.size(); i++) { - String l1 = revLines.get(i); - String l2 = patchedLines.get(i); - if (!l1.equals(l2)) { - fail("Line " + (i + 1) + " of the patched file did not match the revised original"); - } - } - } catch (PatchFailedException e) { - fail(e.getMessage()); - } - } -} diff --git a/src/test/java/diffutils/PatchTest.java b/src/test/java/diffutils/PatchTest.java deleted file mode 100644 index b6b4d74..0000000 --- a/src/test/java/diffutils/PatchTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package diffutils; - -import difflib.DiffUtils; -import difflib.Patch; -import difflib.PatchFailedException; -import junit.framework.TestCase; - -import java.util.Arrays; -import java.util.List; - -public class PatchTest extends TestCase { - - public void testPatch_Insert() { - final List insertTest_from = Arrays.asList("hhh"); - final List insertTest_to = Arrays.asList("hhh", "jjj", "kkk", "lll"); - - final Patch patch = DiffUtils.diff(insertTest_from, insertTest_to); - try { - assertEquals(insertTest_to, DiffUtils.patch(insertTest_from, patch)); - } catch (PatchFailedException e) { - fail(e.getMessage()); - } - } - - public void testPatch_Delete() { - final List deleteTest_from = Arrays.asList("ddd", "fff", "ggg", "hhh"); - final List deleteTest_to = Arrays.asList("ggg"); - - final Patch patch = DiffUtils.diff(deleteTest_from, deleteTest_to); - try { - assertEquals(deleteTest_to, DiffUtils.patch(deleteTest_from, patch)); - } catch (PatchFailedException e) { - fail(e.getMessage()); - } - } - - public void testPatch_Change() { - final List changeTest_from = Arrays.asList("aaa", "bbb", "ccc", "ddd"); - final List changeTest_to = Arrays.asList("aaa", "bxb", "cxc", "ddd"); - - final Patch patch = DiffUtils.diff(changeTest_from, changeTest_to); - try { - assertEquals(changeTest_to, DiffUtils.patch(changeTest_from, patch)); - } catch (PatchFailedException e) { - fail(e.getMessage()); - } - } -} diff --git a/src/test/java/diffutils/TestConstants.java b/src/test/java/diffutils/TestConstants.java deleted file mode 100644 index 5803394..0000000 --- a/src/test/java/diffutils/TestConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -package diffutils; - -import java.io.File; - -/** - * Test constants - * @author simon.mittermueller@gmail.com - * - */ -public final class TestConstants { - - private TestConstants() { - // prevent construction. - } - - /** File separator. */ - public static final String FS = File.separator; - - /** The base resource path. */ - public static String BASE_FOLDER_RESOURCES = "src" + FS + "test" + FS + "resources"; - - /** The base folder containing the test files. Ends with {@link #FS}. */ - public static final String MOCK_FOLDER = BASE_FOLDER_RESOURCES + FS + "mocks" + FS; - -} diff --git a/src/test/java/diffutils/examples/ApplyPatch.java b/src/test/java/diffutils/examples/ApplyPatch.java deleted file mode 100644 index 7ec1b45..0000000 --- a/src/test/java/diffutils/examples/ApplyPatch.java +++ /dev/null @@ -1,27 +0,0 @@ -package diffutils.examples; - -import java.util.List; - -import difflib.DiffUtils; -import difflib.Patch; -import difflib.PatchFailedException; -import diffutils.TestConstants; - -public class ApplyPatch extends Example { - - static final String ORIGINAL = TestConstants.MOCK_FOLDER + "issue10_base.txt"; - static final String PATCH = TestConstants.MOCK_FOLDER + "issue10_patch.txt"; - - public static void main(String[] args) throws PatchFailedException { - List original = fileToLines(ORIGINAL); - List patched = fileToLines(PATCH); - - // At first, parse the unified diff file and get the patch - Patch patch = DiffUtils.parseUnifiedDiff(patched); - - // Then apply the computed patch to the given text - List result = DiffUtils.patch(original, patch); - System.out.println(result); - // / Or we can call patch.applyTo(original). There is no difference. - } -} diff --git a/src/test/java/diffutils/examples/ComputeDifference.java b/src/test/java/diffutils/examples/ComputeDifference.java deleted file mode 100644 index a1a3eb1..0000000 --- a/src/test/java/diffutils/examples/ComputeDifference.java +++ /dev/null @@ -1,27 +0,0 @@ -package diffutils.examples; - -import java.util.List; - -import difflib.Delta; -import difflib.DiffUtils; -import difflib.Patch; -import diffutils.TestConstants; - -public class ComputeDifference extends Example { - - - static final String ORIGINAL = TestConstants.MOCK_FOLDER + "original.txt"; - static final String RIVISED = TestConstants.MOCK_FOLDER + "revised.txt"; - - public static void main(String[] args) { - List original = fileToLines(ORIGINAL); - List revised = fileToLines(RIVISED); - - // Compute diff. Get the Patch object. Patch is the container for computed deltas. - Patch patch = DiffUtils.diff(original, revised); - - for (Delta delta: patch.getDeltas()) { - System.out.println(delta); - } - } -} diff --git a/src/test/java/diffutils/examples/Example.java b/src/test/java/diffutils/examples/Example.java deleted file mode 100644 index 28526cb..0000000 --- a/src/test/java/diffutils/examples/Example.java +++ /dev/null @@ -1,47 +0,0 @@ -package diffutils.examples; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - -public abstract class Example { - - /** File separator. */ - protected static final String FS = File.separator; - /** The base resource path. */ - protected static String BASE_PATH = "src" + FS + "test" + FS + "resources"; - - /** - * Tries to read the file and split it into a list of lines. - * - * @param filename - * The filename as path. - * @return A list of lines. - */ - public static List fileToLines(String filename) { - List lines = new LinkedList(); - String line = ""; - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(filename)); - while ((line = in.readLine()) != null) { - lines.add(line); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - // ignore ... any errors should already have been - // reported via an IOException from the final flush. - } - } - } - return lines; - } -} diff --git a/src/test/resources/mocks/5A.txt b/src/test/resources/mocks/5A.txt deleted file mode 100644 index 96e51b8..0000000 --- a/src/test/resources/mocks/5A.txt +++ /dev/null @@ -1,372 +0,0 @@ -#!/bin/sh -# -# Copyright (c) 2006 Johannes E. Schindelin -# - -test_description='Test special whitespace in diff engine. - -' -. ./test-lib.sh -. ../diff-lib.sh - -# Ray Lehtiniemi's example - -cat << EOF > x -do { - nothing; -} while (0); -EOF - -git update-index --add x - -cat << EOF > x -do -{ - nothing; -} -while (0); -EOF - -cat << EOF > expect -diff --git a/x b/x -index adf3937..6edc172 100644 ---- a/x -+++ b/x -@@ -1,3 +1,5 @@ --do { -+do -+{ - nothing; --} while (0); -+} -+while (0); -EOF - -git diff > out -test_expect_success "Ray's example without options" 'test_cmp expect out' - -git diff -w > out -test_expect_success "Ray's example with -w" 'test_cmp expect out' - -git diff -b > out -test_expect_success "Ray's example with -b" 'test_cmp expect out' - -tr 'Q' '\015' << EOF > x -whitespace at beginning -whitespace change -whitespace in the middle -whitespace at end -unchanged line -CR at endQ -EOF - -git update-index x - -tr '_' ' ' << EOF > x - whitespace at beginning -whitespace change -white space in the middle -whitespace at end__ -unchanged line -CR at end -EOF - -tr 'Q_' '\015 ' << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 ---- a/x -+++ b/x -@@ -1,6 +1,6 @@ --whitespace at beginning --whitespace change --whitespace in the middle --whitespace at end -+ whitespace at beginning -+whitespace change -+white space in the middle -+whitespace at end__ -unchanged line --CR at endQ -+CR at end -EOF -git diff > out -test_expect_success 'another test, without options' 'test_cmp expect out' - -cat << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 -EOF -git diff -w > out -test_expect_success 'another test, with -w' 'test_cmp expect out' - -tr 'Q' '\015' << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 ---- a/x -+++ b/x -@@ -1,6 +1,6 @@ --whitespace at beginning -+ whitespace at beginning -whitespace change --whitespace in the middle -+white space in the middle -whitespace at end -unchanged line -CR at endQ -EOF -git diff -b > out -test_expect_success 'another test, with -b' 'test_cmp expect out' - -test_expect_success 'check mixed spaces and tabs in indent' ' - - # This is indented with SP HT SP. - echo " foo();" > x && - git diff --check | grep "space before tab in indent" - -' - -test_expect_success 'check mixed tabs and spaces in indent' ' - - # This is indented with HT SP HT. - echo " foo();" > x && - git diff --check | grep "space before tab in indent" - -' - -test_expect_success 'check with no whitespace errors' ' - - git commit -m "snapshot" && - echo "foo();" > x && - git diff --check - -' - -test_expect_success 'check with trailing whitespace' ' - - echo "foo(); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check with space before tab in indent' ' - - # indent has space followed by hard tab - echo " foo();" > x && - test_must_fail git diff --check - -' - -test_expect_success '--check and --exit-code are not exclusive' ' - - git checkout x && - git diff --check --exit-code - -' - -test_expect_success '--check and --quiet are not exclusive' ' - - git diff --check --quiet - -' - -test_expect_success 'check staged with no whitespace errors' ' - - echo "foo();" > x && - git add x && - git diff --cached --check - -' - -test_expect_success 'check staged with trailing whitespace' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff --cached --check - -' - -test_expect_success 'check staged with space before tab in indent' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff --cached --check - -' - -test_expect_success 'check with no whitespace errors (diff-index)' ' - - echo "foo();" > x && - git add x && - git diff-index --check HEAD - -' - -test_expect_success 'check with trailing whitespace (diff-index)' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff-index --check HEAD - -' - -test_expect_success 'check with space before tab in indent (diff-index)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff-index --check HEAD - -' - -test_expect_success 'check staged with no whitespace errors (diff-index)' ' - - echo "foo();" > x && - git add x && - git diff-index --cached --check HEAD - -' - -test_expect_success 'check staged with trailing whitespace (diff-index)' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff-index --cached --check HEAD - -' - -test_expect_success 'check staged with space before tab in indent (diff-index)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff-index --cached --check HEAD - -' - -test_expect_success 'check with no whitespace errors (diff-tree)' ' - - echo "foo();" > x && - git commit -m "new commit" x && - git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check with trailing whitespace (diff-tree)' ' - - echo "foo(); " > x && - git commit -m "another commit" x && - test_must_fail git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check with space before tab in indent (diff-tree)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git commit -m "yet another" x && - test_must_fail git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check trailing whitespace (trailing-space: off)' ' - - git config core.whitespace "-trailing-space" && - echo "foo (); " > x && - git diff --check - -' - -test_expect_success 'check trailing whitespace (trailing-space: on)' ' - - git config core.whitespace "trailing-space" && - echo "foo (); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check space before tab in indent (space-before-tab: off)' ' - - # indent contains space followed by HT - git config core.whitespace "-space-before-tab" && - echo " foo ();" > x && - git diff --check - -' - -test_expect_success 'check space before tab in indent (space-before-tab: on)' ' - - # indent contains space followed by HT - git config core.whitespace "space-before-tab" && - echo " foo (); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check spaces as indentation (indent-with-non-tab: off)' ' - - git config core.whitespace "-indent-with-non-tab" - echo " foo ();" > x && - git diff --check - -' - -test_expect_success 'check spaces as indentation (indent-with-non-tab: on)' ' - - git config core.whitespace "indent-with-non-tab" && - echo " foo ();" > x && - test_must_fail git diff --check - -' - -test_expect_success 'check tabs and spaces as indentation (indent-with-non-tab: on)' ' - - git config core.whitespace "indent-with-non-tab" && - echo " foo ();" > x && - test_must_fail git diff --check - -' - -test_expect_success 'line numbers in --check output are correct' ' - - echo "" > x && - echo "foo(); " >> x && - git diff --check | grep "x:2:" - -' - -test_expect_success 'checkdiff detects trailing blank lines' ' - echo "foo();" >x && - echo "" >>x && - git diff --check | grep "ends with blank" -' - -test_expect_success 'checkdiff allows new blank lines' ' - git checkout x && - mv x y && - ( - echo "/* This is new */" && - echo "" && - cat y - ) >x && - git diff --check -' - -test_expect_success 'combined diff with autocrlf conversion' ' - - git reset --hard && - echo >x hello && - git commit -m "one side" x && - git checkout HEAD^ && - echo >x goodbye && - git commit -m "the other side" x && - git config core.autocrlf true && - test_must_fail git merge master && - - git diff | sed -e "1,/^@@@/d" >actual && - ! grep "^-" actual - -' - -test_done - diff --git a/src/test/resources/mocks/5B.txt b/src/test/resources/mocks/5B.txt deleted file mode 100644 index dd12cf4..0000000 --- a/src/test/resources/mocks/5B.txt +++ /dev/null @@ -1,381 +0,0 @@ -#!/bin/sh -# -# Copyright (c) 2006 Johannes E. Schindelin -# - -test_description='Test special whitespace in diff engine. - -' -. ./test-lib.sh -. ../diff-lib.sh - -# Ray Lehtiniemi's example - -cat << EOF > x -do { - nothing; -} while (0); -EOF - -git update-index --add x - -cat << EOF > x -do -{ - nothing; -} -while (0); -EOF - -cat << EOF > expect -diff --git a/x b/x -index adf3937..6edc172 100644 ---- a/x -+++ b/x -@@ -1,3 +1,5 @@ --do { -+do -+{ - nothing; --} while (0); -+} -+while (0); -EOF - -git diff > out -test_expect_success "Ray's example without options" 'test_cmp expect out' - -git diff -w > out -test_expect_success "Ray's example with -w" 'test_cmp expect out' - -git diff -b > out -test_expect_success "Ray's example with -b" 'test_cmp expect out' - -tr 'Q' '\015' << EOF > x -whitespace at beginning -whitespace change -whitespace in the middle -whitespace at end -unchanged line -CR at endQ -EOF - -git update-index x - -tr '_' ' ' << EOF > x - whitespace at beginning -whitespace change -white space in the middle -whitespace at end__ -unchanged line -CR at end -EOF - -tr 'Q_' '\015 ' << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 ---- a/x -+++ b/x -@@ -1,6 +1,6 @@ --whitespace at beginning --whitespace change --whitespace in the middle --whitespace at end -+ whitespace at beginning -+whitespace change -+white space in the middle -+whitespace at end__ -unchanged line --CR at endQ -+CR at end -EOF -git diff > out -test_expect_success 'another test, without options' 'test_cmp expect out' - -cat << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 -EOF -git diff -w > out -test_expect_success 'another test, with -w' 'test_cmp expect out' - -tr 'Q' '\015' << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 ---- a/x -+++ b/x -@@ -1,6 +1,6 @@ --whitespace at beginning -+ whitespace at beginning -whitespace change --whitespace in the middle -+white space in the middle -whitespace at end -unchanged line -CR at endQ -git diff -b --ignore-space-at-eol > out -test_expect_failure 'another test, with -b --ignore-space-at-eol' 'test_cmp expect out' - -tr 'Q' '\015' << EOF > expect -diff --git a/x b/x -index d99af23..8b32fb5 100644 ---- a/x -+++ b/x -EOF -git diff -b > out -test_expect_success 'another test, with -b' 'test_cmp expect out' - -test_expect_success 'check mixed spaces and tabs in indent' ' - - # This is indented with SP HT SP. - echo " foo();" > x && - git diff --check | grep "space before tab in indent" - -' - -test_expect_success 'check mixed tabs and spaces in indent' ' - - # This is indented with HT SP HT. - echo " foo();" > x && - git diff --check | grep "space before tab in indent" - -' - -test_expect_success 'check with no whitespace errors' ' - - git commit -m "snapshot" && - echo "foo();" > x && - git diff --check - -' - -test_expect_success 'check with trailing whitespace' ' - - echo "foo(); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check with space before tab in indent' ' - - # indent has space followed by hard tab - echo " foo();" > x && - test_must_fail git diff --check - -' - -test_expect_success '--check and --exit-code are not exclusive' ' - - git checkout x && - git diff --check --exit-code - -' - -test_expect_success '--check and --quiet are not exclusive' ' - - git diff --check --quiet - -' - -test_expect_success 'check staged with no whitespace errors' ' - - echo "foo();" > x && - git add x && - git diff --cached --check - -' - -test_expect_success 'check staged with trailing whitespace' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff --cached --check - -' - -test_expect_success 'check staged with space before tab in indent' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff --cached --check - -' - -test_expect_success 'check with no whitespace errors (diff-index)' ' - - echo "foo();" > x && - git add x && - git diff-index --check HEAD - -' - -test_expect_success 'check with trailing whitespace (diff-index)' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff-index --check HEAD - -' - -test_expect_success 'check with space before tab in indent (diff-index)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff-index --check HEAD - -' - -test_expect_success 'check staged with no whitespace errors (diff-index)' ' - - echo "foo();" > x && - git add x && - git diff-index --cached --check HEAD - -' - -test_expect_success 'check staged with trailing whitespace (diff-index)' ' - - echo "foo(); " > x && - git add x && - test_must_fail git diff-index --cached --check HEAD - -' - -test_expect_success 'check staged with space before tab in indent (diff-index)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git add x && - test_must_fail git diff-index --cached --check HEAD - -' - -test_expect_success 'check with no whitespace errors (diff-tree)' ' - - echo "foo();" > x && - git commit -m "new commit" x && - git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check with trailing whitespace (diff-tree)' ' - - echo "foo(); " > x && - git commit -m "another commit" x && - test_must_fail git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check with space before tab in indent (diff-tree)' ' - - # indent has space followed by hard tab - echo " foo();" > x && - git commit -m "yet another" x && - test_must_fail git diff-tree --check HEAD^ HEAD - -' - -test_expect_success 'check trailing whitespace (trailing-space: off)' ' - - git config core.whitespace "-trailing-space" && - echo "foo (); " > x && - git diff --check - -' - -test_expect_success 'check trailing whitespace (trailing-space: on)' ' - - git config core.whitespace "trailing-space" && - echo "foo (); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check space before tab in indent (space-before-tab: off)' ' - - # indent contains space followed by HT - git config core.whitespace "-space-before-tab" && - echo " foo ();" > x && - git diff --check - -' - -test_expect_success 'check space before tab in indent (space-before-tab: on)' ' - - # indent contains space followed by HT - git config core.whitespace "space-before-tab" && - echo " foo (); " > x && - test_must_fail git diff --check - -' - -test_expect_success 'check spaces as indentation (indent-with-non-tab: off)' ' - - git config core.whitespace "-indent-with-non-tab" - echo " foo ();" > x && - git diff --check - -' - -test_expect_success 'check spaces as indentation (indent-with-non-tab: on)' ' - - git config core.whitespace "indent-with-non-tab" && - echo " foo ();" > x && - test_must_fail git diff --check - -' - -test_expect_success 'check tabs and spaces as indentation (indent-with-non-tab: on)' ' - - git config core.whitespace "indent-with-non-tab" && - echo " foo ();" > x && - test_must_fail git diff --check - -' - -test_expect_success 'line numbers in --check output are correct' ' - - echo "" > x && - echo "foo(); " >> x && - git diff --check | grep "x:2:" - -' - -test_expect_success 'checkdiff detects trailing blank lines' ' - echo "foo();" >x && - echo "" >>x && - git diff --check | grep "ends with blank" -' - -test_expect_success 'checkdiff allows new blank lines' ' - git checkout x && - mv x y && - ( - echo "/* This is new */" && - echo "" && - cat y - ) >x && - git diff --check -' - -test_expect_success 'combined diff with autocrlf conversion' ' - - git reset --hard && - echo >x hello && - git commit -m "one side" x && - git checkout HEAD^ && - echo >x goodbye && - git commit -m "the other side" x && - git config core.autocrlf true && - test_must_fail git merge master && - - git diff | sed -e "1,/^@@@/d" >actual && - ! grep "^-" actual - -' - -test_done - - diff --git a/src/test/resources/mocks/issue10_base.txt b/src/test/resources/mocks/issue10_base.txt deleted file mode 100644 index c0a2b21..0000000 --- a/src/test/resources/mocks/issue10_base.txt +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/resources/mocks/issue10_patch.txt b/src/test/resources/mocks/issue10_patch.txt deleted file mode 100644 index 736fddd..0000000 --- a/src/test/resources/mocks/issue10_patch.txt +++ /dev/null @@ -1,10 +0,0 @@ ---- /bonobo/bonobo.iml -+++ /bonobo/bonobo.iml -@@ -41,6 +40,7 @@ - - - -+ - - - diff --git a/src/test/resources/mocks/issue11_1.txt b/src/test/resources/mocks/issue11_1.txt deleted file mode 100644 index 29c06f7..0000000 --- a/src/test/resources/mocks/issue11_1.txt +++ /dev/null @@ -1 +0,0 @@ -svn: '77954' path not found diff --git a/src/test/resources/mocks/issue11_2.txt b/src/test/resources/mocks/issue11_2.txt deleted file mode 100644 index 29c06f7..0000000 --- a/src/test/resources/mocks/issue11_2.txt +++ /dev/null @@ -1 +0,0 @@ -svn: '77954' path not found diff --git a/src/test/resources/mocks/one_delta_test_original.txt b/src/test/resources/mocks/one_delta_test_original.txt deleted file mode 100644 index 5d54330..0000000 --- a/src/test/resources/mocks/one_delta_test_original.txt +++ /dev/null @@ -1,54 +0,0 @@ -

Esta é uma obra Online.

-

 

-

Este texto é negrito

-

Este texto é itálico

-

Este texto está sublinhado

-

Este texto está riscado

-

Este texto está centralizado

-

Este texto está alinhado a direita

-
    -
  1. Este texto está em uma lista numérica
      -
    1. Este texto está identado
    2. -
  2. -
-

Este -aqui é um link

-

 

-

 

-

 

, -

 

-

Página 1

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

Página 2

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

 

-

Página 3

-

 

\ No newline at end of file diff --git a/src/test/resources/mocks/one_delta_test_revised.txt b/src/test/resources/mocks/one_delta_test_revised.txt deleted file mode 100644 index 9197a73..0000000 --- a/src/test/resources/mocks/one_delta_test_revised.txt +++ /dev/null @@ -1,11 +0,0 @@ -

Revisão 3

 

Esta é uma obra -Online.

 

Este texto é -negrit

Este texto é itálico/p>

Este texto está -sublinhado

Este texto está riscado agora não -está mais

p style="text-align: left;">Este texto está -centralizado nem este

Este texto -está alinhado a direita

  1. Este texto está em uma -lista numérica

Este aqui é um -link

\ No newline at end of file diff --git a/src/test/resources/mocks/original.txt b/src/test/resources/mocks/original.txt deleted file mode 100644 index 479dca0..0000000 --- a/src/test/resources/mocks/original.txt +++ /dev/null @@ -1,174 +0,0 @@ -/* - Copyright 2009 Dmitry Naumenko (dm.naumenko@gmail.com) - - This file is part of Java Diff Utills Library. - - Java Diff Utills Library is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Java Diff Utills Library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Java Diff Utills Library. If not, see . -*/ -package difflib; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import difflib.myers.*; - -/** - * Implements the difference and patching engine - * - * @author Dmitry Naumenko - * @version 0.4.1 - */ -public class DiffUtils { - private static DiffAlgorithm defaultDiffAlgorithm = new MyersDiff(); - private static Pattern unifiedDiffChunkRe = - Pattern.compile("@@\\s+-(?:(\\d+)(?:,(\\d+))?)\\s+\\+(?:(\\d+)(?:,(\\d+))?)\\s+@@"); - - /** - * Compute the difference between the original and revised texts with default diff algorithm - * - * @param original the original text - * @param revised the revised text - * @return the patch describing the difference between the original and revised texts - */ - public static Patch diff(List original, List revised) { - return DiffUtils.diff(original, revised, defaultDiffAlgorithm); - } - - /** - * Compute the difference between the original and revised texts with given diff algorithm - * - * @param original the original text - * @param revised the revised text - * @param algorithm the given algorithm - * @return the patch describing the difference between the original and revised texts - */ - public static Patch diff(List original, List revised, DiffAlgorithm algorithm) { - return algorithm.diff(original, revised); - } - - /** - * Patch the original text with given patch - * - * @param original the original text - * @param patch the given patch - * @return the revised text - * @throws PatchFailedException if can't apply patch - */ - public static List patch(List original, Patch patch) throws PatchFailedException { - return patch.applyTo(original); - } - - /** - * Unpatch the revised text for a given patch - * - * @param revised the revised text - * @param patch the given patch - * @return the original text - */ - public static List unpatch(List revised, Patch patch) { - return patch.restore(revised); - } - - /** - * Parse the given text in unified format and creates the list of deltas for it. - * - * @param diff the text in unified format - * @return the patch with deltas. - */ - public static Patch parseUnifiedDiff(List diff) { - boolean inPrelude = true; - List rawChunk = new ArrayList(); - Patch patch = new Patch(); - - int old_ln = 0, old_n = 0, new_ln = 0, new_n = 0; - String tag = "", rest = ""; - for (String line: diff) { - // Skip leading lines until after we've seen one starting with '+++' - if (inPrelude) { - if (line.startsWith("+++")) { - inPrelude = false; - } - continue; - } - Matcher m = unifiedDiffChunkRe.matcher(line); - if (m.find()) { - // Process the lines in the previous chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (Object[] raw_line: rawChunk) { - tag = (String)raw_line[0]; - rest = (String)raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) { - newChunkLines.add(rest); - } - } - patch.addDelta(new ChangeDelta(new Chunk(old_ln - 1, old_n, oldChunkLines), - new Chunk(new_ln - 1, new_n, newChunkLines))); - rawChunk.clear(); - } - // Parse the @@ header - old_ln = m.group(1) == null ? 1 : Integer.parseInt(m.group(1)); - old_n = m.group(2) == null ? 1 : Integer.parseInt(m.group(2)); - new_ln = m.group(3) == null ? 1 : Integer.parseInt(m.group(3)); - new_n = m.group(4) == null ? 1 : Integer.parseInt(m.group(4)); - old_ln = Integer.parseInt(m.group(1)); - - if (old_ln == 0) { - old_ln += 1; - } - if (new_ln == 0) { - new_ln += 1; - } - } else { - if (line.length() > 0) { - tag = line.substring(0, 1); - rest = line.substring(1); - if (tag.equals(" ") || tag.equals("+") || tag.equals("-")) { - rawChunk.add(new Object[] {tag, rest}); - } - } - } - } - - // Process the lines in the last chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (Object[] raw_line: rawChunk) { - tag = (String)raw_line[0]; - rest = (String)raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) { - newChunkLines.add(rest); - } - } - - patch.addDelta(new ChangeDelta(new Chunk(old_ln - 1, old_n, oldChunkLines), - new Chunk(new_ln - 1, new_n, newChunkLines))); - rawChunk.clear(); - } - - return patch; - } - -} diff --git a/src/test/resources/mocks/revised.txt b/src/test/resources/mocks/revised.txt deleted file mode 100644 index 3c19df3..0000000 --- a/src/test/resources/mocks/revised.txt +++ /dev/null @@ -1,308 +0,0 @@ -/* - Copyright 2009 Dmitry Naumenko (dm.naumenko@gmail.com) - - This file is part of Java Diff Utils Library. - - Java Diff Utils Library is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Java Diff Utils Library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Java Diff Utils Library. If not, see . -*/ -package difflib; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import difflib.myers.*; - -/** - * Implements the difference and patching engine - * - * @author Dmitry Naumenko - * @version 0.4.1 - */ -public class DiffUtils { - private static DiffAlgorithm defaultDiffAlgorithm = new MyersDiff(); - private static Pattern unifiedDiffChunkRe = - Pattern.compile("@@\\s+-(?:(\\d+)(?:,(\\d+))?)\\s+\\+(?:(\\d+)(?:,(\\d+))?)\\s+@@"); - - /** - * Compute the difference between the original and revised texts with default diff algorithm - * - * @param original the original text - * @param revised the revised text - * @return the patch describing the difference between the original and revised texts - */ - public static Patch diff(List original, List revised) { - return DiffUtils.diff(original, revised, defaultDiffAlgorithm); - } - - /** - * Compute the difference between the original and revised texts with given diff algorithm - * - * @param original the original text - * @param revised the revised text - * @param algorithm the given algorithm - * @return the patch describing the difference between the original and revised texts - */ - public static Patch diff(List original, List revised, DiffAlgorithm algorithm) { - return algorithm.diff(original, revised); - } - - /** - * Patch the original text with given patch - * - * @param original the original text - * @param patch the given patch - * @return the revised text - * @throws PatchFailedException if can't apply patch - */ - public static List patch(List original, Patch patch) throws PatchFailedException { - return patch.applyTo(original); - } - - /** - * Unpatch the revised text for a given patch - * - * @param revised the revised text - * @param patch the given patch - * @return the original text - */ - public static List unpatch(List revised, Patch patch) { - return patch.restore(revised); // bla-bla-bla - } - - /** - * Parse the given text in unified format and creates the list of deltas for it. - * - * @param diff the text in unified format - * @return the patch with deltas. - */ - public static Patch parseUnifiedDiff(List diff) { - boolean inPrelude = true; - List rawChunk = new ArrayList(); - Patch patch = new Patch(); - - int old_ln = 0, old_n = 0, new_ln = 0, new_n = 0; - String tag = "", rest = ""; - for (String line: diff) { - // Skip leading lines until after we've seen one starting with '+++' - if (inPrelude) { - if (line.startsWith("+++")) { - inPrelude = false; - } - continue; - } - Matcher m = unifiedDiffChunkRe.matcher(line); - if (m.find()) { - // Process the lines in the previous chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (Object[] raw_line: rawChunk) { - tag = (String)raw_line[0]; - rest = (String)raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) { - newChunkLines.add(rest); - } - } - patch.addDelta(new ChangeDelta(new Chunk(old_ln - 1, old_n, oldChunkLines), - new Chunk(new_ln - 1, new_n, newChunkLines))); - rawChunk.clear(); - } - // Parse the @@ header - old_ln = m.group(1) == null ? 1 : Integer.parseInt(m.group(1)); - old_n = m.group(2) == null ? 1 : Integer.parseInt(m.group(2)); - new_ln = m.group(3) == null ? 1 : Integer.parseInt(m.group(3)); - new_n = m.group(4) == null ? 1 : Integer.parseInt(m.group(4)); - old_ln = Integer.parseInt(m.group(1)); - - if (old_ln == 0) { - old_ln += 1; - } - if (new_ln == 0) { - new_ln += 1; - } - } else { - if (line.length() > 0) { - tag = line.substring(0, 1); - rest = line.substring(1); - if (tag.equals(" ") || tag.equals("+") || tag.equals("-")) { - rawChunk.add(new Object[] {tag, rest}); - } - } - } - } - - // Process the lines in the last chunk - if (rawChunk.size() != 0) { - List oldChunkLines = new ArrayList(); - List newChunkLines = new ArrayList(); - - for (Object[] raw_line: rawChunk) - { - tag = (String)raw_line[0]; - rest = (String)raw_line[1]; - if (tag.equals(" ") || tag.equals("-")) - { - oldChunkLines.add(rest); - } - if (tag.equals(" ") || tag.equals("+")) - { - newChunkLines.add(rest); - } - } - - patch.addDelta(new ChangeDelta(new Chunk(old_ln - 1, old_n, oldChunkLines), - new Chunk(new_ln - 1, new_n, newChunkLines))); - rawChunk.clear(); - } - - return patch; - } - - /** - * generateUnifiedDiff takes a Patch and some other arguments, returning the Unified Diff format text representing the Patch. - * @author Bill James (tankerbay@gmail.com) - * - * @param fname1 - Filename of the original (unrevised file) - * @param fname2 - Filename of the revised file - * @param originalLines - Lines of the original file - * @param patch - Patch created by the diff() function - * @param contextSize - number of lines of context output around each difference in the file. - * @return List of strings representing the Unified Diff representation of the Patch argument. - */ - public static List generateUnifiedDiff(String fname1, String fname2, List originalLines, Patch patch, int contextSize ) { - List ret = new ArrayList(); - ret.add( "--- " + fname1 ); - ret.add( "+++ " + fname2 ); - - List cur = new ArrayList(); // current list of Delta's to process - int deltact = patch.getDeltas().size(); - // if there's more than 1 Delta, we may need to output them together - if ( deltact > 1 ) { - Delta curDelta = patch.getDelta(0); - cur.add( curDelta ); // add the first Delta to the current set - for ( int i = 1; i < deltact; i++ ) { - int curpos = curDelta.getOriginal().getPosition(); // store the current position of the first Delta - Delta nextDelta = patch.getDelta(i); // Check if the next Delta is too close to the current position - if ( (curpos + curDelta.getOriginal().getSize() + contextSize) >= ( nextDelta.getOriginal().getPosition()-contextSize ) ) { - cur.add( nextDelta ); // if it is, add it to the current set - } else { - List curBlock = processDeltas( originalLines, cur, contextSize ); - ret.addAll( curBlock ); // if it isn't, output the current set, then create a new - cur.clear(); // set and add the current Delta to it. - cur.add( nextDelta ); - } - curDelta = nextDelta; - } - List curBlock = processDeltas( originalLines, cur, contextSize ); // don't forget to process the last set of Deltas - ret.addAll( curBlock ); - } - - return ret; - } - - /** - * processDeltas takes a list of Deltas and outputs them together in a single block of Unified-Diff-format text. - * @author Bill James (tankerbay@gmail.com) - * - * @param origLines - the lines of the original file - * @param deltas - the Deltas to be output as a single block - * @param contextSize - the number of lines of context to place around block - * @return - */ - private static List processDeltas( List origLines, List deltas, int contextSize ) { - List buffer = new ArrayList(); - int origTotal = 0; // counter for total lines output from Original - int revTotal = 0; // counter for total lines output from Original - int line; - - Delta curDelta = deltas.get(0); // start with the first Delta - int origStart = curDelta.getOriginal().getPosition()+1 - contextSize; // note the +1 to overcome the 0-offset Position - if ( origStart < 1 ) origStart = 1; // clamp to the start of the file - int revStart = curDelta.getRevised().getPosition()+1 - contextSize; // note the +1 to overcome the 0-offset Position - if ( revStart < 1 ) revStart = 1; // clamp to the start of the file - int contextStart = curDelta.getOriginal().getPosition() - contextSize; // find the start of the wrapper context code - if ( contextStart < 0 ) contextStart = 0; // clamp to the start of the file - for ( line = contextStart; line < curDelta.getOriginal().getPosition(); line++ ) { // output the context before the first Delta - buffer.add( " " + origLines.get( line ) ); - origTotal++; - revTotal++; - } - buffer.addAll( getDeltaText( curDelta ) ); // output the first Delta - origTotal += curDelta.getOriginal().getLines().size(); - revTotal += curDelta.getRevised().getLines().size(); - - int deltaIndex = 1; - while ( deltaIndex < deltas.size() ) { // for each of the other Deltas - Delta nextDelta = deltas.get( deltaIndex ); - int intermediateStart = curDelta.getOriginal().getPosition() + curDelta.getOriginal().getLines().size(); - for ( line = intermediateStart; line < nextDelta.getOriginal().getPosition(); line++ ) { - buffer.add( " " + origLines.get( line ) ); // output the code between the last Delta and this one - origTotal++; - revTotal++; - } - buffer.addAll( getDeltaText( nextDelta ) ); // output the Delta - origTotal += nextDelta.getOriginal().getLines().size(); - revTotal += nextDelta.getRevised().getLines().size(); - curDelta = nextDelta; - deltaIndex++; // increment the iterator - } - - // Now output the post-Delta context code, clamping the end of the file - contextStart = curDelta.getOriginal().getPosition() + curDelta.getOriginal().getLines().size(); - for ( line = contextStart; ( line < (contextStart + contextSize )) && ( line < origLines.size() ); line++ ) { - buffer.add( " " + origLines.get( line ) ); - origTotal++; - revTotal++; - } - - // Create and insert the block header, conforming to the Unified Diff standard - StringBuffer header = new StringBuffer(); - header.append( "@@ -" ); - header.append( origStart ); - header.append( "," ); - header.append( origTotal ); - header.append( " +" ); - header.append( revStart ); - header.append( "," ); - header.append( revTotal ); - header.append( " @@" ); - buffer.add( 0, header.toString() ); - - return buffer; - } - - /** - * getDeltaText returns the lines to be added to the Unified Diff text from the Delta parameter - * @author Bill James (tankerbay@gmail.com) - * - * @param delta - the Delta to output - * @return list of String lines of code. - */ - private static List getDeltaText( Delta delta ) { - List buffer = new ArrayList(); - for ( Object line: delta.getOriginal().getLines() ) { - buffer.add( "-" + line ); - } - for ( Object line: delta.getRevised().getLines() ) { - buffer.add( "+" + line ); - } - return buffer; - } - -}