Skip to content

Commit

Permalink
Implement sensor to import Clang static analyzer multi-plist output.
Browse files Browse the repository at this point in the history
Intended to be used with xcodebuild's 'analyze' action, allows setting
the sonar.objectivec.clang.reportsPath property to the directory
containing the Clang plist report files.
  • Loading branch information
mjdetullio committed Oct 23, 2015
1 parent bc5f797 commit d7426ff
Show file tree
Hide file tree
Showing 8 changed files with 534 additions and 1 deletion.
7 changes: 6 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@
<dependency>
<groupId>org.codehaus.sonar.sslr-squid-bridge</groupId>
<artifactId>sslr-squid-bridge</artifactId>
<version>2.4</version>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>ant</groupId>
Expand Down Expand Up @@ -188,6 +188,11 @@
<version>1.0.b2</version>
</dependency>

<dependency>
<groupId>com.googlecode.plist</groupId>
<artifactId>dd-plist</artifactId>
<version>1.16</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

import com.google.common.collect.ImmutableList;

import org.sonar.plugins.objectivec.issues.ClangRulesDefinition;
import org.sonar.plugins.objectivec.issues.ClangSensor;
import org.sonar.plugins.objectivec.tests.SurefireSensor;
import org.sonar.plugins.objectivec.violations.OCLintProfile;
import org.sonar.plugins.objectivec.violations.OCLintProfileImporter;
Expand All @@ -59,6 +61,9 @@ public List<Class<? extends Extension>> getExtensions() {

CoberturaSensor.class,

ClangRulesDefinition.class,
ClangSensor.class,

OCLintRuleRepository.class,
OCLintSensor.class,
OCLintProfile.class,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* Sonar Objective-C Plugin
* Copyright (C) 2012 OCTO Technology
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.objectivec.issues;

import com.dd.plist.PropertyListFormatException;
import com.dd.plist.XMLPropertyListParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.XmlParserException;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author Matthew DeTullio
*/
public class ClangPlistParser {
private static final Logger LOGGER = LoggerFactory.getLogger(ClangPlistParser.class.getName());

public static List<ClangWarning> parse(File reportsDir) {
List<ClangWarning> result = new ArrayList<ClangWarning>();

File[] reports = getReports(reportsDir);

for (File report : reports) {
try {
result.addAll(parsePlist(report));
} catch (Exception e) {
throw new XmlParserException("Unable to parse Clang reports", e);
}
}

return result;
}

private static File[] getReports(final File reportsDir) {
if (reportsDir == null || !reportsDir.isDirectory() || !reportsDir.exists()) {
return new File[0];
}

return reportsDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".plist");
}
});
}

@SuppressWarnings("unchecked")
private static List<ClangWarning> parsePlist(final File file) {
List<ClangWarning> result = new ArrayList<ClangWarning>();

try {
// Clang report is NSDictionary, which converts to a Map
Map<String, Object> report =
(Map<String, Object>) XMLPropertyListParser.parse(file).toJavaObject();

// Files reported on in this report
List<String> files = new ArrayList<String>();
for (Object obj : (Object[]) report.get("files")) {
files.add((String) obj);
}

// Diagnostics which contain the warning and the execution path
// (we're only interested in the final location)
List<Map<String, Object>> diagnostics = new ArrayList<Map<String, Object>>();
for (Object obj : (Object[]) report.get("diagnostics")) {
diagnostics.add((Map<String, Object>) obj);
}

// Extract warning type, line number, and file, then add to results
for (Map<String, Object> diagnostic : diagnostics) {
Map<String, Object> location = (Map<String, Object>) diagnostic.get("location");

ClangWarning clangWarning = new ClangWarning();
clangWarning.setCategory((String) diagnostic.get("category"));
// file is an integer representing the index of the file in the files array
clangWarning.setFile(new File(files.get((Integer) location.get("file"))));
clangWarning.setLine((Integer) location.get("line"));
clangWarning.setType((String) diagnostic.get("type"));

result.add(clangWarning);
}
} catch (final IOException e) {
LOGGER.error("Error processing file named {}", file, e);
} catch (final ParserConfigurationException e) {
LOGGER.error("Error processing file named {}", file, e);
} catch (final ParseException e) {
LOGGER.error("Error processing file named {}", file, e);
} catch (final SAXException e) {
LOGGER.error("Error processing file named {}", file, e);
} catch (final PropertyListFormatException e) {
LOGGER.error("Error processing file named {}", file, e);
}

return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Sonar Objective-C Plugin
* Copyright (C) 2012 OCTO Technology
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.objectivec.issues;

import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinitionXmlLoader;
import org.sonar.plugins.objectivec.core.ObjectiveC;
import org.sonar.squidbridge.rules.SqaleXmlLoader;

/**
* @author Matthew DeTullio
*/
public class ClangRulesDefinition implements RulesDefinition {
public static final String REPOSITORY_KEY = "clang";
public static final String REPOSITORY_NAME = "Clang";

@Override
public void define(Context context) {
NewRepository repository = context
.createRepository(REPOSITORY_KEY, ObjectiveC.KEY)
.setName(REPOSITORY_NAME);

RulesDefinitionXmlLoader ruleLoader = new RulesDefinitionXmlLoader();
ruleLoader.load(
repository,
ClangRulesDefinition.class.getResourceAsStream("/org/sonar/plugins/objectivec/rules-clang.xml"),
"UTF-8");

SqaleXmlLoader.load(repository, "/com/sonar/sqale/clang-model.xml");

repository.done();
}
}
107 changes: 107 additions & 0 deletions src/main/java/org/sonar/plugins/objectivec/issues/ClangSensor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Sonar Objective-C Plugin
* Copyright (C) 2012 OCTO Technology
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.objectivec.issues;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.Sensor;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.component.ResourcePerspectives;
import org.sonar.api.config.Settings;
import org.sonar.api.issue.Issuable;
import org.sonar.api.issue.Issue;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.api.rule.RuleKey;
import org.sonar.plugins.objectivec.ObjectiveCPlugin;
import org.sonar.plugins.objectivec.core.ObjectiveC;

import java.io.File;
import java.util.List;

/**
* @author Matthew DeTullio
*/
public class ClangSensor implements Sensor {
private static final Logger LOGGER = LoggerFactory.getLogger(ClangSensor.class.getName());

private static final String REPORT_PATH_KEY = ObjectiveCPlugin.PROPERTY_PREFIX + ".clang.reportsPath";

private FileSystem fileSystem;
private ResourcePerspectives resourcePerspectives;
private RulesProfile rulesProfile;
private Settings settings;

public ClangSensor(FileSystem fileSystem, ResourcePerspectives resourcePerspectives, RulesProfile rulesProfile, Settings settings) {
this.fileSystem = fileSystem;
this.resourcePerspectives = resourcePerspectives;
this.rulesProfile = rulesProfile;
this.settings = settings;
}

@Override
public boolean shouldExecuteOnProject(Project project) {
return project.isRoot() && fileSystem.hasFiles(fileSystem.predicates().hasLanguage(ObjectiveC.KEY))
&& !rulesProfile.getActiveRulesByRepository(ClangRulesDefinition.REPOSITORY_KEY).isEmpty();
}

@Override
public void analyse(Project project, SensorContext context) {
String reportPath = settings.getString(REPORT_PATH_KEY);
if (reportPath == null) {
return;
}

LOGGER.info("Processing Clang reports path: {}", reportPath);

List<ClangWarning> clangWarnings = ClangPlistParser.parse(new File(reportPath));

for (ClangWarning clangWarning : clangWarnings) {
// TODO: Add check for enabled rule if/when rules get split up

Resource resource = context.getResource(
org.sonar.api.resources.File.fromIOFile(clangWarning.getFile(), project));

if (resource == null) {
LOGGER.debug("Skipping file (not found in index): {}", clangWarning.getFile().getPath());
continue;
}

Issuable issuable = resourcePerspectives.as(Issuable.class, resource);

if (issuable != null) {
Issue issue = issuable.newIssueBuilder()
.ruleKey(RuleKey.of(ClangRulesDefinition.REPOSITORY_KEY, "other"))
.message(String.format("%s - %s", clangWarning.getCategory(), clangWarning.getType()))
.line(clangWarning.getLine())
.build();

issuable.addIssue(issue);
}
}
}

@Override
public String toString() {
return "Objective-C Clang Sensor";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Sonar Objective-C Plugin
* Copyright (C) 2012 OCTO Technology
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.objectivec.issues;

import java.io.File;

/**
* @author Matthew DeTullio
*/
public class ClangWarning {
private String category;
private File file;
private Integer line;
private String type;

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

public File getFile() {
return file;
}

public void setFile(File file) {
this.file = file;
}

public Integer getLine() {
return line;
}

public void setLine(Integer line) {
this.line = line;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}
}
Loading

0 comments on commit d7426ff

Please sign in to comment.