001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * SonarQube is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public License
017     * along with this program; if not, write to the Free Software Foundation,
018     * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019     */
020    
021    package org.sonar.batch.issue.ignore.pattern;
022    
023    import com.google.common.annotations.VisibleForTesting;
024    import com.google.common.collect.Lists;
025    import org.apache.commons.lang.StringUtils;
026    import org.sonar.api.utils.SonarException;
027    
028    import java.util.List;
029    
030    public class PatternDecoder {
031    
032      private static final int THREE_FIELDS_PER_LINE = 3;
033      private static final String LINE_RANGE_REGEXP = "\\[((\\d+|\\d+-\\d+),?)*\\]";
034      private static final String CONFIG_FORMAT_ERROR_PREFIX = "Exclusions > Issues : Invalid format. ";
035    
036      public List<IssuePattern> decode(String patternsList) {
037        List<IssuePattern> patterns = Lists.newLinkedList();
038        String[] patternsLines = StringUtils.split(patternsList, "\n");
039        for (String patternLine : patternsLines) {
040          IssuePattern pattern = decodeLine(patternLine.trim());
041          if (pattern != null) {
042            patterns.add(pattern);
043          }
044        }
045        return patterns;
046      }
047    
048      /**
049       * Main method that decodes a line which defines a pattern
050       */
051      public IssuePattern decodeLine(String line) {
052        if (isBlankOrComment(line)) {
053          return null;
054        }
055    
056        String[] fields = StringUtils.splitPreserveAllTokens(line, ';');
057        if (fields.length > THREE_FIELDS_PER_LINE) {
058          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The following line has more than 3 fields separated by comma: " + line);
059        }
060    
061        IssuePattern pattern;
062        if (fields.length == THREE_FIELDS_PER_LINE) {
063          checkRegularLineConstraints(line, fields);
064          pattern = new IssuePattern(StringUtils.trim(fields[0]), StringUtils.trim(fields[1]));
065          decodeRangeOfLines(pattern, fields[2]);
066        } else if (fields.length == 2) {
067          checkDoubleRegexpLineConstraints(line, fields);
068          pattern = new IssuePattern().setBeginBlockRegexp(fields[0]).setEndBlockRegexp(fields[1]);
069        } else {
070          checkWholeFileRegexp(fields[0]);
071          pattern = new IssuePattern().setAllFileRegexp(fields[0]);
072        }
073    
074        return pattern;
075      }
076    
077      static void checkRegularLineConstraints(String line, String[] fields) {
078        if (!isResource(fields[0])) {
079          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The first field does not define a resource pattern: " + line);
080        }
081        if (!isRule(fields[1])) {
082          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The second field does not define a rule pattern: " + line);
083        }
084        if (!isLinesRange(fields[2])) {
085          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The third field does not define a range of lines: " + line);
086        }
087      }
088    
089      static void checkDoubleRegexpLineConstraints(String line, String[] fields) {
090        if (!isRegexp(fields[0])) {
091          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The first field does not define a regular expression: " + line);
092        }
093        // As per configuration help, missing second field means: from start regexp to EOF
094      }
095    
096      static void checkWholeFileRegexp(String regexp) {
097        if (!isRegexp(regexp)) {
098          throw new SonarException(CONFIG_FORMAT_ERROR_PREFIX + "The field does not define a regular expression: " + regexp);
099        }
100      }
101    
102      public static void decodeRangeOfLines(IssuePattern pattern, String field) {
103        if (StringUtils.equals(field, "*")) {
104          pattern.setCheckLines(false);
105        } else {
106          pattern.setCheckLines(true);
107          String s = StringUtils.substringBetween(StringUtils.trim(field), "[", "]");
108          String[] parts = StringUtils.split(s, ',');
109          for (String part : parts) {
110            if (StringUtils.contains(part, '-')) {
111              String[] range = StringUtils.split(part, '-');
112              pattern.addLineRange(Integer.valueOf(range[0]), Integer.valueOf(range[1]));
113            } else {
114              pattern.addLine(Integer.valueOf(part));
115            }
116          }
117        }
118      }
119    
120      @VisibleForTesting
121      static boolean isLinesRange(String field) {
122        return StringUtils.equals(field, "*") || java.util.regex.Pattern.matches(LINE_RANGE_REGEXP, field);
123      }
124    
125      @VisibleForTesting
126      static boolean isBlankOrComment(String line) {
127        return StringUtils.isBlank(line) ^ StringUtils.startsWith(line, "#");
128      }
129    
130      @VisibleForTesting
131      static boolean isResource(String field) {
132        return StringUtils.isNotBlank(field);
133      }
134    
135      @VisibleForTesting
136      static boolean isRule(String field) {
137        return StringUtils.isNotBlank(field);
138      }
139    
140      @VisibleForTesting
141      static boolean isRegexp(String field) {
142        return StringUtils.isNotBlank(field);
143      }
144    }