1 19 package org.netbeans.api.java.source.gen; 20 21 import java.io.File ; 22 import java.io.FileReader ; 23 import java.io.IOException ; 24 import java.io.Reader ; 25 import java.util.EnumSet ; 26 import java.util.Set ; 27 import org.netbeans.api.java.lexer.JavaTokenId; 28 import org.netbeans.api.lexer.Token; 29 import org.netbeans.api.lexer.TokenHierarchy; 30 import org.netbeans.api.lexer.TokenSequence; 31 import org.netbeans.api.lexer.TokenUtilities; 32 import org.netbeans.junit.diff.Diff; 33 import org.netbeans.junit.diff.LineDiff; 34 35 39 public class WhitespaceIgnoringDiff implements Diff { 40 41 42 public WhitespaceIgnoringDiff() { 43 } 44 45 private Set <JavaTokenId> IGNORED_TOKENS = EnumSet.of(JavaTokenId.WHITESPACE, JavaTokenId.LINE_COMMENT, JavaTokenId.BLOCK_COMMENT, JavaTokenId.JAVADOC_COMMENT); 46 47 public boolean diff(File first, File second, File diff) throws IOException { 48 boolean result = diffImpl(first, second); 49 50 if (result) { 51 new LineDiff().diff(first, second, diff); 52 } 53 54 return result; 55 } 56 57 private boolean diffImpl(File first, File second) throws IOException { 58 Reader firstReader = new FileReader (first); 59 Reader secondReader = new FileReader (second); 60 try { 61 TokenHierarchy firstH = TokenHierarchy.create(firstReader, JavaTokenId.language(), null, null); 62 TokenHierarchy secondH = TokenHierarchy.create(secondReader, JavaTokenId.language(), null, null); 63 TokenSequence<JavaTokenId> firstTS = firstH.tokenSequence(JavaTokenId.language()); 64 TokenSequence<JavaTokenId> secondTS = secondH.tokenSequence(JavaTokenId.language()); 65 66 70 firstTS.moveNext(); 71 secondTS.moveNext(); 72 73 boolean firstHasNext = true; 74 boolean secondHasNext = true; 75 76 do { 77 Token<JavaTokenId> firstToken = firstTS.token(); 78 Token<JavaTokenId> secondToken = secondTS.token(); 79 80 while (IGNORED_TOKENS.contains(firstToken.id()) && firstHasNext) { 81 firstHasNext = firstTS.moveNext(); 82 firstToken = firstTS.token(); 83 } 84 85 while (IGNORED_TOKENS.contains(secondToken.id()) && secondHasNext) { 86 secondHasNext = secondTS.moveNext(); 87 secondToken = secondTS.token(); 88 } 89 90 if (!firstHasNext || !secondHasNext) 91 break; 92 93 if (firstToken.id() != secondToken.id() || !TokenUtilities.equals(firstToken.text(), secondToken.text())) 94 return true; 95 96 firstHasNext = firstTS.moveNext(); 97 secondHasNext = secondTS.moveNext(); 98 } while (firstHasNext && secondHasNext); 99 100 if (firstHasNext || secondHasNext) 101 return true; 102 } finally { 103 firstReader.close(); 104 secondReader.close(); 105 } 106 107 return false; 108 } 109 110 public boolean diff(String first, String second, String diff) throws IOException { 111 File fFirst = new File (first); 112 File fSecond = new File (second); 113 File fDiff = null != diff ? new File (diff) : null; 114 return diff(fFirst, fSecond, fDiff); 115 } 116 117 } 118 | Popular Tags |