org.sonar.squidbridge.AstScanner Java Examples

The following examples show how to use org.sonar.squidbridge.AstScanner. 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: FlowAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates the AstScanner. It will set flow and metric checks, next to the default ones.
 * 
 * @param conf
 *          Configuration
 * @param checks
 *          Additional checks to set
 * @param metrics
 *          Additional metrics to set
 * @return
 */
public static AstScanner<Grammar> create(FlowConfiguration conf, Collection<FlowCheck> checks,
    @Nullable List<SquidAstVisitor<Grammar>> metrics) {
  final SquidAstVisitorContextImpl<Grammar> context = new SquidAstVisitorContextImpl<Grammar>(
      new SourceProject("Flow Project"));
  final Parser<Grammar> parser = FlowParser.create(conf);

  AstScanner.Builder<Grammar> builder = AstScanner.<Grammar>builder(context)
      .setBaseParser(parser);
  /* Required commentAnalyzer */
  builder.setCommentAnalyser(new CommentAnalyser());
  /* Metrics */
  ArrayList<SquidAstVisitor<Grammar>> metricList = new ArrayList<SquidAstVisitor<Grammar>>();
  metricList.addAll(MetricList.getFlowVisitors());
  if (metrics != null) {
    metricList.addAll(metrics);
  }
  setMetrics(builder, metricList);
  /* Checks */
  for (FlowCheck flowCheck : checks) {
    builder.withSquidAstVisitor(flowCheck);
  }
  return builder.build();
}
 
Example #2
Source File: NodeAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates the AstScanner. It will set flow and metric checks, next to the default ones.
 * 
 * @param conf
 *          Configuration
 * @param checks
 *          Additional checks to set
 * @param metrics
 *          Additional metrics to set
 * @return
 */
public static AstScanner<Grammar> create(FlowConfiguration conf, Collection<FlowCheck> checks,
    @Nullable List<SquidAstVisitor<Grammar>> metrics) {
  final SquidAstVisitorContextImpl<Grammar> context = new SquidAstVisitorContextImpl<Grammar>(
      new SourceProject("Flow Project"));
  final Parser<Grammar> parser = NodeParser.create(conf);

  AstScanner.Builder<Grammar> builder = AstScanner.<Grammar>builder(context)
      .setBaseParser(parser);
  /* Required commentAnalyzer */
  builder.setCommentAnalyser(new CommentAnalyser());
  /* Metrics */
  ArrayList<SquidAstVisitor<Grammar>> metricList = new ArrayList<SquidAstVisitor<Grammar>>();
  metricList.addAll(MetricList.getDefaultNodeVisitors());
  if (metrics != null) {
    metricList.addAll(metrics);
  }
  setMetrics(builder, metricList);
  /* Checks */
  for (FlowCheck flowCheck : checks) {
    builder.withSquidAstVisitor(flowCheck);
  }
  return builder.build();
}
 
Example #3
Source File: NodeAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, Collection<FlowCheck> nodeChecks,
    List<SquidAstVisitor<Grammar>> metrics) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<Grammar> scanner = create(new FlowConfiguration(Charsets.UTF_8), nodeChecks,
      metrics);
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException(
        "Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #4
Source File: ApexAstScannerTest.java    From enforce-sonarqube-plugin with MIT License 5 votes vote down vote up
@Test
public void testTheNumberOfScannedFiles() {
    AstScanner<Grammar> scanner = ApexAstScanner.create(apexConfiguration);
    scanner.scanFiles(ImmutableList.of(
            new File("src/test/resources/metrics/methods.cls"),
            new File("src/test/resources/metrics/lines.cls")));
    SourceProject project = buildProject(scanner);
    assertThat(project.getInt(ApexMetric.FILES)).isEqualTo(2);
}
 
Example #5
Source File: FlowAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, List<FlowCheck> flowChecks,
    List<SquidAstVisitor<Grammar>> metrics) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<Grammar> scanner = create(new FlowConfiguration(Charsets.UTF_8), flowChecks,
      metrics);
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException(
        "Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  for (SourceCode squidSourceFile : sources) {
    logger.debug("+++Checking Dependencies +++");
    @SuppressWarnings("unchecked")
    ArrayList<String> dependencies = (ArrayList<String>) squidSourceFile
        .getData(FlowMetric.DEPENDENCIES);
    if (dependencies != null) {
      for (String dependency : dependencies) {
        logger.debug("+++Dependency: " + dependency);
      }
    }
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #6
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 #7
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 #8
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void save(SensorContext context, AstScanner<Grammar> flowScanner,
    Collection<SourceCode> squidSourceFiles) {
  for (SourceCode squidSourceFile : squidSourceFiles) {
    SourceFile squidFile = (SourceFile) squidSourceFile;

    String relativePath = pathResolver.relativePath(fileSystem.baseDir(),
        new java.io.File(squidFile.getKey()));
    InputFile inputFile = fileSystem
        .inputFile(fileSystem.predicates().hasRelativePath(relativePath));

    saveClassComplexity(context, flowScanner, inputFile, squidFile);
    saveMeasures(context, inputFile, squidFile);
    saveViolations(context, inputFile, squidFile);
  }
}
 
Example #9
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveClassComplexity(SensorContext context, AstScanner<Grammar> flowScanner,
    InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> classes = flowScanner.getIndex().search(new QueryByParent(squidFile),
      new QueryByType(SourceClass.class));
  Integer complexityInClasses = 0;
  for (SourceCode squidClass : classes) {
    int classComplexity = squidClass.getInt(FlowMetric.INVOKES);
    complexityInClasses += classComplexity;
  }
  context.<Integer>newMeasure().on(inputFile).forMetric(CoreMetrics.COMPLEXITY_IN_CLASSES)
      .withValue(complexityInClasses).save();
}
 
Example #10
Source File: LuaAstScanner.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, SquidAstVisitor<LexerlessGrammar>... visitors) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<LexerlessGrammar> scanner = create(new LuaConfiguration(Charsets.UTF_8), Arrays.asList(visitors));
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException("Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #11
Source File: LuaAstScannerTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void files() {
  AstScanner<LexerlessGrammar> scanner = LuaAstScanner.create(new LuaConfiguration(Charsets.UTF_8), Collections.emptyList());
  scanner.scanFiles(ImmutableList.of(new File("src/test/resources/metrics/comments.lua"),
    new File("src/test/resources/metrics/lines.lua")));
  SourceProject project = (SourceProject) scanner.getIndex().search(new QueryByType(SourceProject.class)).iterator().next();
  assertThat(project.getInt(LuaMetric.FILES)).isEqualTo(2);
}
 
Example #12
Source File: ApexAstScannerTest.java    From enforce-sonarqube-plugin with MIT License 4 votes vote down vote up
private SourceProject buildProject(AstScanner<Grammar> scanner) {
    return (SourceProject) scanner.getIndex().search(new QueryByType(SourceProject.class)).iterator().next();
}