Java Code Examples for org.sonar.api.batch.fs.FileSystem

The following examples show how to use org.sonar.api.batch.fs.FileSystem. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
public EsqlSensor(
        CheckFactory checkFactory, FileLinesContextFactory fileLinesContextFactory, FileSystem fileSystem, NoSonarFilter noSonarFilter,
        @Nullable CustomEsqlRulesDefinition[] customRulesDefinition
) {

    this.checks = EsqlChecks.createEsqlCheck(checkFactory)
            .addChecks(CheckList.REPOSITORY_KEY, CheckList.getChecks())
            .addCustomChecks(customRulesDefinition);
    this.fileLinesContextFactory = fileLinesContextFactory;
    this.fileSystem = fileSystem;
    this.noSonarFilter = noSonarFilter;
    this.mainFilePredicate = fileSystem.predicates().and(
            fileSystem.predicates().hasType(InputFile.Type.MAIN),
            fileSystem.predicates().hasLanguage(EsqlLanguage.KEY));
    this.parser = EsqlParserBuilder.createParser();
}
 
Example 2
Source Project: sonar-esql-plugin   Source File: TraceSensor.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(SensorContext context, Map<InputFile, Set<Integer>> executableLines,  String[] traces) {
	
	for (String trace : traces) {
		FileSystem fs = context.fileSystem();
		File report = fs.resolvePath(trace);
		if (report.isFile()) {
			new UnitTestsAnalyzer(report, executableLines).analyse(context);
		}else if(report.isDirectory()){
			for (File reportFile:report.listFiles()){
				new UnitTestsAnalyzer(reportFile, executableLines).analyse(context);
			}
		} else {
			LOG.info("Trace not found: '{}'", trace);
		}
	} 
}
 
Example 3
@Override
public void execute(SensorContext context) {
  FileSystem fileSystem = context.fileSystem();
  FilePredicates predicates = fileSystem.predicates();
  List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all());
  visitors.add(new FileLinesVisitor(fileLinesContextFactory, fileSystem));
  LuaConfiguration configuration = new LuaConfiguration(fileSystem.encoding());

  scanner = LuaAstScanner.create(configuration, visitors);

  Iterable<java.io.File> files = fileSystem.files(
    predicates.and(
      predicates.hasType(InputFile.Type.MAIN),
      predicates.hasLanguage(Lua.KEY),
      inputFile -> !inputFile.absolutePath().endsWith("mxml")
    ));
  scanner.scanFiles(ImmutableList.copyOf(files));

  Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class));
  save(context, squidSourceFiles);
}
 
Example 4
Source Project: sonar-p3c-pmd   Source File: PmdExecutor.java    License: MIT License 5 votes vote down vote up
public PmdExecutor(FileSystem fileSystem, RulesProfile rulesProfile, PmdProfileExporter pmdProfileExporter,
                   PmdConfiguration pmdConfiguration, JavaResourceLocator javaResourceLocator, Settings settings) {
  this.fs = fileSystem;
  this.rulesProfile = rulesProfile;
  this.pmdProfileExporter = pmdProfileExporter;
  this.pmdConfiguration = pmdConfiguration;
  this.javaResourceLocator = javaResourceLocator;
  this.settings = settings;
}
 
Example 5
Source Project: sonar-clojure   Source File: CloverageMetricParser.java    License: MIT License 5 votes vote down vote up
private static Optional<FileAnalysis> findFileBySources(SensorContext context, String filename) {
    FileSystem fs = context.fileSystem();
    FilePredicate pattern = fs.predicates().matchesPathPattern("**/" + filename);
    InputFile potentialFile = fs.inputFile(pattern);

    if (potentialFile != null) {
        LOG.debug("Found file");
        FileAnalysis foundSource = new FileAnalysis();
        foundSource.setInputFile(potentialFile);
        return Optional.of(foundSource);
    }

    return Optional.empty();
}
 
Example 6
Source Project: sonar-ansible   Source File: AbstractAnsibleSensor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param fileSystem the underlying file system that will give access to the files to be analyzed
 */
protected AbstractAnsibleSensor(FileSystem fileSystem) {
    this.fileSystem = fileSystem;
    this.mainFilesPredicate = fileSystem.predicates().and(
            fileSystem.predicates().hasType(InputFile.Type.MAIN),
            fileSystem.predicates().hasLanguage(YamlLanguage.KEY));
}
 
Example 7
public AbstractLanguageAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
                                      @Nullable CustomRulesDefinition[] customRulesDefinition) {

  this.fileSystem = fileSystem;
  this.settings = settings;
  this.noSonarFilter = noSonarFilter;
  this.checkFactory = checkFactory;
  this.customRulesDefinition = customRulesDefinition;
  this.parser = parser(fileSystem);
}
 
Example 8
private FilePredicate mainFilePredicate(FileSystem fileSystem) {
  String[] suffixes = getSettings().getStringArray(Plugin.EMBEDDED_CSS_FILE_SUFFIXES_KEY);
  if (suffixes == null || suffixes.length == 0) {
    suffixes = StringUtils.split(Plugin.CSS_FILE_SUFFIXES_DEFAULT_VALUE, ",");
  }

  List<FilePredicate> filePredicates = new ArrayList<>();
  for (String suffix : suffixes) {
    filePredicates.add(fileSystem.predicates().matchesPathPattern("**/*." + suffix));
  }

  return fileSystem.predicates().or(filePredicates);
}
 
Example 9
Source Project: sonar-ruby-plugin   Source File: RubocopSensor.java    License: MIT License 5 votes vote down vote up
private InputFile findMatchingFile(FileSystem fs, String filePath) {
    File matchingFile = fs.resolvePath(filePath);

    if (matchingFile != null) {
        try {
            return fs.inputFile(fs.predicates().is(matchingFile));
        }
        catch (IllegalArgumentException e) {
            LOG.error("Failed to resolve " + filePath + " to a single path", e);
        }
    }
    return null;
}
 
Example 10
public CheckstyleConfiguration(
        org.sonar.api.config.Configuration conf,
        CheckstyleProfileExporter confExporter,
        ActiveRules activeRules,
        FileSystem fileSystem) {
    this.conf = conf;
    this.confExporter = confExporter;
    this.activeRules = activeRules;
    this.fileSystem = fileSystem;
}
 
Example 11
@Before
public void before() {
    fileSystem = mock(FileSystem.class);
    context = mock(SensorContext.class);
    inputFile = mock(InputFile.class);
    ruleFinder = mock(ActiveRules.class);

    final FilePredicates predicates = mock(FilePredicates.class);
    final FilePredicate filePredicate = mock(FilePredicate.class);
    when(fileSystem.inputFile(any(FilePredicate.class))).thenReturn(inputFile);
    when(fileSystem.predicates()).thenReturn(predicates);
    when(predicates.hasAbsolutePath(anyString())).thenReturn(filePredicate);
}
 
Example 12
Source Project: enforce-sonarqube-plugin   Source File: ApexSquidSensor.java    License: MIT License 5 votes vote down vote up
/**
 * Default construct to initialize the variables.
 *
 * @param fileSystem source files.
 * @param perspectives perspective from resources.
 * @param checkFactory factory to create a check.
 */
public ApexSquidSensor(FileSystem fileSystem, ResourcePerspectives perspectives, CheckFactory checkFactory) {
    this.checks = checkFactory
            .<SquidAstVisitor<Grammar>>create(CheckList.REPOSITORY_KEY)
            .addAnnotatedChecks(CheckList.getChecks());
    this.fileSystem = fileSystem;
    this.resourcePerspectives = perspectives;

    FilePredicates predicates = fileSystem.predicates();
    filePredicate = predicates.and(
            predicates.hasType(InputFile.Type.MAIN),
            predicates.hasLanguage(Apex.KEY));
}
 
Example 13
Source Project: enforce-sonarqube-plugin   Source File: ApexCpdMappingTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testApexCpdMappingProperties() {
    Apex language = mock(Apex.class);
    FileSystem fileSystem = mock(FileSystem.class);
    ApexCpdMapping mapping = new ApexCpdMapping(language, fileSystem);
    assertThat(mapping.getLanguage(), equalTo(language));
    assertThat(mapping.getTokenizer(), instanceOf(ApexTokenizer.class));
}
 
Example 14
Source Project: sonar-coldfusion   Source File: ColdFusionSensor.java    License: Apache License 2.0 5 votes vote down vote up
public ColdFusionSensor(FileSystem fs, ActiveRules ruleProfile) {
    Preconditions.checkNotNull(fs);
    Preconditions.checkNotNull(ruleProfile);

    this.fs = fs;
    this.ruleProfile = ruleProfile;
}
 
Example 15
Source Project: sonarqube-licensecheck   Source File: LicenseCheckSensor.java    License: Apache License 2.0 5 votes vote down vote up
public LicenseCheckSensor(FileSystem fs, Configuration configuration, ValidateLicenses validateLicenses,
    MavenLicenseService mavenLicenseService, MavenDependencyService mavenDependencyService)
{
    this.fs = fs;
    this.configuration = configuration;
    this.validateLicenses = validateLicenses;
    this.scanners = new Scanner[]{
        new PackageJsonDependencyScanner(
            configuration.getBoolean(LicenseCheckPropertyKeys.NPM_RESOLVE_TRANSITIVE_DEPS).orElse(false)),
        new MavenDependencyScanner(mavenLicenseService, mavenDependencyService)};
}
 
Example 16
/**
 * Main Constructor. Parameters are injected.
 * 
 * @param config
 *          Configuration
 * @param checkFactory
 *          Checkfactory
 * @param fileSystem
 *          Filesystem
 * @param pathResolver
 *          Pathresolver
 */
public FlowSquidSensor(Configuration config, CheckFactory checkFactory, FileSystem fileSystem,
    PathResolver pathResolver) {
  logger.debug("** FlowSquidSenser constructor");
  this.fileSystem = fileSystem;
  this.config = config;
  this.pathResolver = pathResolver;
  this.flowChecks = checkFactory.<FlowCheck>create(FlowRulesDefinition.REPO_KEY)
      .addAnnotatedChecks(CheckList.getFlowChecks().toArray()).addAnnotatedChecks(
          config.getBoolean(FlowLanguageProperties.IGNORE_TOPLEVEL_KEY).get() ? null
              : CheckList.getTopLevelChecks().toArray());
  this.nodeChecks = checkFactory.<FlowCheck>create(FlowRulesDefinition.REPO_KEY)
      .addAnnotatedChecks(CheckList.getNodeChecks().toArray());
}
 
Example 17
@SuppressWarnings("deprecation")
@Override
public void execute(SensorContext context) {
  logger.debug("FlowSquidSensor analysis called");
  AstScanner<Grammar> flowScanner = FlowAstScanner.create(createConfiguration(), flowChecks.all(),
      null);
  logger.debug("Scanning Flow Files with " + flowChecks.all().size() + " checks active");
  FileSystem fs = context.fileSystem();
  Iterable<InputFile> flowFiles = fs
      .inputFiles(fs.predicates().and(fs.predicates().hasLanguage(FlowLanguage.KEY),
          fs.predicates().matchesPathPatterns(FlowLanguage.getFlowFilePatterns())));
  ArrayList<File> files = new ArrayList<File>();
  flowFiles.forEach(file -> files.add(file.file()));
  try {
    flowScanner.scanFiles(files);
  } catch (Exception e) {
    if (config.getBoolean(FlowLanguageProperties.FAIL_ON_SCANERROR).get()) {
      throw e;
    } else {
      logger.error("** * Exception while scanning file, skipping.", e);
    }
  }
  Collection<SourceCode> squidSourceFiles = flowScanner.getIndex()
      .search(new QueryByType(SourceFile.class));
  logger.debug("** Done Scanning");
  // Process sourceFiles
  logger.debug("** Getting Interface Files");
  getInterfaceFiles(squidSourceFiles, context);
  logger.debug("** Setting Top Level Services");
  setTopLevelServices(squidSourceFiles);
  logger.debug("** Saving Source Files");
  save(context, flowScanner, squidSourceFiles);

}
 
Example 18
@SuppressWarnings("deprecation")
private void getInterfaceFiles(Collection<SourceCode> squidSourceFiles, SensorContext context) {
  // Scan node.ndf files
  AstScanner<Grammar> scanner = NodeAstScanner.create(createConfiguration(), nodeChecks.all(),
      null);
  logger.debug("Scanning Interface Files with " + nodeChecks.all().size() + " checks active");
  FileSystem fs = context.fileSystem();
  Iterable<InputFile> nodeFiles = fs
      .inputFiles(fs.predicates().matchesPathPatterns(FlowLanguage.getNodeFilePatterns()));
  try {
    ArrayList<File> files = new ArrayList<File>();
    nodeFiles.forEach(file -> files.add(file.file()));
    scanner.scanFiles(files);
  } catch (Exception e) {
    if (config.getBoolean(FlowLanguageProperties.FAIL_ON_SCANERROR).get()) {
      throw e;
    } else {
      logger.error("** * Exception while scanning file, skipping.", e);
    }
  }
  Collection<SourceCode> nodeSources = scanner.getIndex()
      .search(new QueryByType(SourceFile.class));
  logger.debug("*NODE* nodes found:" + nodeSources.size() + " *");
  for (SourceCode squidSourceFile : squidSourceFiles) {
    for (SourceCode nodeSource : nodeSources) {
      if ((new File(nodeSource.getKey())).getParent()
          .equals((new File(squidSourceFile.getKey())).getParent())) {
        squidSourceFile.addChild(nodeSource);
        String relativePath = pathResolver.relativePath(fileSystem.baseDir(),
            new java.io.File(nodeSource.getKey()));
        InputFile inputFile = fileSystem
            .inputFile(fileSystem.predicates().hasRelativePath(relativePath));
        saveViolations(context, inputFile, (SourceFile) nodeSource);
      }

    }
  }
}
 
Example 19
public GherkinSquidSensor(FileSystem fileSystem, CheckFactory checkFactory, @Nullable CustomGherkinRulesDefinition[] customRulesDefinition) {
  this.fileSystem = fileSystem;

  this.mainFilePredicate = fileSystem.predicates().and(
    fileSystem.predicates().hasType(Type.MAIN),
    fileSystem.predicates().hasLanguage(GherkinLanguage.KEY));

  this.checks = GherkinChecks.createGherkinChecks(checkFactory)
    .addChecks(GherkinRulesDefinition.REPOSITORY_KEY, GherkinRulesDefinition.getChecks())
    .addCustomChecks(customRulesDefinition);
}
 
Example 20
private static void collectFileMeasures(SensorContext context, SMInputCursor clazz) throws XMLStreamException {
  FileSystem fileSystem = context.fileSystem();
  FilePredicates predicates = fileSystem.predicates();
  Map<String, InputFile> inputFileByFilename = new HashMap<>();
  while (clazz.getNext() != null) {
    String fileName = clazz.getAttrValue("filename");

    InputFile inputFile;
    // mxml files are not supported by the plugin
    if (inputFileByFilename.containsKey(fileName)) {
      inputFile = inputFileByFilename.get(fileName);
    } else {
      String key = fileName.startsWith(File.separator) ? fileName : (File.separator + fileName);
      inputFile = fileSystem.inputFile(predicates.and(
        predicates.matchesPathPattern("file:**" + key.replace(File.separator, "/")),
        predicates.hasType(InputFile.Type.MAIN),
        predicates.hasLanguage(Lua.KEY)));
      inputFileByFilename.put(fileName, inputFile);
      if (inputFile == null && !fileName.endsWith(".mxml")) {
        LOG.warn("Cannot save coverage result for file: {}, because resource not found.", fileName);
      }
    }
    if (inputFile != null) {
      collectFileData(
        clazz,
        context.newCoverage()
          .onFile(inputFile)
          .ofType(CoverageType.UNIT)
      );
    } else {
      SMInputCursor line = clazz.childElementCursor("lines").advance().childElementCursor("line");
      while (line.getNext() != null) {
        // advance
      }
    }
  }
}
 
Example 21
private void save(SensorContext context, Collection<SourceCode> squidSourceFiles) {
  FileSystem fileSystem = context.fileSystem();
  for (SourceCode squidSourceFile : squidSourceFiles) {
    SourceFile squidFile = (SourceFile) squidSourceFile;

    InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(squidFile.getKey()));

    saveClassComplexity(context, inputFile, squidFile);
    saveMeasures(context, inputFile, squidFile);
    saveFunctionsComplexityDistribution(context, inputFile, squidFile);
    saveFilesComplexityDistribution(context, inputFile, squidFile);
    visitors.add(new LuaTokensVisitor(context, LuaLexer.create(configuration)));
    saveViolations(context, inputFile, squidFile);
  }
}
 
Example 22
Source Project: sonar-p3c-pmd   Source File: PmdConfiguration.java    License: MIT License 4 votes vote down vote up
public PmdConfiguration(FileSystem fileSystem, Settings settings) {
  this.fileSystem = fileSystem;
  this.settings = settings;
}
 
Example 23
Source Project: sonar-p3c-pmd   Source File: PmdViolationRecorder.java    License: MIT License 4 votes vote down vote up
public PmdViolationRecorder(FileSystem fs, RuleFinder ruleFinder, ResourcePerspectives perspectives) {
  this.fs = fs;
  this.ruleFinder = ruleFinder;
  this.perspectives = perspectives;
}
 
Example 24
Source Project: sonar-p3c-pmd   Source File: PmdSensor.java    License: MIT License 4 votes vote down vote up
public PmdSensor(RulesProfile profile, PmdExecutor executor, PmdViolationRecorder pmdViolationRecorder, FileSystem fs) {
  this.profile = profile;
  this.executor = executor;
  this.pmdViolationRecorder = pmdViolationRecorder;
  this.fs = fs;
}
 
Example 25
Source Project: sonar-clojure   Source File: AbstractSensor.java    License: MIT License 4 votes vote down vote up
protected Optional<InputFile> getFile(String filePath, FileSystem fileSystem) {
    return Optional.ofNullable(fileSystem.inputFile(
            fileSystem.predicates().and(
                    fileSystem.predicates().hasRelativePath(filePath),
                    fileSystem.predicates().hasType(InputFile.Type.MAIN))));
}
 
Example 26
Source Project: sonar-ansible   Source File: AbstractAnsibleSensorTest.java    License: Apache License 2.0 4 votes vote down vote up
protected MySensor(FileSystem fileSystem) {
    super(fileSystem);
}
 
Example 27
protected MySensor(FileSystem fileSystem) {
    super(fileSystem);
}
 
Example 28
public AbstractLanguageAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter) {
  this(fileSystem, checkFactory, settings, noSonarFilter, null);
}
 
Example 29
public CssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter) {
  super(fileSystem, checkFactory, settings, noSonarFilter);
}
 
Example 30
public CssAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter,
                         @Nullable CustomCssRulesDefinition[] customRulesDefinition) {
  super(fileSystem, checkFactory, settings, noSonarFilter, customRulesDefinition);
}