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