001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2011 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     */
020    package org.sonar.batch.bootstrap;
021    
022    import org.apache.commons.lang.ArrayUtils;
023    import org.apache.commons.lang.StringUtils;
024    import org.sonar.api.config.Settings;
025    import org.sonar.api.resources.Project;
026    
027    /**
028     * Filter projects to analyze by using the properties sonar.skippedModules and sonar.includedModules
029     *
030     * @since 2.12
031     */
032    public class ProjectFilter {
033    
034      private Settings settings;
035    
036      public ProjectFilter(Settings settings) {
037        this.settings = settings;
038      }
039    
040      public boolean isExcluded(Project project) {
041        Project p = project;
042        while (p != null) {
043          if (isExcluded(getArtifactId(p))) {
044            return true;
045          }
046          p = p.getParent();
047        }
048        return false;
049      }
050    
051      private boolean isExcluded(String artifactId) {
052        String[] includedArtifactIds = settings.getStringArray("sonar.includedModules");
053    
054        if (includedArtifactIds.length > 0) {
055          return !ArrayUtils.contains(includedArtifactIds, artifactId);
056        }
057        String[] excludedArtifactIds = settings.getStringArray("sonar.skippedModules");
058        return ArrayUtils.contains(excludedArtifactIds, artifactId);
059      }
060    
061      // TODO see http://jira.codehaus.org/browse/SONAR-2324
062      static String getArtifactId(Project project) {
063        String key = project.getKey();
064        if (StringUtils.isNotBlank(project.getBranch())) {
065          // remove branch part
066          key = StringUtils.removeEnd(project.getKey(), ":" + project.getBranch());
067        }
068        if (key.contains(":")) {
069          return StringUtils.substringAfter(key, ":");
070        }
071        return key;
072      }
073    }