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

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

The newest version!
/*
 * Copyright © 2022 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 com.google.common.annotations.VisibleForTesting;
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.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.codehaus.plexus.util.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import static java.lang.String.format;

@Mojo(name = "copy-listed-artifacts")
public class CopyArtifactsFromListMojo extends DependencyInspectingMojo {

    /**
     * The artifact factory
     */
    @Component
    private ArtifactFactory artifactFactory;
    private Boolean cachedUseHardLinks = null;
    /**
     * The gav of the list artifact deployed by generate-dependencies-artifacts mojo
     */
    @Parameter(name = "sourceList")
    private String sourceList;
    /**
     * The target directory to copy artifacts to
     */
    @Parameter(defaultValue = "${project.build.directory}")
    private String targetDirectory;

    public CopyArtifactsFromListMojo() {
        //Used by Maven/Plexus
    }

    @VisibleForTesting
    public CopyArtifactsFromListMojo(ArtifactResolver artifactResolver, String excludeArtifactIds, String includeScope,
                                     ArtifactRepository localRepository, MavenProject project,
                                     MavenProjectHelper projectHelper, List remoteRepositories,
                                     ArtifactFactory artifactFactory,
                                      String sourceList,
                                     String targetDirectory) {
        //used by tests
        super(artifactResolver, excludeArtifactIds, includeScope, localRepository, project, projectHelper, remoteRepositories);
        this.artifactFactory = artifactFactory;
        this.artifactResolver = artifactResolver;
        this.remoteRepositories = remoteRepositories;
        this.sourceList = sourceList;
        this.targetDirectory = targetDirectory;
    }

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

        File targetDirectoryFile = new File(targetDirectory);
        ensureDirectoryExists(targetDirectoryFile);
        ArtifactUtil artifactUtil = new ArtifactUtil(artifactFactory);
        try (BufferedReader br = new BufferedReader(new FileReader(sourceList))) {
            String line;
            while ((line = br.readLine()) != null) {
                log.debug("Line is: " + line);

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

                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);
                }
            }
        } catch (IOException | ArtifactResolutionException | ArtifactNotFoundException e) {
            throw new MojoFailureException("Failed to copy artifacts", e);
        }
    }

    private static void ensureDirectoryExists(File targetDirectoryFile) throws MojoExecutionException {
        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.getAbsolutePath());
            }
        }
    }

    private void copyArtifactToDirectory(Artifact artifact, File targetDirectoryFile) throws IOException {
        log.debug(format("Copying %s to %s", artifact.getFile().getAbsolutePath(), targetDirectoryFile.getAbsolutePath()));
        FileUtils.copyFileToDirectory(artifact.getFile(), targetDirectoryFile);
    }

    private void copyOrHardLink(Artifact artifact, File targetDirectoryFile) throws IOException {

        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) throws IOException {
        File targetFile = new File(targetDirectoryFile, artifact.getFile().getName());
        if (targetFile.exists()) {
            targetFile.delete();
        }
        Path linkPath = FileSystems.getDefault().getPath(targetFile.getAbsolutePath());
        Path artifactPath = FileSystems.getDefault().getPath(artifact.getFile().getAbsolutePath());
        log.debug(format("Linking %s to %s", artifactPath, linkPath));
        Files.createLink(linkPath, artifactPath);
    }

    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;
        }
        return cachedUseHardLinks;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy