Fix yang-maven-plugin generating superfluous files
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang2sources.plugin;
9
10 import java.util.HashSet;
11 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
12 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.Maps;
16 import java.io.Closeable;
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.concurrent.ConcurrentMap;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.maven.model.Resource;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.project.MavenProject;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
35 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
36 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
37 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
38 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
39 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
40 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
41 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.sonatype.plexus.build.incremental.BuildContext;
45 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
46
47 class YangToSourcesProcessor {
48     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
49
50     static final String LOG_PREFIX = "yang-to-sources:";
51     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
52     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
53
54     private final File yangFilesRootDir;
55     private final File[] excludedFiles;
56     private final List<CodeGeneratorArg> codeGenerators;
57     private final MavenProject project;
58     private final boolean inspectDependencies;
59     private final BuildContext buildContext;
60     private final YangProvider yangProvider;
61     private final URLSchemaContextResolver resolver;
62
63     @VisibleForTesting
64     YangToSourcesProcessor(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
65             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
66         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
67                 inspectDependencies, yangProvider);
68     }
69
70     private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
71             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
72                                            yangProvider) {
73         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
74         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
75         this.excludedFiles = new File[excludedFiles.length];
76         int i = 0;
77         for (File file : excludedFiles) {
78             this.excludedFiles[i++] = new File(file.getPath());
79         }
80         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
81         this.project = Util.checkNotNull(project, "project");
82         this.inspectDependencies = inspectDependencies;
83         this.yangProvider = yangProvider;
84         this.resolver = URLSchemaContextResolver.create("maven-plugin");
85     }
86
87     YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
88                            List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies) {
89         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
90     }
91
92     public void execute() throws MojoExecutionException, MojoFailureException {
93         ContextHolder context = processYang();
94         if (context != null) {
95             generateSources(context);
96             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
97         }
98     }
99
100     private ContextHolder processYang() throws MojoExecutionException {
101         final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
102         SchemaContext resolveSchemaContext;
103         List<Closeable> closeables = new ArrayList<>();
104         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
105         try {
106             /*
107              * Collect all files which affect YANG context. This includes all
108              * files in current project and optionally any jars/files in the
109              * dependencies.
110              */
111             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
112
113
114             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
115             if (inspectDependencies) {
116                 allFiles.addAll(Util.findYangFilesInDependencies(project));
117             }
118
119             if (allFiles.isEmpty()) {
120                 LOG.info("{} No input files found", LOG_PREFIX);
121                 return null;
122             }
123
124             /*
125              * Check if any of the listed files changed. If no changes occurred,
126              * simply return null, which indicates and of execution.
127              */
128             boolean noChange = true;
129             for (final File f : allFiles) {
130                 if (buildContext.hasDelta(f)) {
131                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
132                             buildContext, f);
133                     noChange = false;
134                 }
135             }
136
137             if (noChange) {
138                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
139                 return null;
140             }
141
142             final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
143             for (final File f : yangFilesInProject) {
144                 // FIXME: This is hack - normal path should be reported.
145                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
146             }
147
148             List<InputStream> all = new ArrayList<>();
149             all.addAll(yangsInProject);
150             closeables.addAll(yangsInProject);
151
152             /**
153              * Set contains all modules generated from input sources. Number of
154              * modules may differ from number of sources due to submodules
155              * (parsed submodule's data are added to its parent module). Set
156              * cannot contains null values.
157              */
158             Set<Module> projectYangModules;
159             try {
160                 if (inspectDependencies) {
161                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
162                     Closeable dependentYangResult1 = dependentYangResult;
163                     closeables.add(dependentYangResult1);
164                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
165                     all.addAll(yangStreams);
166                     closeables.addAll(yangStreams);
167                 }
168
169                 resolveSchemaContext = reactor.buildEffective(all);
170
171                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
172                 projectYangModules = new HashSet<>();
173                 for (Module module : parsedAllYangModules) {
174                     final String path = module.getModuleSourcePath();
175                     if (path != null) {
176                         LOG.debug("Looking for source {}", path);
177                         for (NamedFileInputStream is : yangsInProject) {
178                             LOG.debug("In project destination {}", is.getFileDestination());
179                             if (path.equals(is.getFileDestination())) {
180                                 LOG.debug("Module {} belongs to current project", module);
181                                 projectYangModules.add(module);
182                                 break;
183                             }
184                         }
185                     }
186                 }
187             } finally {
188                 for (AutoCloseable closeable : closeables) {
189                     closeable.close();
190                 }
191             }
192
193             LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
194             return new ContextHolder(resolveSchemaContext, projectYangModules);
195
196             // MojoExecutionException is thrown since execution cannot continue
197         } catch (Exception e) {
198             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
199             Throwable rootCause = Throwables.getRootCause(e);
200             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
201                     yangFilesRootDir, rootCause);
202         }
203     }
204
205     private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
206         ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
207
208         for (YangSourceFromDependency yangFromDependency : list) {
209             try (InputStream dataStream = yangFromDependency.openStream()) {
210                 String contents = IOUtils.toString(dataStream);
211                 byContent.putIfAbsent(contents, yangFromDependency);
212             }
213
214         }
215         List<InputStream> inputs = new ArrayList<>(byContent.size());
216         for (YangSourceFromDependency entry : byContent.values()) {
217             inputs.add(entry.openStream());
218         }
219         return inputs;
220     }
221
222     static class YangProvider {
223         private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
224
225         void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
226                 throws MojoFailureException {
227
228             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
229
230             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
231             addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
232
233             // Also copy to the actual build output dir if different than "target". When running in
234             // Eclipse this can differ (eg "target-ide").
235
236             File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
237                     CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
238             if(!actualGeneratedYangDir.equals(generatedYangDir)) {
239                 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
240             }
241         }
242
243         private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
244                 File[] excludedFiles, File generatedYangDir)
245                 throws MojoFailureException {
246
247             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
248             withMetaInf.mkdirs();
249
250             try {
251                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
252                 for (File file : files) {
253                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
254                 }
255             } catch (IOException e) {
256                 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
257                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
258             }
259
260             setResource(generatedYangDir, project);
261
262             LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
263                     META_INF_YANG_STRING_JAR);
264         }
265
266         private static void setResource(File targetYangDir, MavenProject project) {
267             Resource res = new Resource();
268             res.setDirectory(targetYangDir.getPath());
269             project.addResource(res);
270         }
271     }
272
273     /**
274      * Call generate on every generator from plugin configuration
275      */
276     private void generateSources(ContextHolder context) throws MojoFailureException {
277         if (codeGenerators.size() == 0) {
278             LOG.warn("{} No code generators provided", LOG_PREFIX);
279             return;
280         }
281
282         Map<String, String> thrown = Maps.newHashMap();
283         for (CodeGeneratorArg codeGenerator : codeGenerators) {
284             try {
285                 generateSourcesWithOneGenerator(context, codeGenerator);
286             } catch (Exception e) {
287                 // try other generators, exception will be thrown after
288                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
289                         .getCodeGeneratorClass(), e);
290                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
291             }
292         }
293
294         if (!thrown.isEmpty()) {
295             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
296             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
297             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
298         }
299     }
300
301     /**
302      * Instantiate generator from class and call required method
303      */
304     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
305             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
306
307         codeGeneratorCfg.check();
308
309         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
310         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
311
312         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
313
314         if (outputDir != null) {
315           project.addCompileSourceRoot(outputDir.getAbsolutePath());
316         } else {
317           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
318                   "pom.xml");
319         }
320
321         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
322         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
323         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
324                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
325
326         if (g instanceof BuildContextAware) {
327             ((BuildContextAware)g).setBuildContext(buildContext);
328         }
329         if (g instanceof MavenProjectAware) {
330             ((MavenProjectAware)g).setMavenProject(project);
331         }
332         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
333         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
334
335         YangProvider.setResource(resourceBaseDir, project);
336         g.setResourceBaseDir(resourceBaseDir);
337         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
338                 codeGeneratorCfg.getCodeGeneratorClass());
339
340         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
341
342         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
343     }
344
345 }