All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.atlassian.maven.plugins.CopyArtifactsFromListMojo.groovy Maven / Gradle / Ivy

/*
 * Copyright © 2015 Atlassian Pty Ltd. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.atlassian.maven.plugins

import org.apache.maven.artifact.Artifact
import org.apache.maven.artifact.factory.ArtifactFactory
import org.apache.maven.artifact.repository.ArtifactRepository
import org.apache.maven.artifact.resolver.ArtifactResolver
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugin.MojoFailureException
import org.apache.maven.project.MavenProject
import org.codehaus.gmaven.mojo.GroovyMojo
import org.codehaus.plexus.util.FileUtils

import java.nio.file.FileSystems
import java.nio.file.Files

/**
 * Copy artifacts from a gavpc list MOJO.
 *
 * @goal copy-listed-artifacts
 */
class CopyArtifactsFromListMojo extends GroovyMojo {
    /**
     * The gav of the list artifact deployed by generate-dependencies-artifacts mojo
     *
     * @parameter
     */
    String sourceList

    /**
     * The target directory to copy artifacts to
     *
     * @parameter default-value='${project.build.directory}'
     */
    String targetDirectory

    /**
     * The local Maven repository.
     *
     * @parameter expression="${localRepository}"
     * @required
     * @readonly
     */
    ArtifactRepository localRepository;

    /**
     * The remote Maven repositories.
     *
     * @parameter default-value="${project.remoteArtifactRepositories}"
     * @required
     * @readonly
     */
    List remoteRepositories;

    /**
     * @component
     */
    ArtifactResolver artifactResolver;

    /**
     * @parameter expression="${project}"
     * @required
     * @readonly
     */
    MavenProject project

    /**
     * The artifact factory
     *
     * @component
     */
    private ArtifactFactory artifactFactory;

    private Boolean cachedUseHardLinks = null;

    /**
     * Creates the archive containing the artifacts of this project's dependencies.
     * Call from superclass and put your code in closure.
     */
    @Override
    void execute() throws MojoExecutionException, MojoFailureException {
        log.debug('List at: ' + sourceList)

        def targetDirectoryFile = new File(targetDirectory)
        ensureDirectoryExists(targetDirectoryFile)
        def artifactUtil = new ArtifactUtil(artifactFactory)

        new File(sourceList).eachLine { line ->

            log.debug("Line is: ${line}")

            Artifact artifact = artifactUtil.fromString(line)
            if (artifact == null) {
                throw new MojoExecutionException("Could not decode artifact: ${line}".toString())
            }

            if (!artifact.isResolved()) {
                artifactResolver.resolve(artifact, remoteRepositories, localRepository)
            }

            if (artifact.isResolved()) {
                log.debug("Configured artifact: ${line}")
                copyOrHardLink(artifact, targetDirectoryFile)
            } else {
                throw new MojoExecutionException("Could not resolve artifact: ${line}".toString())
            }
        }
    }

    private static void ensureDirectoryExists(File targetDirectoryFile) {
        if (targetDirectoryFile.exists()) {
            if (targetDirectoryFile.isDirectory()) {
                // cool, it's a directory, we're done here.
            } else {
                // if it's a file, delete it.
                targetDirectoryFile.delete()
            }
        } else {
            // the path does not exist:
            if (!targetDirectoryFile.mkdirs()) {
                throw new MojoExecutionException("Could not create directory ${targetDirectoryFile.absolutePath}")
            }
        }
    }

    private copyOrHardLink(Artifact artifact, File targetDirectoryFile) {

        if (useHardLinks()) {
            try {
                createHardLink(targetDirectoryFile, artifact)
            } catch (Exception exception) {
                log.warn('Could not create hard link. Switching off hard linking, defaulting to copying.', exception)
                forceDisableHardLinks()
                copyArtifactToDirectory(artifact, targetDirectoryFile)
            }
        } else {
            copyArtifactToDirectory(artifact, targetDirectoryFile)
        }
    }

    private void createHardLink(File targetDirectoryFile, Artifact artifact) {
        File targetFile = new File(targetDirectoryFile, artifact.file.name)
        if (targetFile.exists()) {
            targetFile.delete()
        }
        def linkPath = FileSystems.default.getPath(targetFile.absolutePath)
        def artifactPath = FileSystems.default.getPath(artifact.file.absolutePath)
        log.debug("Linking ${artifactPath} to ${linkPath}")
        Files.createLink(linkPath, artifactPath)
    }

    private void copyArtifactToDirectory(Artifact artifact, File targetDirectoryFile) {
        log.debug("Copying ${artifact.file.absolutePath} to ${targetDirectoryFile.absolutePath}")
        FileUtils.copyFileToDirectory(artifact.file, targetDirectoryFile)
    }

    private void forceDisableHardLinks() {
        cachedUseHardLinks = false
    }

    private boolean useHardLinks() {
        if (cachedUseHardLinks != null) {
            return cachedUseHardLinks;
        }

        try {
            FileSystems.getDefault()
            log.info('Will use hardlinks instead of copying for listed dependencies.')
            cachedUseHardLinks = true
        } catch (NoClassDefFoundError ignored) {
            log.info('Hard links are not available. Will use plain copying.')
            cachedUseHardLinks = false
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy