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