<commit_before>/*
 * Copyright 2004-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.
 */

import griffon.util.Environment
import griffon.util.Metadata
import griffon.util.PlatformUtils
import griffon.util.RunMode
import java.text.SimpleDateFormat
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import org.springframework.core.io.Resource
import static griffon.util.GriffonApplicationUtils.is64Bit
import static griffon.util.GriffonApplicationUtils.osArch
import static griffon.util.GriffonNameUtils.capitalize

/**
 * Gant script that packages a Griffon application (note: does not create WAR)
 *
 * @author <NAME> (Grails 0.4)
 * @author <NAME>
 * @author <NAME>
 */

// No point doing this stuff more than once.
if (getBinding().variables.containsKey("_griffon_package_called")) return
_griffon_package_called = true

includeTargets << griffonScript('_GriffonCompile')

configTweaks = []

target(name: 'createConfig', description: 'Creates the configuration object',
        prehook: null, posthook: null) {
    depends(compile)
    configTweaks.each {tweak -> tweak() }
}

target(name: 'packageApp', description: '',
        prehook: null, posthook: null) {
    depends(createStructure)

    try {
        profile("compile") {
            compile()
        }
    }
    catch (Exception e) {
        logError("Compilation error", e)
        exit(1)
    }
    profile("creating config") {
        createConfig()
    }

    // flag if <application>.jar is up to date
    jardir = ant.antProject.replaceProperties(buildConfig.griffon.jars.destDir)
    ant.uptodate(property: 'appJarUpToDate', targetfile: "${jardir}/${buildConfig.griffon.jars.jarName}") {
        srcfiles(dir: "${basedir}/griffon-app/", includes: "**/*")
        srcfiles(dir: "$projectMainClassesDir", includes: "**/*")
    }

    packageResources()

    checkKey()
    _copyLibs()
    jarFiles()

    event("PackagingEnd", [])
}

target(name: 'packageResources', description: "Presp app/plugin resources for packaging",
        prehook: null, posthook: null) {
    i18nDir = new File("${resourcesDirPath}/griffon-app/i18n")
    ant.mkdir(dir: i18nDir)

    resourcesDir = new File("${resourcesDirPath}/griffon-app/resources")
    ant.mkdir(dir: resourcesDir)

    if (!isPluginProject || isAddonPlugin) {
        collectArtifactMetadata()
        collectAddonMetadata()
    }

    if (buildConfig.griffon.enable.native2ascii) {
        profile("converting native message bundles to ascii") {
            ant.native2ascii(src: "${basedir}/griffon-app/i18n",
                    dest: i18nDir,
                    includes: "*.properties",
                    encoding: "UTF-8")
            ant.native2ascii(src: "${basedir}/griffon-app/resources",
                    dest: resourcesDir,
                    includes: "*.properties",
                    encoding: "UTF-8")
        }
    }
    else {
        ant.copy(todir: i18nDir) {
            fileset(dir: "${basedir}/griffon-app/i18n", includes: "*.properties")
        }
        ant.copy(todir: resourcesDir) {
            fileset(dir: "${basedir}/griffon-app/resources", includes: "*.properties")
        }
    }
    ant.copy(todir: i18nDir) {
        fileset(dir: "${basedir}/griffon-app/i18n", includes: "*.groovy")
    }
    ant.copy(todir: resourcesDir) {
        fileset(dir: "${basedir}/griffon-app/resources", includes: "**/*.*", excludes: "**/*.properties")
        fileset(dir: "${basedir}/src/main") {
            include(name: "**/*")
            exclude(name: "**/*.java")
            exclude(name: "**/*.groovy")
        }
    }
    ant.copy(todir: projectMainClassesDir) {
        fileset(dir: "${basedir}", includes: metadataFile.name)
    }

    // GRIFFON-189 add environment info to metadata
    File metaFile = new File(projectMainClassesDir, metadataFile.name)
    updateMetadata(metaFile, (Environment.KEY): Environment.current.name)

    ant.copy(todir: resourcesDirPath, failonerror: false) {
        fileset(dir: "${basedir}/griffon-app/conf", includes: "**", excludes: "*.groovy, log4j*, webstart")
        fileset(dir: "${basedir}/src/main") {
            include(name: "**/**")
            exclude(name: "**/*.java")
            exclude(name: "**/*.groovy")
        }
    }
}

collectArtifactMetadata = {
    def artifactPaths = [
            [type: "model", path: "models", suffix: "Model"],
            [type: "view", path: "views", suffix: "View"],
            [type: "controller", path: "controllers", suffix: "Controller"],
            [type: "service", path: "services", suffix: "Service"]
    ]

    event("CollectArtifacts", [artifactPaths])

    def artifacts = [:]
    searchPath = new File(basedir, 'griffon-app')
    searchPath.eachFileRecurse { file ->
        artifactPaths.find { entry ->
            def fixedPath = file.path - searchPath.canonicalPath //fix problem when project inside dir "jobs" (eg. hudson stores projects under jobs-directory)
            if (fixedPath =~ entry.path && file.isFile()) {
                def klass = fixedPath.substring(2 + entry.path.size()).replace(File.separator, ".")
                klass = klass.substring(0, klass.lastIndexOf("."))
                if (entry.suffix) {
                    if (klass.endsWith(entry.suffix)) artifacts.get(entry.type, []) << klass
                } else {
                    artifacts.get(entry.type, []) << klass
                }
            }
        }
    }

    if (artifacts) {
        File artifactMetadataDir = new File("${resourcesDirPath}/griffon-app/resources/META-INF")
        artifactMetadataDir.mkdirs()
        File artifactMetadataFile = new File(artifactMetadataDir, '/griffon-artifacts.properties')
        artifactMetadataFile.withPrintWriter { writer ->
            artifacts.each { type, list ->
                writer.println("$type = '${list.join(',')}'")
            }
        }
    }
}

collectAddonMetadata = {
    Map addons = [:]
    pluginSettings.sortedPluginDirectories.each { String name, Resource dir ->
        if (resolveResources("file://${dir.file}/dist/griffon-${name}-*-runtime.jar") ||
                resolveResources("file://${dir.file}/addon/griffon-${name}-addon-*.jar")) {
            String pluginDirName = dir.file.name<commit_msg>Missed one change in packaging when removed classifier usage<commit_after>/*
 * Copyright 2004-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.
 */

import griffon.util.Environment
import griffon.util.Metadata
import griffon.util.PlatformUtils
import griffon.util.RunMode
import java.text.SimpleDateFormat
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import org.springframework.core.io.Resource
import static griffon.util.GriffonApplicationUtils.is64Bit
import static griffon.util.GriffonApplicationUtils.osArch
import static griffon.util.GriffonNameUtils.capitalize

/**
 * Gant script that packages a Griffon application (note: does not create WAR)
 *
 * @author <NAME> (Grails 0.4)
 * @author <NAME>
 * @author <NAME>
 */

// No point doing this stuff more than once.
if (getBinding().variables.containsKey("_griffon_package_called")) return
_griffon_package_called = true

includeTargets << griffonScript('_GriffonCompile')

configTweaks = []

target(name: 'createConfig', description: 'Creates the configuration object',
        prehook: null, posthook: null) {
    depends(compile)
    configTweaks.each {tweak -> tweak() }
}

target(name: 'packageApp', description: '',
        prehook: null, posthook: null) {
    depends(createStructure)

    try {
        profile("compile") {
            compile()
        }
    }
    catch (Exception e) {
        logError("Compilation error", e)
        exit(1)
    }
    profile("creating config") {
        createConfig()
    }

    // flag if <application>.jar is up to date
    jardir = ant.antProject.replaceProperties(buildConfig.griffon.jars.destDir)
    ant.uptodate(property: 'appJarUpToDate', targetfile: "${jardir}/${buildConfig.griffon.jars.jarName}") {
        srcfiles(dir: "${basedir}/griffon-app/", includes: "**/*")
        srcfiles(dir: "$projectMainClassesDir", includes: "**/*")
    }

    packageResources()

    checkKey()
    _copyLibs()
    jarFiles()

    event("PackagingEnd", [])
}

target(name: 'packageResources', description: "Presp app/plugin resources for packaging",
        prehook: null, posthook: null) {
    i18nDir = new File("${resourcesDirPath}/griffon-app/i18n")
    ant.mkdir(dir: i18nDir)

    resourcesDir = new File("${resourcesDirPath}/griffon-app/resources")
    ant.mkdir(dir: resourcesDir)

    if (!isPluginProject || isAddonPlugin) {
        collectArtifactMetadata()
        collectAddonMetadata()
    }

    if (buildConfig.griffon.enable.native2ascii) {
        profile("converting native message bundles to ascii") {
            ant.native2ascii(src: "${basedir}/griffon-app/i18n",
                    dest: i18nDir,
                    includes: "*.properties",
                    encoding: "UTF-8")
            ant.native2ascii(src: "${basedir}/griffon-app/resources",
                    dest: resourcesDir,
                    includes: "*.properties",
                    encoding: "UTF-8")
        }
    }
    else {
        ant.copy(todir: i18nDir) {
            fileset(dir: "${basedir}/griffon-app/i18n", includes: "*.properties")
        }
        ant.copy(todir: resourcesDir) {
            fileset(dir: "${basedir}/griffon-app/resources", includes: "*.properties")
        }
    }
    ant.copy(todir: i18nDir) {
        fileset(dir: "${basedir}/griffon-app/i18n", includes: "*.groovy")
    }
    ant.copy(todir: resourcesDir) {
        fileset(dir: "${basedir}/griffon-app/resources", includes: "**/*.*", excludes: "**/*.properties")
        fileset(dir: "${basedir}/src/main") {
            include(name: "**/*")
            exclude(name: "**/*.java")
            exclude(name: "**/*.groovy")
        }
    }
    ant.copy(todir: projectMainClassesDir) {
        fileset(dir: "${basedir}", includes: metadataFile.name)
    }

    // GRIFFON-189 add environment info to metadata
    File metaFile = new File(projectMainClassesDir, metadataFile.name)
    updateMetadata(metaFile, (Environment.KEY): Environment.current.name)

    ant.copy(todir: resourcesDirPath, failonerror: false) {
        fileset(dir: "${basedir}/griffon-app/conf", includes: "**", excludes: "*.groovy, log4j*, webstart")
        fileset(dir: "${basedir}/src/main") {
            include(name: "**/**")
            exclude(name: "**/*.java")
            exclude(name: "**/*.groovy")
        }
    }
}

collectArtifactMetadata = {
    def artifactPaths = [
            [type: "model", path: "models", suffix: "Model"],
            [type: "view", path: "views", suffix: "View"],
            [type: "controller", path: "controllers", suffix: "Controller"],
            [type: "service", path: "services", suffix: "Service"]
    ]

    event("CollectArtifacts", [artifactPaths])

    def artifacts = [:]
    searchPath = new File(basedir, 'griffon-app')
    searchPath.eachFileRecurse { file ->
        artifactPaths.find { entry ->
            def fixedPath = file.path - searchPath.canonicalPath //fix problem when project inside dir "jobs" (eg. hudson stores projects under jobs-directory)
            if (fixedPath =~ entry.path && file.isFile()) {
                def klass = fixedPath.substring(2 + entry.path.size()).replace(File.separator, ".")
                klass = klass.substring(0, klass.lastIndexOf("."))
                if (entry.suffix) {
                    if (klass.endsWith(entry.suffix)) artifacts.get(entry.type, []) << klass
                } else {
                    artifacts.get(entry.type, []) << klass
                }
            }
        }
    }

    if (artifacts) {
        File artifactMetadataDir = new File("${resourcesDirPath}/griffon-app/resources/META-INF")
        artifactMetadataDir.mkdirs()
        File artifactMetadataFile = new File(artifactMetadataDir, '/griffon-artifacts.properties')
        artifactMetadataFile.withPrintWriter { writer ->
            artifacts.each { type, list ->
                writer.println("$type = '${list.join(',')}'")
            }
        }
    }
}

collectAddonMetadata = {
    Map addons = [:]
    pluginSettings.sortedPluginDirectories.each { String name, Resource dir ->
        if (resolveResources("file://${dir.file}/dist/griffon-${name}-runtime-*.jar") ||
                resolveResources("file://${dir.file}/addon/griffon-${name}-addon-*.jar")) {
            String pluginDirName = dir.file.name
{'fraction_non_alphanumeric': 0.13904607922392886, 'fraction_numerical': 0.006761225839641361, 'mean_word_length': 2.702857142857143, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 23, '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': '5563695', 'n_tokens_mistral': 4167, 'n_tokens_neox': 4007, 'n_words': 883}