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.api.resources;
021    
022    import com.google.common.collect.Lists;
023    import org.apache.commons.io.FileUtils;
024    import org.apache.commons.io.FilenameUtils;
025    import org.apache.commons.io.filefilter.*;
026    import org.apache.commons.lang.CharEncoding;
027    import org.apache.commons.lang.StringUtils;
028    import org.sonar.api.CoreProperties;
029    import org.sonar.api.batch.FileFilter;
030    import org.sonar.api.utils.Logs;
031    import org.sonar.api.utils.SonarException;
032    import org.sonar.api.utils.WildcardPattern;
033    
034    import java.io.File;
035    import java.io.IOException;
036    import java.nio.charset.Charset;
037    import java.util.ArrayList;
038    import java.util.Arrays;
039    import java.util.List;
040    
041    /**
042     * An implementation of {@link ProjectFileSystem}.
043     * For internal use only.
044     * 
045     * @since 1.10
046     * @TODO in fact this class should not be located in sonar-plugin-api
047     */
048    public class DefaultProjectFileSystem implements ProjectFileSystem {
049    
050      private Project project;
051      private Languages languages;
052      private List<IOFileFilter> filters = Lists.newArrayList();
053    
054      public DefaultProjectFileSystem(Project project, Languages languages) {
055        this.project = project;
056        this.languages = languages;
057      }
058    
059      public DefaultProjectFileSystem(Project project, Languages languages, FileFilter... fileFilters) {
060        this(project, languages);
061        for (FileFilter fileFilter : fileFilters) {
062          filters.add(new DelegateFileFilter(fileFilter));
063        }
064      }
065    
066      public Charset getSourceCharset() {
067        String encoding = project.getConfiguration().getString(CoreProperties.ENCODING_PROPERTY);
068        if (StringUtils.isNotEmpty(encoding)) {
069          try {
070            return Charset.forName(encoding);
071          } catch (Exception e) {
072            Logs.INFO.warn("Can not get project charset", e);
073          }
074        }
075        return Charset.defaultCharset();
076      }
077    
078      public File getBasedir() {
079        return project.getPom().getBasedir();
080      }
081    
082      public File getBuildDir() {
083        return resolvePath(project.getPom().getBuild().getDirectory());
084      }
085    
086      public File getBuildOutputDir() {
087        return resolvePath(project.getPom().getBuild().getOutputDirectory());
088      }
089    
090      /**
091       * Maven can modify source directories during Sonar execution - see MavenPhaseExecutor.
092       */
093      public List<File> getSourceDirs() {
094        return resolvePaths(project.getPom().getCompileSourceRoots());
095      }
096    
097      /**
098       * @deprecated since 2.6, because should be immutable
099       */
100      @Deprecated
101      public DefaultProjectFileSystem addSourceDir(File dir) {
102        if (dir == null) {
103          throw new IllegalArgumentException("Can not add null to project source dirs");
104        }
105        project.getPom().getCompileSourceRoots().add(0, dir.getAbsolutePath());
106        return this;
107      }
108    
109      /**
110       * Maven can modify test directories during Sonar execution - see MavenPhaseExecutor.
111       */
112      public List<File> getTestDirs() {
113        return resolvePaths(project.getPom().getTestCompileSourceRoots());
114      }
115    
116      /**
117       * @deprecated since 2.6, because should be immutable
118       */
119      @Deprecated
120      public DefaultProjectFileSystem addTestDir(File dir) {
121        if (dir == null) {
122          throw new IllegalArgumentException("Can not add null to project test dirs");
123        }
124        project.getPom().getTestCompileSourceRoots().add(0, dir.getAbsolutePath());
125        return this;
126      }
127    
128      public File getReportOutputDir() {
129        return resolvePath(project.getPom().getReporting().getOutputDirectory());
130      }
131    
132      public File getSonarWorkingDirectory() {
133        try {
134          File dir = new File(getBuildDir(), "sonar");
135          FileUtils.forceMkdir(dir);
136          return dir;
137    
138        } catch (IOException e) {
139          throw new SonarException("Unable to retrieve Sonar working directory.", e);
140        }
141      }
142    
143      public File resolvePath(String path) {
144        File file = new File(path);
145        if (!file.isAbsolute()) {
146          file = new File(getBasedir(), path);
147        }
148        return file;
149      }
150    
151      private List<File> resolvePaths(List<String> paths) {
152        List<File> result = Lists.newArrayList();
153        if (paths != null) {
154          for (String path : paths) {
155            result.add(resolvePath(path));
156          }
157        }
158        return result;
159      }
160    
161      @Deprecated
162      public List<File> getSourceFiles(Language... langs) {
163        return toFiles(mainFiles(getLanguageKeys(langs)));
164      }
165    
166      @Deprecated
167      public List<File> getJavaSourceFiles() {
168        return getSourceFiles(Java.INSTANCE);
169      }
170    
171      public boolean hasJavaSourceFiles() {
172        return !mainFiles(Java.KEY).isEmpty();
173      }
174    
175      @Deprecated
176      public List<File> getTestFiles(Language... langs) {
177        return toFiles(testFiles(getLanguageKeys(langs)));
178      }
179    
180      @Deprecated
181      public boolean hasTestFiles(Language lang) {
182        return !testFiles(lang.getKey()).isEmpty();
183      }
184    
185      private List<InputFile> getFiles(List<File> directories, boolean applyExclusionPatterns, String... langs) {
186        List<InputFile> result = Lists.newArrayList();
187        if (directories == null) {
188          return result;
189        }
190    
191        IOFileFilter suffixFilter = getFileSuffixFilter(langs);
192        WildcardPattern[] exclusionPatterns = getExclusionPatterns(applyExclusionPatterns);
193    
194        for (File dir : directories) {
195          if (dir.exists()) {
196            IOFileFilter exclusionFilter = new ExclusionFilter(dir, exclusionPatterns);
197            IOFileFilter visibleFileFilter = HiddenFileFilter.VISIBLE;
198            List<IOFileFilter> dirFilters = Lists.newArrayList(visibleFileFilter, suffixFilter, exclusionFilter);
199            dirFilters.addAll(this.filters);
200            List<File> files = (List<File>) FileUtils.listFiles(dir, new AndFileFilter(dirFilters), HiddenFileFilter.VISIBLE);
201            for (File file : files) {
202              String relativePath = DefaultProjectFileSystem.getRelativePath(file, dir);
203              result.add(new DefaultInputFile(dir, relativePath));
204            }
205          }
206        }
207        return result;
208      }
209    
210      private WildcardPattern[] getExclusionPatterns(boolean applyExclusionPatterns) {
211        WildcardPattern[] exclusionPatterns;
212        if (applyExclusionPatterns) {
213          exclusionPatterns = WildcardPattern.create(project.getExclusionPatterns());
214        } else {
215          exclusionPatterns = new WildcardPattern[0];
216        }
217        return exclusionPatterns;
218      }
219    
220      private IOFileFilter getFileSuffixFilter(String... langKeys) {
221        IOFileFilter suffixFilter = FileFilterUtils.trueFileFilter();
222        if (langKeys != null && langKeys.length > 0) {
223          List<String> suffixes = Arrays.asList(languages.getSuffixes(langKeys));
224          if (!suffixes.isEmpty()) {
225            suffixFilter = new SuffixFileFilter(suffixes);
226          }
227        }
228        return suffixFilter;
229      }
230    
231      private static class ExclusionFilter implements IOFileFilter {
232        File sourceDir;
233        WildcardPattern[] patterns;
234    
235        ExclusionFilter(File sourceDir, WildcardPattern[] patterns) {
236          this.sourceDir = sourceDir;
237          this.patterns = patterns;
238        }
239    
240        public boolean accept(File file) {
241          String relativePath = getRelativePath(file, sourceDir);
242          if (relativePath == null) {
243            return false;
244          }
245          for (WildcardPattern pattern : patterns) {
246            if (pattern.match(relativePath)) {
247              return false;
248            }
249          }
250          return true;
251        }
252    
253        public boolean accept(File file, String name) {
254          return accept(file);
255        }
256      }
257    
258      public File writeToWorkingDirectory(String content, String fileName) throws IOException {
259        return writeToFile(content, getSonarWorkingDirectory(), fileName);
260      }
261    
262      protected static File writeToFile(String content, File dir, String fileName) throws IOException {
263        File file = new File(dir, fileName);
264        FileUtils.writeStringToFile(file, content, CharEncoding.UTF_8);
265        return file;
266      }
267    
268      /**
269       * getRelativePath("c:/foo/src/my/package/Hello.java", "c:/foo/src") is "my/package/Hello.java"
270       * 
271       * @return null if file is not in dir (including recursive subdirectories)
272       */
273      public static String getRelativePath(File file, File dir) {
274        return getRelativePath(file, Arrays.asList(dir));
275      }
276    
277      /**
278       * getRelativePath("c:/foo/src/my/package/Hello.java", ["c:/bar", "c:/foo/src"]) is "my/package/Hello.java".
279       * <p>
280       * Relative path is composed of slashes. Windows backslaches are replaced by /
281       * </p>
282       * 
283       * @return null if file is not in dir (including recursive subdirectories)
284       */
285      public static String getRelativePath(File file, List<File> dirs) {
286        List<String> stack = new ArrayList<String>();
287        String path = FilenameUtils.normalize(file.getAbsolutePath());
288        File cursor = new File(path);
289        while (cursor != null) {
290          if (containsFile(dirs, cursor)) {
291            return StringUtils.join(stack, "/");
292          }
293          stack.add(0, cursor.getName());
294          cursor = cursor.getParentFile();
295        }
296        return null;
297      }
298    
299      public File getFileFromBuildDirectory(String filename) {
300        File file = new File(getBuildDir(), filename);
301        return (file.exists() ? file : null);
302      }
303    
304      public Resource toResource(File file) {
305        if (file == null || !file.exists()) {
306          return null;
307        }
308    
309        String relativePath = getRelativePath(file, getSourceDirs());
310        if (relativePath == null) {
311          return null;
312        }
313    
314        return (file.isFile() ? new org.sonar.api.resources.File(relativePath) : new org.sonar.api.resources.Directory(relativePath));
315      }
316    
317      private static boolean containsFile(List<File> dirs, File cursor) {
318        for (File dir : dirs) {
319          if (FilenameUtils.equalsNormalizedOnSystem(dir.getAbsolutePath(), cursor.getAbsolutePath())) {
320            return true;
321          }
322        }
323        return false;
324      }
325    
326      /**
327       * Conversion from Language to key. Allows to provide backward compatibility.
328       */
329      private String[] getLanguageKeys(Language[] langs) {
330        String[] keys = new String[langs.length];
331        for (int i = 0; i < langs.length; i++) {
332          keys[i] = langs[i].getKey();
333        }
334        return keys;
335      }
336    
337      /**
338       * Conversion from InputFile to File. Allows to provide backward compatibility.
339       */
340      private static List<File> toFiles(List<InputFile> files) {
341        List<File> result = Lists.newArrayList();
342        for (InputFile file : files) {
343          result.add(file.getFile());
344        }
345        return result;
346      }
347    
348      /**
349       * @since 2.6
350       */
351      public List<InputFile> mainFiles(String... langs) {
352        return getFiles(getSourceDirs(), true, langs);
353      }
354    
355      /**
356       * @since 2.6
357       */
358      public List<InputFile> testFiles(String... langs) {
359        return getFiles(getTestDirs(), false /* FIXME should be true? */, langs);
360      }
361    
362      private static final class DefaultInputFile implements InputFile {
363        private File basedir;
364        private String relativePath;
365    
366        DefaultInputFile(File basedir, String relativePath) {
367          this.basedir = basedir;
368          this.relativePath = relativePath;
369        }
370    
371        public File getFileBaseDir() {
372          return basedir;
373        }
374    
375        public File getFile() {
376          return new File(basedir, relativePath);
377        }
378    
379        public String getRelativePath() {
380          return relativePath;
381        }
382      }
383    }