001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar 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 * Sonar 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
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019 */
020package org.sonar.plugins.findbugs;
021
022import org.apache.commons.lang.StringUtils;
023import org.sonar.api.resources.Java;
024
025public final class FindbugsAntConverter {
026
027  private FindbugsAntConverter() {
028  }
029
030  /**
031   * Convert the exclusion ant pattern to a java regexp accepted by findbugs
032   * exclusion file
033   *
034   * @param exclusion ant pattern to convert
035   * @return Exclusion pattern for findbugs
036   */
037  public static String antToJavaRegexpConvertor(String exclusion) {
038    StringBuilder builder = new StringBuilder("~");
039    int offset = 0;
040    // First **/ or */ is optional
041    if (exclusion.startsWith("**/")) {
042      builder.append("(.*\\.)?");
043      offset += 3;
044    } else if (exclusion.startsWith("*/")) {
045      builder.append("([^\\\\^\\s]*\\.)?");
046      offset += 2;
047    }
048    for (String suffix : Java.SUFFIXES) {
049      exclusion = StringUtils.removeEndIgnoreCase(exclusion, "." + suffix);
050    }
051
052    char[] array = exclusion.toCharArray();
053    for (int i = offset; i < array.length; i++) {
054      char c = array[i];
055      if (c == '?') {
056        builder.append('.');
057      } else if (c == '*') {
058        if (i + 1 < array.length && array[i + 1] == '*') {
059          builder.append(".*");
060          i++;
061        } else {
062          builder.append("[^\\\\^\\s]*");
063        }
064      } else if (c == '/') {
065        builder.append("\\.");
066      } else {
067        builder.append(c);
068      }
069    }
070    return builder.toString();
071  }
072}