Get rid of commons-io
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.java
index c32dcc27fe9863debe4f1fc862b5293258d422ed..ff274d19e22403a57f76eee5f6e6013ee2cb598d 100644 (file)
  */
 package org.opendaylight.yangtools.yang2sources.plugin;
 
-import java.io.Closeable;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.CharStreams;
 import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
+import java.io.Reader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
+import java.util.Comparator;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
-
-import org.apache.maven.model.Resource;
+import java.util.stream.Collectors;
 import org.apache.maven.plugin.MojoExecutionException;
 import org.apache.maven.plugin.MojoFailureException;
-import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.project.MavenProject;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+import org.opendaylight.yangtools.yang.common.YangConstants;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
+import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
-import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
-import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
-import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Maps;
+import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
+import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
+import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonatype.plexus.build.incremental.BuildContext;
+import org.sonatype.plexus.build.incremental.DefaultBuildContext;
 
 class YangToSourcesProcessor {
+    private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
+
     static final String LOG_PREFIX = "yang-to-sources:";
-    static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
-    static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
-    static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
+    private static final String META_INF_STR = "META-INF";
+    private static final String YANG_STR = "yang";
+
+    static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
+    static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
+    static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
 
-    private final Log log;
     private final File yangFilesRootDir;
-    private final File[] excludedFiles;
+    private final Set<File> excludedFiles;
     private final List<CodeGeneratorArg> codeGenerators;
     private final MavenProject project;
     private final boolean inspectDependencies;
-    private YangProvider yangProvider;
+    private final BuildContext buildContext;
+    private final YangProvider yangProvider;
+
+    private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
+            final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
+            final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
+        this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
+        this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
+        this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
+        this.codeGenerators = ImmutableList.copyOf(codeGenerators);
+        this.project = Preconditions.checkNotNull(project);
+        this.inspectDependencies = inspectDependencies;
+        this.yangProvider = Preconditions.checkNotNull(yangProvider);
+    }
 
     @VisibleForTesting
-    YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
-            MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
-        this.log = Util.checkNotNull(log, "log");
-        this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
-        this.excludedFiles = new File[excludedFiles.length];
-        int i = 0;
-        for (File file : excludedFiles) {
-            this.excludedFiles[i++] = new File(file.getPath());
-        }
-        this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
-        this.project = Util.checkNotNull(project, "project");
-        this.inspectDependencies = inspectDependencies;
-        this.yangProvider = yangProvider;
+    YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
+            final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
+            final YangProvider yangProvider) {
+        this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
+                inspectDependencies, yangProvider);
     }
 
-    YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
-            MavenProject project, boolean inspectDependencies) {
-        this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
+    YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
+                final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
+                final MavenProject project, final boolean inspectDependencies) {
+        this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
     }
 
     public void execute() throws MojoExecutionException, MojoFailureException {
-        ContextHolder context = processYang();
-        generateSources(context);
-        yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
+        conditionalExecute(false);
     }
 
-    private ContextHolder processYang() throws MojoExecutionException {
-        YangParserImpl parser = new YangParserImpl();
-        List<Closeable> closeables = new ArrayList<>();
-        log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
-        try {
-            List<InputStream> yangsInProject = Util.listFilesAsStream(yangFilesRootDir, excludedFiles, log);
-            List<InputStream> all = new ArrayList<>(yangsInProject);
-            closeables.addAll(yangsInProject);
-            Map<InputStream, Module> allYangModules;
-            Set<Module> projectYangModules;
+    void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
+        final Optional<ProcessorModuleReactor> optReactor = createReactor();
+        if (!optReactor.isPresent()) {
+            return;
+        }
+
+        final ProcessorModuleReactor reactor = optReactor.get();
+        if (!skip) {
+            final ContextHolder holder;
+
             try {
-                if (inspectDependencies) {
-                    YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
-                    Closeable dependentYangResult1 = dependentYangResult;
-                    closeables.add(dependentYangResult1);
-                    all.addAll(dependentYangResult.getYangStreams());
-                }
+                holder = createContextHolder(reactor);
+            } catch (SchemaSourceException | YangSyntaxErrorException e) {
+                throw new MojoFailureException("Failed to process reactor " + reactor, e);
+            } catch (IOException e) {
+                throw new MojoExecutionException("Failed to read reactor " + reactor, e);
+            }
 
-                allYangModules = parser.parseYangModelsFromStreamsMapped(all);
+            generateSources(holder);
+        } else {
+            LOG.info("Skipping YANG code generation because property yang.skip is true");
+        }
 
-                projectYangModules = new HashSet<>();
-                for (InputStream inProject : yangsInProject) {
-                    projectYangModules.add(allYangModules.get(inProject));
-                }
+        // add META_INF/yang
+        final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
+        try {
+            yangProvider.addYangsToMetaInf(project, models);
+        } catch (IOException e) {
+            throw new MojoExecutionException("Failed write model files for " + models, e);
+        }
+
+        // add META_INF/services
+        File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
+        YangProvider.setResource(generatedServicesDir, project);
+        LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
+            META_INF_YANG_SERVICES_STRING_JAR);
+    }
 
-            } finally {
-                for (AutoCloseable closeable : closeables) {
-                    closeable.close();
+    @SuppressWarnings("checkstyle:illegalCatch")
+    private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
+        LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
+        try {
+            /*
+             * Collect all files which affect YANG context. This includes all
+             * files in current project and optionally any jars/files in the
+             * dependencies.
+             */
+            final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
+
+            final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
+            if (inspectDependencies) {
+                allFiles.addAll(Util.findYangFilesInDependencies(project));
+            }
+
+            if (allFiles.isEmpty()) {
+                LOG.info("{} No input files found", LOG_PREFIX);
+                return Optional.empty();
+            }
+
+            /*
+             * Check if any of the listed files changed. If no changes occurred,
+             * simply return null, which indicates and of execution.
+             */
+            boolean noChange = true;
+            for (final File f : allFiles) {
+                if (buildContext.hasDelta(f)) {
+                    LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
+                            buildContext, f);
+                    noChange = false;
                 }
             }
 
-            Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
-            SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
-            log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
-            return new ContextHolder(resolveSchemaContext, projectYangModules);
+            if (noChange) {
+                LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
+                return Optional.empty();
+            }
 
-            // MojoExecutionException is thrown since execution cannot continue
+            final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
+            for (final File f : yangFilesInProject) {
+                resolver.registerSource(YangTextSchemaSource.forFile(f));
+            }
+
+            LOG.debug("Processed project files: {}", yangFilesInProject);
+            LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
+
+            final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
+            LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
+            return Optional.of(reactor);
         } catch (Exception e) {
-            String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
-                    yangFilesRootDir);
-            log.error(message, e);
-            throw new MojoExecutionException(message, e);
+            // MojoExecutionException is thrown since execution cannot continue
+            LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
+            Throwable rootCause = Throwables.getRootCause(e);
+            throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
+                rootCause);
         }
     }
 
-    static class YangProvider {
-
-        private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
-
-        void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
-                throws MojoFailureException {
-            File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
-
-            try {
-                Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
-                for (File file : files) {
-                    org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
-                }
-            } catch (IOException e) {
-                String message = "Unable to list yang files into resource folder";
-                log.warn(message, e);
-                throw new MojoFailureException(message, e);
+    private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
+            IOException, SchemaSourceException, YangSyntaxErrorException {
+        /**
+         * Set contains all modules generated from input sources. Number of
+         * modules may differ from number of sources due to submodules
+         * (parsed submodule's data are added to its parent module). Set
+         * cannot contains null values.
+         */
+        if (inspectDependencies) {
+            final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
+                project);
+            for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
+                reactor.registerSource(s);
             }
+        }
 
-            setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
+        return reactor.toContext();
+    }
 
-            log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
-                    META_INF_YANG_STRING_JAR));
+    private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
+            throws IOException {
+        if (!root.isDirectory()) {
+            LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
+            return ImmutableList.of();
         }
 
-        private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
-            Resource res = new Resource();
-            res.setDirectory(targetYangDir.getPath());
-            if (targetPath != null) {
-                res.setTargetPath(targetPath);
+        return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
+            if (excludedFiles.contains(f)) {
+                LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
+                return false;
+            }
+            return true;
+        }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
+    }
+
+    private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
+            throws IOException {
+        final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
+        for (YangTextSchemaSource s : sources) {
+            try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
+                final String contents = CharStreams.toString(reader);
+                byContent.putIfAbsent(contents, s);
             }
-            project.addResource(res);
         }
+        return byContent.values();
     }
 
     /**
-     * Call generate on every generator from plugin configuration
+     * Call generate on every generator from plugin configuration.
      */
-    private void generateSources(ContextHolder context) throws MojoFailureException {
+    @SuppressWarnings("checkstyle:illegalCatch")
+    private void generateSources(final ContextHolder context) throws MojoFailureException {
         if (codeGenerators.size() == 0) {
-            log.warn(Util.message("No code generators provided", LOG_PREFIX));
+            LOG.warn("{} No code generators provided", LOG_PREFIX);
             return;
         }
 
-        Map<String, String> thrown = Maps.newHashMap();
+        final Map<String, String> thrown = new HashMap<>();
         for (CodeGeneratorArg codeGenerator : codeGenerators) {
             try {
                 generateSourcesWithOneGenerator(context, codeGenerator);
             } catch (Exception e) {
                 // try other generators, exception will be thrown after
-                log.error(
-                        Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
-                                codeGenerator.getCodeGeneratorClass()), e);
+                LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
+                        .getCodeGeneratorClass(), e);
                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
             }
         }
 
         if (!thrown.isEmpty()) {
-            String message = Util.message(
-                    "One or more code generators failed, including failed list(generatorClass=exception) %s",
-                    LOG_PREFIX, thrown.toString());
-            log.error(message);
-            throw new MojoFailureException(message);
+            String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
+            LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
+            throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
         }
     }
 
     /**
-     * Instantiate generator from class and call required method
+     * Instantiate generator from class and call required method.
      */
-    private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
+    private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
 
         codeGeneratorCfg.check();
 
-        CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
-        log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
-                codeGeneratorCfg.getCodeGeneratorClass()));
+        final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
+        LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
+
+        final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
+
+        if (outputDir == null) {
+            throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
+                    + "pom.xml");
+        }
 
-        File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
+        project.addCompileSourceRoot(outputDir.getAbsolutePath());
 
-        log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
-        log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
-        log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
-                codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
+        LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
+        LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
+        LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
+                        .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
 
-        if (outputDir != null) {
-            project.addCompileSourceRoot(outputDir.getAbsolutePath());
+        if (g instanceof BuildContextAware) {
+            ((BuildContextAware)g).setBuildContext(buildContext);
+        }
+        if (g instanceof MavenProjectAware) {
+            ((MavenProjectAware)g).setMavenProject(project);
         }
-        g.setLog(log);
-        g.setMavenProject(project);
         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
 
-        YangProvider.setResource(resourceBaseDir, null, project);
+        YangProvider.setResource(resourceBaseDir, project);
         g.setResourceBaseDir(resourceBaseDir);
-        log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
-                codeGeneratorCfg.getCodeGeneratorClass()));
+        LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
+                codeGeneratorCfg.getCodeGeneratorClass());
 
-        Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
+        if (outputDir.exists()) {
+            Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
+            LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
+        }
+        Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
+            context::moduleToResourcePath);
 
-        log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
-                generated));
+        LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
     }
 
+    /**
+     * Instantiate object from fully qualified class name.
+     */
+    private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
+            ClassNotFoundException, InstantiationException, IllegalAccessException {
+        final Class<?> clazz = Class.forName(codeGeneratorClass);
+
+        Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
+            baseType);
+        return baseType.cast(clazz.newInstance());
+    }
 }