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