public void analyse(Project project, SensorContext context) {
    this.project = project;
    this.context = context;

    Collection<SquidAstVisitor<LexerlessGrammar>> squidChecks = annotationCheckFactory.getChecks();
    List<SquidAstVisitor<LexerlessGrammar>> visitors = Lists.newArrayList(squidChecks);
    visitors.add(new FileLinesVisitor(project, fileLinesContextFactory));
    this.scanner =
        FlexAstScanner.create(
            createConfiguration(project), visitors.toArray(new SquidAstVisitor[visitors.size()]));
    Collection<java.io.File> files =
        InputFileUtils.toFiles(project.getFileSystem().mainFiles(Flex.KEY));
    files = ImmutableList.copyOf(Collections2.filter(files, Predicates.not(MXML_FILTER)));
    scanner.scanFiles(files);

    Collection<SourceCode> squidSourceFiles =
        scanner.getIndex().search(new QueryByType(SourceFile.class));
    save(squidSourceFiles);

    Collection<SourceCode> squidPackages =
        scanner.getIndex().search(new QueryByType(FlexSquidPackage.class));
    for (SourceCode pkg : squidPackages) {
      String packageName = pkg.getKey();
      if (!"".equals(packageName)) {
        Directory directory = resourceBridge.findDirectory(packageName);
        context.saveMeasure(directory, CoreMetrics.PACKAGES, 1.0);
      }
    }
  }
  @Override
  public void analyse(Project module, SensorContext context) {

    final String projectBaseDir = module.getFileSystem().getBasedir().getPath();

    SwiftLintReportParser parser = new SwiftLintReportParser(module, context);
    saveViolations(parseReportIn(projectBaseDir, parser), context);
  }
  private Project createProject() {
    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
    when(fileSystem.hasJavaSourceFiles()).thenReturn(Boolean.TRUE);

    Project project = mock(Project.class);
    when(project.getFileSystem()).thenReturn(fileSystem);
    return project;
  }
示例#4
0
  public void analyse(Project project, SensorContext context) {
    List<InputFile> sourceFiles = project.getFileSystem().mainFiles(CxxLanguage.KEY);

    for (InputFile inputFile : sourceFiles) {
      if (shouldParseFile(inputFile.getFile())) {
        parseFile(inputFile, project, context);
      }
    }
  }
示例#5
0
 private static File getReportsDirectoryFromProperty(Project project) {
   String path = (String) project.getProperty(SUREFIRE_REPORTS_PATH_PROPERTY);
   if (StringUtils.isBlank(path)) {
     path = (String) project.getProperty(SUREFIRE_REPORTS_PATH_DEPRECATED_PROPERTY);
   }
   if (path != null) {
     return project.getFileSystem().resolvePath(path);
   }
   return null;
 }
 private static File getReportFromPluginConfiguration(
     Project project, MavenProject mavenProject, String file) {
   MavenPlugin mavenPlugin = MavenPlugin.getPlugin(mavenProject, GROUP_ID, ARTIFACT_ID);
   if (mavenPlugin != null) {
     String path = mavenPlugin.getParameter("outputDirectory");
     if (path != null) {
       return project.getFileSystem().resolvePath(path + file);
     }
   }
   return null;
 }
  @Test
  public void testGetReportWithProperty() {
    File desired = new File(getClass().getResource("big/pylint.txt").getFile());
    String dir = desired.getParent();
    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
    when(fileSystem.resolvePath(anyString())).thenReturn(new File(dir));
    when(project.getFileSystem()).thenReturn(fileSystem);
    when(project.getProperty(PyLintUtils.PYLINT_REPORT_PATH_PROPERTY)).thenReturn(dir);
    File report = PyLintUtils.getReport(project);

    assertEquals(desired, report);
  }
  @Test
  public void testGetReportWithDefault() {
    File desired = new File(getClass().getResource("small/pylint.txt").getFile());
    String dir = desired.getParent();
    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
    when(fileSystem.getBasedir()).thenReturn(new File(dir));
    when(project.getFileSystem()).thenReturn(fileSystem);

    File report = PyLintUtils.getReport(project);

    assertEquals(desired, report);
  }
示例#9
0
 private static File getReportsDirectoryFromPluginConfiguration(Project project) {
   MavenPlugin plugin =
       MavenPlugin.getPlugin(
           project.getPom(), MavenSurefireUtils.GROUP_ID, MavenSurefireUtils.ARTIFACT_ID);
   if (plugin != null) {
     String path = plugin.getParameter("reportsDirectory");
     if (path != null) {
       return project.getFileSystem().resolvePath(path);
     }
   }
   return null;
 }
  @Test
  public void writeConfigurationToWorkingDir() throws IOException {
    Project project =
        MavenTestUtils.loadProjectFromPom(getClass(), "writeConfigurationToWorkingDir/pom.xml");

    CheckstyleProfileExporter exporter = new FakeExporter();
    CheckstyleConfiguration configuration =
        new CheckstyleConfiguration(null, exporter, null, project.getFileSystem());
    File xmlFile = configuration.getXMLDefinitionFile();

    assertThat(xmlFile.exists(), is(true));
    assertThat(FileUtils.readFileToString(xmlFile), is("<conf/>"));
  }
示例#11
0
  /** Gets the generated jtl file path, if it was any generated */
  protected String getJtlFilePath(Project project, String innerProjectJMeterReportsPath) {
    String baseDirPath = project.getFileSystem().getBasedir().getAbsolutePath();
    File reportDir = new File(baseDirPath + innerProjectJMeterReportsPath);

    if (reportDir.exists()) {
      for (File file :
          (Collection<File>) FileUtils.listFiles(reportDir, new String[] {"jtl"}, true)) {
        return file.getAbsolutePath();
      }

      for (File file :
          (Collection<File>) FileUtils.listFiles(reportDir, new String[] {"xml"}, true)) {
        return file.getAbsolutePath();
      }
    }
    return null;
  }
示例#12
0
  public void analyse(Project project, SensorContext context) {
    DroolsPlugin.configureSourceDir(project);
    Language drools = new Drools(project);
    ProjectFileSystem fileSystem = project.getFileSystem();
    Map<String, DroolsPackage> packageMap = new HashMap<String, DroolsPackage>();
    VerifierBuilder verifierBuilder = VerifierBuilderFactory.newVerifierBuilder();
    for (File file : fileSystem.getSourceFiles(drools)) {
      Verifier verifier = verifierBuilder.newVerifier();
      try {
        DroolsFile resource = DroolsFile.fromIOFile(file, false);
        Source source = analyseSourceCode(file);
        if (source != null) {
          context.saveMeasure(
              resource, CoreMetrics.LINES, (double) source.getMeasure(Metric.LINES));
          context.saveMeasure(
              resource, CoreMetrics.NCLOC, (double) source.getMeasure(Metric.LINES_OF_CODE));
          context.saveMeasure(
              resource,
              CoreMetrics.COMMENT_LINES,
              (double) source.getMeasure(Metric.COMMENT_LINES));
        }
        context.saveMeasure(resource, CoreMetrics.FILES, 1.0);
        context.saveMeasure(
            resource,
            CoreMetrics.CLASSES,
            (double)
                (resource.getPackageDescr().getRules().size()
                    + resource.getPackageDescr().getFunctions().size()));
        packageMap.put(resource.getParent().getKey(), resource.getParent());

        verifier.addResourcesToVerify(new FileSystemResource(file), ResourceType.DRL);
        verifier.fireAnalysis();
        saveViolations(resource, context, verifier.getResult());
      } catch (Throwable e) {
        DroolsPlugin.LOG.error(
            "error while verifier analyzing '" + file.getAbsolutePath() + "'", e);
      } finally {
        verifier.dispose();
      }
    }

    for (DroolsPackage droolsPackage : packageMap.values()) {
      context.saveMeasure(droolsPackage, CoreMetrics.PACKAGES, 1.0);
    }
  }
  /**
   * Matches to something like: (ATOM:ATOM/NUMBER)(WHITESPACES)(SOMETHING NOT
   * WHITESPACES)(:WHITESPACES)(NUMBER,NUMBER-NUMBER,NUMBER) like: game:start/0
   * /home/dev/project/erlang/game.erl: 4,1-5,12 means: 'application name':'function name'/'number
   * of parameters' 'URL to the file': 'starting row','starting col'-'ending row','ending col'
   */
  public ViolationReport refactorErl(Project project, RulesProfile profile) {
    ViolationReport report = new ViolationReport();
    List<ActiveRule> activeRules = profile.getActiveRulesByRepository("Erlang");

    /** Read refactorErl results */
    File basedir =
        new File(
            project.getFileSystem().getBasedir()
                + File.separator
                + ((Erlang) project.getLanguage()).getEunitFolder());
    LOG.debug("Parsing refactorErl reports from folder {}", basedir.getAbsolutePath());

    String refactorErlPattern = ((Erlang) project.getLanguage()).getRefactorErlFilenamePattern();

    String[] list = getFileNamesByPattern(basedir, refactorErlPattern);

    if (list.length == 0) {
      LOG.warn("no file matches to : ", refactorErlPattern);
      return report;
    }

    for (String file : list) {
      try {
        List<ViolationReportUnit> units = readRefactorErlReportUnits(basedir, file);
        for (ViolationReportUnit refactorErlReportUnit : units) {
          ActiveRule activeRule =
              ActiveRuleFilter.getActiveRuleByRuleName(
                  activeRules, refactorErlReportUnit.getMetricKey());
          if (activeRule != null
              && ViolationUtil.checkIsValid(activeRule, refactorErlReportUnit.getMetricValue())) {
            refactorErlReportUnit.setDescription(
                ViolationUtil.getMessageForMetric(
                    activeRule, refactorErlReportUnit.getMetricValue()));
            /** Replace key coming from activeProfile because it contains the name originaly */
            refactorErlReportUnit.setMetricKey(activeRule.getRuleKey());
            report.addUnit(refactorErlReportUnit);
          }
        }
      } catch (FileNotFoundException e) {
      } catch (IOException e) {
      }
    }
    return report;
  }
  /** {@inheritDoc} */
  public void analyse(Project project, SensorContext context) {
    if (rulesProfile.getActiveRulesByRepository(FxCopConstants.REPOSITORY_KEY).isEmpty()) {
      LOG.warn(
          "/!\\ SKIP FxCop analysis: no rule defined for FxCop in the \"{}\" profil.",
          rulesProfile.getName());
      return;
    }

    fxCopResultParser.setEncoding(fileSystem.getSourceCharset());

    final File reportFile;
    File projectDir = project.getFileSystem().getBasedir();
    String reportDefaultPath =
        getMicrosoftWindowsEnvironment().getWorkingDirectory()
            + "/"
            + FxCopConstants.FXCOP_REPORT_XML;
    if (MODE_REUSE_REPORT.equalsIgnoreCase(executionMode)) {
      String reportPath =
          configuration.getString(FxCopConstants.REPORTS_PATH_KEY, reportDefaultPath);
      reportFile = FileFinder.browse(projectDir, reportPath);
      LOG.info("Reusing FxCop report: " + reportFile);
    } else {
      // prepare config file for FxCop
      File fxCopConfigFile = generateConfigurationFile();
      // and run FxCop
      try {
        FxCopRunner runner =
            FxCopRunner.create(
                configuration.getString(
                    FxCopConstants.INSTALL_DIR_KEY, FxCopConstants.INSTALL_DIR_DEFVALUE));
        launchFxCop(project, runner, fxCopConfigFile);
      } catch (FxCopException e) {
        throw new SonarException("FxCop execution failed.", e);
      }
      reportFile = new File(projectDir, reportDefaultPath);
    }

    // and analyze results
    analyseResults(reportFile);
  }
  @BeforeClass
  public static void init() {
    aRule = Rule.create("gendarme", "Rule", "Rule").setSeverity(RulePriority.BLOCKER);
    aFileIMoney = new org.sonar.api.resources.File("IMoney");
    aFileMoney = new org.sonar.api.resources.File("Money");

    env = mock(MicrosoftWindowsEnvironment.class);
    VisualStudioSolution solution = mock(VisualStudioSolution.class);
    when(env.getCurrentSolution()).thenReturn(solution);
    VisualStudioProject vsProject = mock(VisualStudioProject.class);
    when(solution.getProjectFromSonarProject(any(Project.class))).thenReturn(vsProject);
    when(solution.getProject(any(File.class))).thenReturn(vsProject);

    project = mock(Project.class);
    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
    when(fileSystem.getSourceDirs()).thenReturn(Lists.newArrayList(new File("C:\\Sonar\\Example")));
    when(project.getFileSystem()).thenReturn(fileSystem);
    resourcesBridge = createFakeBridge();

    resourceHelper = mock(ResourceHelper.class);
    when(resourceHelper.isResourceInProject(any(Resource.class), eq(project))).thenReturn(true);
  }
  @Before
  public void init() {
    project = mock(Project.class);
    ProjectFileSystem pfs = mock(ProjectFileSystem.class);

    // Don't pollute current working directory
    when(pfs.getSonarWorkingDirectory()).thenReturn(new File("target"));

    File baseDir = DelphiUtils.getResource(ROOT_NAME);

    when(project.getLanguage()).thenReturn(DelphiLanguage.instance);
    when(project.getFileSystem()).thenReturn(pfs);
    when(project.getLanguageKey()).thenReturn(DelphiLanguage.KEY);

    when(pfs.getBasedir()).thenReturn(baseDir);

    File srcFile = DelphiUtils.getResource(TEST_FILE);
    List<File> sourceFiles = new ArrayList<File>();
    sourceFiles.add(srcFile);

    when(pfs.getSourceFiles(DelphiLanguage.instance)).thenReturn(sourceFiles);

    sensor = new DelphiPmdSensor(new DebugRuleFinder());
  }
  public void saveMeasures(final Map<String, List<Measure>> measures) {

    if (measures == null) {
      return;
    }

    for (Map.Entry<String, List<Measure>> entry : measures.entrySet()) {
      final org.sonar.api.resources.File objcfile =
          org.sonar.api.resources.File.fromIOFile(
              new File(project.getFileSystem().getBasedir(), entry.getKey()), project);
      if (fileExists(sensorContext, objcfile)) {
        for (Measure measure : entry.getValue()) {
          try {
            LoggerFactory.getLogger(getClass())
                .debug("Save measure {} for file {}", measure.getMetric().getName(), objcfile);
            sensorContext.saveMeasure(objcfile, measure);
          } catch (Exception e) {
            LoggerFactory.getLogger(getClass())
                .error(" Exception -> {} -> {}", entry.getKey(), measure.getMetric().getName());
          }
        }
      }
    }
  }
 /** {@inheritDoc} */
 public void analyse(Project project, SensorContext context) {
   analyse(project.getFileSystem(), context);
   onFinished();
 }
示例#19
0
 private static File getReportsDirectoryFromDefaultConfiguration(Project project) {
   return new File(project.getFileSystem().getBuildDir(), "surefire-reports");
 }
示例#20
0
 /** {@inheritDoc} */
 public boolean shouldExecuteOnProject(Project project) {
   return PhpConstants.LANGUAGE_KEY.equals(project.getLanguageKey())
       && configuration.isDynamicAnalysisEnabled()
       && !configuration.isSkip()
       && !project.getFileSystem().testFiles(PhpConstants.LANGUAGE_KEY).isEmpty();
 }
 private static File getReportFromDefaultPath(Project project, String file) {
   return new File(project.getFileSystem().getBuildDir(), file);
 }
示例#22
0
文件: PmdSensor.java 项目: jerr/sonar
 public boolean shouldExecuteOnProject(Project project) {
   return project.getFileSystem().hasJavaSourceFiles()
       && (!profile.getActiveRulesByRepository(PmdConstants.REPOSITORY_KEY).isEmpty()
           || project.getReuseExistingRulesConfig());
 }
 @Override
 public boolean shouldExecuteOnProject(Project project) {
   return project.getAnalysisType().equals(Project.AnalysisType.DYNAMIC)
       && project.getFileSystem().hasTestFiles(Java.INSTANCE);
 }
示例#24
0
 private FlexConfiguration createConfiguration(Project project) {
   return new FlexConfiguration(project.getFileSystem().getSourceCharset());
 }