Maven plugin ignores exact YANG duplicates in dependencies
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.java
index f2b67f46eb40f0236b56b4dc437cd1b8b70def61..d939ccfa34875163a2f35e890bac66af1f6cc29e 100644 (file)
@@ -9,6 +9,19 @@ package org.opendaylight.yangtools.yang2sources.plugin;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.Maps;
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+import org.apache.commons.io.IOUtils;
 import org.apache.maven.model.Resource;
 import org.apache.maven.plugin.MojoExecutionException;
 import org.apache.maven.plugin.MojoFailureException;
@@ -17,34 +30,22 @@ 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.parser.repo.URLSchemaContextResolver;
 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 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.BasicCodeGenerator;
 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
-import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
+import org.opendaylight.yangtools.yang2sources.spi.MavenLogAware;
+import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
 import org.sonatype.plexus.build.incremental.BuildContext;
 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
 
-import java.io.Closeable;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
 class YangToSourcesProcessor {
     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 final Log log;
     private final File yangFilesRootDir;
@@ -53,7 +54,8 @@ class YangToSourcesProcessor {
     private final MavenProject project;
     private final boolean inspectDependencies;
     private final BuildContext buildContext;
-    private YangProvider yangProvider;
+    private final YangProvider yangProvider;
+    private final URLSchemaContextResolver resolver;
 
     @VisibleForTesting
     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
@@ -75,6 +77,7 @@ class YangToSourcesProcessor {
         this.project = Util.checkNotNull(project, "project");
         this.inspectDependencies = inspectDependencies;
         this.yangProvider = yangProvider;
+        this.resolver = URLSchemaContextResolver.create("maven-plugin");
     }
 
     YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
@@ -101,6 +104,8 @@ class YangToSourcesProcessor {
              * dependencies.
              */
             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
+
+
             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
             if (inspectDependencies) {
                 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
@@ -124,33 +129,45 @@ class YangToSourcesProcessor {
             }
 
             if (noChange) {
-               log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
+                log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
                 return null;
             }
 
             final List<InputStream> yangsInProject = new ArrayList<>();
             for (final File f : yangFilesInProject) {
+                // FIXME: This is hack - normal path should be reported.
                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
             }
 
             List<InputStream> all = new ArrayList<>(yangsInProject);
             closeables.addAll(yangsInProject);
             Map<InputStream, Module> allYangModules;
+
+            /**
+             * 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.
+             */
             Set<Module> projectYangModules;
             try {
                 if (inspectDependencies) {
                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
                     Closeable dependentYangResult1 = dependentYangResult;
                     closeables.add(dependentYangResult1);
-                    all.addAll(dependentYangResult.getYangStreams());
+                    List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
+                    all.addAll(yangStreams);
+                    closeables.addAll(yangStreams);
                 }
 
                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
 
                 projectYangModules = new HashSet<>();
                 for (InputStream inProject : yangsInProject) {
-                    Module module = checkNotNull(allYangModules.get(inProject), "Cannot find module by %s", inProject);
-                    projectYangModules.add(module);
+                    Module module = allYangModules.get(inProject);
+                    if (module != null) {
+                        projectYangModules.add(module);
+                    }
                 }
 
             } finally {
@@ -173,37 +190,69 @@ class YangToSourcesProcessor {
         }
     }
 
-    static class YangProvider {
+    private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
+        ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
+
+        for (YangSourceFromDependency yangFromDependency : list) {
+            try (InputStream dataStream = yangFromDependency.openStream()) {
+                String contents = IOUtils.toString(dataStream);
+                byContent.putIfAbsent(contents, yangFromDependency);
+            }
+
+        }
+        List<InputStream> inputs = new ArrayList<>(byContent.size());
+        for (YangSourceFromDependency entry : byContent.values()) {
+            inputs.add(entry.openStream());
+        }
+        return inputs;
+    }
 
-        private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
+    static class YangProvider {
 
         void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
                 throws MojoFailureException {
-            File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
+
+            // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
+
+            File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
+            addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
+
+            // Also copy to the actual build output dir if different than "target". When running in
+            // Eclipse this can differ (eg "target-ide").
+
+            File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
+                    CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
+            if(!actualGeneratedYangDir.equals(generatedYangDir)) {
+                addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
+            }
+        }
+
+        private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
+                File[] excludedFiles, File generatedYangDir)
+                throws MojoFailureException {
+
+            File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
+            withMetaInf.mkdirs();
 
             try {
-                Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
+                Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
                 for (File file : files) {
-                    org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
+                    org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
                 }
             } catch (IOException e) {
-                String message = "Unable to list yang files into resource folder";
-                log.warn(message, e);
-                throw new MojoFailureException(message, e);
+                log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
+                throw new MojoFailureException("Unable to list yang files into resource folder", e);
             }
 
-            setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
+            setResource(generatedYangDir, project);
 
             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
                     META_INF_YANG_STRING_JAR));
         }
 
-        private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
+        private static void setResource(File targetYangDir, MavenProject project) {
             Resource res = new Resource();
             res.setDirectory(targetYangDir.getPath());
-            if (targetPath != null) {
-                res.setTargetPath(targetPath);
-            }
             project.addResource(res);
         }
     }
@@ -247,7 +296,7 @@ class YangToSourcesProcessor {
 
         codeGeneratorCfg.check();
 
-        CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
+        BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
                 codeGeneratorCfg.getCodeGeneratorClass()));
 
@@ -264,15 +313,19 @@ class YangToSourcesProcessor {
         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
 
+        if (g instanceof MavenLogAware) {
+            ((MavenLogAware)g).setLog(log);
+        }
         if (g instanceof BuildContextAware) {
             ((BuildContextAware)g).setBuildContext(buildContext);
         }
-        g.setLog(log);
-        g.setMavenProject(project);
+        if (g instanceof MavenProjectAware) {
+            ((MavenProjectAware)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()));