1 package com.puppycrawl.tools.checkstyle.checks.header; 20 21 import java.util.Arrays ; 22 import java.util.regex.Pattern ; 23 import java.util.regex.PatternSyntaxException ; 24 25 import org.apache.commons.beanutils.ConversionException; 26 27 import com.puppycrawl.tools.checkstyle.api.DetailAST; 28 import com.puppycrawl.tools.checkstyle.api.Utils; 29 import com.puppycrawl.tools.checkstyle.checks.AbstractHeaderCheck; 30 31 39 public class RegexpHeaderCheck extends AbstractHeaderCheck 40 { 41 42 private static final int[] EMPTY_INT_ARRAY = new int[0]; 43 44 45 private int[] mMultiLines = EMPTY_INT_ARRAY; 46 47 48 private Pattern [] mHeaderRegexps; 49 50 54 private boolean isMultiLine(int aLineNo) 55 { 56 return (Arrays.binarySearch(mMultiLines, aLineNo + 1) >= 0); 57 } 58 59 63 public void setMultiLines(int[] aList) 64 { 65 if ((aList == null) || (aList.length == 0)) { 66 mMultiLines = EMPTY_INT_ARRAY; 67 return; 68 } 69 70 mMultiLines = new int[aList.length]; 71 System.arraycopy(aList, 0, mMultiLines, 0, aList.length); 72 Arrays.sort(mMultiLines); 73 } 74 75 81 public void setHeaderFile(String aFileName) 82 throws ConversionException 83 { 84 super.setHeaderFile(aFileName); 85 initHeaderRegexps(); 86 } 87 88 95 public void setHeader(String aHeader) 96 { 97 super.setHeader(aHeader); 98 initHeaderRegexps(); 99 } 100 101 105 private void initHeaderRegexps() 106 { 107 final String [] headerLines = getHeaderLines(); 108 if (headerLines != null) { 109 mHeaderRegexps = new Pattern [headerLines.length]; 110 for (int i = 0; i < headerLines.length; i++) { 111 try { 112 mHeaderRegexps[i] = Utils.getPattern(headerLines[i]); 114 } 115 catch (final PatternSyntaxException ex) { 116 throw new ConversionException( 117 "line " + i + " in header specification" 118 + " is not a regular expression"); 119 } 120 } 121 } 122 } 123 124 130 private boolean isMatch(int aLineNo, int aHeaderLineNo) 131 { 132 final String line = getLines()[aLineNo]; 133 return mHeaderRegexps[aHeaderLineNo].matcher(line).find(); 134 } 135 136 137 public void beginTree(DetailAST aRootAST) 138 { 139 final int headerSize = getHeaderLines().length; 140 final int fileSize = getLines().length; 141 142 if (headerSize - mMultiLines.length > fileSize) { 143 log(1, "header.missing"); 144 } 145 else { 146 int headerLineNo = 0; 147 int i; 148 for (i = 0; (headerLineNo < headerSize) && (i < fileSize); i++) { 149 boolean isMatch = isMatch(i, headerLineNo); 150 while (!isMatch && isMultiLine(headerLineNo)) { 151 headerLineNo++; 152 isMatch = (headerLineNo == headerSize) 153 || isMatch(i, headerLineNo); 154 } 155 if (!isMatch) { 156 log(i + 1, "header.mismatch", 157 getHeaderLines()[headerLineNo]); 158 break; } 160 if (!isMultiLine(headerLineNo)) { 161 headerLineNo++; 162 } 163 } 164 if (i == fileSize) { 165 for (; headerLineNo < headerSize; headerLineNo++) { 168 if (!isMultiLine(headerLineNo)) { 169 log(1, "header.missing"); 170 break; 171 } 172 } 173 } 174 } 175 } 176 } 177 | Popular Tags |