31409aafd970b13135246f801e3cab39bac4fb8c
[yangtools.git] / plugin / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / CodeGeneratorTask.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Stopwatch;
13 import java.io.File;
14 import java.io.IOException;
15 import java.util.Collection;
16 import java.util.List;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
19 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22 import org.sonatype.plexus.build.incremental.BuildContext;
23
24 @NonNullByDefault
25 final class CodeGeneratorTask extends GeneratorTask<CodeGeneratorTaskFactory> {
26     private static final Logger LOG = LoggerFactory.getLogger(CodeGeneratorTask.class);
27
28     private final File outputDir;
29
30     CodeGeneratorTask(final CodeGeneratorTaskFactory factory, final ContextHolder context, final File outputDir) {
31         super(factory, context);
32         this.outputDir = requireNonNull(outputDir);
33     }
34
35     @Override
36     Collection<File> execute(final CodeGeneratorTaskFactory factory, final ContextHolder modelContext,
37             final BuildContext buildContext) throws IOException {
38         final Stopwatch watch = Stopwatch.createStarted();
39         final BasicCodeGenerator gen = factory.generator();
40         final boolean mark;
41         if (gen instanceof BuildContextAware) {
42             ((BuildContextAware)gen).setBuildContext(buildContext);
43             mark = false;
44         } else {
45             mark = true;
46         }
47
48         LOG.debug("Sources will be generated to {}", outputDir);
49         Collection<File> sources = gen.generateSources(modelContext.getContext(), outputDir,
50             modelContext.getYangModules(), modelContext);
51         if (sources == null) {
52             sources = List.of();
53         }
54
55         LOG.debug("Sources generated by {}: {}", gen.getClass(), sources);
56         LOG.info("Sources generated by {}: {} in {}", gen.getClass(), sources.size(), watch);
57
58         if (mark) {
59             sources.forEach(buildContext::refresh);
60         }
61
62         return sources;
63     }
64 }