Search in sources :

Example 6 with TemplateTo

use of com.devonfw.cobigen.api.to.TemplateTo in project cobigen by devonfw.

the class CobiGenWrapper method getOverridingFiles.

/**
 * Returns project dependent paths of all resources which are marked to be overridable (just of
 * {@link #getCurrentRepresentingInput()})
 *
 * @param increments to be considered
 * @return The set of all overridable project dependent file paths
 */
public Set<String> getOverridingFiles(Collection<IncrementTo> increments) {
    if (increments.contains(new ComparableIncrement(ALL_INCREMENT_ID, ALL_INCREMENT_NAME, null, Lists.<TemplateTo>newLinkedList(), Lists.<IncrementTo>newLinkedList()))) {
        increments = this.cobiGen.getMatchingIncrements(getCurrentRepresentingInput());
    }
    Set<String> overridablePaths = Sets.newHashSet();
    Map<String, Set<TemplateTo>> templateDestinationPaths = getTemplateDestinationPaths(increments);
    for (Entry<String, Set<TemplateTo>> entry : templateDestinationPaths.entrySet()) {
        if (isOverridableFile(entry.getValue())) {
            overridablePaths.add(entry.getKey());
        }
    }
    return overridablePaths;
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) HashSet(java.util.HashSet) Set(java.util.Set) ComparableIncrement(com.devonfw.cobigen.eclipse.generator.entity.ComparableIncrement) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 7 with TemplateTo

use of com.devonfw.cobigen.api.to.TemplateTo in project cobigen by devonfw.

the class CobiGenWrapper method generate.

/**
 * Generates the the list of templates based on the given {@link #inputs}.
 *
 * @param templates to be generated
 * @param monitor to track the progress
 * @return the {@link GenerationReportTo generation report of CobiGen}
 * @throws Exception if anything during generation fails.
 */
public GenerationReportTo generate(List<TemplateTo> templates, IProgressMonitor monitor) throws Exception {
    final IProject proj = getGenerationTargetProject();
    if (proj != null) {
        LOG.debug("Generating files...");
        SubMonitor subMonitor = SubMonitor.convert(monitor, 105);
        if (monitor.isCanceled()) {
            throw new CancellationException("generation got Cancelled by the User");
        }
        monitor.setTaskName("Load templates...");
        SubMonitor loadTemplates = subMonitor.split(2);
        // set override flags individually for every template
        for (TemplateTo template : templates) {
            // wizard and does not declare any merge strategy), the complete file should be overwritten
            if (template.getMergeStrategy() == null) {
                template.setForceOverride(true);
            }
        }
        loadTemplates.done();
        if (monitor.isCanceled()) {
            throw new CancellationException("Generation got cancelled by the user");
        }
        monitor.setTaskName("Determine destination paths...");
        SubMonitor generateTargetUri = subMonitor.split(1);
        URI generationTargetUri = getGenerationTargetProject().getLocationURI();
        if (generationTargetUri == null) {
            throw new CobiGenRuntimeException("The location URI of the generation target project " + getGenerationTargetProject().getName() + " could not be resolved. This might be " + "a temporary issue. If this problem persists, please state a bug report.");
        }
        generateTargetUri.done();
        monitor.setTaskName("Generate files...");
        GenerationReportTo report;
        if (this.singleNonContainerInput) {
            // if we only consider one input, we want to allow some customizations of the generation
            LOG.debug("Generating with single non container input ...");
            report = this.cobiGen.generate(this.inputs.get(0), templates, Paths.get(generationTargetUri), false, (String taskName, Integer progress) -> {
                monitor.setTaskName(taskName);
                monitor.worked(progress);
            });
        } else {
            report = new GenerationReportTo();
            for (Object input : this.inputs) {
                report.aggregate(this.cobiGen.generate(input, templates, Paths.get(generationTargetUri), false, (taskname, progress) -> {
                    monitor.setTaskName(taskname);
                    monitor.worked(progress);
                }));
            }
        }
        monitor.setTaskName("Refresh workspace...");
        proj.getProject().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        monitor.done();
        if (report.isSuccessful()) {
            LOG.info("Generation finished successfully.");
        }
        return report;
    } else {
        throw new CobiGenRuntimeException("No generation target project configured! This is a Bug!");
    }
}
Also used : ConfigurationConstants(com.devonfw.cobigen.api.constants.ConfigurationConstants) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) Arrays(java.util.Arrays) ResourcesPlugin(org.eclipse.core.resources.ResourcesPlugin) SubMonitor(org.eclipse.core.runtime.SubMonitor) LoggerFactory(org.slf4j.LoggerFactory) CobiGen(com.devonfw.cobigen.api.CobiGen) Function(java.util.function.Function) PlatformUIUtil(com.devonfw.cobigen.eclipse.common.tools.PlatformUIUtil) InvalidInputException(com.devonfw.cobigen.eclipse.common.exceptions.InvalidInputException) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) IProject(org.eclipse.core.resources.IProject) ComparableIncrement(com.devonfw.cobigen.eclipse.generator.entity.ComparableIncrement) Map(java.util.Map) URI(java.net.URI) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) MapUtils(com.devonfw.cobigen.eclipse.common.tools.MapUtils) Trigger(org.eclipse.jface.bindings.Trigger) Logger(org.slf4j.Logger) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) Iterator(java.util.Iterator) CancellationException(java.util.concurrent.CancellationException) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ProgressMonitorDialog(org.eclipse.jface.dialogs.ProgressMonitorDialog) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) IOException(java.io.IOException) CobiGenEclipseRuntimeException(com.devonfw.cobigen.eclipse.common.exceptions.CobiGenEclipseRuntimeException) Display(org.eclipse.swt.widgets.Display) InvalidConfigurationException(com.devonfw.cobigen.api.exception.InvalidConfigurationException) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) InvocationTargetException(java.lang.reflect.InvocationTargetException) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) List(java.util.List) Paths(java.nio.file.Paths) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) GeneratorProjectNotExistentException(com.devonfw.cobigen.eclipse.common.exceptions.GeneratorProjectNotExistentException) IResource(org.eclipse.core.resources.IResource) Entry(java.util.Map.Entry) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CancellationException(java.util.concurrent.CancellationException) SubMonitor(org.eclipse.core.runtime.SubMonitor) URI(java.net.URI) IProject(org.eclipse.core.resources.IProject) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 8 with TemplateTo

use of com.devonfw.cobigen.api.to.TemplateTo in project cobigen by devonfw.

the class GenerationProcessorImpl method flatten.

/**
 * Flattens the {@link GenerableArtifact}s to a list of {@link TemplateTo}s also removing duplicates.
 *
 * @param generableArtifacts {@link List} of {@link GenerableArtifact}s to be flattened
 * @return {@link Collection} of collected {@link TemplateTo}s
 */
private Collection<TemplateTo> flatten(List<? extends GenerableArtifact> generableArtifacts) {
    // create Map to remove duplicates by ID
    Map<String, TemplateTo> templateIdToTemplateMap = Maps.newHashMap();
    for (GenerableArtifact artifact : generableArtifacts) {
        if (artifact instanceof TemplateTo) {
            TemplateTo template = (TemplateTo) artifact;
            checkAndAddToTemplateMap(templateIdToTemplateMap, template);
        } else if (artifact instanceof IncrementTo) {
            for (TemplateTo template : ((IncrementTo) artifact).getTemplates()) {
                checkAndAddToTemplateMap(templateIdToTemplateMap, template);
            }
        } else {
            throw new IllegalArgumentException("Unknown GenerableArtifact type '" + artifact.getClass().getCanonicalName() + "'.");
        }
    }
    return new TreeSet<>(templateIdToTemplateMap.values());
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) TreeSet(java.util.TreeSet) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 9 with TemplateTo

use of com.devonfw.cobigen.api.to.TemplateTo in project cobigen by devonfw.

the class GenerationProcessorImpl method generate.

@Override
public GenerationReportTo generate(Object input, List<? extends GenerableArtifact> generableArtifacts, Path targetRootPath, boolean forceOverride, Map<String, Object> rawModel, BiConsumer<String, Integer> progressCallback) {
    InputValidator.validateInputsUnequalNull(input, generableArtifacts);
    List<Class<?>> logicClasses = null;
    // only implicit dependency to javaplugin to lower classloader complexity
    ClassLoader inputProjectClassLoader = null;
    if (input instanceof Class) {
        inputProjectClassLoader = ((Class<?>) input).getClassLoader();
    } else if (input instanceof Object[]) {
        for (Object obj : (Object[]) input) {
            if (obj instanceof Class) {
                inputProjectClassLoader = ((Class<?>) obj).getClassLoader();
            }
        }
    }
    Path templateConfigPath = Paths.get(this.configurationHolder.getConfigurationLocation());
    progressCallback.accept("Prepend Templates Classloader", 10);
    inputProjectClassLoader = prependTemplatesClassloader(templateConfigPath, inputProjectClassLoader);
    if (inputProjectClassLoader != null) {
        try {
            logicClasses = ConfigurationClassLoaderUtil.resolveUtilClasses(this.configurationHolder, inputProjectClassLoader);
        } catch (IOException e) {
            LOG.error("An IOException occured while resolving utility classes!", e);
        }
    }
    // initialize
    this.forceOverride = forceOverride;
    this.input = input;
    if (logicClasses != null) {
        progressCallback.accept("Load Template logic classes", 20);
        loadLogicClasses(progressCallback, logicClasses);
    }
    progressCallback.accept("Create Temporary Target Directory", 40);
    this.rawModel = rawModel;
    try {
        this.tmpTargetRootPath = Files.createTempDirectory("cobigen-");
        LOG.info("Temporary working directory: {}", this.tmpTargetRootPath);
    } catch (IOException e) {
        throw new CobiGenRuntimeException("Could not create temporary folder.", e);
    }
    this.targetRootPath = targetRootPath;
    this.generationReport = new GenerationReportTo();
    progressCallback.accept("Load templates", 50);
    LOG.debug("Collecting templates");
    Collection<TemplateTo> templatesToBeGenerated = flatten(generableArtifacts);
    // generate
    Map<File, File> origToTmpFileTrace = Maps.newHashMap();
    try {
        LOG.debug("Generating {} templates", templatesToBeGenerated.size());
        for (TemplateTo template : templatesToBeGenerated) {
            try {
                Trigger trigger = this.configurationHolder.readContextConfiguration().getTrigger(template.getTriggerId());
                TriggerInterpreter triggerInterpreter = PluginRegistry.getTriggerInterpreter(trigger.getType());
                InputValidator.validateTriggerInterpreter(triggerInterpreter, trigger);
                progressCallback.accept("Generating " + template.getId(), Math.round(1 / (float) templatesToBeGenerated.size() * 800));
                generate(template, triggerInterpreter, origToTmpFileTrace, progressCallback);
            } catch (CobiGenCancellationException e) {
                throw (e);
            } catch (CobiGenRuntimeException e) {
                this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
                this.generationReport.addError(e);
            } catch (Throwable e) {
                this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
                this.generationReport.addError(new CobiGenRuntimeException("Something unexpected happened" + ((e.getMessage() != null) ? ": " + e.getMessage() : "!"), e));
            }
        }
    } catch (CobiGenCancellationException e) {
        LOG.error("the Generation has been Canceled.", e);
        this.generationReport.setCancelled(true);
    }
    if (this.generationReport.isCancelled()) {
        this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
        this.tmpTargetRootPath.toFile().deleteOnExit();
    // do nothing if cancelled
    } else if (this.generationReport.isSuccessful()) {
        try {
            for (Entry<File, File> origToTmpFile : origToTmpFileTrace.entrySet()) {
                Files.createDirectories(origToTmpFile.getKey().toPath().getParent());
                Files.copy(origToTmpFile.getValue().toPath(), origToTmpFile.getKey().toPath(), StandardCopyOption.REPLACE_EXISTING);
                this.generationReport.addGeneratedFile(origToTmpFile.getKey().toPath());
            }
            this.tmpTargetRootPath.toFile().deleteOnExit();
        } catch (IOException e) {
            this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
            throw new CobiGenRuntimeException("Could not copy generated files to target location!", e);
        }
    } else {
        this.generationReport.setTemporaryWorkingDirectory(this.tmpTargetRootPath);
        LOG.warn("Generation finished non-successful. Generated contents can be reviewed in " + this.tmpTargetRootPath.toUri());
    }
    return this.generationReport;
}
Also used : Path(java.nio.file.Path) TriggerInterpreter(com.devonfw.cobigen.api.extension.TriggerInterpreter) CobiGenRuntimeException(com.devonfw.cobigen.api.exception.CobiGenRuntimeException) CobiGenCancellationException(com.devonfw.cobigen.api.exception.CobiGenCancellationException) IOException(java.io.IOException) Entry(java.util.Map.Entry) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) Trigger(com.devonfw.cobigen.impl.config.entity.Trigger) URLClassLoader(java.net.URLClassLoader) File(java.io.File) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Example 10 with TemplateTo

use of com.devonfw.cobigen.api.to.TemplateTo in project cobigen by devonfw.

the class GenerateCommand method search.

/**
 * Search for generable artifacts (increments or templates) matching the user input. Generable artifacts similar to
 * the given search string or containing it are returned.
 *
 * @param <T> The type of generable artifacts
 * @param userInput the user's wished increment or template
 * @param matching all increments or templates that are valid to the input file(s)
 * @param c class type, specifies whether Templates or Increments should be preprocessed
 * @return Increments or templates matching the search string
 */
private <T extends GenerableArtifact> List<T> search(String userInput, List<T> matching, Class<?> c) {
    boolean isIncrements = c.getSimpleName().equals(IncrementTo.class.getSimpleName());
    Map<T, Double> scores = new HashMap<>();
    for (int i = 0; i < matching.size(); i++) {
        if (!isIncrements) {
            String description = ((TemplateTo) matching.get(i)).getId();
            JaccardDistance distance = new JaccardDistance();
            scores.put(matching.get(i), distance.apply(description.toUpperCase(), userInput.toUpperCase()));
        } else {
            String description = ((IncrementTo) matching.get(i)).getDescription();
            String id = ((IncrementTo) matching.get(i)).getId();
            JaccardDistance distance = new JaccardDistance();
            double descriptionDistance = distance.apply(description.toUpperCase(), userInput.toUpperCase());
            double idDistance = distance.apply(id.toUpperCase(), userInput.toUpperCase());
            scores.put(matching.get(i), Math.min(idDistance, descriptionDistance));
        }
    }
    Map<T, Double> sorted = scores.entrySet().stream().sorted(comparingByValue()).collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));
    List<T> chosen = new ArrayList<>();
    for (T artifact : sorted.keySet()) {
        T tmp = isIncrements ? artifact : artifact;
        if (!isIncrements) {
            String description = ((TemplateTo) artifact).getId();
            if (description.toUpperCase().contains(userInput.toUpperCase()) || sorted.get(artifact) <= this.SELECTION_THRESHOLD) {
                chosen.add(tmp);
            }
        } else {
            String description = ((IncrementTo) artifact).getDescription();
            String id = ((IncrementTo) artifact).getId();
            if (description.equalsIgnoreCase(userInput) || id.equalsIgnoreCase(userInput)) {
                chosen.add(tmp);
                return chosen;
            }
            if ((description.toUpperCase().contains(userInput.toUpperCase()) || id.toUpperCase().contains(userInput.toUpperCase())) || sorted.get(artifact) <= this.SELECTION_THRESHOLD) {
                chosen.add(tmp);
            }
        }
    }
    return chosen;
}
Also used : IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) Parameters(picocli.CommandLine.Parameters) LoggerFactory(org.slf4j.LoggerFactory) Entry.comparingByValue(java.util.Map.Entry.comparingByValue) HashMap(java.util.HashMap) InputMismatchException(java.util.InputMismatchException) CobiGen(com.devonfw.cobigen.api.CobiGen) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) CobiGenCLI(com.devonfw.cobigen.cli.CobiGenCLI) URI(java.net.URI) FormatterException(com.google.googlejavaformat.java.FormatterException) Command(picocli.CommandLine.Command) Path(java.nio.file.Path) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) ConfigurationFinder(com.devonfw.cobigen.impl.util.ConfigurationFinder) UserAbortException(com.devonfw.cobigen.cli.exceptions.UserAbortException) ValidationUtils(com.devonfw.cobigen.cli.utils.ValidationUtils) Logger(org.slf4j.Logger) Tuple(com.devonfw.cobigen.api.util.Tuple) Files(java.nio.file.Files) MavenUtil(com.devonfw.cobigen.api.util.MavenUtil) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ParsingUtils(com.devonfw.cobigen.cli.utils.ParsingUtils) StandardCharsets(java.nio.charset.StandardCharsets) GenerationReportTo(com.devonfw.cobigen.api.to.GenerationReportTo) CobiGenUtils(com.devonfw.cobigen.cli.utils.CobiGenUtils) List(java.util.List) Option(picocli.CommandLine.Option) MessagesConstants(com.devonfw.cobigen.cli.constants.MessagesConstants) Paths(java.nio.file.Paths) GenerableArtifact(com.devonfw.cobigen.api.to.GenerableArtifact) JaccardDistance(org.apache.commons.text.similarity.JaccardDistance) FileSystemUtil(com.devonfw.cobigen.impl.util.FileSystemUtil) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) JaccardDistance(org.apache.commons.text.similarity.JaccardDistance) ArrayList(java.util.ArrayList) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo)

Aggregations

TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)41 CobiGen (com.devonfw.cobigen.api.CobiGen)30 File (java.io.File)28 Test (org.junit.Test)27 GenerationReportTo (com.devonfw.cobigen.api.to.GenerationReportTo)25 AbstractApiTest (com.devonfw.cobigen.systemtest.common.AbstractApiTest)12 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)9 Path (java.nio.file.Path)9 List (java.util.List)9 AssertionFailedError (junit.framework.AssertionFailedError)9 Paths (java.nio.file.Paths)6 Set (java.util.Set)6 HashSet (java.util.HashSet)5 Collectors (java.util.stream.Collectors)5 CobiGenAsserts.assertThat (com.devonfw.cobigen.api.assertj.CobiGenAsserts.assertThat)4 GenerationReportToAssert (com.devonfw.cobigen.api.assertj.GenerationReportToAssert)4 ComparableIncrement (com.devonfw.cobigen.eclipse.generator.entity.ComparableIncrement)4 CobiGenFactory (com.devonfw.cobigen.impl.CobiGenFactory)4 AbstractIntegrationTest (com.devonfw.cobigen.javaplugin.integrationtest.common.AbstractIntegrationTest)4 StandardCharsets (java.nio.charset.StandardCharsets)4