Switch YangToSourcesProcessor to use YangParser
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.java
index a708c412b9415ba58abe0dc4fc52835a2b89a860..d53d06ee18cda46a2deeacf02c873782c8fc8cf0 100644 (file)
@@ -7,8 +7,11 @@
  */
 package org.opendaylight.yangtools.yang2sources.plugin;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
 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;
@@ -17,21 +20,29 @@ import java.io.File;
 import java.io.IOException;
 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.Comparator;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import java.util.ServiceLoader;
 import java.util.Set;
+import java.util.stream.Collectors;
 import org.apache.maven.plugin.MojoExecutionException;
 import org.apache.maven.plugin.MojoFailureException;
 import org.apache.maven.project.MavenProject;
-import org.codehaus.plexus.util.FileUtils;
-import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
-import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
+import org.opendaylight.yangtools.yang.common.YangConstants;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
-import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
@@ -43,6 +54,13 @@ import org.sonatype.plexus.build.incremental.DefaultBuildContext;
 
 class YangToSourcesProcessor {
     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
+    private static final YangParserFactory DEFAULT_PARSER_FACTORY;
+
+    static {
+        final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
+        checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
+        DEFAULT_PARSER_FACTORY = it.next();
+    }
 
     static final String LOG_PREFIX = "yang-to-sources:";
     private static final String META_INF_STR = "META-INF";
@@ -52,6 +70,7 @@ class YangToSourcesProcessor {
     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 YangParserFactory parserFactory;
     private final File yangFilesRootDir;
     private final Set<File> excludedFiles;
     private final List<CodeGeneratorArg> codeGenerators;
@@ -63,13 +82,14 @@ class YangToSourcesProcessor {
     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.buildContext = requireNonNull(buildContext, "buildContext");
+        this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
-        this.project = Preconditions.checkNotNull(project);
+        this.project = requireNonNull(project);
         this.inspectDependencies = inspectDependencies;
-        this.yangProvider = Preconditions.checkNotNull(yangProvider);
+        this.yangProvider = requireNonNull(yangProvider);
+        this.parserFactory = DEFAULT_PARSER_FACTORY;
     }
 
     @VisibleForTesting
@@ -102,7 +122,7 @@ class YangToSourcesProcessor {
 
             try {
                 holder = createContextHolder(reactor);
-            } catch (SchemaSourceException | YangSyntaxErrorException e) {
+            } catch (YangParserException e) {
                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
             } catch (IOException e) {
                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
@@ -137,7 +157,7 @@ class YangToSourcesProcessor {
              * files in current project and optionally any jars/files in the
              * dependencies.
              */
-            final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
+            final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
 
             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
             if (inspectDependencies) {
@@ -153,42 +173,46 @@ class YangToSourcesProcessor {
              * 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;
-                }
-            }
-
-            if (noChange) {
+            if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
                 return Optional.empty();
             }
 
-            final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
+            // FIXME: add correct mode
+            final YangParser parser = parserFactory.createParser();
+            final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
             for (final File f : yangFilesInProject) {
-                resolver.registerSource(YangTextSchemaSource.forFile(f));
+                final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(f);
+                final ASTSchemaSource astSource = TextToASTTransformer.transformText(textSource);
+
+                parser.addSource(astSource);
+
+                if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
+                    // AST indicates a different source identifier, make sure we use that
+                    sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
+                        textSource));
+                } else {
+                    sourcesInProject.add(textSource);
+                }
             }
 
             LOG.debug("Processed project files: {}", yangFilesInProject);
             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
 
-            final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
+            final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject);
             LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
             return Optional.of(reactor);
         } catch (Exception e) {
             // MojoExecutionException is thrown since execution cannot continue
-            LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
+            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 " + Util.YANG_SUFFIX + " files from "
-                    + yangFilesRootDir, rootCause);
+            throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
+                rootCause);
         }
     }
 
     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
-            IOException, SchemaSourceException, YangSyntaxErrorException {
+            IOException, YangParserException {
         /**
          * Set contains all modules generated from input sources. Number of
          * modules may differ from number of sources due to submodules
@@ -199,13 +223,29 @@ class YangToSourcesProcessor {
             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
                 project);
             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
-                reactor.registerSource(s);
+                reactor.registerSourceFromDependency(s);
             }
         }
 
         return reactor.toContext();
     }
 
+    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();
+        }
+
+        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<>();
@@ -223,7 +263,7 @@ class YangToSourcesProcessor {
      */
     @SuppressWarnings("checkstyle:illegalCatch")
     private void generateSources(final ContextHolder context) throws MojoFailureException {
-        if (codeGenerators.size() == 0) {
+        if (codeGenerators.isEmpty()) {
             LOG.warn("{} No code generators provided", LOG_PREFIX);
             return;
         }
@@ -242,7 +282,7 @@ class YangToSourcesProcessor {
 
         if (!thrown.isEmpty()) {
             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
-            LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
+            LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
         }
     }
@@ -258,12 +298,8 @@ class YangToSourcesProcessor {
         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");
-        }
+        final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
+            "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
 
         project.addCompileSourceRoot(outputDir.getAbsolutePath());
 
@@ -286,9 +322,10 @@ class YangToSourcesProcessor {
         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
                 codeGeneratorCfg.getCodeGeneratorClass());
 
-        FileUtils.deleteDirectory(outputDir);
-        LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
-
+        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);
 
@@ -301,9 +338,7 @@ class YangToSourcesProcessor {
     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);
+        checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
         return baseType.cast(clazz.newInstance());
     }
 }