Search in sources :

Example 1 with GeneratorException

use of net.morimekta.providence.generator.GeneratorException in project providence by morimekta.

the class BaseGenerateSourcesMojo method executeInternal.

boolean executeInternal(IncludeExcludeFileSelector includeDirs, File outputDir, IncludeExcludeFileSelector inputSelector, String defaultInputIncludes, boolean testCompile) throws MojoExecutionException, MojoFailureException {
    Set<File> inputFiles = ProvidenceInput.getInputFiles(project, inputSelector, defaultInputIncludes, print_debug, getLog());
    if (inputFiles.isEmpty()) {
        return false;
    }
    if (!outputDir.exists()) {
        if (!outputDir.mkdirs()) {
            throw new MojoExecutionException("Unable to create target directory " + outputDir);
        }
    }
    TreeSet<File> includes = new TreeSet<>();
    File workingDir = new File(buildDir, testCompile ? "providence-test" : "providence");
    File[] deleteFiles = workingDir.listFiles();
    if (!workingDir.exists()) {
        if (!workingDir.mkdirs()) {
            throw new MojoExecutionException("Unable to create working directory " + workingDir);
        }
    } else if (deleteFiles != null) {
        StreamSupport.<File>stream(Spliterators.spliterator(deleteFiles, Spliterator.DISTINCT | Spliterator.IMMUTABLE), false).forEach(File::delete);
    }
    Set<Artifact> resolvedArtifacts = new HashSet<>();
    for (Dependency dep : dependencies) {
        if (testCompile || !TEST.equalsIgnoreCase(dep.getScope())) {
            resolveDependency(dep, includes, workingDir, resolvedArtifacts);
        }
    }
    if (includeDirs != null) {
        DirectoryScanner includeScanner = new DirectoryScanner();
        includeScanner.setIncludes(includeDirs.getIncludes());
        if (includeDirs.getExcludes() != null) {
            includeScanner.setExcludes(includeDirs.getExcludes());
        }
        includeScanner.setBasedir(project.getBasedir());
        includeScanner.scan();
        for (String dir : includeScanner.getIncludedDirectories()) {
            includes.add(new File(project.getBasedir(), dir));
        }
        for (String dir : includeScanner.getExcludedDirectories()) {
            includes.remove(new File(project.getBasedir(), dir));
        }
    }
    FileManager fileManager = new FileManager(outputDir);
    ProgramParser parser = new ThriftProgramParser(require_field_id, require_enum_value, allow_language_reserved_names);
    TypeLoader loader = new TypeLoader(includes, parser);
    if (print_debug) {
        inputFiles.stream().filter(Objects::nonNull).map(file -> {
            try {
                return file.getAbsoluteFile().getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }).sorted().forEach(f -> getLog().info("Compiling: " + f));
    }
    JavaOptions javaOptions = new JavaOptions();
    javaOptions.android = android;
    javaOptions.jackson = jackson;
    javaOptions.rw_binary = rw_binary;
    javaOptions.hazelcast_portable = hazelcast_portable;
    javaOptions.generated_annotation_version = generated_annotation_version;
    javaOptions.public_constructors = public_constructors;
    GeneratorOptions generatorOptions = new GeneratorOptions();
    generatorOptions.generator_program_name = "providence-maven-plugin";
    generatorOptions.program_version = getVersionString();
    GeneratorFactory factory = new JavaGeneratorFactory();
    Generator generator = new JavaGenerator(fileManager, generatorOptions, javaOptions);
    Path base = project.getBasedir().toPath().toAbsolutePath();
    if (project.getParent() != null && project.getParent().getBasedir() != null) {
        // Only replace with parent if parent is a parent directory of this.
        Path parentBase = project.getParent().getBasedir().toPath().toAbsolutePath();
        if (base.toString().startsWith(parentBase.toString())) {
            base = parentBase;
        }
    }
    for (File in : inputFiles) {
        ProgramTypeRegistry registry;
        try {
            registry = loader.load(in);
        } catch (SerializerException e) {
            // ParseException is a SerializerException. And serialize exceptions can come from
            // failing to make sense of constant definitions.
            getLog().error("    ============ >> PROVIDENCE << ============");
            getLog().error("");
            Arrays.stream(e.asString().split("\r?\n")).forEach(l -> getLog().error(l));
            getLog().error("");
            getLog().error("    ============ << PROVIDENCE >> ============");
            throw new MojoFailureException("Failed to parse thrift file: " + in.getName(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read thrift file: " + in.getName(), e);
        }
        try {
            if (skipIfMissingNamespace && registry.getProgram().getNamespaceForLanguage(factory.generatorName()) == null) {
                getLog().warn("Skipping (no " + factory.generatorName() + " namespace) " + base.relativize(in.toPath()));
                continue;
            }
            generator.generate(registry);
        } catch (GeneratorException e) {
            throw new MojoFailureException("Failed to generate program: " + registry.getProgram().getProgramName(), e);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to write program file: " + registry.getProgram().getProgramName(), e);
        }
    }
    try {
        generator.generateGlobal(loader.getProgramRegistry(), inputFiles);
    } catch (GeneratorException e) {
        throw new MojoFailureException("Failed to generate global", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to write global file", e);
    }
    return compileOutput;
}
Also used : Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) ArtifactResolutionRequest(org.apache.maven.artifact.resolver.ArtifactResolutionRequest) Spliterators(java.util.Spliterators) Parameter(org.apache.maven.plugins.annotations.Parameter) IncludeExcludeFileSelector(org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector) MavenProject(org.apache.maven.project.MavenProject) Strings(net.morimekta.util.Strings) Artifact(org.apache.maven.artifact.Artifact) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) GeneratorException(net.morimekta.providence.generator.GeneratorException) Set(java.util.Set) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) ArtifactResolver(org.apache.maven.artifact.resolver.ArtifactResolver) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) FileManager(net.morimekta.providence.generator.util.FileManager) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) Spliterator(java.util.Spliterator) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) AbstractMojo(org.apache.maven.plugin.AbstractMojo) ZipInputStream(java.util.zip.ZipInputStream) Generator(net.morimekta.providence.generator.Generator) Dependency(org.apache.maven.model.Dependency) Component(org.apache.maven.plugins.annotations.Component) ProvidenceInput(net.morimekta.providence.maven.util.ProvidenceInput) ProgramParser(net.morimekta.providence.reflect.parser.ProgramParser) ArtifactResolutionResult(org.apache.maven.artifact.resolver.ArtifactResolutionResult) TreeSet(java.util.TreeSet) BufferedOutputStream(java.io.BufferedOutputStream) HashSet(java.util.HashSet) ArtifactRepository(org.apache.maven.artifact.repository.ArtifactRepository) ProvidenceDependency(net.morimekta.providence.maven.util.ProvidenceDependency) StreamSupport(java.util.stream.StreamSupport) IOUtils(net.morimekta.util.io.IOUtils) Properties(java.util.Properties) JavaOptions(net.morimekta.providence.generator.format.java.JavaOptions) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) File(java.io.File) ReflectionUtils(net.morimekta.providence.reflect.util.ReflectionUtils) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Paths(java.nio.file.Paths) RepositorySystem(org.apache.maven.repository.RepositorySystem) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) SerializerException(net.morimekta.providence.serializer.SerializerException) TypeLoader(net.morimekta.providence.reflect.TypeLoader) InputStream(java.io.InputStream) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) ProgramParser(net.morimekta.providence.reflect.parser.ProgramParser) TypeLoader(net.morimekta.providence.reflect.TypeLoader) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) TreeSet(java.util.TreeSet) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) GeneratorException(net.morimekta.providence.generator.GeneratorException) ThriftProgramParser(net.morimekta.providence.reflect.parser.ThriftProgramParser) HashSet(java.util.HashSet) Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Dependency(org.apache.maven.model.Dependency) ProvidenceDependency(net.morimekta.providence.maven.util.ProvidenceDependency) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) SerializerException(net.morimekta.providence.serializer.SerializerException) Artifact(org.apache.maven.artifact.Artifact) FileManager(net.morimekta.providence.generator.util.FileManager) JavaGeneratorFactory(net.morimekta.providence.generator.format.java.JavaGeneratorFactory) GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) JavaOptions(net.morimekta.providence.generator.format.java.JavaOptions) File(java.io.File) Generator(net.morimekta.providence.generator.Generator) JavaGenerator(net.morimekta.providence.generator.format.java.JavaGenerator)

Example 2 with GeneratorException

use of net.morimekta.providence.generator.GeneratorException in project providence by morimekta.

the class BuilderCoreOverridesFormatter method appendOverrideAdder.

private void appendOverrideAdder(JMessage<?> message) throws GeneratorException {
    writer.appendln("@Override").appendln("public _Builder addTo(int key, Object value) {").begin().appendln("switch (key) {").begin();
    message.numericalOrderFields().stream().filter(field -> field.type() == PType.LIST || field.type() == PType.SET).forEachOrdered(field -> {
        PContainer<?> ct = (PContainer<?>) field.field().getDescriptor();
        PDescriptor itype = ct.itemDescriptor();
        writer.formatln("case %d: %s((%s) value); break;", field.id(), field.adder(), helper.getValueType(itype));
    });
    writer.appendln("default: break;").end().appendln('}').appendln("return this;").end().appendln('}').newline();
}
Also used : PDescriptor(net.morimekta.providence.descriptor.PDescriptor) MessageMemberFormatter(net.morimekta.providence.generator.format.java.shared.MessageMemberFormatter) GeneratorException(net.morimekta.providence.generator.GeneratorException) IndentedPrintWriter(net.morimekta.util.io.IndentedPrintWriter) PContainer(net.morimekta.providence.descriptor.PContainer) JMessage(net.morimekta.providence.generator.format.java.utils.JMessage) ArrayList(java.util.ArrayList) PType(net.morimekta.providence.PType) UNION_FIELD(net.morimekta.providence.generator.format.java.messages.CoreOverridesFormatter.UNION_FIELD) JHelper(net.morimekta.providence.generator.format.java.utils.JHelper) Strings(net.morimekta.util.Strings) PMessageBuilder(net.morimekta.providence.PMessageBuilder) JAnnotation(net.morimekta.providence.generator.format.java.utils.JAnnotation) JField(net.morimekta.providence.generator.format.java.utils.JField) PDescriptor(net.morimekta.providence.descriptor.PDescriptor) PContainer(net.morimekta.providence.descriptor.PContainer)

Example 3 with GeneratorException

use of net.morimekta.providence.generator.GeneratorException in project providence by morimekta.

the class HazelcastPortableProgramFormatter method appendTypeField.

private void appendTypeField(JField field) {
    if (field.portableRequiresBinarySerialization()) {
        writer.formatln(".addByteArrayField(\"%s\")", field.name());
        return;
    }
    switch(field.type()) {
        case BINARY:
            writer.formatln(".addByteArrayField(\"%s\")", field.name());
            break;
        case BYTE:
            writer.formatln(".addByteField(\"%s\")", field.name());
            break;
        case BOOL:
            writer.formatln(".addBooleanField(\"%s\")", field.name());
            break;
        case DOUBLE:
            writer.formatln(".addDoubleField(\"%s\")", field.name());
            break;
        case ENUM:
        case I32:
            writer.formatln(".addIntField(\"%s\")", field.name());
            break;
        case I16:
            writer.formatln(".addShortField(\"%s\")", field.name());
            break;
        case I64:
            writer.formatln(".addLongField(\"%s\")", field.name());
            break;
        case STRING:
            writer.formatln(".addUTFField(\"%s\")", field.name());
            break;
        case LIST:
            final PList pList = field.toPList();
            appendCollectionTypeField(field, pList.itemDescriptor());
            break;
        case SET:
            final PSet pSet = field.toPSet();
            appendCollectionTypeField(field, pSet.itemDescriptor());
            break;
        case MESSAGE:
            writer.formatln(".addPortableField(\"%s\", %s(%s))", field.name(), camelCase("get", field.field().getDescriptor().getName() + "Definition"), PORTABLE_VERSION);
            break;
        default:
            throw new GeneratorException("Not implemented appendTypeField for type: " + field.type() + " in " + this.getClass().getSimpleName());
    }
}
Also used : PList(net.morimekta.providence.descriptor.PList) PSet(net.morimekta.providence.descriptor.PSet) GeneratorException(net.morimekta.providence.generator.GeneratorException)

Example 4 with GeneratorException

use of net.morimekta.providence.generator.GeneratorException in project providence by morimekta.

the class GeneratorOptions method getGenerator.

public Generator getGenerator(TypeLoader loader) throws ArgumentException, GeneratorException, IOException {
    net.morimekta.providence.generator.GeneratorOptions generatorOptions = new net.morimekta.providence.generator.GeneratorOptions();
    generatorOptions.generator_program_name = "pvdgen";
    generatorOptions.program_version = Utils.getVersionString();
    try {
        return gen.factory.createGenerator(getFileManager(), generatorOptions, gen.options);
    } catch (GeneratorException e) {
        throw new ArgumentException(e, e.getMessage());
    }
}
Also used : ArgumentException(net.morimekta.console.args.ArgumentException) GeneratorException(net.morimekta.providence.generator.GeneratorException)

Example 5 with GeneratorException

use of net.morimekta.providence.generator.GeneratorException in project providence by morimekta.

the class BuilderCommonMemberFormatter method appendMutableGetters.

/**
 * Get mutable values. This returns message builders for messages, collection
 * builders for collections, and the normal immutable value for everything
 * else.
 *
 * @param message The message to get mutable getters for.
 * @param field The field to generate getter for.
 */
private void appendMutableGetters(JMessage message, JField field) throws GeneratorException {
    if (field.field().getDescriptor() instanceof PPrimitive || field.type() == PType.ENUM) {
        // The other fields will have ordinary non-mutable getters.
        appendGetter(field);
        return;
    }
    BlockCommentBuilder comment = new BlockCommentBuilder(writer);
    if (field.hasComment()) {
        comment.comment(field.comment());
    } else {
        comment.comment("Gets the builder for the contained " + field.name() + ".");
    }
    comment.newline().return_("The field builder");
    if (JAnnotation.isDeprecated(field)) {
        String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
        if (reason != null && reason.trim().length() > 0) {
            comment.deprecated_(reason);
        }
    }
    comment.finish();
    if (JAnnotation.isDeprecated(field)) {
        writer.appendln(JAnnotation.DEPRECATED);
    }
    writer.appendln(JAnnotation.NON_NULL);
    switch(field.type()) {
        case MESSAGE:
            {
                writer.formatln("public %s._Builder %s() {", field.instanceType(), field.mutable()).begin();
                if (message.isUnion()) {
                    writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum()).formatln("    %s();", field.resetter()).appendln('}').formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum());
                    writer.appendln("modified = true;");
                } else {
                    writer.formatln("optionals.set(%d);", field.index());
                    writer.formatln("modified.set(%d);", field.index());
                }
                writer.newline().formatln("if (%s != null) {", field.member()).formatln("    %s_builder = %s.mutate();", field.member(), field.member()).formatln("    %s = null;", field.member()).formatln("} else if (%s_builder == null) {", field.member()).formatln("    %s_builder = %s.builder();", field.member(), field.instanceType()).appendln('}').formatln("return %s_builder;", field.member());
                writer.end().appendln('}').newline();
                // Also add "normal" getter for the message field, which will
                // return the message or the builder dependent on which is set.
                // It will not change the state of the builder.
                comment = new BlockCommentBuilder(writer);
                if (field.hasComment()) {
                    comment.comment(field.comment());
                } else {
                    comment.comment("Gets the value for the contained " + field.name() + ".");
                }
                comment.newline().return_("The field value");
                if (JAnnotation.isDeprecated(field)) {
                    String reason = field.field().getAnnotationValue(ThriftAnnotation.DEPRECATED);
                    if (reason != null && reason.trim().length() > 0) {
                        comment.deprecated_(reason);
                    }
                }
                comment.finish();
                if (JAnnotation.isDeprecated(field)) {
                    writer.appendln(JAnnotation.DEPRECATED);
                }
                writer.formatln("public %s %s() {", field.instanceType(), field.getter()).begin();
                if (message.isUnion()) {
                    writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum()).formatln("    return null;").appendln('}');
                }
                writer.newline().formatln("if (%s_builder != null) {", field.member()).formatln("    return %s_builder.build();", field.member()).appendln('}').formatln("return %s;", field.member());
                writer.end().appendln('}').newline();
                break;
            }
        case SET:
        case LIST:
        case MAP:
            writer.formatln("public %s %s() {", field.fieldType(), field.mutable()).begin();
            if (message.isUnion()) {
                writer.formatln("if (%s != _Field.%s) {", UNION_FIELD, field.fieldEnum()).formatln("    %s();", field.resetter()).appendln('}').formatln("%s = _Field.%s;", UNION_FIELD, field.fieldEnum());
                writer.appendln("modified = true;");
            } else {
                writer.formatln("optionals.set(%d);", field.index());
                writer.formatln("modified.set(%d);", field.index());
            }
            writer.newline().formatln("if (%s == null) {", field.member()).formatln("    %s = new %s<>();", field.member(), field.builderMutableType()).formatln("} else if (!(%s instanceof %s)) {", field.member(), field.builderMutableType()).formatln("    %s = new %s<>(%s);", field.member(), field.builderMutableType(), field.member()).appendln("}");
            writer.formatln("return %s;", field.member());
            writer.end().appendln('}').newline();
            break;
        default:
            throw new GeneratorException("Unexpected field type: " + field.type());
    }
}
Also used : BlockCommentBuilder(net.morimekta.providence.generator.format.java.utils.BlockCommentBuilder) GeneratorException(net.morimekta.providence.generator.GeneratorException) PPrimitive(net.morimekta.providence.descriptor.PPrimitive)

Aggregations

GeneratorException (net.morimekta.providence.generator.GeneratorException)11 IOException (java.io.IOException)3 PDescriptor (net.morimekta.providence.descriptor.PDescriptor)3 Generator (net.morimekta.providence.generator.Generator)3 GeneratorOptions (net.morimekta.providence.generator.GeneratorOptions)3 BlockCommentBuilder (net.morimekta.providence.generator.format.java.utils.BlockCommentBuilder)3 BufferedOutputStream (java.io.BufferedOutputStream)2 File (java.io.File)2 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Generated (javax.annotation.Generated)2 ArgumentException (net.morimekta.console.args.ArgumentException)2 PType (net.morimekta.providence.PType)2 PContainer (net.morimekta.providence.descriptor.PContainer)2 PDeclaredDescriptor (net.morimekta.providence.descriptor.PDeclaredDescriptor)2 PList (net.morimekta.providence.descriptor.PList)2 PSet (net.morimekta.providence.descriptor.PSet)2 GeneratorFactory (net.morimekta.providence.generator.GeneratorFactory)2