Search in sources :

Example 1 with GeneratorFactory

use of net.morimekta.providence.generator.GeneratorFactory 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 GeneratorFactory

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

the class FactoryLoaderTest method testLoader.

@Test
public void testLoader() {
    GeneratorOptions options = new GeneratorOptions();
    options.generator_program_name = "loader-test";
    options.program_version = "1.0";
    ResourceUtils.copyResourceTo("/test.jar", tmp.getRoot());
    List<GeneratorFactory> factories = loader.getFactories(tmp.getRoot());
    assertThat(factories, hasSize(1));
    GeneratorFactory factory = factories.get(0);
    assertThat(factory.generatorName(), is("js"));
    assertThat(factory.generatorDescription(), is("Generates JavaScript (es5.1 or es6)."));
    // Make sure we can instantiate the generator.
    Generator generator = factory.createGenerator(new FakeFileManager(tmp.getRoot()), options, ImmutableList.of());
    assertThat(generator, is(notNullValue()));
}
Also used : GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) GeneratorOptions(net.morimekta.providence.generator.GeneratorOptions) Generator(net.morimekta.providence.generator.Generator) Test(org.junit.Test)

Example 3 with GeneratorFactory

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

the class GeneratorSpecParser method parse.

@Override
public GeneratorSpec parse(String spec) {
    Map<String, GeneratorFactory> factoryMap = generatorFactoryMap.get();
    ArrayList<String> options = new ArrayList<>();
    String[] gen = spec.split("[:]");
    if (gen.length > 2) {
        throw new ArgumentException("Invalid generator spec, only one ':' allowed: " + spec);
    }
    GeneratorFactory factory = factoryMap.get(gen[0].toLowerCase());
    if (factory == null) {
        throw new ArgumentException("Unknown output language " + gen[0]);
    }
    if (gen.length == 2) {
        Collections.addAll(options, gen[1].split("[,]"));
    }
    return new GeneratorSpec(factory, options);
}
Also used : GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) ArrayList(java.util.ArrayList) ArgumentException(net.morimekta.console.args.ArgumentException)

Example 4 with GeneratorFactory

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

the class GeneratorMain method run.

public void run(String... args) {
    try {
        ArgumentParser cli = options.getArgumentParser("pvdgen", "Providence generator");
        cli.parse(args);
        if (options.isHelp()) {
            System.out.println("Providence generator - " + Utils.getVersionString());
            System.out.println("Usage: pvdgen [-I dir] [-o dir] -g generator[:opt[,opt]*] file...");
            System.out.println();
            if (options.help.factory != null) {
                System.out.format("%s : %s%n", options.help.factory.generatorName(), options.help.factory.generatorDescription());
                System.out.println();
                System.out.println("Available options");
                System.out.println();
                options.help.factory.printGeneratorOptionsHelp(System.out);
            } else {
                System.out.println("Example code to run:");
                System.out.println("$ pvdgen -I thrift/ --out target/ --gen java:android thrift/the-one.thrift");
                System.out.println();
                cli.printUsage(System.out);
                System.out.println();
                System.out.println("Available generators:");
                Map<String, GeneratorFactory> factories = options.getFactories();
                for (GeneratorFactory lang : factories.values()) {
                    System.out.format(" - %-10s : %s%n", lang.generatorName(), lang.generatorDescription());
                }
            }
            return;
        } else if (options.version) {
            System.out.println("Providence generator - " + Utils.getVersionString());
            return;
        }
        cli.validate();
        ProgramParser parser = options.getParser();
        List<File> includes = options.getIncludes();
        List<File> input = options.getInputFiles();
        TypeLoader loader = new TypeLoader(includes, parser);
        Generator generator = options.getGenerator(loader);
        for (File f : input) {
            ProgramTypeRegistry registry = loader.load(f);
            if (options.skipIfMissingNamespace && registry.getProgram().getNamespaceForLanguage(options.gen.factory.generatorName()) == null) {
                System.out.println("Skipping (no " + options.gen.factory.generatorName() + " namespace) " + f.getCanonicalFile().getAbsolutePath());
            }
            generator.generate(loader.load(f));
        }
        generator.generateGlobal(loader.getProgramRegistry(), input);
        return;
    } catch (ArgumentException e) {
        System.err.println("Usage: pvdgen [-I dir] [-o dir] -g generator[:opt[,opt]*] file...");
        System.err.println(e.getLocalizedMessage());
        System.err.println();
        System.err.println("Run $ pvdgen --help # for available options.");
        if (options.verbose) {
            e.printStackTrace();
        }
    } catch (ParseException e) {
        System.err.println(e.asString());
        if (options.verbose) {
            e.printStackTrace();
        }
    } catch (IllegalArgumentException e) {
        System.err.println(e.getMessage());
        if (options.verbose) {
            e.printStackTrace();
        }
    } catch (GeneratorException e) {
        System.err.println("Generator error: " + e.getMessage());
        if (options.verbose) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        System.err.println("I/O error: " + e.getMessage());
        if (options.verbose) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    exit(1);
}
Also used : ProgramParser(net.morimekta.providence.reflect.parser.ProgramParser) TypeLoader(net.morimekta.providence.reflect.TypeLoader) IOException(java.io.IOException) ArgumentParser(net.morimekta.console.args.ArgumentParser) GeneratorException(net.morimekta.providence.generator.GeneratorException) IOException(java.io.IOException) ParseException(net.morimekta.providence.reflect.parser.ParseException) ArgumentException(net.morimekta.console.args.ArgumentException) GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) ProgramTypeRegistry(net.morimekta.providence.reflect.util.ProgramTypeRegistry) ArgumentException(net.morimekta.console.args.ArgumentException) ParseException(net.morimekta.providence.reflect.parser.ParseException) GeneratorException(net.morimekta.providence.generator.GeneratorException) File(java.io.File) Generator(net.morimekta.providence.generator.Generator)

Example 5 with GeneratorFactory

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

the class GeneratorOptions method getFactories.

public Map<String, GeneratorFactory> getFactories() {
    try {
        FactoryLoader<GeneratorFactory> loader = new FactoryLoader<>(GeneratorFactory.MANIFEST_PROPERTY);
        Map<String, GeneratorFactory> factories = new TreeMap<>();
        factories.put("json", new JsonGeneratorFactory());
        File currentDir = currentJarDirectory();
        if (currentDir != null) {
            File generators = new File(currentDir, "generator");
            if (generators.isDirectory()) {
                addToMap(factories, loader.getFactories(generators));
            }
        }
        {
            ProvidenceTools config = getConfig();
            if (config.hasGeneratorPaths()) {
                for (String path : config.getGeneratorPaths()) {
                    addToMap(factories, loader.getFactories(new File(path)));
                }
            }
        }
        for (File extra : extraGenerators) {
            GeneratorFactory factory = loader.getFactory(extra);
            factories.put(factory.generatorName(), factory);
        }
        return factories;
    } catch (ProvidenceConfigException e) {
        throw new UncheckedProvidenceConfigException(e);
    }
}
Also used : GeneratorFactory(net.morimekta.providence.generator.GeneratorFactory) JsonGeneratorFactory(net.morimekta.providence.generator.format.json.JsonGeneratorFactory) FactoryLoader(net.morimekta.providence.generator.util.FactoryLoader) ProvidenceTools(net.morimekta.providence.tools.common.ProvidenceTools) JsonGeneratorFactory(net.morimekta.providence.generator.format.json.JsonGeneratorFactory) TreeMap(java.util.TreeMap) UncheckedProvidenceConfigException(net.morimekta.providence.config.UncheckedProvidenceConfigException) File(java.io.File) ProvidenceConfigException(net.morimekta.providence.config.ProvidenceConfigException) UncheckedProvidenceConfigException(net.morimekta.providence.config.UncheckedProvidenceConfigException)

Aggregations

GeneratorFactory (net.morimekta.providence.generator.GeneratorFactory)6 File (java.io.File)3 ArgumentException (net.morimekta.console.args.ArgumentException)3 Generator (net.morimekta.providence.generator.Generator)3 IOException (java.io.IOException)2 GeneratorException (net.morimekta.providence.generator.GeneratorException)2 GeneratorOptions (net.morimekta.providence.generator.GeneratorOptions)2 TypeLoader (net.morimekta.providence.reflect.TypeLoader)2 ProgramParser (net.morimekta.providence.reflect.parser.ProgramParser)2 ProgramTypeRegistry (net.morimekta.providence.reflect.util.ProgramTypeRegistry)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 UncheckedIOException (java.io.UncheckedIOException)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1