From 955ea0ed5c2a7a3189159158e1fcb10e1ed2964e Mon Sep 17 00:00:00 2001 From: Sylwester Lachiewicz Date: Sat, 15 Apr 2023 02:00:11 +0200 Subject: [PATCH] [MGPG-94] Reformat code --- pom.xml | 31 +- .../maven/plugins/gpg/AbstractGpgMojo.java | 112 ++--- .../maven/plugins/gpg/AbstractGpgSigner.java | 138 ++--- .../plugins/gpg/AscArtifactMetadata.java | 109 ++-- .../plugins/gpg/AttachedSignedArtifact.java | 213 +++----- .../plugins/gpg/GpgSignAttachedMojo.java | 139 +++-- .../apache/maven/plugins/gpg/GpgSigner.java | 186 +++---- .../apache/maven/plugins/gpg/GpgVersion.java | 87 ++-- .../maven/plugins/gpg/GpgVersionParser.java | 73 +-- .../plugins/gpg/SignAndDeployFileMojo.java | 475 +++++++----------- .../maven/plugins/gpg/SigningBundle.java | 22 +- .../plugins/gpg/GpgVersionConsumerTest.java | 21 +- .../maven/plugins/gpg/GpgVersionTest.java | 70 +-- .../maven/plugins/gpg/it/BuildResult.java | 16 +- .../plugins/gpg/it/GpgSignArtifactIT.java | 86 ++-- .../plugins/gpg/it/GpgSignAttachedMojoIT.java | 49 +- .../plugins/gpg/it/InvokerTestUtils.java | 81 ++- 17 files changed, 779 insertions(+), 1129 deletions(-) diff --git a/pom.xml b/pom.xml index b75b5be..aa8aa25 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - + - 4.0.0 - maven-plugins org.apache.maven.plugins + maven-plugins 39 @@ -43,8 +41,8 @@ under the License. scm:git:https://gitbox.apache.org/repos/asf/maven-gpg-plugin.git scm:git:https://gitbox.apache.org/repos/asf/maven-gpg-plugin.git - https://github.com/apache/maven-gpg-plugin/tree/${project.scm.tag} HEAD + https://github.com/apache/maven-gpg-plugin/tree/${project.scm.tag} jira @@ -139,7 +137,7 @@ under the License. plexus-sec-dispatcher 1.4 - + junit junit @@ -163,8 +161,8 @@ under the License. - ${basedir}/src/test/resources true + ${basedir}/src/test/resources **/pom.xml **/settings.xml @@ -238,14 +236,6 @@ under the License. org.apache.maven.plugins maven-failsafe-plugin - - - - integration-test - verify - - - true @@ -258,6 +248,14 @@ under the License. /it/settings.xml + + + + integration-test + verify + + + org.apache.maven.plugins @@ -268,7 +266,8 @@ under the License. * - alternative-secret-keyring + + alternative-secret-keyring clean diff --git a/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgMojo.java b/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgMojo.java index fdf33d5..ad9f47a 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgMojo.java +++ b/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.io.IOException; @@ -38,9 +37,7 @@ /** * @author Benjamin Bentmann */ -public abstract class AbstractGpgMojo - extends AbstractMojo -{ +public abstract class AbstractGpgMojo extends AbstractMojo { /** * The directory from which gpg will load keyrings. If not specified, gpg will use the value configured for its @@ -48,27 +45,27 @@ public abstract class AbstractGpgMojo * * @since 1.0 */ - @Parameter( property = "gpg.homedir" ) + @Parameter(property = "gpg.homedir") private File homedir; /** * The passphrase to use when signing. If not given, look up the value under Maven * settings using server id at 'passphraseServerKey' configuration. **/ - @Parameter( property = "gpg.passphrase" ) + @Parameter(property = "gpg.passphrase") private String passphrase; /** * Server id to lookup the passphrase under Maven settings. * @since 1.6 */ - @Parameter( property = "gpg.passphraseServerId", defaultValue = "gpg.passphrase" ) + @Parameter(property = "gpg.passphraseServerId", defaultValue = "gpg.passphrase") private String passphraseServerId; /** * The "name" of the key to sign with. Passed to gpg as --local-user. */ - @Parameter( property = "gpg.keyname" ) + @Parameter(property = "gpg.keyname") private String keyname; /** @@ -76,12 +73,12 @@ public abstract class AbstractGpgMojo * optional as the agent will provide it. For gpg2, specify true as --no-use-agent was removed in gpg2 and doesn't * ask for a passphrase anymore. */ - @Parameter( property = "gpg.useagent", defaultValue = "true" ) + @Parameter(property = "gpg.useagent", defaultValue = "true") private boolean useAgent; /** */ - @Parameter( defaultValue = "${settings.interactiveMode}", readonly = true ) + @Parameter(defaultValue = "${settings.interactiveMode}", readonly = true) private boolean interactive; /** @@ -90,7 +87,7 @@ public abstract class AbstractGpgMojo * * @since 1.1 */ - @Parameter( property = "gpg.executable" ) + @Parameter(property = "gpg.executable") private String executable; /** @@ -98,7 +95,7 @@ public abstract class AbstractGpgMojo * * @since 1.2 */ - @Parameter( property = "gpg.defaultKeyring", defaultValue = "true" ) + @Parameter(property = "gpg.defaultKeyring", defaultValue = "true") private boolean defaultKeyring; /** @@ -111,7 +108,7 @@ public abstract class AbstractGpgMojo * * @since 1.2 */ - @Parameter( property = "gpg.secretKeyring" ) + @Parameter(property = "gpg.secretKeyring") private String secretKeyring; /** @@ -121,7 +118,7 @@ public abstract class AbstractGpgMojo * * @since 1.2 */ - @Parameter( property = "gpg.publicKeyring" ) + @Parameter(property = "gpg.publicKeyring") private String publicKeyring; /** @@ -133,7 +130,7 @@ public abstract class AbstractGpgMojo * --lock-options * @since 1.5 */ - @Parameter( property = "gpg.lockMode" ) + @Parameter(property = "gpg.lockMode") private String lockMode; /** @@ -156,7 +153,7 @@ public abstract class AbstractGpgMojo * * @since 1.6 */ - @Parameter( defaultValue = "${settings}", readonly = true ) + @Parameter(defaultValue = "${settings}", readonly = true) private Settings settings; /** @@ -164,41 +161,34 @@ public abstract class AbstractGpgMojo * * @since 1.6 */ - @Component( hint = "mng-4384" ) + @Component(hint = "mng-4384") private SecDispatcher securityDispatcher; - AbstractGpgSigner newSigner( MavenProject project ) - throws MojoExecutionException, MojoFailureException - { - AbstractGpgSigner signer = new GpgSigner( executable ); - - signer.setLog( getLog() ); - signer.setInteractive( interactive ); - signer.setKeyName( keyname ); - signer.setUseAgent( useAgent ); - signer.setHomeDirectory( homedir ); - signer.setDefaultKeyring( defaultKeyring ); - signer.setSecretKeyring( secretKeyring ); - signer.setPublicKeyring( publicKeyring ); - signer.setLockMode( lockMode ); - signer.setArgs( gpgArguments ); + AbstractGpgSigner newSigner(MavenProject project) throws MojoExecutionException, MojoFailureException { + AbstractGpgSigner signer = new GpgSigner(executable); + + signer.setLog(getLog()); + signer.setInteractive(interactive); + signer.setKeyName(keyname); + signer.setUseAgent(useAgent); + signer.setHomeDirectory(homedir); + signer.setDefaultKeyring(defaultKeyring); + signer.setSecretKeyring(secretKeyring); + signer.setPublicKeyring(publicKeyring); + signer.setLockMode(lockMode); + signer.setArgs(gpgArguments); loadGpgPassphrase(); - signer.setPassPhrase( passphrase ); - if ( null == passphrase && !useAgent ) - { - if ( !interactive ) - { - throw new MojoFailureException( "Cannot obtain passphrase in batch mode" ); - } - try - { - signer.setPassPhrase( signer.getPassphrase( project ) ); + signer.setPassPhrase(passphrase); + if (null == passphrase && !useAgent) { + if (!interactive) { + throw new MojoFailureException("Cannot obtain passphrase in batch mode"); } - catch ( IOException e ) - { - throw new MojoExecutionException( "Exception reading passphrase", e ); + try { + signer.setPassPhrase(signer.getPassphrase(project)); + } catch (IOException e) { + throw new MojoExecutionException("Exception reading passphrase", e); } } @@ -210,24 +200,16 @@ AbstractGpgSigner newSigner( MavenProject project ) * * @throws MojoFailureException */ - private void loadGpgPassphrase() - throws MojoFailureException - { - if ( StringUtils.isEmpty( this.passphrase ) ) - { - Server server = this.settings.getServer( passphraseServerId ); - - if ( server != null ) - { - if ( server.getPassphrase() != null ) - { - try - { - this.passphrase = securityDispatcher.decrypt( server.getPassphrase() ); - } - catch ( SecDispatcherException e ) - { - throw new MojoFailureException( "Unable to decrypt gpg passphrase", e ); + private void loadGpgPassphrase() throws MojoFailureException { + if (StringUtils.isEmpty(this.passphrase)) { + Server server = this.settings.getServer(passphraseServerId); + + if (server != null) { + if (server.getPassphrase() != null) { + try { + this.passphrase = securityDispatcher.decrypt(server.getPassphrase()); + } catch (SecDispatcherException e) { + throw new MojoFailureException("Unable to decrypt gpg passphrase", e); } } } diff --git a/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgSigner.java b/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgSigner.java index 977a575..3255b8f 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgSigner.java +++ b/src/main/java/org/apache/maven/plugins/gpg/AbstractGpgSigner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.io.IOException; @@ -33,8 +32,7 @@ * @author Dennis Lundberg * @since 1.5 */ -public abstract class AbstractGpgSigner -{ +public abstract class AbstractGpgSigner { private static final String GPG_PASSPHRASE = "gpg.passphrase"; public static final String SIGNATURE_EXTENSION = ".asc"; @@ -67,78 +65,63 @@ public abstract class AbstractGpgSigner protected List args; - public Log getLog() - { + public Log getLog() { return log; } - public void setArgs( List args ) - { + public void setArgs(List args) { this.args = args; } - public void setInteractive( boolean b ) - { + public void setInteractive(boolean b) { isInteractive = b; } - public void setLockMode( String lockMode ) - { + public void setLockMode(String lockMode) { this.lockMode = lockMode; } - public void setUseAgent( boolean b ) - { + public void setUseAgent(boolean b) { useAgent = b; } - public void setDefaultKeyring( boolean enabled ) - { + public void setDefaultKeyring(boolean enabled) { defaultKeyring = enabled; } - public void setKeyName( String s ) - { + public void setKeyName(String s) { keyname = s; } - public void setLog( Log log ) - { + public void setLog(Log log) { this.log = log; } - public void setPassPhrase( String s ) - { + public void setPassPhrase(String s) { passphrase = s; } - public void setOutputDirectory( File out ) - { + public void setOutputDirectory(File out) { outputDir = out; } - public void setBuildDirectory( File out ) - { + public void setBuildDirectory(File out) { buildDir = out; } - public void setBaseDirectory( File out ) - { + public void setBaseDirectory(File out) { baseDir = out; } - public void setHomeDirectory( File homeDirectory ) - { + public void setHomeDirectory(File homeDirectory) { homeDir = homeDirectory; } - public void setSecretKeyring( String path ) - { + public void setSecretKeyring(String path) { secretKeyring = path; } - public void setPublicKeyring( String path ) - { + public void setPublicKeyring(String path) { publicKeyring = path; } @@ -149,47 +132,38 @@ public void setPublicKeyring( String path ) * @return A reference to the generated signature file * @throws MojoExecutionException if signature generation fails */ - public File generateSignatureForArtifact( File file ) - throws MojoExecutionException - { + public File generateSignatureForArtifact(File file) throws MojoExecutionException { // ---------------------------------------------------------------------------- // Set up the file and directory for the signature file // ---------------------------------------------------------------------------- - File signature = new File( file + SIGNATURE_EXTENSION ); + File signature = new File(file + SIGNATURE_EXTENSION); boolean isInBuildDir = false; - if ( buildDir != null ) - { + if (buildDir != null) { File parent = signature.getParentFile(); - if ( buildDir.equals( parent ) ) - { + if (buildDir.equals(parent)) { isInBuildDir = true; } } - if ( !isInBuildDir && outputDir != null ) - { + if (!isInBuildDir && outputDir != null) { String fileDirectory = ""; File signatureDirectory = signature; - while ( ( signatureDirectory = signatureDirectory.getParentFile() ) != null ) - { - if ( isPossibleRootOfArtifact( signatureDirectory ) ) - { + while ((signatureDirectory = signatureDirectory.getParentFile()) != null) { + if (isPossibleRootOfArtifact(signatureDirectory)) { break; } fileDirectory = signatureDirectory.getName() + File.separatorChar + fileDirectory; } - signatureDirectory = new File( outputDir, fileDirectory ); - if ( !signatureDirectory.exists() ) - { + signatureDirectory = new File(outputDir, fileDirectory); + if (!signatureDirectory.exists()) { signatureDirectory.mkdirs(); } - signature = new File( signatureDirectory, file.getName() + SIGNATURE_EXTENSION ); + signature = new File(signatureDirectory, file.getName() + SIGNATURE_EXTENSION); } - if ( signature.exists() ) - { + if (signature.exists()) { signature.delete(); } @@ -197,7 +171,7 @@ public File generateSignatureForArtifact( File file ) // Generate the signature file // ---------------------------------------------------------------------------- - generateSignatureForFile( file, signature ); + generateSignatureForFile(file, signature); return signature; } @@ -209,53 +183,43 @@ public File generateSignatureForArtifact( File file ) * @param signature The file in which the generate signature will be put * @throws MojoExecutionException if signature generation fails */ - protected abstract void generateSignatureForFile( File file, File signature ) - throws MojoExecutionException; - - private MavenProject findReactorProject( MavenProject prj ) - { - if ( prj.getParent() != null && prj.getParent().getBasedir() != null && prj.getParent().getBasedir().exists() ) - { - return findReactorProject( prj.getParent() ); + protected abstract void generateSignatureForFile(File file, File signature) throws MojoExecutionException; + + private MavenProject findReactorProject(MavenProject prj) { + if (prj.getParent() != null + && prj.getParent().getBasedir() != null + && prj.getParent().getBasedir().exists()) { + return findReactorProject(prj.getParent()); } return prj; } - public String getPassphrase( MavenProject project ) - throws IOException - { + public String getPassphrase(MavenProject project) throws IOException { String pass = null; - if ( project != null ) - { - pass = project.getProperties().getProperty( GPG_PASSPHRASE ); - if ( pass == null ) - { - MavenProject prj2 = findReactorProject( project ); - pass = prj2.getProperties().getProperty( GPG_PASSPHRASE ); + if (project != null) { + pass = project.getProperties().getProperty(GPG_PASSPHRASE); + if (pass == null) { + MavenProject prj2 = findReactorProject(project); + pass = prj2.getProperties().getProperty(GPG_PASSPHRASE); } } - if ( pass == null ) - { - pass = new String( readPassword( "GPG Passphrase: " ) ); + if (pass == null) { + pass = new String(readPassword("GPG Passphrase: ")); } - if ( project != null ) - { - findReactorProject( project ).getProperties().setProperty( GPG_PASSPHRASE, pass ); + if (project != null) { + findReactorProject(project).getProperties().setProperty(GPG_PASSPHRASE, pass); } return pass; } - private char[] readPassword( String prompt ) - throws IOException - { + private char[] readPassword(String prompt) throws IOException { return System.console().readPassword(); } - private boolean isPossibleRootOfArtifact( File signatureDirectory ) - { - return signatureDirectory.equals( outputDir ) - || signatureDirectory.equals( buildDir ) - || signatureDirectory.equals( baseDir ); + private boolean isPossibleRootOfArtifact(File signatureDirectory) { + return signatureDirectory.equals(outputDir) + || signatureDirectory.equals(buildDir) + || signatureDirectory.equals(baseDir); } } diff --git a/src/main/java/org/apache/maven/plugins/gpg/AscArtifactMetadata.java b/src/main/java/org/apache/maven/plugins/gpg/AscArtifactMetadata.java index e3cbbca..605eb2d 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/AscArtifactMetadata.java +++ b/src/main/java/org/apache/maven/plugins/gpg/AscArtifactMetadata.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.io.IOException; @@ -33,121 +32,97 @@ * @author dkulp * */ -public class AscArtifactMetadata - extends AbstractArtifactMetadata implements org.apache.maven.shared.transfer.metadata.ArtifactMetadata -{ +public class AscArtifactMetadata extends AbstractArtifactMetadata + implements org.apache.maven.shared.transfer.metadata.ArtifactMetadata { private final File file; private final boolean isPom; - public AscArtifactMetadata( Artifact artifact, File file, boolean isPom ) - { - super( artifact ); + public AscArtifactMetadata(Artifact artifact, File file, boolean isPom) { + super(artifact); this.file = file; this.isPom = isPom; } @Override - public String getBaseVersion() - { + public String getBaseVersion() { return artifact.getBaseVersion(); } @Override - public Object getKey() - { + public Object getKey() { return "gpg signature " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getType() - + ":" + artifact.getClassifier() + ( isPom ? ":pom" : "" ); + + ":" + artifact.getClassifier() + (isPom ? ":pom" : ""); } - private String getFilename() - { - StringBuilder buf = new StringBuilder( 128 ); - buf.append( getArtifactId() ); - buf.append( "-" ).append( artifact.getVersion() ); - if ( isPom ) - { - buf.append( ".pom" ); - } - else - { - if ( artifact.getClassifier() != null && !"".equals( artifact.getClassifier() ) ) - { - buf.append( "-" ).append( artifact.getClassifier() ); + private String getFilename() { + StringBuilder buf = new StringBuilder(128); + buf.append(getArtifactId()); + buf.append("-").append(artifact.getVersion()); + if (isPom) { + buf.append(".pom"); + } else { + if (artifact.getClassifier() != null && !"".equals(artifact.getClassifier())) { + buf.append("-").append(artifact.getClassifier()); } - buf.append( "." ).append( artifact.getArtifactHandler().getExtension() ); + buf.append(".").append(artifact.getArtifactHandler().getExtension()); } - buf.append( ".asc" ); + buf.append(".asc"); return buf.toString(); } @Override - public String getLocalFilename( ArtifactRepository repository ) - { + public String getLocalFilename(ArtifactRepository repository) { return getFilename(); } @Override - public String getRemoteFilename() - { + public String getRemoteFilename() { return getFilename(); } @Override - public void merge( ArtifactMetadata metadata ) - { - merge( (AscArtifactMetadata) metadata ); + public void merge(ArtifactMetadata metadata) { + merge((AscArtifactMetadata) metadata); } @Override - public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) - { - merge( (AscArtifactMetadata) metadata ); + public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) { + merge((AscArtifactMetadata) metadata); } - - private void merge( AscArtifactMetadata metadata ) - { - if ( !metadata.file.equals( file ) ) - { - throw new IllegalStateException( "Cannot add two different pieces of metadata for: " + getKey() ); - } + + private void merge(AscArtifactMetadata metadata) { + if (!metadata.file.equals(file)) { + throw new IllegalStateException("Cannot add two different pieces of metadata for: " + getKey()); + } } @Override - public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException - { - File destination = - new File( localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata( this, - remoteRepository ) ); - - try - { - FileUtils.copyFile( file, destination ); - } - catch ( IOException e ) - { - throw new RepositoryMetadataStoreException( "Error copying ASC to the local repository.", e ); + public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException { + File destination = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository)); + + try { + FileUtils.copyFile(file, destination); + } catch (IOException e) { + throw new RepositoryMetadataStoreException("Error copying ASC to the local repository.", e); } } @Override - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return true; } @Override - public String toString() - { + public String toString() { return getFilename(); } @Override - public File getFile() - { + public File getFile() { return file; } - } diff --git a/src/main/java/org/apache/maven/plugins/gpg/AttachedSignedArtifact.java b/src/main/java/org/apache/maven/plugins/gpg/AttachedSignedArtifact.java index ff1243b..4749e6f 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/AttachedSignedArtifact.java +++ b/src/main/java/org/apache/maven/plugins/gpg/AttachedSignedArtifact.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.util.ArrayList; @@ -37,325 +36,269 @@ * A wrapper class for attached artifacts which have a GPG signature. Needed as attached artifacts in general do not * have metadata. */ -public class AttachedSignedArtifact - implements Artifact -{ +public class AttachedSignedArtifact implements Artifact { private final Artifact delegate; private final AscArtifactMetadata signature; - public AttachedSignedArtifact( Artifact delegate, AscArtifactMetadata signature ) - { + public AttachedSignedArtifact(Artifact delegate, AscArtifactMetadata signature) { this.delegate = delegate; this.signature = signature; } @Override - public void setArtifactId( String artifactId ) - { - delegate.setArtifactId( artifactId ); + public void setArtifactId(String artifactId) { + delegate.setArtifactId(artifactId); } @Override - public List getAvailableVersions() - { + public List getAvailableVersions() { return delegate.getAvailableVersions(); } @Override - public void setAvailableVersions( List availableVersions ) - { - delegate.setAvailableVersions( availableVersions ); + public void setAvailableVersions(List availableVersions) { + delegate.setAvailableVersions(availableVersions); } @Override - public String getBaseVersion() - { + public String getBaseVersion() { return delegate.getBaseVersion(); } @Override - public void setBaseVersion( String baseVersion ) - { - delegate.setBaseVersion( baseVersion ); + public void setBaseVersion(String baseVersion) { + delegate.setBaseVersion(baseVersion); } @Override - public String getDownloadUrl() - { + public String getDownloadUrl() { return delegate.getDownloadUrl(); } @Override - public void setDownloadUrl( String downloadUrl ) - { - delegate.setDownloadUrl( downloadUrl ); + public void setDownloadUrl(String downloadUrl) { + delegate.setDownloadUrl(downloadUrl); } @Override - public void setGroupId( String groupId ) - { - delegate.setGroupId( groupId ); + public void setGroupId(String groupId) { + delegate.setGroupId(groupId); } @Override - public ArtifactRepository getRepository() - { + public ArtifactRepository getRepository() { return delegate.getRepository(); } @Override - public void setRepository( ArtifactRepository repository ) - { - delegate.setRepository( repository ); + public void setRepository(ArtifactRepository repository) { + delegate.setRepository(repository); } @Override - public String getScope() - { + public String getScope() { return delegate.getScope(); } @Override - public void setScope( String scope ) - { - delegate.setScope( scope ); + public void setScope(String scope) { + delegate.setScope(scope); } @Override - public String getVersion() - { + public String getVersion() { return delegate.getVersion(); } @Override - public void setVersion( String version ) - { - delegate.setVersion( version ); + public void setVersion(String version) { + delegate.setVersion(version); } @Override - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return delegate.getVersionRange(); } @Override - public void setVersionRange( VersionRange range ) - { - delegate.setVersionRange( range ); + public void setVersionRange(VersionRange range) { + delegate.setVersionRange(range); } @Override - public boolean isRelease() - { + public boolean isRelease() { return delegate.isRelease(); } @Override - public void setRelease( boolean release ) - { - delegate.setRelease( release ); + public void setRelease(boolean release) { + delegate.setRelease(release); } @Override - public boolean isSnapshot() - { + public boolean isSnapshot() { return delegate.isSnapshot(); } @Override - public void addMetadata( ArtifactMetadata metadata ) - { - delegate.addMetadata( metadata ); + public void addMetadata(ArtifactMetadata metadata) { + delegate.addMetadata(metadata); } @Override - public String getClassifier() - { + public String getClassifier() { return delegate.getClassifier(); } @Override - public boolean hasClassifier() - { + public boolean hasClassifier() { return delegate.hasClassifier(); } @Override - public String getGroupId() - { + public String getGroupId() { return delegate.getGroupId(); } @Override - public String getArtifactId() - { + public String getArtifactId() { return delegate.getArtifactId(); } @Override - public String getType() - { + public String getType() { return delegate.getType(); } @Override - public void setFile( File file ) - { - delegate.setFile( file ); + public void setFile(File file) { + delegate.setFile(file); } @Override - public File getFile() - { + public File getFile() { return delegate.getFile(); } @Override - public String getId() - { + public String getId() { return delegate.getId(); } @Override - public String getDependencyConflictId() - { + public String getDependencyConflictId() { return delegate.getDependencyConflictId(); } @Override - public String toString() - { + public String toString() { return delegate.toString(); } @Override - public int hashCode() - { + public int hashCode() { return delegate.hashCode(); } @Override - public boolean equals( Object o ) - { - return delegate.equals( o ); + public boolean equals(Object o) { + return delegate.equals(o); } @Override - public void updateVersion( String version, ArtifactRepository localRepository ) - { - delegate.updateVersion( version, localRepository ); + public void updateVersion(String version, ArtifactRepository localRepository) { + delegate.updateVersion(version, localRepository); } @Override - public ArtifactFilter getDependencyFilter() - { + public ArtifactFilter getDependencyFilter() { return delegate.getDependencyFilter(); } @Override - public void setDependencyFilter( ArtifactFilter artifactFilter ) - { - delegate.setDependencyFilter( artifactFilter ); + public void setDependencyFilter(ArtifactFilter artifactFilter) { + delegate.setDependencyFilter(artifactFilter); } @Override - public ArtifactHandler getArtifactHandler() - { + public ArtifactHandler getArtifactHandler() { return delegate.getArtifactHandler(); } @Override - public List getDependencyTrail() - { + public List getDependencyTrail() { return delegate.getDependencyTrail(); } @Override - public void setDependencyTrail( List dependencyTrail ) - { - delegate.setDependencyTrail( dependencyTrail ); + public void setDependencyTrail(List dependencyTrail) { + delegate.setDependencyTrail(dependencyTrail); } @Override - public void selectVersion( String version ) - { - delegate.selectVersion( version ); + public void selectVersion(String version) { + delegate.selectVersion(version); } @Override - public void setResolved( boolean resolved ) - { - delegate.setResolved( resolved ); + public void setResolved(boolean resolved) { + delegate.setResolved(resolved); } @Override - public boolean isResolved() - { + public boolean isResolved() { return delegate.isResolved(); } @Override - public void setResolvedVersion( String version ) - { - delegate.setResolvedVersion( version ); + public void setResolvedVersion(String version) { + delegate.setResolvedVersion(version); } @Override - public void setArtifactHandler( ArtifactHandler artifactHandler ) - { - delegate.setArtifactHandler( artifactHandler ); + public void setArtifactHandler(ArtifactHandler artifactHandler) { + delegate.setArtifactHandler(artifactHandler); } @Override - public boolean isOptional() - { + public boolean isOptional() { return delegate.isOptional(); } @Override - public ArtifactVersion getSelectedVersion() - throws OverConstrainedVersionException - { + public ArtifactVersion getSelectedVersion() throws OverConstrainedVersionException { return delegate.getSelectedVersion(); } @Override - public boolean isSelectedVersionKnown() - throws OverConstrainedVersionException - { + public boolean isSelectedVersionKnown() throws OverConstrainedVersionException { return delegate.isSelectedVersionKnown(); } @Override - public void setOptional( boolean optional ) - { - delegate.setOptional( optional ); + public void setOptional(boolean optional) { + delegate.setOptional(optional); } @Override - public Collection getMetadataList() - { - List result = new ArrayList<>( delegate.getMetadataList() ); + public Collection getMetadataList() { + List result = new ArrayList<>(delegate.getMetadataList()); - for ( ArtifactMetadata metadata : result ) - { - if ( signature.getKey().equals( metadata.getKey() ) ) - { + for (ArtifactMetadata metadata : result) { + if (signature.getKey().equals(metadata.getKey())) { // already signed return result; } } - result.add( signature ); + result.add(signature); return result; } @Override - public int compareTo( Artifact o ) - { - return delegate.compareTo( o ); + public int compareTo(Artifact o) { + return delegate.compareTo(o); } } diff --git a/src/main/java/org/apache/maven/plugins/gpg/GpgSignAttachedMojo.java b/src/main/java/org/apache/maven/plugins/gpg/GpgSignAttachedMojo.java index 98b600a..f441dd4 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/GpgSignAttachedMojo.java +++ b/src/main/java/org/apache/maven/plugins/gpg/GpgSignAttachedMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.io.IOException; @@ -44,18 +43,16 @@ * @author Jason Dillon * @author Daniel Kulp */ -@Mojo( name = "sign", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true ) -public class GpgSignAttachedMojo - extends AbstractGpgMojo -{ +@Mojo(name = "sign", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) +public class GpgSignAttachedMojo extends AbstractGpgMojo { private static final String DEFAULT_EXCLUDES[] = - new String[] { "**/*.md5", "**/*.sha1", "**/*.sha256", "**/*.sha512", "**/*.asc" }; + new String[] {"**/*.md5", "**/*.sha1", "**/*.sha256", "**/*.sha512", "**/*.asc"}; /** * Skip doing the gpg signing. */ - @Parameter( property = "gpg.skip", defaultValue = "false" ) + @Parameter(property = "gpg.skip", defaultValue = "false") private boolean skip; /** @@ -72,13 +69,13 @@ public class GpgSignAttachedMojo * * @since 1.0-alpha-4 */ - @Parameter( defaultValue = "${project.build.directory}/gpg", alias = "outputDirectory" ) + @Parameter(defaultValue = "${project.build.directory}/gpg", alias = "outputDirectory") private File ascDirectory; /** * The maven project. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; /** @@ -88,46 +85,39 @@ public class GpgSignAttachedMojo private MavenProjectHelper projectHelper; @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { // We're skipping the signing stuff return; } - if ( excludes == null || excludes.length == 0 ) - { + if (excludes == null || excludes.length == 0) { excludes = DEFAULT_EXCLUDES; } String newExcludes[] = new String[excludes.length]; - for ( int i = 0; i < excludes.length; i++ ) - { + for (int i = 0; i < excludes.length; i++) { String pattern; - pattern = excludes[i].trim().replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); - if ( pattern.endsWith( File.separator ) ) - { + pattern = excludes[i].trim().replace('/', File.separatorChar).replace('\\', File.separatorChar); + if (pattern.endsWith(File.separator)) { pattern += "**"; } newExcludes[i] = pattern; } excludes = newExcludes; - AbstractGpgSigner signer = newSigner( project ); + AbstractGpgSigner signer = newSigner(project); // ---------------------------------------------------------------------------- // What we need to generateSignatureForArtifact here // ---------------------------------------------------------------------------- - signer.setOutputDirectory( ascDirectory ); - signer.setBuildDirectory( new File( project.getBuild().getDirectory() ) ); - signer.setBaseDirectory( project.getBasedir() ); + signer.setOutputDirectory(ascDirectory); + signer.setBuildDirectory(new File(project.getBuild().getDirectory())); + signer.setBaseDirectory(project.getBasedir()); List signingBundles = new ArrayList<>(); - if ( !"pom".equals( project.getPackaging() ) ) - { + if (!"pom".equals(project.getPackaging())) { // ---------------------------------------------------------------------------- // Project artifact // ---------------------------------------------------------------------------- @@ -136,26 +126,20 @@ public void execute() File file = artifact.getFile(); - if ( file != null && file.isFile() ) - { - getLog().debug( "Generating signature for " + file ); + if (file != null && file.isFile()) { + getLog().debug("Generating signature for " + file); - File projectArtifactSignature = signer.generateSignatureForArtifact( file ); + File projectArtifactSignature = signer.generateSignatureForArtifact(file); - if ( projectArtifactSignature != null ) - { - signingBundles.add( new SigningBundle( artifact.getArtifactHandler().getExtension(), - projectArtifactSignature ) ); + if (projectArtifactSignature != null) { + signingBundles.add( + new SigningBundle(artifact.getArtifactHandler().getExtension(), projectArtifactSignature)); } - } - else if ( project.getAttachedArtifacts().isEmpty() ) - { - throw new MojoFailureException( "The project artifact has not been assembled yet. " - + "Please do not invoke this goal before the lifecycle phase \"package\"." ); - } - else - { - getLog().debug( "Main artifact not assembled, skipping signature generation" ); + } else if (project.getAttachedArtifacts().isEmpty()) { + throw new MojoFailureException("The project artifact has not been assembled yet. " + + "Please do not invoke this goal before the lifecycle phase \"package\"."); + } else { + getLog().debug("Main artifact not assembled, skipping signature generation"); } } @@ -163,50 +147,44 @@ else if ( project.getAttachedArtifacts().isEmpty() ) // POM // ---------------------------------------------------------------------------- - File pomToSign = new File( project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".pom" ); + File pomToSign = + new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".pom"); - try - { - FileUtils.copyFile( project.getFile(), pomToSign ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error copying POM for signing.", e ); + try { + FileUtils.copyFile(project.getFile(), pomToSign); + } catch (IOException e) { + throw new MojoExecutionException("Error copying POM for signing.", e); } - getLog().debug( "Generating signature for " + pomToSign ); + getLog().debug("Generating signature for " + pomToSign); - File pomSignature = signer.generateSignatureForArtifact( pomToSign ); + File pomSignature = signer.generateSignatureForArtifact(pomToSign); - if ( pomSignature != null ) - { - signingBundles.add( new SigningBundle( "pom", pomSignature ) ); + if (pomSignature != null) { + signingBundles.add(new SigningBundle("pom", pomSignature)); } // ---------------------------------------------------------------------------- // Attached artifacts // ---------------------------------------------------------------------------- - for ( Object o : project.getAttachedArtifacts() ) - { + for (Object o : project.getAttachedArtifacts()) { Artifact artifact = (Artifact) o; File file = artifact.getFile(); - if ( isExcluded( artifact ) ) - { - getLog().debug( "Skipping generation of signature for excluded " + file ); + if (isExcluded(artifact)) { + getLog().debug("Skipping generation of signature for excluded " + file); continue; } - getLog().debug( "Generating signature for " + file ); + getLog().debug("Generating signature for " + file); - File signature = signer.generateSignatureForArtifact( file ); + File signature = signer.generateSignatureForArtifact(file); - if ( signature != null ) - { - signingBundles.add( new SigningBundle( artifact.getArtifactHandler().getExtension(), - artifact.getClassifier(), signature ) ); + if (signature != null) { + signingBundles.add(new SigningBundle( + artifact.getArtifactHandler().getExtension(), artifact.getClassifier(), signature)); } } @@ -214,10 +192,12 @@ else if ( project.getAttachedArtifacts().isEmpty() ) // Attach all the signatures // ---------------------------------------------------------------------------- - for ( SigningBundle bundle : signingBundles ) - { - projectHelper.attachArtifact( project, bundle.getExtension() + AbstractGpgSigner.SIGNATURE_EXTENSION, - bundle.getClassifier(), bundle.getSignature() ); + for (SigningBundle bundle : signingBundles) { + projectHelper.attachArtifact( + project, + bundle.getExtension() + AbstractGpgSigner.SIGNATURE_EXTENSION, + bundle.getClassifier(), + bundle.getSignature()); } } @@ -228,21 +208,18 @@ else if ( project.getAttachedArtifacts().isEmpty() ) * @return true when the name matches against at least one exclude pattern, or false * otherwise. */ - protected boolean isExcluded( Artifact artifact ) - { + protected boolean isExcluded(Artifact artifact) { final Path projectBasePath = project.getBasedir().toPath(); final Path artifactPath = artifact.getFile().toPath(); - final String relativeArtifactPath = projectBasePath.relativize( artifactPath ).toString(); + final String relativeArtifactPath = + projectBasePath.relativize(artifactPath).toString(); - for ( String exclude : excludes ) - { - if ( SelectorUtils.matchPath( exclude, relativeArtifactPath ) ) - { + for (String exclude : excludes) { + if (SelectorUtils.matchPath(exclude, relativeArtifactPath)) { return true; } } return false; } - } diff --git a/src/main/java/org/apache/maven/plugins/gpg/GpgSigner.java b/src/main/java/org/apache/maven/plugins/gpg/GpgSigner.java index fd12276..36f0e97 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/GpgSigner.java +++ b/src/main/java/org/apache/maven/plugins/gpg/GpgSigner.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.ByteArrayInputStream; import java.io.File; @@ -34,13 +33,10 @@ /** * A signer implementation that uses the GnuPG command line executable. */ -public class GpgSigner - extends AbstractGpgSigner -{ +public class GpgSigner extends AbstractGpgSigner { private String executable; - public GpgSigner( String executable ) - { + public GpgSigner(String executable) { this.executable = executable; } @@ -48,175 +44,139 @@ public GpgSigner( String executable ) * {@inheritDoc} */ @Override - protected void generateSignatureForFile( File file, File signature ) - throws MojoExecutionException - { + protected void generateSignatureForFile(File file, File signature) throws MojoExecutionException { // ---------------------------------------------------------------------------- // Set up the command line // ---------------------------------------------------------------------------- Commandline cmd = new Commandline(); - if ( StringUtils.isNotEmpty( executable ) ) - { - cmd.setExecutable( executable ); - } - else - { - cmd.setExecutable( "gpg" + ( Os.isFamily( Os.FAMILY_WINDOWS ) ? ".exe" : "" ) ); + if (StringUtils.isNotEmpty(executable)) { + cmd.setExecutable(executable); + } else { + cmd.setExecutable("gpg" + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".exe" : "")); } - GpgVersionParser versionParser = GpgVersionParser.parse( executable ); + GpgVersionParser versionParser = GpgVersionParser.parse(executable); GpgVersion gpgVersion = versionParser.getGpgVersion(); - if ( gpgVersion == null ) - { - throw new MojoExecutionException( "Could not determine gpg version" ); + if (gpgVersion == null) { + throw new MojoExecutionException("Could not determine gpg version"); } - getLog().debug( gpgVersion.toString() ); + getLog().debug(gpgVersion.toString()); - if ( args != null ) - { - for ( String arg : args ) - { - cmd.createArg().setValue( arg ); + if (args != null) { + for (String arg : args) { + cmd.createArg().setValue(arg); } } - if ( homeDir != null ) - { - cmd.createArg().setValue( "--homedir" ); - cmd.createArg().setFile( homeDir ); + if (homeDir != null) { + cmd.createArg().setValue("--homedir"); + cmd.createArg().setFile(homeDir); } - if ( gpgVersion.isBefore( GpgVersion.parse( "2.1" ) ) ) - { - if ( useAgent ) - { - cmd.createArg().setValue( "--use-agent" ); - } - else - { - cmd.createArg().setValue( "--no-use-agent" ); + if (gpgVersion.isBefore(GpgVersion.parse("2.1"))) { + if (useAgent) { + cmd.createArg().setValue("--use-agent"); + } else { + cmd.createArg().setValue("--no-use-agent"); } } InputStream in = null; - if ( null != passphrase ) - { - if ( gpgVersion.isAtLeast( GpgVersion.parse( "2.0" ) ) ) - { + if (null != passphrase) { + if (gpgVersion.isAtLeast(GpgVersion.parse("2.0"))) { // required for option --passphrase-fd since GPG 2.0 - cmd.createArg().setValue( "--batch" ); + cmd.createArg().setValue("--batch"); } - if ( gpgVersion.isAtLeast( GpgVersion.parse( "2.1" ) ) ) - { + if (gpgVersion.isAtLeast(GpgVersion.parse("2.1"))) { // required for option --passphrase-fd since GPG 2.1 - cmd.createArg().setValue( "--pinentry-mode" ); - cmd.createArg().setValue( "loopback" ); + cmd.createArg().setValue("--pinentry-mode"); + cmd.createArg().setValue("loopback"); } // make --passphrase-fd effective in gpg2 - cmd.createArg().setValue( "--passphrase-fd" ); - cmd.createArg().setValue( "0" ); + cmd.createArg().setValue("--passphrase-fd"); + cmd.createArg().setValue("0"); // Prepare the input stream which will be used to pass the passphrase to the executable - in = new ByteArrayInputStream( passphrase.getBytes() ); + in = new ByteArrayInputStream(passphrase.getBytes()); } - if ( null != keyname ) - { - cmd.createArg().setValue( "--local-user" ); + if (null != keyname) { + cmd.createArg().setValue("--local-user"); - cmd.createArg().setValue( keyname ); + cmd.createArg().setValue(keyname); } - cmd.createArg().setValue( "--armor" ); + cmd.createArg().setValue("--armor"); - cmd.createArg().setValue( "--detach-sign" ); + cmd.createArg().setValue("--detach-sign"); - if ( getLog().isDebugEnabled() ) - { + if (getLog().isDebugEnabled()) { // instruct GPG to write status information to stdout - cmd.createArg().setValue( "--status-fd" ); - cmd.createArg().setValue( "1" ); + cmd.createArg().setValue("--status-fd"); + cmd.createArg().setValue("1"); } - if ( !isInteractive ) - { - cmd.createArg().setValue( "--batch" ); - cmd.createArg().setValue( "--no-tty" ); + if (!isInteractive) { + cmd.createArg().setValue("--batch"); + cmd.createArg().setValue("--no-tty"); - if ( null == passphrase && gpgVersion.isAtLeast( GpgVersion.parse( "2.1" ) ) ) - { + if (null == passphrase && gpgVersion.isAtLeast(GpgVersion.parse("2.1"))) { // prevent GPG from spawning input prompts in Maven non-interactive mode - cmd.createArg().setValue( "--pinentry-mode" ); - cmd.createArg().setValue( "error" ); + cmd.createArg().setValue("--pinentry-mode"); + cmd.createArg().setValue("error"); } } - if ( !defaultKeyring ) - { - cmd.createArg().setValue( "--no-default-keyring" ); + if (!defaultKeyring) { + cmd.createArg().setValue("--no-default-keyring"); } - if ( StringUtils.isNotEmpty( secretKeyring ) ) - { - if ( gpgVersion.isBefore( GpgVersion.parse( "2.1" ) ) ) - { - cmd.createArg().setValue( "--secret-keyring" ); - cmd.createArg().setValue( secretKeyring ); - } - else - { - getLog().warn( "'secretKeyring' is an obsolete option and ignored. All secret keys " - + "are stored in the ‘private-keys-v1.d’ directory below the GnuPG home directory." ); + if (StringUtils.isNotEmpty(secretKeyring)) { + if (gpgVersion.isBefore(GpgVersion.parse("2.1"))) { + cmd.createArg().setValue("--secret-keyring"); + cmd.createArg().setValue(secretKeyring); + } else { + getLog().warn("'secretKeyring' is an obsolete option and ignored. All secret keys " + + "are stored in the ‘private-keys-v1.d’ directory below the GnuPG home directory."); } } - if ( StringUtils.isNotEmpty( publicKeyring ) ) - { - cmd.createArg().setValue( "--keyring" ); - cmd.createArg().setValue( publicKeyring ); + if (StringUtils.isNotEmpty(publicKeyring)) { + cmd.createArg().setValue("--keyring"); + cmd.createArg().setValue(publicKeyring); } - if ( "once".equalsIgnoreCase( lockMode ) ) - { - cmd.createArg().setValue( "--lock-once" ); - } - else if ( "multiple".equalsIgnoreCase( lockMode ) ) - { - cmd.createArg().setValue( "--lock-multiple" ); - } - else if ( "never".equalsIgnoreCase( lockMode ) ) - { - cmd.createArg().setValue( "--lock-never" ); + if ("once".equalsIgnoreCase(lockMode)) { + cmd.createArg().setValue("--lock-once"); + } else if ("multiple".equalsIgnoreCase(lockMode)) { + cmd.createArg().setValue("--lock-multiple"); + } else if ("never".equalsIgnoreCase(lockMode)) { + cmd.createArg().setValue("--lock-never"); } - cmd.createArg().setValue( "--output" ); - cmd.createArg().setFile( signature ); + cmd.createArg().setValue("--output"); + cmd.createArg().setFile(signature); - cmd.createArg().setFile( file ); + cmd.createArg().setFile(file); // ---------------------------------------------------------------------------- // Execute the command line // ---------------------------------------------------------------------------- - try - { - int exitCode = CommandLineUtils.executeCommandLine( cmd, in, new DefaultConsumer(), new DefaultConsumer() ); + try { + int exitCode = CommandLineUtils.executeCommandLine(cmd, in, new DefaultConsumer(), new DefaultConsumer()); - if ( exitCode != 0 ) - { - throw new MojoExecutionException( "Exit code: " + exitCode ); + if (exitCode != 0) { + throw new MojoExecutionException("Exit code: " + exitCode); } - } - catch ( CommandLineException e ) - { - throw new MojoExecutionException( "Unable to execute gpg command", e ); + } catch (CommandLineException e) { + throw new MojoExecutionException("Unable to execute gpg command", e); } } - } diff --git a/src/main/java/org/apache/maven/plugins/gpg/GpgVersion.java b/src/main/java/org/apache/maven/plugins/gpg/GpgVersion.java index eee73c9..f1a784d 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/GpgVersion.java +++ b/src/main/java/org/apache/maven/plugins/gpg/GpgVersion.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.util.Arrays; import java.util.regex.Matcher; @@ -26,61 +25,53 @@ /** * Represents the semver value of GPG. * This is in most cases the first line of gpg --version - * + * * * @author Robert Scholte * @since 3.0.0 */ -public class GpgVersion implements Comparable -{ +public class GpgVersion implements Comparable { - private static final Pattern VERSION_PATTERN = Pattern.compile( "(\\d+\\.)+(\\d+)" ); + private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+\\.)+(\\d+)"); private final int[] versionSegments; - private GpgVersion( int... versionSegments ) - { + private GpgVersion(int... versionSegments) { this.versionSegments = versionSegments; } - public static GpgVersion parse( String rawVersion ) - { - final Matcher versionMatcher = VERSION_PATTERN.matcher( rawVersion ); - if ( !versionMatcher.find() ) - { - throw new IllegalArgumentException( "Can't parse version of " + rawVersion ); + public static GpgVersion parse(String rawVersion) { + final Matcher versionMatcher = VERSION_PATTERN.matcher(rawVersion); + if (!versionMatcher.find()) { + throw new IllegalArgumentException("Can't parse version of " + rawVersion); } - final String[] rawVersionSegments = versionMatcher.group( 0 ).split( "\\." ); + final String[] rawVersionSegments = versionMatcher.group(0).split("\\."); final int[] versionSegments = new int[rawVersionSegments.length]; - for ( int index = 0; index < rawVersionSegments.length; index++ ) - { - versionSegments[index] = Integer.parseInt( rawVersionSegments[index] ); + for (int index = 0; index < rawVersionSegments.length; index++) { + versionSegments[index] = Integer.parseInt(rawVersionSegments[index]); } - return new GpgVersion( versionSegments ); + return new GpgVersion(versionSegments); } @Override - public int compareTo( GpgVersion other ) - { + public int compareTo(GpgVersion other) { final int[] thisSegments = versionSegments; final int[] otherSegments = other.versionSegments; - int minSegments = Math.min( thisSegments.length, otherSegments.length ); + int minSegments = Math.min(thisSegments.length, otherSegments.length); - for ( int index = 0; index < minSegments; index++ ) - { - int compareValue = Integer.compare( thisSegments[index], otherSegments[index] ); + for (int index = 0; index < minSegments; index++) { + int compareValue = Integer.compare(thisSegments[index], otherSegments[index]); - if ( compareValue != 0 ) - { + if (compareValue != 0) { return compareValue; } } - return ( thisSegments.length - otherSegments.length ); + return (thisSegments.length - otherSegments.length); } /** @@ -89,9 +80,8 @@ public int compareTo( GpgVersion other ) * @param other the version to compare with * @return {@code true} is this is less than {@code other}, otherwise {@code false} */ - public boolean isBefore( GpgVersion other ) - { - return this.compareTo( other ) < 0; + public boolean isBefore(GpgVersion other) { + return this.compareTo(other) < 0; } /** @@ -100,52 +90,43 @@ public boolean isBefore( GpgVersion other ) * @param other the version to compare with * @return {@code true} is this is greater than or equal to {@code other}, otherwise {@code false} */ - public boolean isAtLeast( GpgVersion other ) - { - return this.compareTo( other ) >= 0; + public boolean isAtLeast(GpgVersion other) { + return this.compareTo(other) >= 0; } @Override - public String toString() - { - if ( versionSegments.length == 0 ) - { + public String toString() { + if (versionSegments.length == 0) { return ""; } final StringBuilder versionStringBuilder = new StringBuilder(); - versionStringBuilder.append( versionSegments[0] ); + versionStringBuilder.append(versionSegments[0]); - for ( int index = 1; index < versionSegments.length; index++ ) - { - versionStringBuilder.append( '.' ).append( versionSegments[index] ); + for (int index = 1; index < versionSegments.length; index++) { + versionStringBuilder.append('.').append(versionSegments[index]); } return versionStringBuilder.toString(); } @Override - public boolean equals( final Object other ) - { - if ( this == other ) - { + public boolean equals(final Object other) { + if (this == other) { return true; } - if ( !( other instanceof GpgVersion ) ) - { + if (!(other instanceof GpgVersion)) { return false; } final GpgVersion that = (GpgVersion) other; - return compareTo( that ) == 0; + return compareTo(that) == 0; } @Override - public int hashCode() - { - return Arrays.hashCode( versionSegments ); + public int hashCode() { + return Arrays.hashCode(versionSegments); } - } diff --git a/src/main/java/org/apache/maven/plugins/gpg/GpgVersionParser.java b/src/main/java/org/apache/maven/plugins/gpg/GpgVersionParser.java index 034807c..b5289a1 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/GpgVersionParser.java +++ b/src/main/java/org/apache/maven/plugins/gpg/GpgVersionParser.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugin.MojoExecutionException; - import org.codehaus.plexus.util.Os; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineException; @@ -34,7 +32,7 @@ /** * Parse the output of gpg --version and exposes these as dedicated objects. - * + * * Supported: *
    *
  • gpg version, i.e. gpg (GnuPG) 2.2.15
  • @@ -45,55 +43,41 @@ *
  • Home
  • *
  • Supported algorithms (Pubkey, Cipher, Hash, Compression)
  • *
- * + * * @author Robert Scholte * @since 3.0.0 */ -public class GpgVersionParser -{ +public class GpgVersionParser { private final GpgVersionConsumer consumer; - private GpgVersionParser( GpgVersionConsumer consumer ) - { + private GpgVersionParser(GpgVersionConsumer consumer) { this.consumer = consumer; - } - public static GpgVersionParser parse( String executable ) - throws MojoExecutionException - { + public static GpgVersionParser parse(String executable) throws MojoExecutionException { Commandline cmd = new Commandline(); - if ( StringUtils.isNotEmpty( executable ) ) - { - cmd.setExecutable( executable ); + if (StringUtils.isNotEmpty(executable)) { + cmd.setExecutable(executable); + } else { + cmd.setExecutable("gpg" + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".exe" : "")); } - else - { - cmd.setExecutable( "gpg" + ( Os.isFamily( Os.FAMILY_WINDOWS ) ? ".exe" : "" ) ); - } - - cmd.createArg().setValue( "--version" ); + cmd.createArg().setValue("--version"); GpgVersionConsumer out = new GpgVersionConsumer(); - try - { - CommandLineUtils.executeCommandLine( cmd, null, out, null ); - } - catch ( CommandLineException e ) - { - throw new MojoExecutionException( "failed to execute gpg", e ); + try { + CommandLineUtils.executeCommandLine(cmd, null, out, null); + } catch (CommandLineException e) { + throw new MojoExecutionException("failed to execute gpg", e); } - return new GpgVersionParser( out ); + return new GpgVersionParser(out); } - public GpgVersion getGpgVersion() - { + public GpgVersion getGpgVersion() { return consumer.getGpgVersion(); - } /** @@ -102,28 +86,21 @@ public GpgVersion getGpgVersion() * @author Robert Scholte * @since 3.0.0 */ - static class GpgVersionConsumer - implements StreamConsumer - { - private final Pattern gpgVersionPattern = Pattern.compile( "gpg \\([^)]+\\) .+" ); + static class GpgVersionConsumer implements StreamConsumer { + private final Pattern gpgVersionPattern = Pattern.compile("gpg \\([^)]+\\) .+"); private GpgVersion gpgVersion; @Override - public void consumeLine( String line ) - throws IOException - { - Matcher m = gpgVersionPattern.matcher( line ); - if ( m.matches() ) - { - gpgVersion = GpgVersion.parse( m.group() ); + public void consumeLine(String line) throws IOException { + Matcher m = gpgVersionPattern.matcher(line); + if (m.matches()) { + gpgVersion = GpgVersion.parse(m.group()); } } - - public GpgVersion getGpgVersion() - { + + public GpgVersion getGpgVersion() { return gpgVersion; } } - } diff --git a/src/main/java/org/apache/maven/plugins/gpg/SignAndDeployFileMojo.java b/src/main/java/org/apache/maven/plugins/gpg/SignAndDeployFileMojo.java index 872bf80..a80ed83 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/SignAndDeployFileMojo.java +++ b/src/main/java/org/apache/maven/plugins/gpg/SignAndDeployFileMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "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 + * 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 @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; import java.io.FileNotFoundException; @@ -69,96 +68,94 @@ * @author Daniel Kulp * @since 1.0-beta-4 */ -@Mojo( name = "sign-and-deploy-file", requiresProject = false, threadSafe = true ) -public class SignAndDeployFileMojo - extends AbstractGpgMojo -{ +@Mojo(name = "sign-and-deploy-file", requiresProject = false, threadSafe = true) +public class SignAndDeployFileMojo extends AbstractGpgMojo { /** * The directory where to store signature files. */ - @Parameter( property = "gpg.ascDirectory" ) + @Parameter(property = "gpg.ascDirectory") private File ascDirectory; /** * Flag whether Maven is currently in online/offline mode. */ - @Parameter( defaultValue = "${settings.offline}", readonly = true ) + @Parameter(defaultValue = "${settings.offline}", readonly = true) private boolean offline; /** * GroupId of the artifact to be deployed. Retrieved from POM file if specified. */ - @Parameter( property = "groupId" ) + @Parameter(property = "groupId") private String groupId; /** * ArtifactId of the artifact to be deployed. Retrieved from POM file if specified. */ - @Parameter( property = "artifactId" ) + @Parameter(property = "artifactId") private String artifactId; /** * Version of the artifact to be deployed. Retrieved from POM file if specified. */ - @Parameter( property = "version" ) + @Parameter(property = "version") private String version; /** * Type of the artifact to be deployed. Retrieved from POM file if specified. * Defaults to file extension if not specified via command line or POM. */ - @Parameter( property = "packaging" ) + @Parameter(property = "packaging") private String packaging; /** * Add classifier to the artifact */ - @Parameter( property = "classifier" ) + @Parameter(property = "classifier") private String classifier; /** * Description passed to a generated POM file (in case of generatePom=true). */ - @Parameter( property = "generatePom.description" ) + @Parameter(property = "generatePom.description") private String description; /** * File to be deployed. */ - @Parameter( property = "file", required = true ) + @Parameter(property = "file", required = true) private File file; /** * Location of an existing POM file to be deployed alongside the main artifact, given by the ${file} parameter. */ - @Parameter( property = "pomFile" ) + @Parameter(property = "pomFile") private File pomFile; /** * Upload a POM for this artifact. Will generate a default POM if none is supplied with the pomFile argument. */ - @Parameter( property = "generatePom", defaultValue = "true" ) + @Parameter(property = "generatePom", defaultValue = "true") private boolean generatePom; /** * URL where the artifact will be deployed.
* ie ( file:///C:/m2-repo or scp://host.com/path/to/repo ) */ - @Parameter( property = "url", required = true ) + @Parameter(property = "url", required = true) private String url; /** * Server Id to map on the <id> under <server> section of settings.xml. In most cases, this * parameter will be required for authentication. */ - @Parameter( property = "repositoryId", defaultValue = "remote-repository", required = true ) + @Parameter(property = "repositoryId", defaultValue = "remote-repository", required = true) private String repositoryId; /** * The type of remote repository layout to deploy to. Try legacy for a Maven 1.x-style repository layout. */ - @Parameter( property = "repositoryLayout", defaultValue = "default" ) + @Parameter(property = "repositoryLayout", defaultValue = "default") private String repositoryLayout; /** @@ -168,7 +165,7 @@ public class SignAndDeployFileMojo /** */ - @Parameter( defaultValue = "${localRepository}", required = true, readonly = true ) + @Parameter(defaultValue = "${localRepository}", required = true, readonly = true) private ArtifactRepository localRepository; /** @@ -188,13 +185,13 @@ public class SignAndDeployFileMojo * * @since 1.3 */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * @since 3.0.0 */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** @@ -210,7 +207,7 @@ public class SignAndDeployFileMojo * * @since 1.3 */ - @Parameter( property = "javadoc" ) + @Parameter(property = "javadoc") private File javadoc; /** @@ -218,7 +215,7 @@ public class SignAndDeployFileMojo * * @since 1.3 */ - @Parameter( property = "sources" ) + @Parameter(property = "sources") private File sources; /** @@ -227,7 +224,7 @@ public class SignAndDeployFileMojo * * @since 1.3 */ - @Parameter( property = "retryFailedDeploymentCount", defaultValue = "1" ) + @Parameter(property = "retryFailedDeploymentCount", defaultValue = "1") private int retryFailedDeploymentCount; /** @@ -235,232 +232,191 @@ public class SignAndDeployFileMojo * * @since 1.3 */ - @Parameter( property = "updateReleaseInfo", defaultValue = "false" ) + @Parameter(property = "updateReleaseInfo", defaultValue = "false") protected boolean updateReleaseInfo; /** * A comma separated list of types for each of the extra side artifacts to deploy. If there is a mis-match in * the number of entries in {@link #files} or {@link #classifiers}, then an error will be raised. */ - @Parameter( property = "types" ) + @Parameter(property = "types") private String types; /** * A comma separated list of classifiers for each of the extra side artifacts to deploy. If there is a mis-match in * the number of entries in {@link #files} or {@link #types}, then an error will be raised. */ - @Parameter( property = "classifiers" ) + @Parameter(property = "classifiers") private String classifiers; /** * A comma separated list of files for each of the extra side artifacts to deploy. If there is a mis-match in * the number of entries in {@link #types} or {@link #classifiers}, then an error will be raised. */ - @Parameter( property = "files" ) + @Parameter(property = "files") private String files; - private void initProperties() - throws MojoExecutionException - { + private void initProperties() throws MojoExecutionException { // Process the supplied POM (if there is one) - if ( pomFile != null ) - { + if (pomFile != null) { generatePom = false; - Model model = readModel( pomFile ); + Model model = readModel(pomFile); - processModel( model ); + processModel(model); } - if ( packaging == null && file != null ) - { - packaging = FileUtils.getExtension( file.getName() ); + if (packaging == null && file != null) { + packaging = FileUtils.getExtension(file.getName()); } } @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - AbstractGpgSigner signer = newSigner( null ); - signer.setOutputDirectory( ascDirectory ); - signer.setBaseDirectory( new File( "" ).getAbsoluteFile() ); - - if ( offline ) - { - throw new MojoFailureException( "Cannot deploy artifacts when Maven is in offline mode" ); + public void execute() throws MojoExecutionException, MojoFailureException { + AbstractGpgSigner signer = newSigner(null); + signer.setOutputDirectory(ascDirectory); + signer.setBaseDirectory(new File("").getAbsoluteFile()); + + if (offline) { + throw new MojoFailureException("Cannot deploy artifacts when Maven is in offline mode"); } initProperties(); validateArtifactInformation(); - if ( !file.exists() ) - { - throw new MojoFailureException( file.getPath() + " not found." ); + if (!file.exists()) { + throw new MojoFailureException(file.getPath() + " not found."); } - - ArtifactRepository deploymentRepository = createDeploymentArtifactRepository( repositoryId, url ); + ArtifactRepository deploymentRepository = createDeploymentArtifactRepository(repositoryId, url); - if ( StringUtils.isEmpty( deploymentRepository.getProtocol() ) ) - { - throw new MojoFailureException( "No transfer protocol found." ); + if (StringUtils.isEmpty(deploymentRepository.getProtocol())) { + throw new MojoFailureException("No transfer protocol found."); } Artifact artifact = - artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, packaging, classifier ); + artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, packaging, classifier); - if ( file.equals( getLocalRepoFile( artifact ) ) ) - { - throw new MojoFailureException( "Cannot deploy artifact from the local repository: " + file ); + if (file.equals(getLocalRepoFile(artifact))) { + throw new MojoFailureException("Cannot deploy artifact from the local repository: " + file); } - artifact.setFile( file ); + artifact.setFile(file); - File fileSig = signer.generateSignatureForArtifact( file ); - ArtifactMetadata metadata = new AscArtifactMetadata( artifact, fileSig, false ); - artifact.addMetadata( metadata ); + File fileSig = signer.generateSignatureForArtifact(file); + ArtifactMetadata metadata = new AscArtifactMetadata(artifact, fileSig, false); + artifact.addMetadata(metadata); - if ( !"pom".equals( packaging ) ) - { - if ( pomFile == null && generatePom ) - { + if (!"pom".equals(packaging)) { + if (pomFile == null && generatePom) { pomFile = generatePomFile(); } - if ( pomFile != null ) - { - metadata = new ProjectArtifactMetadata( artifact, pomFile ); - artifact.addMetadata( metadata ); - - fileSig = signer.generateSignatureForArtifact( pomFile ); - metadata = new AscArtifactMetadata( artifact, fileSig, true ); - artifact.addMetadata( metadata ); + if (pomFile != null) { + metadata = new ProjectArtifactMetadata(artifact, pomFile); + artifact.addMetadata(metadata); + + fileSig = signer.generateSignatureForArtifact(pomFile); + metadata = new AscArtifactMetadata(artifact, fileSig, true); + artifact.addMetadata(metadata); } } - if ( updateReleaseInfo ) - { - artifact.setRelease( true ); + if (updateReleaseInfo) { + artifact.setRelease(true); } - project.setArtifact( artifact ); + project.setArtifact(artifact); - try - { - deploy( artifact, deploymentRepository ); - } - catch ( ArtifactDeployerException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + deploy(artifact, deploymentRepository); + } catch (ArtifactDeployerException e) { + throw new MojoExecutionException(e.getMessage(), e); } - if ( sources != null ) - { - projectHelper.attachArtifact( project, "jar", "sources", sources ); + if (sources != null) { + projectHelper.attachArtifact(project, "jar", "sources", sources); } - if ( javadoc != null ) - { - projectHelper.attachArtifact( project, "jar", "javadoc", javadoc ); + if (javadoc != null) { + projectHelper.attachArtifact(project, "jar", "javadoc", javadoc); } - if ( files != null ) - { - if ( types == null ) - { - throw new MojoExecutionException( "You must specify 'types' if you specify 'files'" ); + if (files != null) { + if (types == null) { + throw new MojoExecutionException("You must specify 'types' if you specify 'files'"); } - if ( classifiers == null ) - { - throw new MojoExecutionException( "You must specify 'classifiers' if you specify 'files'" ); + if (classifiers == null) { + throw new MojoExecutionException("You must specify 'classifiers' if you specify 'files'"); } - int filesLength = StringUtils.countMatches( files, "," ); - int typesLength = StringUtils.countMatches( types, "," ); - int classifiersLength = StringUtils.countMatches( classifiers, "," ); - if ( typesLength != filesLength ) - { - throw new MojoExecutionException( "You must specify the same number of entries in 'files' and " - + "'types' (respectively " + filesLength + " and " + typesLength + " entries )" ); + int filesLength = StringUtils.countMatches(files, ","); + int typesLength = StringUtils.countMatches(types, ","); + int classifiersLength = StringUtils.countMatches(classifiers, ","); + if (typesLength != filesLength) { + throw new MojoExecutionException("You must specify the same number of entries in 'files' and " + + "'types' (respectively " + filesLength + " and " + typesLength + " entries )"); } - if ( classifiersLength != filesLength ) - { - throw new MojoExecutionException( "You must specify the same number of entries in 'files' and " - + "'classifiers' (respectively " + filesLength + " and " + classifiersLength + " entries )" ); + if (classifiersLength != filesLength) { + throw new MojoExecutionException("You must specify the same number of entries in 'files' and " + + "'classifiers' (respectively " + filesLength + " and " + classifiersLength + " entries )"); } int fi = 0; int ti = 0; int ci = 0; - for ( int i = 0; i <= filesLength; i++ ) - { - int nfi = files.indexOf( ',', fi ); - if ( nfi == -1 ) - { + for (int i = 0; i <= filesLength; i++) { + int nfi = files.indexOf(',', fi); + if (nfi == -1) { nfi = files.length(); } - int nti = types.indexOf( ',', ti ); - if ( nti == -1 ) - { + int nti = types.indexOf(',', ti); + if (nti == -1) { nti = types.length(); } - int nci = classifiers.indexOf( ',', ci ); - if ( nci == -1 ) - { + int nci = classifiers.indexOf(',', ci); + if (nci == -1) { nci = classifiers.length(); } - File file = new File( files.substring( fi, nfi ) ); - if ( !file.isFile() ) - { + File file = new File(files.substring(fi, nfi)); + if (!file.isFile()) { // try relative to the project basedir just in case - file = new File( project.getBasedir(), files.substring( fi, nfi ) ); + file = new File(project.getBasedir(), files.substring(fi, nfi)); } - if ( file.isFile() ) - { - if ( StringUtils.isWhitespace( classifiers.substring( ci, nci ) ) ) - { - projectHelper.attachArtifact( project, types.substring( ti, nti ).trim(), file ); + if (file.isFile()) { + if (StringUtils.isWhitespace(classifiers.substring(ci, nci))) { + projectHelper.attachArtifact( + project, types.substring(ti, nti).trim(), file); + } else { + projectHelper.attachArtifact( + project, + types.substring(ti, nti).trim(), + classifiers.substring(ci, nci).trim(), + file); } - else - { - projectHelper.attachArtifact( project, types.substring( ti, nti ).trim(), - classifiers.substring( ci, nci ).trim(), file ); - } - } - else - { - throw new MojoExecutionException( "Specified side artifact " + file + " does not exist" ); + } else { + throw new MojoExecutionException("Specified side artifact " + file + " does not exist"); } fi = nfi + 1; ti = nti + 1; ci = nci + 1; } - } - else - { - if ( types != null ) - { - throw new MojoExecutionException( "You must specify 'files' if you specify 'types'" ); + } else { + if (types != null) { + throw new MojoExecutionException("You must specify 'files' if you specify 'types'"); } - if ( classifiers != null ) - { - throw new MojoExecutionException( "You must specify 'files' if you specify 'classifiers'" ); + if (classifiers != null) { + throw new MojoExecutionException("You must specify 'files' if you specify 'classifiers'"); } } - for ( Artifact attached : project.getAttachedArtifacts() ) - { - fileSig = signer.generateSignatureForArtifact( attached.getFile() ); - attached = new AttachedSignedArtifact( attached, new AscArtifactMetadata( attached, fileSig, false ) ); - try - { - deploy( attached, deploymentRepository ); - } - catch ( ArtifactDeployerException e ) - { - throw new MojoExecutionException( "Error deploying attached artifact " + attached.getFile() + ": " - + e.getMessage(), e ); + for (Artifact attached : project.getAttachedArtifacts()) { + fileSig = signer.generateSignatureForArtifact(attached.getFile()); + attached = new AttachedSignedArtifact(attached, new AscArtifactMetadata(attached, fileSig, false)); + try { + deploy(attached, deploymentRepository); + } catch (ArtifactDeployerException e) { + throw new MojoExecutionException( + "Error deploying attached artifact " + attached.getFile() + ": " + e.getMessage(), e); } } - } /** @@ -470,10 +426,9 @@ public void execute() * @param artifact The artifact whose local repo path should be determined, must not be null. * @return The absolute path to the artifact when installed, never null. */ - private File getLocalRepoFile( Artifact artifact ) - { - String path = localRepository.pathOf( artifact ); - return new File( localRepository.getBasedir(), path ); + private File getLocalRepoFile(Artifact artifact) { + String path = localRepository.pathOf(artifact); + return new File(localRepository.getBasedir(), path); } /** @@ -481,32 +436,25 @@ private File getLocalRepoFile( Artifact artifact ) * * @param model The POM to extract missing artifact coordinates from, must not be null. */ - private void processModel( Model model ) - { + private void processModel(Model model) { Parent parent = model.getParent(); - if ( this.groupId == null ) - { + if (this.groupId == null) { this.groupId = model.getGroupId(); - if ( this.groupId == null && parent != null ) - { + if (this.groupId == null && parent != null) { this.groupId = parent.getGroupId(); } } - if ( this.artifactId == null ) - { + if (this.artifactId == null) { this.artifactId = model.getArtifactId(); } - if ( this.version == null ) - { + if (this.version == null) { this.version = model.getVersion(); - if ( this.version == null && parent != null ) - { + if (this.version == null && parent != null) { this.version = parent.getVersion(); } } - if ( this.packaging == null ) - { + if (this.packaging == null) { this.packaging = model.getPackaging(); } } @@ -518,25 +466,16 @@ private void processModel( Model model ) * @return The model from the POM file, never null. * @throws MojoExecutionException If the file doesn't exist of cannot be read. */ - private Model readModel( File pomFile ) - throws MojoExecutionException - { - try ( Reader reader = ReaderFactory.newXmlReader( pomFile ) ) - { - final Model model = new MavenXpp3Reader().read( reader ); + private Model readModel(File pomFile) throws MojoExecutionException { + try (Reader reader = ReaderFactory.newXmlReader(pomFile)) { + final Model model = new MavenXpp3Reader().read(reader); return model; - } - catch ( FileNotFoundException e ) - { - throw new MojoExecutionException( "POM not found " + pomFile, e ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error reading POM " + pomFile, e ); - } - catch ( XmlPullParserException e ) - { - throw new MojoExecutionException( "Error parsing POM " + pomFile, e ); + } catch (FileNotFoundException e) { + throw new MojoExecutionException("POM not found " + pomFile, e); + } catch (IOException e) { + throw new MojoExecutionException("Error reading POM " + pomFile, e); + } catch (XmlPullParserException e) { + throw new MojoExecutionException("Error parsing POM " + pomFile, e); } } @@ -546,26 +485,20 @@ private Model readModel( File pomFile ) * @return The path to the generated POM file, never null. * @throws MojoExecutionException If the generation failed. */ - private File generatePomFile() - throws MojoExecutionException - { + private File generatePomFile() throws MojoExecutionException { Model model = generateModel(); - - try - { - File tempFile = File.createTempFile( "mvndeploy", ".pom" ); + + try { + File tempFile = File.createTempFile("mvndeploy", ".pom"); tempFile.deleteOnExit(); - try ( Writer fw = WriterFactory.newXmlWriter( tempFile ) ) - { - new MavenXpp3Writer().write( fw, model ); + try (Writer fw = WriterFactory.newXmlWriter(tempFile)) { + new MavenXpp3Writer().write(fw, model); } return tempFile; - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error writing temporary pom file: " + e.getMessage(), e ); + } catch (IOException e) { + throw new MojoExecutionException("Error writing temporary pom file: " + e.getMessage(), e); } } @@ -574,28 +507,24 @@ private File generatePomFile() * * @throws MojoFailureException If any artifact coordinate is invalid. */ - private void validateArtifactInformation() - throws MojoFailureException - { + private void validateArtifactInformation() throws MojoFailureException { Model model = generateModel(); - ModelBuildingRequest request = new DefaultModelBuildingRequest() - .setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 ); - + ModelBuildingRequest request = + new DefaultModelBuildingRequest().setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0); + List result = new ArrayList<>(); - SimpleModelProblemCollector problemCollector = new SimpleModelProblemCollector( result ); + SimpleModelProblemCollector problemCollector = new SimpleModelProblemCollector(result); - modelValidator.validateEffectiveModel( model, request, problemCollector ); + modelValidator.validateEffectiveModel(model, request, problemCollector); - if ( !result.isEmpty() ) - { - StringBuilder msg = new StringBuilder( "The artifact information is incomplete or not valid:\n" ); - for ( String e : result ) - { - msg.append( " - " + e + '\n' ); + if (!result.isEmpty()) { + StringBuilder msg = new StringBuilder("The artifact information is incomplete or not valid:\n"); + for (String e : result) { + msg.append(" - " + e + '\n'); } - throw new MojoFailureException( msg.toString() ); + throw new MojoFailureException(msg.toString()); } } @@ -604,18 +533,17 @@ private void validateArtifactInformation() * * @return The generated model, never null. */ - private Model generateModel() - { + private Model generateModel() { Model model = new Model(); - model.setModelVersion( "4.0.0" ); + model.setModelVersion("4.0.0"); - model.setGroupId( groupId ); - model.setArtifactId( artifactId ); - model.setVersion( version ); - model.setPackaging( packaging ); + model.setGroupId(groupId); + model.setArtifactId(artifactId); + model.setVersion(version); + model.setPackaging(packaging); - model.setDescription( description ); + model.setDescription(description); return model; } @@ -627,77 +555,58 @@ private Model generateModel() * @param deploymentRepository the repository to deploy to * @throws ArtifactDeployerException if an error occurred deploying the artifact */ - protected void deploy( Artifact artifact, - ArtifactRepository deploymentRepository ) - throws ArtifactDeployerException - { + protected void deploy(Artifact artifact, ArtifactRepository deploymentRepository) throws ArtifactDeployerException { final ProjectBuildingRequest buildingRequest = session.getProjectBuildingRequest(); - - int retryFailedDeploymentCount = Math.max( 1, Math.min( 10, this.retryFailedDeploymentCount ) ); + + int retryFailedDeploymentCount = Math.max(1, Math.min(10, this.retryFailedDeploymentCount)); ArtifactDeployerException exception = null; - for ( int count = 0; count < retryFailedDeploymentCount; count++ ) - { - try - { - if ( count > 0 ) - { + for (int count = 0; count < retryFailedDeploymentCount; count++) { + try { + if (count > 0) { // CHECKSTYLE_OFF: LineLength - getLog().info( "Retrying deployment attempt " + ( count + 1 ) + " of " + retryFailedDeploymentCount ); + getLog().info("Retrying deployment attempt " + (count + 1) + " of " + retryFailedDeploymentCount); // CHECKSTYLE_ON: LineLength } - deployer.deploy( buildingRequest, deploymentRepository, Collections.singletonList( artifact ) ); + deployer.deploy(buildingRequest, deploymentRepository, Collections.singletonList(artifact)); - for ( Object o : artifact.getMetadataList() ) - { + for (Object o : artifact.getMetadataList()) { ArtifactMetadata metadata = (ArtifactMetadata) o; - getLog().info( "Metadata[" + metadata.getKey() + "].filename = " + metadata.getRemoteFilename() ); + getLog().info("Metadata[" + metadata.getKey() + "].filename = " + metadata.getRemoteFilename()); } exception = null; break; - } - catch ( ArtifactDeployerException e ) - { - if ( count + 1 < retryFailedDeploymentCount ) - { - getLog().warn( "Encountered issue during deployment: " + e.getLocalizedMessage() ); - getLog().debug( e ); + } catch (ArtifactDeployerException e) { + if (count + 1 < retryFailedDeploymentCount) { + getLog().warn("Encountered issue during deployment: " + e.getLocalizedMessage()); + getLog().debug(e); } - if ( exception == null ) - { + if (exception == null) { exception = e; } } } - if ( exception != null ) - { + if (exception != null) { throw exception; } } - - protected ArtifactRepository createDeploymentArtifactRepository( String id, String url ) - { - return new MavenArtifactRepository( id, url, new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), - new ArtifactRepositoryPolicy() ); + + protected ArtifactRepository createDeploymentArtifactRepository(String id, String url) { + return new MavenArtifactRepository( + id, url, new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy()); } - private static class SimpleModelProblemCollector - implements ModelProblemCollector - { + private static class SimpleModelProblemCollector implements ModelProblemCollector { private final List result; - SimpleModelProblemCollector( List result ) - { + SimpleModelProblemCollector(List result) { this.result = result; } - public void add( ModelProblemCollectorRequest req ) - { - if ( !ModelProblem.Severity.WARNING.equals( req.getSeverity() ) ) - { - result.add( req.getMessage() ); + public void add(ModelProblemCollectorRequest req) { + if (!ModelProblem.Severity.WARNING.equals(req.getSeverity())) { + result.add(req.getMessage()); } } - } } diff --git a/src/main/java/org/apache/maven/plugins/gpg/SigningBundle.java b/src/main/java/org/apache/maven/plugins/gpg/SigningBundle.java index fd474b1..be43592 100644 --- a/src/main/java/org/apache/maven/plugins/gpg/SigningBundle.java +++ b/src/main/java/org/apache/maven/plugins/gpg/SigningBundle.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import java.io.File; /** @author Jason van Zyl */ -public class SigningBundle -{ +public class SigningBundle { private String extension; @@ -31,33 +29,27 @@ public class SigningBundle private File signature; - public SigningBundle( String extension, File signature ) - { + public SigningBundle(String extension, File signature) { this.extension = extension; this.signature = signature; } - public SigningBundle( String extension, String classifier, File signature ) - { + public SigningBundle(String extension, String classifier, File signature) { this.extension = extension; this.classifier = classifier; this.signature = signature; } - public String getExtension() - { + public String getExtension() { return extension; } - public File getSignature() - { + public File getSignature() { return signature; } - public String getClassifier() - { + public String getClassifier() { return classifier; } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/GpgVersionConsumerTest.java b/src/test/java/org/apache/maven/plugins/gpg/GpgVersionConsumerTest.java index 3bcd912..fc71836 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/GpgVersionConsumerTest.java +++ b/src/test/java/org/apache/maven/plugins/gpg/GpgVersionConsumerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,23 +16,20 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +package org.apache.maven.plugins.gpg; import org.apache.maven.plugins.gpg.GpgVersionParser.GpgVersionConsumer; import org.junit.Test; -public class GpgVersionConsumerTest -{ +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class GpgVersionConsumerTest { @Test - public void test() - throws Exception - { + public void test() throws Exception { GpgVersionConsumer consumer = new GpgVersionConsumer(); - consumer.consumeLine( "gpg (GnuPG/MacGPG2) 2.2.10" ); + consumer.consumeLine("gpg (GnuPG/MacGPG2) 2.2.10"); - assertThat( consumer.getGpgVersion(), is( GpgVersion.parse( "2.2.10" ) ) ); + assertThat(consumer.getGpgVersion(), is(GpgVersion.parse("2.2.10"))); } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/GpgVersionTest.java b/src/test/java/org/apache/maven/plugins/gpg/GpgVersionTest.java index 659952a..9cc31cd 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/GpgVersionTest.java +++ b/src/test/java/org/apache/maven/plugins/gpg/GpgVersionTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg; import org.junit.Test; @@ -29,46 +28,51 @@ /** * Tests for {@link GpgVersion}. */ -public class GpgVersionTest -{ +public class GpgVersionTest { @Test - public void test() - { - assertTrue( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).isAtLeast( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ) ) ); - assertTrue( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).isAtLeast( GpgVersion.parse( "2.1" ) ) ); - assertTrue( GpgVersion.parse( "gpg (GnuPG/MacGPG2) 2.2.10" ).isAtLeast( GpgVersion.parse( "2.2.10" ) ) ); - assertTrue( GpgVersion.parse( "gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)" ) - .isAtLeast( GpgVersion.parse( "2.0.26" ) ) ); + public void test() { + assertTrue(GpgVersion.parse("gpg (GnuPG) 2.2.1").isAtLeast(GpgVersion.parse("gpg (GnuPG) 2.2.1"))); + assertTrue(GpgVersion.parse("gpg (GnuPG) 2.2.1").isAtLeast(GpgVersion.parse("2.1"))); + assertTrue(GpgVersion.parse("gpg (GnuPG/MacGPG2) 2.2.10").isAtLeast(GpgVersion.parse("2.2.10"))); + assertTrue(GpgVersion.parse("gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)").isAtLeast(GpgVersion.parse("2.0.26"))); } @Test - public void testOpposite() - { - assertFalse( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).isBefore( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ) ) ); - assertFalse( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).isBefore( GpgVersion.parse( "2.1" ) ) ); - assertFalse( GpgVersion.parse( "gpg (GnuPG/MacGPG2) 2.2.10" ).isBefore( GpgVersion.parse( "2.2.10" ) ) ); - assertFalse( GpgVersion.parse( "gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)" ) - .isBefore( GpgVersion.parse( "2.0.26" ) ) ); + public void testOpposite() { + assertFalse(GpgVersion.parse("gpg (GnuPG) 2.2.1").isBefore(GpgVersion.parse("gpg (GnuPG) 2.2.1"))); + assertFalse(GpgVersion.parse("gpg (GnuPG) 2.2.1").isBefore(GpgVersion.parse("2.1"))); + assertFalse(GpgVersion.parse("gpg (GnuPG/MacGPG2) 2.2.10").isBefore(GpgVersion.parse("2.2.10"))); + assertFalse(GpgVersion.parse("gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)").isBefore(GpgVersion.parse("2.0.26"))); } @Test - public void testEquality() - { - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ), GpgVersion.parse( "gpg (GnuPG) 2.2.1" ) ); - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ), GpgVersion.parse( "2.2.1" ) ); - assertEquals( GpgVersion.parse( "gpg (GnuPG/MacGPG2) 2.2.10" ), GpgVersion.parse( "2.2.10" ) ); - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)" ), GpgVersion.parse( "2.0.26" ) ); + public void testEquality() { + assertEquals(GpgVersion.parse("gpg (GnuPG) 2.2.1"), GpgVersion.parse("gpg (GnuPG) 2.2.1")); + assertEquals(GpgVersion.parse("gpg (GnuPG) 2.2.1"), GpgVersion.parse("2.2.1")); + assertEquals(GpgVersion.parse("gpg (GnuPG/MacGPG2) 2.2.10"), GpgVersion.parse("2.2.10")); + assertEquals(GpgVersion.parse("gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)"), GpgVersion.parse("2.0.26")); - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).hashCode(), GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).hashCode() ); - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).hashCode(), GpgVersion.parse( "2.2.1" ).hashCode() ); - assertEquals( GpgVersion.parse( "gpg (GnuPG/MacGPG2) 2.2.10" ).hashCode(), GpgVersion.parse( "2.2.10" ).hashCode() ); - assertEquals( GpgVersion.parse( "gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)" ).hashCode(), GpgVersion.parse( "2.0.26" ).hashCode() ); + assertEquals( + GpgVersion.parse("gpg (GnuPG) 2.2.1").hashCode(), + GpgVersion.parse("gpg (GnuPG) 2.2.1").hashCode()); + assertEquals( + GpgVersion.parse("gpg (GnuPG) 2.2.1").hashCode(), + GpgVersion.parse("2.2.1").hashCode()); + assertEquals( + GpgVersion.parse("gpg (GnuPG/MacGPG2) 2.2.10").hashCode(), + GpgVersion.parse("2.2.10").hashCode()); + assertEquals( + GpgVersion.parse("gpg (GnuPG) 2.0.26 (Gpg4win 2.2.3)").hashCode(), + GpgVersion.parse("2.0.26").hashCode()); - assertNotEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ), GpgVersion.parse( "2.2.0" ) ); - assertNotEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ), GpgVersion.parse( "2.2" ) ); + assertNotEquals(GpgVersion.parse("gpg (GnuPG) 2.2.1"), GpgVersion.parse("2.2.0")); + assertNotEquals(GpgVersion.parse("gpg (GnuPG) 2.2.1"), GpgVersion.parse("2.2")); - assertNotEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).hashCode(), GpgVersion.parse( "2.2.0" ).hashCode() ); - assertNotEquals( GpgVersion.parse( "gpg (GnuPG) 2.2.1" ).hashCode(), GpgVersion.parse( "2.2" ).hashCode() ); + assertNotEquals( + GpgVersion.parse("gpg (GnuPG) 2.2.1").hashCode(), + GpgVersion.parse("2.2.0").hashCode()); + assertNotEquals( + GpgVersion.parse("gpg (GnuPG) 2.2.1").hashCode(), + GpgVersion.parse("2.2").hashCode()); } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/it/BuildResult.java b/src/test/java/org/apache/maven/plugins/gpg/it/BuildResult.java index 3e40566..51537cb 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/it/BuildResult.java +++ b/src/test/java/org/apache/maven/plugins/gpg/it/BuildResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg.it; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,31 +16,27 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg.it; import java.io.File; import org.apache.maven.shared.invoker.InvocationResult; -public class BuildResult -{ +public class BuildResult { private final File buildLog; private final InvocationResult invocationResult; - public BuildResult( final File buildLog, final InvocationResult invocationResult ) - { + public BuildResult(final File buildLog, final InvocationResult invocationResult) { this.buildLog = buildLog; this.invocationResult = invocationResult; } - public File getBuildLog() - { + public File getBuildLog() { return buildLog; } - public InvocationResult getInvocationResult() - { + public InvocationResult getInvocationResult() { return invocationResult; } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignArtifactIT.java b/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignArtifactIT.java index 0cd72de..8ea07dd 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignArtifactIT.java +++ b/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignArtifactIT.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg.it; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,75 +16,85 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg.it; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; import org.apache.maven.shared.invoker.InvocationRequest; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.File; -import java.util.Arrays; -import java.util.Collection; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.junit.runners.Parameterized.Parameter; import static org.junit.runners.Parameterized.Parameters; -@RunWith( Parameterized.class ) -public class GpgSignArtifactIT -{ +@RunWith(Parameterized.class) +public class GpgSignArtifactIT { private final File mavenHome; private final File localRepository; private final File mavenUserSettings; private final File gpgHome; - public GpgSignArtifactIT() throws Exception - { - this.mavenHome = new File( System.getProperty( "maven.home" ) ); - this.localRepository = new File( System.getProperty( "localRepositoryPath" ) ); - this.mavenUserSettings = InvokerTestUtils.getTestResource( "/it/settings-with-passphrase.xml" ); - this.gpgHome = new File( System.getProperty( "gpg.homedir" ) ); + public GpgSignArtifactIT() throws Exception { + this.mavenHome = new File(System.getProperty("maven.home")); + this.localRepository = new File(System.getProperty("localRepositoryPath")); + this.mavenUserSettings = InvokerTestUtils.getTestResource("/it/settings-with-passphrase.xml"); + this.gpgHome = new File(System.getProperty("gpg.homedir")); } @Parameters - public static Collection data() - { - return Arrays.asList( new Object[][] { - { "/it/sign-release-in-default-dir/pom.xml", "/target/gpg/tarballs/", - new String[] { "sign-release-in-default-dir-1.0.jar.asc" }}, - { "/it/sign-release-in-output-dir/pom.xml", "/target/signed-files/tarballs/", - new String[] { "sign-release-in-output-dir-1.0.jar.asc" }}, - { "/it/sign-release-in-root-dir/pom.xml", "/signed-files/tarballs/", - new String[] { "sign-release-in-root-dir-1.0.jar.asc" }}, - { "/it/sign-release-in-same-dir/pom.xml", "/target/tarballs/", - new String[] { "sign-release-in-same-dir-1.0.jar", "sign-release-in-same-dir-1.0.jar.asc" }}, - } ); + public static Collection data() { + return Arrays.asList(new Object[][] { + { + "/it/sign-release-in-default-dir/pom.xml", + "/target/gpg/tarballs/", + new String[] {"sign-release-in-default-dir-1.0.jar.asc"} + }, + { + "/it/sign-release-in-output-dir/pom.xml", + "/target/signed-files/tarballs/", + new String[] {"sign-release-in-output-dir-1.0.jar.asc"} + }, + { + "/it/sign-release-in-root-dir/pom.xml", + "/signed-files/tarballs/", + new String[] {"sign-release-in-root-dir-1.0.jar.asc"} + }, + { + "/it/sign-release-in-same-dir/pom.xml", + "/target/tarballs/", + new String[] {"sign-release-in-same-dir-1.0.jar", "sign-release-in-same-dir-1.0.jar.asc"} + }, + }); } @Parameter public String pomPath; - @Parameter( 1 ) + + @Parameter(1) public String expectedFileLocation; - @Parameter( 2 ) + + @Parameter(2) public String[] expectedFiles; @Test - public void testPlacementOfArtifactInOutputDirectory() throws Exception - { + public void testPlacementOfArtifactInOutputDirectory() throws Exception { // given - final File pomFile = InvokerTestUtils.getTestResource( pomPath ); - final InvocationRequest request = InvokerTestUtils.createRequest( pomFile, mavenUserSettings, gpgHome ); - final File integrationTestRootDirectory = new File( pomFile.getParent() ); - final File expectedOutputDirectory = new File( integrationTestRootDirectory + expectedFileLocation ); + final File pomFile = InvokerTestUtils.getTestResource(pomPath); + final InvocationRequest request = InvokerTestUtils.createRequest(pomFile, mavenUserSettings, gpgHome); + final File integrationTestRootDirectory = new File(pomFile.getParent()); + final File expectedOutputDirectory = new File(integrationTestRootDirectory + expectedFileLocation); // when - InvokerTestUtils.executeRequest( request, mavenHome, localRepository ); + InvokerTestUtils.executeRequest(request, mavenHome, localRepository); // then - assertThat( expectedOutputDirectory.exists(), equalTo( true ) ); - assertThat( expectedOutputDirectory.list(), arrayContainingInAnyOrder( expectedFiles ) ); + assertThat(expectedOutputDirectory.exists(), equalTo(true)); + assertThat(expectedOutputDirectory.list(), arrayContainingInAnyOrder(expectedFiles)); } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignAttachedMojoIT.java b/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignAttachedMojoIT.java index ea36ac1..c6df9c7 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignAttachedMojoIT.java +++ b/src/test/java/org/apache/maven/plugins/gpg/it/GpgSignAttachedMojoIT.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg.it; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; +package org.apache.maven.plugins.gpg.it; import java.io.File; @@ -30,45 +25,45 @@ import org.codehaus.plexus.util.FileUtils; import org.junit.Test; -public class GpgSignAttachedMojoIT -{ +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +public class GpgSignAttachedMojoIT { private final File mavenHome; private final File localRepository; private final File mavenUserSettings; private final File gpgHome; - public GpgSignAttachedMojoIT() throws Exception - { - this.mavenHome = new File( System.getProperty( "maven.home" ) ); - this.localRepository = new File( System.getProperty( "localRepositoryPath" ) ); - this.mavenUserSettings = InvokerTestUtils.getTestResource( System.getProperty( "settingsFile" ) ); - this.gpgHome = new File( System.getProperty( "gpg.homedir" ) ); + public GpgSignAttachedMojoIT() throws Exception { + this.mavenHome = new File(System.getProperty("maven.home")); + this.localRepository = new File(System.getProperty("localRepositoryPath")); + this.mavenUserSettings = InvokerTestUtils.getTestResource(System.getProperty("settingsFile")); + this.gpgHome = new File(System.getProperty("gpg.homedir")); } @Test - public void testInteractiveWithoutPassphrase() throws Exception - { + public void testInteractiveWithoutPassphrase() throws Exception { // given - final File pomFile = InvokerTestUtils.getTestResource( "/it/sign-release-without-passphrase-interactive/pom.xml" ); - final InvocationRequest request = InvokerTestUtils.createRequest( pomFile, mavenUserSettings, gpgHome ); + final File pomFile = + InvokerTestUtils.getTestResource("/it/sign-release-without-passphrase-interactive/pom.xml"); + final InvocationRequest request = InvokerTestUtils.createRequest(pomFile, mavenUserSettings, gpgHome); // require Maven interactive mode - request.setBatchMode( false ); + request.setBatchMode(false); // when - final BuildResult result = InvokerTestUtils.executeRequest( request, mavenHome, localRepository ); + final BuildResult result = InvokerTestUtils.executeRequest(request, mavenHome, localRepository); final InvocationResult invocationResult = result.getInvocationResult(); - final String buildLogContent = FileUtils.fileRead( result.getBuildLog() ); + final String buildLogContent = FileUtils.fileRead(result.getBuildLog()); // then - assertThat( "Maven execution must fail", invocationResult.getExitCode(), not( 0 ) ); + assertThat("Maven execution must fail", invocationResult.getExitCode(), not(0)); assertThat( - "Maven execution failed because no pinentry program is available", - buildLogContent, - containsString( "[GNUPG:] FAILURE sign 67108949" ) - ); + "Maven execution failed because no pinentry program is available", + buildLogContent, + containsString("[GNUPG:] FAILURE sign 67108949")); } - } diff --git a/src/test/java/org/apache/maven/plugins/gpg/it/InvokerTestUtils.java b/src/test/java/org/apache/maven/plugins/gpg/it/InvokerTestUtils.java index 3dd041d..a08eb0f 100644 --- a/src/test/java/org/apache/maven/plugins/gpg/it/InvokerTestUtils.java +++ b/src/test/java/org/apache/maven/plugins/gpg/it/InvokerTestUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.gpg.it; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.gpg.it; import java.io.File; import java.io.FileNotFoundException; @@ -39,68 +38,64 @@ import org.apache.maven.shared.invoker.PrintStreamHandler; import org.apache.maven.shared.invoker.PrintStreamLogger; -public class InvokerTestUtils -{ +public class InvokerTestUtils { - public static InvocationRequest createRequest( final File pomFile, final File mavenUserSettings, final File gpgHome ) - { + public static InvocationRequest createRequest( + final File pomFile, final File mavenUserSettings, final File gpgHome) { final InvocationRequest request = new DefaultInvocationRequest(); - request.setUserSettingsFile( mavenUserSettings ); - request.setShowVersion( true ); - request.setDebug( true ); - request.setShowErrors( true ); - request.setTimeoutInSeconds( 60 ); // safeguard against GPG freezes - request.setGoals( Arrays.asList( "clean", "install" ) ); - request.setPomFile( pomFile ); + request.setUserSettingsFile(mavenUserSettings); + request.setShowVersion(true); + request.setDebug(true); + request.setShowErrors(true); + request.setTimeoutInSeconds(60); // safeguard against GPG freezes + request.setGoals(Arrays.asList("clean", "install")); + request.setPomFile(pomFile); final Properties properties = new Properties(); - request.setProperties( properties ); + request.setProperties(properties); // Required for JRE 7 to connect to Maven Central with TLSv1.2 - final String httpsProtocols = System.getProperty( "https.protocols" ); - if ( httpsProtocols != null && !httpsProtocols.isEmpty() ) { - properties.setProperty( "https.protocols", httpsProtocols ); + final String httpsProtocols = System.getProperty("https.protocols"); + if (httpsProtocols != null && !httpsProtocols.isEmpty()) { + properties.setProperty("https.protocols", httpsProtocols); } - properties.setProperty( "gpg.homedir", gpgHome.getAbsolutePath() ); + properties.setProperty("gpg.homedir", gpgHome.getAbsolutePath()); return request; } - public static BuildResult executeRequest( final InvocationRequest request, final File mavenHome, final File localRepository ) - throws FileNotFoundException, MavenInvocationException - { + public static BuildResult executeRequest( + final InvocationRequest request, final File mavenHome, final File localRepository) + throws FileNotFoundException, MavenInvocationException { final InvocationResult result; - final File buildLog = new File( request.getBaseDirectory( request.getPomFile().getParentFile() ), "build.log" ); - try ( final PrintStream buildLogStream = new PrintStream( buildLog ) ) - { - final InvocationOutputHandler buildLogOutputHandler = new PrintStreamHandler( buildLogStream, false ); - final InvokerLogger logger = new PrintStreamLogger( buildLogStream, InvokerLogger.DEBUG ); + final File buildLog = + new File(request.getBaseDirectory(request.getPomFile().getParentFile()), "build.log"); + try (final PrintStream buildLogStream = new PrintStream(buildLog)) { + final InvocationOutputHandler buildLogOutputHandler = new PrintStreamHandler(buildLogStream, false); + final InvokerLogger logger = new PrintStreamLogger(buildLogStream, InvokerLogger.DEBUG); final Invoker invoker = new DefaultInvoker(); - invoker.setMavenHome( mavenHome ); - invoker.setLocalRepositoryDirectory( localRepository ); - invoker.setInputStream( new NullInputStream( 0 ) ); - invoker.setOutputHandler( buildLogOutputHandler ); - invoker.setErrorHandler( buildLogOutputHandler ); - invoker.setLogger( logger ); - - result = invoker.execute( request ); + invoker.setMavenHome(mavenHome); + invoker.setLocalRepositoryDirectory(localRepository); + invoker.setInputStream(new NullInputStream(0)); + invoker.setOutputHandler(buildLogOutputHandler); + invoker.setErrorHandler(buildLogOutputHandler); + invoker.setLogger(logger); + + result = invoker.execute(request); } - return new BuildResult( buildLog, result ); + return new BuildResult(buildLog, result); } - public static File getTestResource( final String path ) throws URISyntaxException, FileNotFoundException - { - final URL resourceUrl = InvokerTestUtils.class.getResource( path ); - if ( resourceUrl == null ) - { - throw new FileNotFoundException( "Cannot find file " + path ); + public static File getTestResource(final String path) throws URISyntaxException, FileNotFoundException { + final URL resourceUrl = InvokerTestUtils.class.getResource(path); + if (resourceUrl == null) { + throw new FileNotFoundException("Cannot find file " + path); } - return new File( resourceUrl.toURI() ); + return new File(resourceUrl.toURI()); } - }