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

The following examples show how to use org.sonar.api.batch.fs.FileSystem. 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 File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #2
Source File: TraceSensor.java    From sonar-esql-plugin with 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
Source File: EsqlSensor.java    From sonar-esql-plugin with 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 #4
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #5
Source File: AbstractAnsibleSensor.java    From sonar-ansible with 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 #6
Source File: CloverageMetricParser.java    From sonar-clojure with 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 #7
Source File: AbstractLanguageAnalyzerSensor.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
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
Source File: EmbeddedCssAnalyzerSensor.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 File: RubocopSensor.java    From sonar-ruby-plugin with 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
Source File: CheckstyleConfiguration.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
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
Source File: CheckstyleAuditListenerTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 File: ApexSquidSensor.java    From enforce-sonarqube-plugin with 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 File: ColdFusionSensor.java    From sonar-coldfusion with 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 #14
Source File: LicenseCheckSensor.java    From sonarqube-licensecheck with 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 #15
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #16
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #17
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #18
Source File: ApexCpdMappingTest.java    From enforce-sonarqube-plugin with 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 #19
Source File: GherkinSquidSensor.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
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
Source File: PmdExecutor.java    From sonar-p3c-pmd with 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 #21
Source File: CoberturaReportParser.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #22
Source File: PmdViolationRecorder.java    From sonar-p3c-pmd with 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 #23
Source File: SqlCoverCoverageProvider.java    From sonar-tsql-plugin with GNU General Public License v3.0 4 votes vote down vote up
public SqlCoverCoverageProvider(final Settings settings, final FileSystem fileSystem) {
	this.settings = settings;
	this.fileSystem = fileSystem;

}
 
Example #24
Source File: GherkinSquidSensor.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 4 votes vote down vote up
public GherkinSquidSensor(FileSystem fileSystem, CheckFactory checkFactory) {
  this(fileSystem, checkFactory, null);
}
 
Example #25
Source File: AbstractAnsibleSensorTest.java    From sonar-ansible with Apache License 2.0 4 votes vote down vote up
protected MySensor(FileSystem fileSystem) {
    super(fileSystem);
}
 
Example #26
Source File: AbstractAnsibleSensorNoRuleTest.java    From sonar-ansible with Apache License 2.0 4 votes vote down vote up
protected MySensor(FileSystem fileSystem) {
    super(fileSystem);
}
 
Example #27
Source File: CFLintAnalysisResultImporter.java    From sonar-coldfusion with Apache License 2.0 4 votes vote down vote up
public CFLintAnalysisResultImporter(FileSystem fs, SensorContext sensorContext) {
    this.fs = fs;
    this.sensorContext = sensorContext;
}
 
Example #28
Source File: AbstractLanguageAnalyzerSensor.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 4 votes vote down vote up
public AbstractLanguageAnalyzerSensor(FileSystem fileSystem, CheckFactory checkFactory, Settings settings, NoSonarFilter noSonarFilter) {
  this(fileSystem, checkFactory, settings, noSonarFilter, null);
}
 
Example #29
Source File: ApexCommonRulesDecoratorTest.java    From enforce-sonarqube-plugin with MIT License 4 votes vote down vote up
@Before
public void setup() {
    decorator = new ApexCommonRulesDecorator(mock(FileSystem.class),
            mock(CheckFactory.class),
            mock(ResourcePerspectives.class));
}
 
Example #30
Source File: SmellMeasuresSensor.java    From qualinsight-plugins-sonarqube-smell with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * {@link SmellMeasuresSensor} IoC constructor.
 *
 * @param fileSystem SonarQube {@link FileSystem}
 */
public SmellMeasuresSensor(final FileSystem fileSystem) {
    this.fileSystem = fileSystem;
    this.javaFilesPredicate = this.fileSystem.predicates()
        .hasLanguage(Java.KEY);
}