Search in sources :

Example 16 with AnalysisContext

use of org.revapi.AnalysisContext in project revapi by revapi.

the class TextReporter method initialize.

@Override
public void initialize(@Nonnull AnalysisContext analysis) {
    // noinspection ConstantConditions
    if (analysis != null) {
        try {
            flushReports();
        } catch (IOException e) {
            throw new IllegalStateException("Failed to output previous analysis report.");
        }
    }
    this.analysis = analysis;
    String minLevel = analysis.getConfiguration().get("minSeverity").asString();
    String output = analysis.getConfiguration().get("output").asString();
    output = "undefined".equals(output) ? "out" : output;
    String templatePath = analysis.getConfiguration().get("template").asString();
    if ("undefined".equals(templatePath)) {
        templatePath = null;
    }
    boolean append = analysis.getConfiguration().get("append").asBoolean(false);
    this.minLevel = "undefined".equals(minLevel) ? DifferenceSeverity.POTENTIALLY_BREAKING : DifferenceSeverity.valueOf(minLevel);
    OutputStream out;
    switch(output) {
        case "out":
            out = System.out;
            break;
        case "err":
            out = System.err;
            break;
        default:
            File f = new File(output);
            if (f.exists() && !f.canWrite()) {
                LOG.warn("The configured file for text reporter, '" + f.getAbsolutePath() + "' is not a writable file." + " Defaulting the output to standard output.");
                out = System.out;
            } else {
                File parent = f.getParentFile();
                if (!parent.exists()) {
                    if (!parent.mkdirs()) {
                        LOG.warn("Failed to create directory structure to write to the configured output file '" + f.getAbsolutePath() + "'. Defaulting the output to standard output.");
                        out = System.out;
                        break;
                    }
                }
                try {
                    out = new FileOutputStream(output, append);
                } catch (FileNotFoundException e) {
                    LOG.warn("Failed to create the configured output file '" + f.getAbsolutePath() + "'." + " Defaulting the output to standard output.", e);
                    out = System.out;
                }
            }
    }
    shouldClose = out != System.out && out != System.err;
    this.output = new PrintWriter(new OutputStreamWriter(out, Charset.forName("UTF-8")));
    this.reports = new TreeSet<>((r1, r2) -> {
        Element r1El = r1.getOldElement() == null ? r1.getNewElement() : r1.getOldElement();
        Element r2El = r2.getOldElement() == null ? r2.getNewElement() : r2.getOldElement();
        // noinspection ConstantConditions
        return r1El.compareTo(r2El);
    });
    Configuration freeMarker = createFreeMarkerConfiguration();
    template = null;
    try {
        template = templatePath == null ? freeMarker.getTemplate("default-template-with-improbable-name@@#(*&$)(.ftl") : freeMarker.getTemplate(templatePath);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to initialize the freemarker template.", e);
    }
}
Also used : Reporter(org.revapi.Reporter) SortedSet(java.util.SortedSet) Report(org.revapi.Report) TemplateException(freemarker.template.TemplateException) Element(org.revapi.Element) LoggerFactory(org.slf4j.LoggerFactory) ClassTemplateLoader(freemarker.cache.ClassTemplateLoader) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) Charset(java.nio.charset.Charset) DifferenceSeverity(org.revapi.DifferenceSeverity) OutputStreamWriter(java.io.OutputStreamWriter) Template(freemarker.template.Template) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) Logger(org.slf4j.Logger) AnalysisContext(org.revapi.AnalysisContext) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Difference(org.revapi.Difference) DefaultObjectWrapperBuilder(freemarker.template.DefaultObjectWrapperBuilder) TemplateLoader(freemarker.cache.TemplateLoader) Configuration(freemarker.template.Configuration) MultiTemplateLoader(freemarker.cache.MultiTemplateLoader) Configuration(freemarker.template.Configuration) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Element(org.revapi.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 17 with AnalysisContext

use of org.revapi.AnalysisContext in project revapi by revapi.

the class ConvertToXmlConfigMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        return;
    }
    AnalyzerBuilder.Result res = buildAnalyzer(project, SimpleReporter.class, Collections.emptyMap());
    if (res.skip) {
        return;
    }
    Revapi revapi = res.analyzer.getRevapi();
    AnalysisContext ctx = AnalysisContext.builder(revapi).build();
    AnalysisResult.Extensions extensions = revapi.prepareAnalysis(ctx);
    Map<String, ModelNode> knownExtensionSchemas;
    try {
        knownExtensionSchemas = getKnownExtensionSchemas(extensions);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to extract the extension schemas from the configured Revapi extensions.", e);
    }
    int indentationSize;
    try (BufferedReader rdr = new BufferedReader(new FileReader(project.getFile()))) {
        indentationSize = XmlUtil.estimateIndentationSize(rdr);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to read pom.xml", e);
    }
    if (convertPomXml) {
        try {
            updateAllConfigurations(project.getFile(), knownExtensionSchemas, indentationSize);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to convert the JSON configuration in pom.xml to XML format.", e);
        }
    }
    if (convertAnalysisConfigurationFiles) {
        try {
            updateAllConfigurationFiles(project, knownExtensionSchemas, indentationSize);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to update the configuration files.", e);
        }
    }
}
Also used : Revapi(org.revapi.Revapi) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) AnalysisContext(org.revapi.AnalysisContext) IOException(java.io.IOException) AnalysisResult(org.revapi.AnalysisResult) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) ModelNode(org.jboss.dmr.ModelNode)

Example 18 with AnalysisContext

use of org.revapi.AnalysisContext in project revapi by revapi.

the class AbstractJavaElementAnalyzerTest method runAnalysis.

protected <R extends Reporter> R runAnalysis(Class<R> reporterType, String configurationJSON, String[] v1Source, String[] v2Source) throws Exception {
    boolean doV1 = v1Source != null && v1Source.length > 0;
    boolean doV2 = v2Source != null && v2Source.length > 0;
    ArchiveAndCompilationPath v1Archive = doV1 ? createCompiledJar("v1", v1Source) : new ArchiveAndCompilationPath(null, null);
    ArchiveAndCompilationPath v2Archive = doV2 ? createCompiledJar("v2", v2Source) : new ArchiveAndCompilationPath(null, null);
    Revapi revapi = createRevapi(reporterType);
    AnalysisContext.Builder bld = AnalysisContext.builder(revapi).withOldAPI(doV1 ? API.of(new ShrinkwrapArchive(v1Archive.archive)).build() : API.builder().build()).withNewAPI(doV2 ? API.of(new ShrinkwrapArchive(v2Archive.archive)).build() : API.builder().build());
    if (configurationJSON != null) {
        bld.withConfigurationFromJSON(configurationJSON);
    }
    AnalysisContext ctx = bld.build();
    revapi.validateConfiguration(ctx);
    try (AnalysisResult result = revapi.analyze(ctx)) {
        result.throwIfFailed();
        return result.getExtensions().getFirstExtension(reporterType, null);
    } finally {
        if (doV1) {
            deleteDir(v1Archive.compilationPath);
        }
        if (doV2) {
            deleteDir(v2Archive.compilationPath);
        }
    }
}
Also used : Revapi(org.revapi.Revapi) AnalysisContext(org.revapi.AnalysisContext) AnalysisResult(org.revapi.AnalysisResult)

Example 19 with AnalysisContext

use of org.revapi.AnalysisContext in project revapi by revapi.

the class TextReporterTest method testDefaultTemplate.

@Test
public void testDefaultTemplate() throws Exception {
    TextReporter reporter = new TextReporter();
    Revapi r = new Revapi(emptySet(), singleton(TextReporter.class), emptySet(), emptySet());
    AnalysisContext ctx = AnalysisContext.builder(r).withOldAPI(API.of(new FileArchive(new File("old-dummy.archive"))).build()).withNewAPI(API.of(new FileArchive(new File("new-dummy.archive"))).build()).build();
    AnalysisContext reporterCtx = r.prepareAnalysis(ctx).getFirstConfigurationOrNull(TextReporter.class);
    reporter.initialize(reporterCtx);
    buildReports().forEach(reporter::report);
    StringWriter out = new StringWriter();
    PrintWriter wrt = new PrintWriter(out);
    reporter.setOutput(wrt);
    reporter.close();
    String expected = "Analysis results\n" + "----------------\n" + "\n" + "Old API: old-dummy.archive\n" + "New API: new-dummy.archive\n" + "old: old1\n" + "new: new1\n" + "code1: descr1\n" + "SOURCE: BREAKING\n" + "\n" + "old: old2\n" + "new: new2\n" + "code2: descr2\n" + "BINARY: BREAKING\n\n";
    Assert.assertEquals(expected, out.toString());
}
Also used : Revapi(org.revapi.Revapi) StringWriter(java.io.StringWriter) FileArchive(org.revapi.simple.FileArchive) AnalysisContext(org.revapi.AnalysisContext) File(java.io.File) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 20 with AnalysisContext

use of org.revapi.AnalysisContext in project revapi by revapi.

the class TextReporterTest method testCustomTemplate.

@Test
public void testCustomTemplate() throws Exception {
    Path tempFile = Files.createTempFile(new File(".").toPath(), "text-report-test", ".ftl");
    try {
        Files.copy(getClass().getResourceAsStream("/custom-template.ftl"), tempFile, StandardCopyOption.REPLACE_EXISTING);
        TextReporter reporter = new TextReporter();
        Revapi r = new Revapi(emptySet(), singleton(TextReporter.class), emptySet(), emptySet());
        AnalysisContext ctx = AnalysisContext.builder(r).withConfigurationFromJSON("{\"revapi\": {\"reporter\": {\"text\": {\"template\": \"" + tempFile.toString() + "\"}}}}").withOldAPI(API.of(new FileArchive(new File("old-dummy.archive"))).build()).withNewAPI(API.of(new FileArchive(new File("new-dummy.archive"))).build()).build();
        AnalysisContext reporterCtx = r.prepareAnalysis(ctx).getFirstConfigurationOrNull(TextReporter.class);
        reporter.initialize(reporterCtx);
        buildReports().forEach(reporter::report);
        StringWriter out = new StringWriter();
        PrintWriter wrt = new PrintWriter(out);
        reporter.setOutput(wrt);
        reporter.close();
        String expected = "old1 VS new1\nold2 VS new2\n";
        Assert.assertEquals(expected, out.toString());
    } finally {
        Files.delete(tempFile);
    }
}
Also used : Path(java.nio.file.Path) Revapi(org.revapi.Revapi) StringWriter(java.io.StringWriter) FileArchive(org.revapi.simple.FileArchive) AnalysisContext(org.revapi.AnalysisContext) File(java.io.File) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Aggregations

AnalysisContext (org.revapi.AnalysisContext)25 Test (org.junit.Test)15 Revapi (org.revapi.Revapi)13 Difference (org.revapi.Difference)7 API (org.revapi.API)6 AnalysisResult (org.revapi.AnalysisResult)6 Report (org.revapi.Report)6 ModelNode (org.jboss.dmr.ModelNode)4 File (java.io.File)3 PrintWriter (java.io.PrintWriter)3 Element (org.revapi.Element)3 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 Nonnull (javax.annotation.Nonnull)2 JavaModelElement (org.revapi.java.spi.JavaModelElement)2 FileArchive (org.revapi.simple.FileArchive)2 ClassTemplateLoader (freemarker.cache.ClassTemplateLoader)1 MultiTemplateLoader (freemarker.cache.MultiTemplateLoader)1 TemplateLoader (freemarker.cache.TemplateLoader)1 Configuration (freemarker.template.Configuration)1