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