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

The following examples show how to use org.sonar.api.batch.fs.InputFile. 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: PluginHelper.java    From sonar-tsql-plugin with GNU General Public License v3.0 6 votes vote down vote up
public static AntlrContext createRequestFromStream(final InputFile file, final Charset encoding,
		final CharStream mainStream, InputStream fileInputStream) {
	final SourceLinesProvider linesProvider = new SourceLinesProvider();
	final CharStream charStream = new CaseChangingCharStream(mainStream, true);
	final TSqlLexer lexer = new TSqlLexer(charStream);

	lexer.removeErrorListeners();

	final CommonTokenStream stream = new CommonTokenStream(lexer);

	stream.fill();
	final TSqlParser parser = new TSqlParser(stream);
	parser.removeErrorListeners();
	final ParseTree root = parser.tsql_file();
	final AntlrContext antrlFile = new AntlrContext(file, stream, root,
			linesProvider.getLines(fileInputStream, encoding));
	return antrlFile;
}
 
Example #2
Source File: ClojureSensor.java    From sonar-clojure with MIT License 6 votes vote down vote up
@Override
public void execute(SensorContext context) {
    LOG.info("Running ClojureSensor");
    FilePredicates predicates = context.fileSystem().predicates();
    FilePredicate clojure = predicates.hasLanguage(Clojure.KEY);
    FilePredicate main = predicates.hasType(InputFile.Type.MAIN);

    //TODO This is inaccurate. We need to properly count the lines of code, excluding spaces, comments, etc.
    //TODO This is here to make sure analysis data will show up in the Sonar UI.
    Iterable<InputFile> sources = context.fileSystem().inputFiles(predicates.and(clojure, main));

    for (InputFile source : sources) {
        LOG.info(source.toString());
        context.<Integer>newMeasure().withValue(source.lines()).forMetric(NCLOC).on(source).save();
    }
}
 
Example #3
Source File: LOCSensorImpl.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Override
public Map<InputFile, Set<Integer>> execute(SensorContext ctx) {
    HashMap<InputFile, Set<Integer>> toReturn = new HashMap<>();
    
    Iterable<InputFile> affectedFiles = 
            ctx
                .fileSystem()
                .inputFiles(ctx.fileSystem().predicates().hasLanguage(TypeScriptLanguage.LANGUAGE_KEY));
    
    for (InputFile inputFile : affectedFiles) {
        Set<Integer> nonCommentLineNumbers = this.getNonCommentLineNumbers(inputFile);
        toReturn.put(inputFile, nonCommentLineNumbers);
        
        ctx.<Integer>newMeasure().forMetric(CoreMetrics.NCLOC).on(inputFile).withValue(nonCommentLineNumbers.size()).save();
    }
    
    return toReturn;
}
 
Example #4
Source File: AbstractSensor.java    From sonar-clojure with MIT License 6 votes vote down vote up
protected void saveIssue(Issue issue, SensorContext context) {
    try {
        Optional<InputFile> fileOptional = getFile(issue.getFilePath(), context.fileSystem());

        if (fileOptional.isPresent()) {
            InputFile file = fileOptional.get();
            RuleKey ruleKey = RuleKey.of(ClojureLintRulesDefinition.REPOSITORY_KEY, issue.getExternalRuleId().trim());

            NewIssue newIssue = context.newIssue().forRule(ruleKey);

            NewIssueLocation primaryLocation = newIssue
                    .newLocation()
                    .on(file)
                    .message(issue.getDescription().trim());

            primaryLocation.at(file.selectLine(issue.getLine()));

            newIssue.at(primaryLocation);
            newIssue.save();
        } else {
            LOG.warn("Not able to find a file with path '{}'", issue.getFilePath());
        }
    } catch (Exception e) {
        LOG.error("Can not save the issue due to: " + e.getMessage());
    }
}
 
Example #5
Source File: PmdViolationRecorder.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
public void saveViolation(RuleViolation pmdViolation) {
  InputFile inputFile = findResourceFor(pmdViolation);
  if (inputFile == null) {
    // Save violations only for existing resources
    return;
  }

  Issuable issuable = perspectives.as(Issuable.class, inputFile);

  Rule rule = findRuleFor(pmdViolation);
  if (issuable == null || rule == null) {
    // Save violations only for enabled rules
    return;
  }

  IssueBuilder issueBuilder = issuable.newIssueBuilder()
    .ruleKey(rule.ruleKey())
    .message(pmdViolation.getDescription())
    .line(pmdViolation.getBeginLine());
  issuable.addIssue(issueBuilder.build());
}
 
Example #6
Source File: PmdExecutorTest.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
@Test
public void should_execute_pmd_on_source_files_and_test_files() throws Exception {
  InputFile srcFile = file("src/Class.java", Type.MAIN);
  InputFile tstFile = file("test/ClassTest.java", Type.TEST);
  setupPmdRuleSet(PmdConstants.REPOSITORY_KEY, "simple.xml");
  setupPmdRuleSet(PmdConstants.TEST_REPOSITORY_KEY, "junit.xml");
  fileSystem.add(srcFile);
  fileSystem.add(tstFile);

  Report report = pmdExecutor.execute();

  assertThat(report).isNotNull();

  // setting java source version to the default value
  settings.removeProperty(PmdConstants.JAVA_SOURCE_VERSION);
  report = pmdExecutor.execute();

  assertThat(report).isNotNull();
}
 
Example #7
Source File: TraceSensorTest.java    From sonar-esql-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws FileNotFoundException {
	settings = new MapSettings();
	settings.setProperty("sonar.esql.trace.reportPaths", "TraceSensorTest/trace.txt");
	context = SensorContextTester.create(moduleBaseDir);
	context.setSettings(settings);

	InputFile inputFile1 = inputFile("file1.esql", Type.MAIN);
	InputFile inputFile2 = inputFile("file2.esql", Type.MAIN);
	InputFile inputFile3 = inputFile("file3.esql", Type.MAIN);
	// inputFile("tests/file1.esql", Type.TEST);

	linesOfCode = new HashMap<>();
	linesOfCode.put(inputFile1, ImmutableSet.of(1, 2, 3, 4));
	linesOfCode.put(inputFile2, null);
	linesOfCode.put(inputFile3, ImmutableSet.of(1, 2, 3, 4));

	sensor = new TraceSensor();

}
 
Example #8
Source File: EsqlSensor.java    From sonar-esql-plugin with Apache License 2.0 6 votes vote down vote up
public void execute(SensorContext context) {
    LOG.warn("ESQL sensor execute");
    List<TreeVisitor> treeVisitors = Lists.newArrayList();
    treeVisitors.addAll(getTreeVisitors(context));
    treeVisitors.addAll(checks.visitorChecks());

    for (TreeVisitor check : treeVisitors) {
        if (check instanceof ParsingErrorCheck) {
            parsingErrorRuleKey = checks.ruleKeyFor((EsqlCheck) check);
            break;
        }
    }

    Iterable<InputFile> inputFiles = fileSystem.inputFiles(mainFilePredicate);
    Collection<String> files = StreamSupport.stream(inputFiles.spliterator(), false)
            .map(InputFile::toString)
            .collect(Collectors.toList());

    ProgressReport progressReport = new ProgressReport("Report about progress of ESQL analyzer", TimeUnit.SECONDS.toMillis(10));
    progressReport.start(files);

    analyseFiles(context, treeVisitors, inputFiles, progressReport);

    executeCoverageSensors(context);
}
 
Example #9
Source File: AbstractAnsibleSensor.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
/**
 * Saves the found issues in SonarQube
 *
 * @param context the context
 * @param inputFile the file where the issue was found
 * @param line the line where the issue was found
 * @param ruleId the Id of the rule that raised the issue
 * @param message a message describing the issue
 */
protected void saveIssue(SensorContext context, InputFile inputFile, int line, String ruleId, String message) {
    RuleKey ruleKey = getRuleKey(context, ruleId);

    // Old rules (ansible-lint < 3.5) had id ANSIBLE... but now it is E... so we may need to add the heading E back
    if (ruleKey == null) {
        ruleKey = getRuleKey(context, "E" + ruleId);
    }

    if (ruleKey == null) {
        LOGGER.debug("Rule " + ruleId + " ignored, not found in repository");
        return;
    }

    NewIssue newIssue = context.newIssue().forRule(ruleKey);
    NewIssueLocation location = newIssue.newLocation()
            .on(inputFile)
            .message(message)
            .at(inputFile.selectLine(line));
    newIssue.at(location).save();
    LOGGER.debug("Issue {} saved for {}", ruleId, inputFile.filename());
}
 
Example #10
Source File: AbstractAnsibleSensorTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintErrorOutput() throws IOException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY,
                new File(getClass().getResource("/scripts/ansible-lint2.cmd").getFile()).getAbsolutePath());
    } else {
        String path = new File(getClass().getResource("/scripts/ansible-lint2.sh").getFile()).getAbsolutePath();
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY, path);
        setShellRights(path);
    }

    sensor.executeWithAnsibleLint(context, null);
    assertEquals(3, sensor.scannedFiles.size());
    assertTrue(sensor.scannedFiles.contains(playbook1));
    assertTrue(sensor.scannedFiles.contains(playbook2));
    assertTrue(sensor.scannedFiles.contains(playbook3));
    assertEquals(0, context.allIssues().size());

    assertEquals(3, logTester.logs(LoggerLevel.WARN).size());
    logTester.logs(LoggerLevel.WARN).stream().forEach(log -> assertTrue(log.startsWith("Errors happened during analysis:")));
}
 
Example #11
Source File: AbstractAnsibleSensorTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintIOException() throws IOException, InterruptedException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    MySensor theSensor = spy(sensor);
    doThrow(new IOException("Boom!")).when(theSensor).executeCommand(any(), any(), any());

    theSensor.executeWithAnsibleLint(context, Arrays.asList("foo", "bar"));
    assertEquals(1, theSensor.scannedFiles.size());
    assertTrue(theSensor.scannedFiles.contains(playbook1));

    Collection<Issue> issues = context.allIssues();
    assertEquals(0, issues.size());
}
 
Example #12
Source File: AbstractAnsibleSensorTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintWinthConf() throws IOException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    context.fileSystem().add(playbook1);

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY,
                new File(getClass().getResource("/scripts/echo_as_issue.cmd").getFile()).getAbsolutePath());
    } else {
        String path = new File(getClass().getResource("/scripts/echo_as_issue.sh").getFile()).getAbsolutePath();
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY, path);
        setShellRights(path);
    }

    context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_CONF_PATH_KEY, "/path/to/ansible-lint.conf");

    sensor.executeWithAnsibleLint(context, null);
    Collection<Issue> issues = context.allIssues();
    assertEquals(1, issues.size());
    assertTrue(issueExists(issues, ruleKey1, playbook1, 2, "-p --nocolor -c /path/to/ansible-lint\\.conf " + Pattern.quote(new File(playbook1.uri()).getAbsolutePath())));
}
 
Example #13
Source File: EsqlCheckVerifier.java    From sonar-esql-plugin with Apache License 2.0 6 votes vote down vote up
static void verify(EsqlCheck check, InputFile file) {
	EsqlVisitorContext context = TestUtils.createContext(file);

	List<TestIssue> expectedIssues = ExpectedIssuesParser.parseExpectedIssues(context);
	Iterator<Issue> actualIssues = getActualIssues(check, context);

	for (TestIssue expected : expectedIssues) {
		if (actualIssues.hasNext()) {
			verifyIssue(expected, actualIssues.next());
		} else {
			throw new AssertionError("Missing issue at line " + expected.line());
		}
	}

	if (actualIssues.hasNext()) {
		Issue issue = actualIssues.next();
		throw new AssertionError("Unexpected issue at line " + line(issue) + ": \"" + message(issue) + "\"");
	}
}
 
Example #14
Source File: AbstractAnsibleSensorTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    ActiveRules activeRules = new ActiveRulesBuilder()
            .create(ruleKey1)
            .activate()
            .create(ruleKey2)
            .activate()
            .create(ruleKey3)
            .activate()
            .build();
    context.setActiveRules(activeRules);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    sensor = new MySensor(fs);
}
 
Example #15
Source File: AbstractAnsibleSensorNoRuleTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoActiveRule() throws IOException {
    SensorContextTester context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    MySensor sensor = new MySensor(fs);

    sensor.executeWithAnsibleLint(context, null);
    assertEquals(1, logTester.logs(LoggerLevel.INFO).size());
    assertEquals("No active rules found for this plugin, skipping.", logTester.logs(LoggerLevel.INFO).get(0));
    assertEquals(0, context.allIssues().size());
}
 
Example #16
Source File: AnsibleExtraSensorTest.java    From sonar-ansible with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    ActiveRules activeRules = new ActiveRulesBuilder()
            .create(ruleKey1)
            .activate()
            .create(ruleKey2)
            .activate()
            .build();
    context.setActiveRules(activeRules);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    sensor = new AnsibleExtraSensor(context.fileSystem());
}
 
Example #17
Source File: EsqlSensor.java    From sonar-esql-plugin with Apache License 2.0 6 votes vote down vote up
private static void savePreciseIssue(SensorContext sensorContext, InputFile inputFile, RuleKey ruleKey, PreciseIssue issue) {
    NewIssue newIssue = sensorContext.newIssue();

    newIssue
            .forRule(ruleKey)
            .at(newLocation(inputFile, newIssue, issue.primaryLocation()));

    if (issue.cost() != null) {
        newIssue.gap(issue.cost());
    }

    for (IssueLocation secondary : issue.secondaryLocations()) {
        newIssue.addLocation(newLocation(inputFile, newIssue, secondary));
    }
    newIssue.save();
}
 
Example #18
Source File: CssSyntaxHighlighterVisitorTest.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  DefaultFileSystem fileSystem = new DefaultFileSystem(tempFolder.getRoot());
  fileSystem.setEncoding(Charsets.UTF_8);
  file = tempFolder.newFile();
  inputFile = new DefaultInputFile("moduleKey", file.getName())
    .setLanguage("css")
    .setType(InputFile.Type.MAIN);
  fileSystem.add(inputFile);

  sensorContext = SensorContextTester.create(tempFolder.getRoot());
  sensorContext.setFileSystem(fileSystem);

  visitorContext = mock(TreeVisitorContext.class);
  highlighterVisitor = new CssSyntaxHighlighterVisitor(sensorContext);
  when(visitorContext.getFile()).thenReturn(file);
}
 
Example #19
Source File: HtlFilesAnalyzer.java    From AEM-Rules-for-SonarQube with Apache License 2.0 6 votes vote down vote up
public void analyseFiles(SensorContext context, Iterable<InputFile> inputFiles, ProgressReport progressReport) {
    boolean success = false;
    try {
        for (InputFile inputFile : inputFiles) {
            if (context.isCancelled()) {
                throw new CancellationException(
                    "Analysis interrupted because the SensorContext is in cancelled state");
            }
            analyse(context, inputFile);
            progressReport.nextFile();
        }
        success = true;
    } catch (CancellationException e) {
        // do not propagate the exception
        LOGGER.debug(e.toString());
    } finally {
        stopProgressReport(progressReport, success);
    }
}
 
Example #20
Source File: LessMetricsVisitorTest.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void setUp(String fileName) {
  File moduleBaseDir = new File("src/test/resources/metrics/");
  context = SensorContextTester.create(moduleBaseDir);

  DefaultInputFile inputFile = new DefaultInputFile("moduleKey", fileName)
    .setModuleBaseDir(moduleBaseDir.toPath())
    .setLanguage("less")
    .setType(InputFile.Type.MAIN);

  context.fileSystem().add(inputFile);
  context.fileSystem().setEncoding(Charsets.UTF_8);

  LessMetricsVisitor metricsVisitor = new LessMetricsVisitor(context, mock(NoSonarFilter.class));

  TreeVisitorContext treeVisitorContext = mock(TreeVisitorContext.class);
  when(treeVisitorContext.getFile()).thenReturn(inputFile.file());
  when(treeVisitorContext.getTopTree()).thenReturn(LessParser.createParser(Charsets.UTF_8).parse(inputFile.file()));

  metricsVisitor.scanTree(treeVisitorContext);
}
 
Example #21
Source File: IssueSaver.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void savePreciseIssue(PreciseIssue issue) {
  NewIssue newIssue = sensorContext.newIssue();
  InputFile primaryFile = Preconditions.checkNotNull(fileSystem.inputFile(fileSystem.predicates().is(issue.primaryLocation().file())));

  newIssue
    .forRule(ruleKey(issue.check()))
    .at(newLocation(primaryFile, newIssue, issue.primaryLocation()));

  if (issue.cost() != null) {
    newIssue.gap(issue.cost());
  }

  InputFile secondaryFile;
  for (IssueLocation secondary : issue.secondaryLocations()) {
    secondaryFile = fileSystem.inputFile(fileSystem.predicates().is(secondary.file()));
    if (secondaryFile == null) {
      secondaryFile = primaryFile;
    }
    newIssue.addLocation(newLocation(secondaryFile, newIssue, secondary));
  }

  newIssue.save();
}
 
Example #22
Source File: CpdVisitorTest.java    From sonar-css-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  DefaultFileSystem fileSystem = new DefaultFileSystem(tempFolder.getRoot());
  fileSystem.setEncoding(Charsets.UTF_8);
  file = tempFolder.newFile();
  inputFile = new DefaultInputFile("moduleKey", file.getName())
    .setLanguage("css")
    .setType(InputFile.Type.MAIN);
  fileSystem.add(inputFile);

  sensorContext = SensorContextTester.create(tempFolder.getRoot());
  sensorContext.setFileSystem(fileSystem);

  visitorContext = mock(TreeVisitorContext.class);
  cpdVisitor = new CpdVisitor(sensorContext);
  when(visitorContext.getFile()).thenReturn(file);
}
 
Example #23
Source File: TsCoverageSensorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void usesNonCommentLinesSetForLinesToCoverMetrics_IfSettingZeroCoverage() {
    Map<InputFile, Set<Integer>> nonCommentLineNumbersByFile = new HashMap<InputFile, Set<Integer>>();
    HashSet<Integer> nonCommentLineNumbers = new HashSet<Integer>();
    nonCommentLineNumbers.add(1);
    nonCommentLineNumbers.add(3);
    nonCommentLineNumbers.add(5);
    
    nonCommentLineNumbersByFile.put(this.file, nonCommentLineNumbers);
    
    this.sensor.execute(this.context, nonCommentLineNumbersByFile);

    // Expect lines 1, 3 and 5 to have zero coverage...
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 1));
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 3));
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 5));
 
    // and lines 2 and 5 to not have any coverage since they're not counted as code
    // according to our supplied map
    assertNull(this.context.lineHits(this.file.key(), CoverageType.UNIT, 2));
    assertNull(this.context.lineHits(this.file.key(), CoverageType.UNIT, 4));
}
 
Example #24
Source File: TsCoverageSensorImpl.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
private void saveZeroValue(InputFile inputFile, SensorContext context, Set<Integer> nonCommentLineNumbers) {
      NewCoverage newCoverage = 
              context
              .newCoverage()
              .ofType(CoverageType.UNIT)
              .onFile(inputFile);

      if (nonCommentLineNumbers != null) {
          for (Integer nonCommentLineNumber : nonCommentLineNumbers) {
              newCoverage.lineHits(nonCommentLineNumber, 0);
          }
      }
      else {
          for (int i = 1; i <= inputFile.lines(); i++) {
              newCoverage.lineHits(i, 0);
          }
      }

      newCoverage.save();
}
 
Example #25
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  if (messages != null) {

    for (CheckMessage message : messages) {
      RuleKey ruleKey = checks.ruleKey((SquidCheck<LexerlessGrammar>) message.getCheck());
      NewIssue newIssue = context.newIssue()
        .forRule(ruleKey)
        .gap(message.getCost());
      Integer line = message.getLine();
      NewIssueLocation location = newIssue.newLocation()
        .on(inputFile)
        .message(message.getText(Locale.ENGLISH));
      if (line != null) {
        location.at(inputFile.selectLine(line));
      }
      newIssue.at(location);
      newIssue.save();
    }
  }
}
 
Example #26
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  logger.debug("+++Nr of violations found: " + messages.size());
  if (messages != null) {
    for (CheckMessage message : messages) {
      Object c = message.getCheck();
      if (c instanceof FlowCheck) {
        FlowCheck fc = (FlowCheck) c;
        if (squidFile.getInt(FlowMetric.IS_TOP_LEVEL) != 1 && fc.isTopLevelCheck()) {
          logger.debug("+++Ignoring toplevelCheck for file: " + squidFile.getKey());
        } else {
          RuleKey ruleKey;
          if (fc.isNodeCheck()) {
            ruleKey = nodeChecks.ruleKey(fc);
          } else {
            ruleKey = flowChecks.ruleKey(fc);
          }
          FlowIssue.create(context, ruleKey, message.getCost())
              .setPrimaryLocation(inputFile, message).save();
        }
      }
    }
  }
}
 
Example #27
Source File: AntlrHighlighter.java    From sonar-tsql-plugin with GNU General Public License v3.0 6 votes vote down vote up
private void addHighlighting(final NewHighlighting newHighlightning, final Token token, final InputFile file,
		final TextRange range) {
	try {
		if (token.getType() == TSqlParser.COMMENT || token.getType() == TSqlParser.LINE_COMMENT) {
			newHighlightning.highlight(range, TypeOfText.COMMENT);
		}

		if (token.getType() == TSqlParser.STRING) {
			newHighlightning.highlight(range, TypeOfText.STRING);
		}

		if (this.keywordsProvider.isKeyword(TSqlParser.VOCABULARY.getSymbolicName(token.getType()))) {
			newHighlightning.highlight(range, TypeOfText.KEYWORD);
		}
	} catch (final Throwable e) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(format("Unexpected error adding highlighting on file %s", file.absolutePath()), e);
		}
	}
}
 
Example #28
Source File: LCOVParserImplTest.java    From SonarTsPlugin with MIT License 5 votes vote down vote up
@Test
public void ignoresFilesNotPartOfAnalysisSet() {
    Map<InputFile, NewCoverage> coverage = executeForTestCase("existingandnot");
    DefaultCoverage c = (DefaultCoverage) coverage.get(this.inputFile);
    
    assertNotNull(c);
    assertEquals(1, coverage.size());
}
 
Example #29
Source File: ColdFusionSensor.java    From sonar-coldfusion with Apache License 2.0 5 votes vote down vote up
private void metricsLinesCounter(InputFile inputFile, SensorContext context) throws IOException {
    String currentLine;
    int commentLines = 0;
    int blankLines = 0;
    int lines = 0;
    int complexity = 1;

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputFile.inputStream()))) {
        if (inputFile.inputStream() != null) {
            while ((currentLine = reader.readLine()) != null) {
                lines++;
                if (currentLine.contains("<!--")) {
                    commentLines++;
                    if (currentLine.contains("-->")) {
                        continue;
                    }
                    commentLines++;
                    lines++;
                    while (!(reader.readLine()).contains("-->")) {
                        lines++;
                        commentLines++;
                    }
                } else if (currentLine.trim().isEmpty()) {
                    blankLines++;
                }

                complexity = getLineComplexity(currentLine, complexity);
            }
        }
    }
    int linesOfCode = lines-blankLines-commentLines;
    // every 100 lines of code add 1 to the content's complexity
    complexity = complexity + (linesOfCode / 100);


    context.<Integer>newMeasure().forMetric(CoreMetrics.COMMENT_LINES).on(inputFile).withValue(commentLines).save();
    context.<Integer>newMeasure().forMetric(CoreMetrics.NCLOC).on(inputFile).withValue(linesOfCode).save();
    context.<Integer>newMeasure().forMetric(CoreMetrics.LINES).on(inputFile).withValue(lines).save();
    context.<Integer>newMeasure().forMetric(CoreMetrics.COMPLEXITY).on(inputFile).withValue(complexity).save();
}
 
Example #30
Source File: ApexSquidSensorTest.java    From enforce-sonarqube-plugin with MIT License 5 votes vote down vote up
@Test
public void testAnalyse() {
    String relativePath = "src/test/resources/sensor/Book.cls";
    DefaultInputFile inputFile = new DefaultInputFile(relativePath).setLanguage(Apex.KEY);
    inputFile.setAbsolutePath((new File(relativePath)).getAbsolutePath());
    fileSystem.add(inputFile);

    Issuable issuable = mock(Issuable.class);
    Issuable.IssueBuilder issueBuilder = mock(Issuable.IssueBuilder.class);
    when(perspectives.as(Mockito.eq(Issuable.class), Mockito.any(InputFile.class))).thenReturn(issuable);
    when(issuable.newIssueBuilder()).thenReturn(issueBuilder);
    when(issueBuilder.ruleKey(Mockito.any(RuleKey.class))).thenReturn(issueBuilder);
    when(issueBuilder.line(Mockito.any(Integer.class))).thenReturn(issueBuilder);
    when(issueBuilder.message(Mockito.any(String.class))).thenReturn(issueBuilder);

    Project project = new Project("cls");
    SensorContext context = mock(SensorContext.class);
    squidSensor.analyse(project, context);

    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.FILES), eq(1.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.LINES), eq(7.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.NCLOC), eq(6.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.STATEMENTS), eq(2.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.FUNCTIONS), eq(1.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.CLASSES), eq(1.0));
    verify(context).saveMeasure(any(InputFile.class), eq(CoreMetrics.COMPLEXITY), eq(1.0));
}