<commit_before>/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.codehaus.griffon.artifacts

import groovy.json.JsonException
import groovy.json.JsonSlurper
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import org.codehaus.griffon.artifacts.model.Archetype
import org.codehaus.griffon.artifacts.model.Plugin
import org.codehaus.griffon.artifacts.model.Release
import org.codehaus.griffon.cli.CommandLineHelper
import org.codehaus.griffon.cli.ScriptExitException
import org.codehaus.griffon.resolve.IvyDependencyManager
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import griffon.util.*
import static griffon.util.GriffonNameUtils.*
import static griffon.util.GriffonUtil.getScriptName
import static org.codehaus.griffon.artifacts.ArtifactUtils.*

/**
 * @author <NAME>
 * @since 0.9.5
 */
class ArtifactInstallEngine {
    private static final Logger LOG = LoggerFactory.getLogger(ArtifactInstallEngine)
    private static final String INSTALL_FAILURE_KEY = 'griffon.install.failure'
    private static final String INSTALL_FAILURE_ABORT = 'abort'
    private static final String INSTALL_FAILURE_CONTINUE = 'continue'

    private final BuildSettings settings
    private final Metadata metadata
    private final AntBuilder ant
    private CommandLineHelper commandLineHelper = new CommandLineHelper(System.out)

    final List installedArtifacts = []
    final List uninstalledArtifacts = []
    def variableStore = [:]

    Closure errorHandler = { String msg -> throw new ScriptExitException(msg) }
    Closure eventHandler = { String name, String msg -> println msg }
    Closure pluginScriptRunner
    boolean interactive

    ArtifactInstallEngine(BuildSettings settings, Metadata metadata, AntBuilder ant) {
        this.settings = settings
        this.metadata = metadata
        this.ant = ant
    }

    String getInstallFailureStrategy() {
        String value = System.getProperty(INSTALL_FAILURE_KEY)
        if (isBlank(value)) {
            value = settings.config[INSTALL_FAILURE_KEY]
        }

        value = value ? value.toString().toLowerCase() : INSTALL_FAILURE_CONTINUE
        value in [INSTALL_FAILURE_ABORT, INSTALL_FAILURE_CONTINUE] ? value : INSTALL_FAILURE_CONTINUE
    }

    boolean resolvePluginDependencies() {
        Map<String, String> registeredPlugins = getRegisteredArtifacts(Plugin.TYPE, metadata)
        Map<String, String> installedPlugins = getInstalledArtifacts(Plugin.TYPE)

        if (LOG.debugEnabled) {
            String registered = registeredPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (registered) LOG.debug("Registered plugins:\n\t${registered}")
            String installed = installedPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (installed) LOG.debug("Installed plugins:\n\t${installed}")
        }

        Map<String, String> pluginsToDelete = [:]
        Map<String, String> missingPlugins = [:]
        registeredPlugins.each {name, version ->
            String v = installedPlugins[name]
            if (v != version) {
                missingPlugins[name] = version
            }
        }

        installedPlugins.each {name, version ->
            String v = registeredPlugins[name]
            if (v != version) {
                pluginsToDelete[name] = version
            }
        }

        if (LOG.debugEnabled) {
            String installed = installedPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (installed) LOG.debug("Installed plugins (confirmed):\n\t${installed}")
            String missing = missingPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (missing) LOG.debug("Missing plugins:\n\t${missing}")
            String todelete = pluginsToDelete.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (todelete) LOG.debug("Plugins to be deleted:\n\t${todelete}")
        }

        pluginsToDelete.each {name, version ->
            eventHandler 'StatusUpdate', "Plugin ${name}-${version} is installed, but was not found in the application's metadata. Removing this plugin from the application's plugin base"
            ant.delete(dir: getInstallPathFor(Plugin.TYPE, name, version), failonerror: false)
            installedPlugins.remove(name)
        }

        if (!missingPlugins) {
            /*
            try {
                installedPlugins.each { name, version ->
                    resolvePluginJarDependencies(getInstallPathFor(Plugin.TYPE, name, version).absolutePath, name, version)
                }
            } catch (Exception e) {
                GriffonExceptionHandler.sanitize(e)
                eventHandler 'StatusError', e.message
                errorHandler "Cannot continue with unresolved dependencies."
            }
            */
            return true
        }<commit_msg>1st attempt to reduce time when resolving dependencies at startup<commit_after>/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.codehaus.griffon.artifacts

import groovy.json.JsonException
import groovy.json.JsonSlurper
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import org.codehaus.griffon.artifacts.model.Archetype
import org.codehaus.griffon.artifacts.model.Plugin
import org.codehaus.griffon.artifacts.model.Release
import org.codehaus.griffon.cli.CommandLineHelper
import org.codehaus.griffon.cli.ScriptExitException
import org.codehaus.griffon.resolve.IvyDependencyManager
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import griffon.util.*
import static griffon.util.GriffonNameUtils.*
import static griffon.util.GriffonUtil.getScriptName
import static org.codehaus.griffon.artifacts.ArtifactUtils.*

/**
 * @author <NAME>
 * @since 0.9.5
 */
class ArtifactInstallEngine {
    private static final Logger LOG = LoggerFactory.getLogger(ArtifactInstallEngine)
    private static final String INSTALL_FAILURE_KEY = 'griffon.install.failure'
    private static final String INSTALL_FAILURE_ABORT = 'abort'
    private static final String INSTALL_FAILURE_CONTINUE = 'continue'

    private final BuildSettings settings
    private final Metadata metadata
    private final AntBuilder ant
    private CommandLineHelper commandLineHelper = new CommandLineHelper(System.out)

    final List installedArtifacts = []
    final List uninstalledArtifacts = []
    def variableStore = [:]

    Closure errorHandler = { String msg -> throw new ScriptExitException(msg) }
    Closure eventHandler = { String name, String msg -> println msg }
    Closure pluginScriptRunner
    boolean interactive

    ArtifactInstallEngine(BuildSettings settings, Metadata metadata, AntBuilder ant) {
        this.settings = settings
        this.metadata = metadata
        this.ant = ant
    }

    String getInstallFailureStrategy() {
        String value = System.getProperty(INSTALL_FAILURE_KEY)
        if (isBlank(value)) {
            value = settings.config[INSTALL_FAILURE_KEY]
        }

        value = value ? value.toString().toLowerCase() : INSTALL_FAILURE_CONTINUE
        value in [INSTALL_FAILURE_ABORT, INSTALL_FAILURE_CONTINUE] ? value : INSTALL_FAILURE_CONTINUE
    }

    boolean resolvePluginDependencies() {
        Map<String, String> registeredPlugins = getRegisteredArtifacts(Plugin.TYPE, metadata)
        Map<String, String> installedPlugins = getInstalledArtifacts(Plugin.TYPE)

        if (LOG.debugEnabled) {
            String registered = registeredPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (registered) LOG.debug("Registered plugins:\n\t${registered}")
            String installed = installedPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (installed) LOG.debug("Installed plugins:\n\t${installed}")
        }

        Map<String, String> pluginsToDelete = [:]
        Map<String, String> missingPlugins = [:]
        registeredPlugins.each {name, version ->
            String v = installedPlugins[name]
            if (v != version) {
                missingPlugins[name] = version
            }
        }

        installedPlugins.each {name, version ->
            String v = registeredPlugins[name]
            if (v != version) {
                pluginsToDelete[name] = version
            }
        }

        if (LOG.debugEnabled) {
            String installed = installedPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (installed) LOG.debug("Installed plugins (confirmed):\n\t${installed}")
            String missing = missingPlugins.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (missing) LOG.debug("Missing plugins:\n\t${missing}")
            String todelete = pluginsToDelete.collect([]) {k, v -> "${k}-${v}"}.join('\n\t')
            if (todelete) LOG.debug("Plugins to be deleted:\n\t${todelete}")
        }

        pluginsToDelete.each {name, version ->
            eventHandler 'StatusUpdate', "Plugin ${name}-${version} is installed, but was not found in the application's metadata. Removing this plugin from the application's plugin base"
            ant.delete(dir: getInstallPathFor(Plugin.TYPE, name, version), failonerror: false)
            installedPlugins.remove(name)
        }

        if (!missingPlugins) {
            return true
        }
{'fraction_non_alphanumeric': 0.10486819318837791, 'fraction_numerical': 0.00336732730421397, 'mean_word_length': 2.9950038431975403, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7255248', 'n_tokens_mistral': 2895, 'n_tokens_neox': 2836, 'n_words': 752}