2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang2sources.plugin;
10 import java.io.Closeable;
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;
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.NamedFileInputStream;
33 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
34 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
35 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
36 import org.sonatype.plexus.build.incremental.BuildContext;
37 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.collect.Maps;
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 static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
48 private final Log log;
49 private final File yangFilesRootDir;
50 private final File[] excludedFiles;
51 private final List<CodeGeneratorArg> codeGenerators;
52 private final MavenProject project;
53 private final boolean inspectDependencies;
54 private final BuildContext buildContext;
55 private YangProvider yangProvider;
58 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
59 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
60 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
63 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
64 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
65 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
66 this.log = Util.checkNotNull(log, "log");
67 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
68 this.excludedFiles = new File[excludedFiles.length];
70 for (File file : excludedFiles) {
71 this.excludedFiles[i++] = new File(file.getPath());
73 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
74 this.project = Util.checkNotNull(project, "project");
75 this.inspectDependencies = inspectDependencies;
76 this.yangProvider = yangProvider;
79 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
80 MavenProject project, boolean inspectDependencies) {
81 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
84 public void execute() throws MojoExecutionException, MojoFailureException {
85 ContextHolder context = processYang();
86 if (context != null) {
87 generateSources(context);
88 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
92 private ContextHolder processYang() throws MojoExecutionException {
93 YangParserImpl parser = new YangParserImpl();
94 List<Closeable> closeables = new ArrayList<>();
95 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
98 * Collect all files which affect YANG context. This includes all
99 * files in current project and optionally any jars/files in the
102 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
103 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
104 if (inspectDependencies) {
105 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
108 if (allFiles.isEmpty()) {
109 log.info(Util.message("No input files found", LOG_PREFIX));
114 * Check if any of the listed files changed. If no changes occurred,
115 * simply return null, which indicates and of execution.
117 boolean noChange = true;
118 for (final File f : allFiles) {
119 if (buildContext.hasDelta(f)) {
120 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
126 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
130 final List<InputStream> yangsInProject = new ArrayList<>();
131 for (final File f : yangFilesInProject) {
132 yangsInProject.add(new NamedFileInputStream(f));
135 List<InputStream> all = new ArrayList<>(yangsInProject);
136 closeables.addAll(yangsInProject);
137 Map<InputStream, Module> allYangModules;
138 Set<Module> projectYangModules;
140 if (inspectDependencies) {
141 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
142 Closeable dependentYangResult1 = dependentYangResult;
143 closeables.add(dependentYangResult1);
144 all.addAll(dependentYangResult.getYangStreams());
147 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
149 projectYangModules = new HashSet<>();
150 for (InputStream inProject : yangsInProject) {
151 projectYangModules.add(allYangModules.get(inProject));
155 for (AutoCloseable closeable : closeables) {
160 Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
161 SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
162 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
163 return new ContextHolder(resolveSchemaContext, projectYangModules);
165 // MojoExecutionException is thrown since execution cannot continue
166 } catch (Exception e) {
167 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
169 log.error(message, e);
170 throw new MojoExecutionException(message, e);
174 static class YangProvider {
176 private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
178 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
179 throws MojoFailureException {
180 File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
183 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
184 for (File file : files) {
185 org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
187 } catch (IOException e) {
188 String message = "Unable to list yang files into resource folder";
189 log.warn(message, e);
190 throw new MojoFailureException(message, e);
193 setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
195 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
196 META_INF_YANG_STRING_JAR));
199 private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
200 Resource res = new Resource();
201 res.setDirectory(targetYangDir.getPath());
202 if (targetPath != null) {
203 res.setTargetPath(targetPath);
205 project.addResource(res);
210 * Call generate on every generator from plugin configuration
212 private void generateSources(ContextHolder context) throws MojoFailureException {
213 if (codeGenerators.size() == 0) {
214 log.warn(Util.message("No code generators provided", LOG_PREFIX));
218 Map<String, String> thrown = Maps.newHashMap();
219 for (CodeGeneratorArg codeGenerator : codeGenerators) {
221 generateSourcesWithOneGenerator(context, codeGenerator);
222 } catch (Exception e) {
223 // try other generators, exception will be thrown after
225 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
226 codeGenerator.getCodeGeneratorClass()), e);
227 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
231 if (!thrown.isEmpty()) {
232 String message = Util.message(
233 "One or more code generators failed, including failed list(generatorClass=exception) %s",
234 LOG_PREFIX, thrown.toString());
236 throw new MojoFailureException(message);
241 * Instantiate generator from class and call required method
243 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
244 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
246 codeGeneratorCfg.check();
248 CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
249 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
250 codeGeneratorCfg.getCodeGeneratorClass()));
252 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
254 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
255 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
256 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
257 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
259 if (outputDir != null) {
260 project.addCompileSourceRoot(outputDir.getAbsolutePath());
263 if (g instanceof BuildContextAware) {
264 ((BuildContextAware)g).setBuildContext(buildContext);
267 g.setMavenProject(project);
268 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
269 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
271 YangProvider.setResource(resourceBaseDir, null, project);
272 g.setResourceBaseDir(resourceBaseDir);
273 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
274 codeGeneratorCfg.getCodeGeneratorClass()));
276 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
278 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),