Added 'excludeFiles' option to yang-maven-plugin configuration.
[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.io.Closeable;
11 import java.io.File;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.apache.maven.model.Resource;
23 import org.apache.maven.plugin.MojoExecutionException;
24 import org.apache.maven.plugin.MojoFailureException;
25 import org.apache.maven.plugin.logging.Log;
26 import org.apache.maven.project.MavenProject;
27 import org.opendaylight.yangtools.yang.model.api.Module;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
30 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
31 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
32 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
33 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
34
35 import com.google.common.annotations.VisibleForTesting;
36 import com.google.common.collect.Maps;
37
38 class YangToSourcesProcessor {
39     static final String LOG_PREFIX = "yang-to-sources:";
40     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
41     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
42     static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
43
44     private final Log log;
45     private final File yangFilesRootDir;
46     private final File[] excludedFiles;
47     private final List<CodeGeneratorArg> codeGenerators;
48     private final MavenProject project;
49     private final boolean inspectDependencies;
50     private YangProvider yangProvider;
51
52     @VisibleForTesting
53     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
54             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
55         this.log = Util.checkNotNull(log, "log");
56         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
57         this.excludedFiles = excludedFiles;
58         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
59         this.project = Util.checkNotNull(project, "project");
60         this.inspectDependencies = inspectDependencies;
61         this.yangProvider = yangProvider;
62     }
63
64     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
65             MavenProject project, boolean inspectDependencies) {
66         this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
67     }
68
69     public void execute() throws MojoExecutionException, MojoFailureException {
70         ContextHolder context = processYang();
71         generateSources(context);
72         yangProvider.addYangsToMETA_INF(log, project, yangFilesRootDir, excludedFiles);
73     }
74
75     private ContextHolder processYang() throws MojoExecutionException {
76         YangParserImpl parser = new YangParserImpl();
77         List<Closeable> closeables = new ArrayList<>();
78         log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
79         try {
80             List<InputStream> yangsInProject = Util.listFilesAsStream(yangFilesRootDir, excludedFiles, log);
81             List<InputStream> all = new ArrayList<>(yangsInProject);
82             closeables.addAll(yangsInProject);
83             Map<InputStream, Module> allYangModules;
84             Set<Module> projectYangModules;
85             try {
86                 if (inspectDependencies) {
87                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
88                     Closeable dependentYangResult1 = dependentYangResult;
89                     closeables.add(dependentYangResult1);
90                     all.addAll(dependentYangResult.yangStreams);
91                 }
92
93                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
94
95                 projectYangModules = new HashSet<>();
96                 for (InputStream inProject : yangsInProject) {
97                     projectYangModules.add(allYangModules.get(inProject));
98                 }
99
100             } finally {
101                 for (AutoCloseable closeable : closeables) {
102                     closeable.close();
103                 }
104             }
105
106             Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
107             SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
108             log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
109             return new ContextHolder(resolveSchemaContext, projectYangModules);
110
111             // MojoExecutionException is thrown since execution cannot continue
112         } catch (Exception e) {
113             String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
114                     yangFilesRootDir);
115             log.error(message, e);
116             throw new MojoExecutionException(message, e);
117         }
118     }
119
120     static class YangProvider {
121
122         private static final String yangResourceDir = "target" + File.separator + "yang";
123
124         void addYangsToMETA_INF(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
125                 throws MojoFailureException {
126             File targetYangDir = new File(project.getBasedir(), yangResourceDir);
127
128             try {
129                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
130                 for (File file : files) {
131                     org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
132                 }
133             } catch (IOException e) {
134                 String message = "Unable to list yang files into resource folder";
135                 log.warn(message, e);
136                 throw new MojoFailureException(message, e);
137             }
138
139             setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
140
141             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
142                     META_INF_YANG_STRING_JAR));
143         }
144
145         private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
146             Resource res = new Resource();
147             res.setDirectory(targetYangDir.getPath());
148             if (targetPath != null)
149                 res.setTargetPath(targetPath);
150             project.addResource(res);
151         }
152     }
153
154     /**
155      * Call generate on every generator from plugin configuration
156      */
157     private void generateSources(ContextHolder context) throws MojoFailureException {
158         if (codeGenerators.size() == 0) {
159             log.warn(Util.message("No code generators provided", LOG_PREFIX));
160             return;
161         }
162
163         Map<String, String> thrown = Maps.newHashMap();
164         for (CodeGeneratorArg codeGenerator : codeGenerators) {
165             try {
166                 generateSourcesWithOneGenerator(context, codeGenerator);
167             } catch (Exception e) {
168                 // try other generators, exception will be thrown after
169                 log.error(
170                         Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
171                                 codeGenerator.getCodeGeneratorClass()), e);
172                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
173             }
174         }
175
176         if (!thrown.isEmpty()) {
177             String message = Util.message(
178                     "One or more code generators failed, including failed list(generatorClass=exception) %s",
179                     LOG_PREFIX, thrown.toString());
180             log.error(message);
181             throw new MojoFailureException(message);
182         }
183     }
184
185     /**
186      * Instantiate generator from class and call required method
187      */
188     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
189             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
190
191         codeGeneratorCfg.check();
192
193         CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
194         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
195                 codeGeneratorCfg.getCodeGeneratorClass()));
196
197         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
198
199         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
200         log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
201         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
202                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
203
204         if (outputDir != null) {
205             project.addCompileSourceRoot(outputDir.getAbsolutePath());
206         }
207         g.setLog(log);
208         g.setMavenProject(project);
209         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
210         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
211
212         YangProvider.setResource(resourceBaseDir, null, project);
213         g.setResourceBaseDir(resourceBaseDir);
214         log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
215                 codeGeneratorCfg.getCodeGeneratorClass()));
216
217         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
218
219         log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
220                 generated));
221     }
222
223 }