From 32950abe20a1b04985b856857deae24c9483223c Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sat, 10 Jul 2021 17:01:36 +0200 Subject: [PATCH 1/6] move build-script into .github-folder --- {.buildscript => .github/.buildscript}/settings.xml | 0 .github/workflows/default-tests.yml | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) rename {.buildscript => .github/.buildscript}/settings.xml (100%) diff --git a/.buildscript/settings.xml b/.github/.buildscript/settings.xml similarity index 100% rename from .buildscript/settings.xml rename to .github/.buildscript/settings.xml diff --git a/.github/workflows/default-tests.yml b/.github/workflows/default-tests.yml index d2d53b8e..a86b88f5 100644 --- a/.github/workflows/default-tests.yml +++ b/.github/workflows/default-tests.yml @@ -104,9 +104,9 @@ jobs: - name: Verify Setup of Maven ${{ matrix.maven_version }} run: bash -c "echo ${M2_HOME}; echo ${PATH}; mvn -version" - name: Install a test version with Maven - run: mvn clean install -B --settings=./.buildscript/settings.xml + run: mvn clean install -B --settings=./.github/.buildscript/settings.xml - name: Run the local testversion with Maven - run: mvn clean initialize -B -Pdemo -Dmaven.test.skip=true --settings=./.buildscript/settings.xml + run: mvn clean initialize -B -Pdemo -Dmaven.test.skip=true --settings=./.github/.buildscript/settings.xml - name: Validate if the testversion has produced the desired output run: /bin/bash -c '[[ -f target/testing.properties ]] && cat target/testing.properties || exit 1;' @@ -155,7 +155,7 @@ jobs: key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2 - name: Deploy snapshot with Maven - run: mvn clean deploy -B --settings=./.buildscript/settings.xml + run: mvn clean deploy -B --settings=./.github/.buildscript/settings.xml env: CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} From 9096f2603022a8c4b0210fc7cf94d4248fa0fa19 Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sat, 10 Jul 2021 17:11:51 +0200 Subject: [PATCH 2/6] https://github.com/git-commit-id/git-commit-id-plugin-core/issues/3: remove plexus dependency in the plugin-core --- pom.xml | 23 +++++++++++++++++-- .../project13/maven/git/GitCommitIdMojo.java | 9 +++++++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 4e664cca..346f4f6e 100644 --- a/pom.xml +++ b/pom.xml @@ -58,7 +58,8 @@ ${project.groupId} git-commit-id-plugin-core - 5.0.0 + + 5.0.1-SNAPSHOT com.google.code.findbugs @@ -245,7 +246,12 @@ maven-core ${maven-plugin-api.version} - + + + org.sonatype.plexus + plexus-build-api + 0.0.7 + ${project.groupId} git-commit-id-plugin-core @@ -272,6 +278,19 @@ test + + org.codehaus.plexus + plexus-utils + 3.3.0 + test + + + org.codehaus.plexus + plexus-container-default + 2.1.0 + test + + org.assertj assertj-core diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 67a36959..9129db26 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -45,6 +45,7 @@ import pl.project13.core.git.GitDescribeConfig; import pl.project13.core.log.LoggerBridge; import pl.project13.core.cibuild.BuildServerDataProvider; +import pl.project13.core.util.BuildFileChangeListener; import pl.project13.maven.log.MavenLoggerBridge; import javax.annotation.Nonnull; @@ -537,7 +538,13 @@ public void execute() throws MojoExecutionException { logProperties(); if (generateGitPropertiesFile) { - new PropertiesFileGenerator(log, buildContext, format, prefixDot, project.getName()).maybeGeneratePropertiesFile( + BuildFileChangeListener buildFileChangeListener = new BuildFileChangeListener() { + public void changed(@Nonnull File file) { + buildContext.refresh(file); + } + }; + + new PropertiesFileGenerator(log, buildFileChangeListener, format, prefixDot, project.getName()).maybeGeneratePropertiesFile( properties, project.getBasedir(), generateGitPropertiesFilename, sourceCharset); } From d2c8bc017c3b0ddf1d91337a490f4eb21b27a682 Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sat, 10 Jul 2021 17:33:12 +0200 Subject: [PATCH 3/6] the reactorProjects inside GitDirLocator seems unused -> remove it --- src/main/java/pl/project13/maven/git/GitCommitIdMojo.java | 2 +- src/main/java/pl/project13/maven/git/GitDirLocator.java | 5 +---- src/test/java/pl/project13/maven/git/GitDirLocatorTest.java | 4 +--- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 9129db26..17734e25 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -670,7 +670,7 @@ private void appendPropertiesToReactorProjects() { * @return the File representation of the .git directory */ private File lookupGitDirectory() throws GitCommitIdExecutionException { - return new GitDirLocator(project, reactorProjects).lookupGitDirectory(dotGitDirectory); + return new GitDirLocator(project).lookupGitDirectory(dotGitDirectory); } private void logProperties() { diff --git a/src/main/java/pl/project13/maven/git/GitDirLocator.java b/src/main/java/pl/project13/maven/git/GitDirLocator.java index d196eb9d..d10014cd 100644 --- a/src/main/java/pl/project13/maven/git/GitDirLocator.java +++ b/src/main/java/pl/project13/maven/git/GitDirLocator.java @@ -31,16 +31,13 @@ */ public class GitDirLocator { final MavenProject mavenProject; - final List reactorProjects; /** * Constructor to encapsulates all references required to locate a valid .git directory * @param mavenProject The currently used (maven) project. - * @param reactorProjects The list of reactor projects (sub-projects) of the current (maven) project. */ - public GitDirLocator(MavenProject mavenProject, List reactorProjects) { + public GitDirLocator(MavenProject mavenProject) { this.mavenProject = mavenProject; - this.reactorProjects = reactorProjects; } /** diff --git a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java index 0b4fc657..84cc895b 100644 --- a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java +++ b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java @@ -36,8 +36,6 @@ public class GitDirLocatorTest { @Mock MavenProject project; - List reactorProjects = Collections.emptyList(); - @Test public void shouldUseTheManuallySpecifiedDirectory() throws Exception { // given @@ -45,7 +43,7 @@ public void shouldUseTheManuallySpecifiedDirectory() throws Exception { try { // when - GitDirLocator locator = new GitDirLocator(project, reactorProjects); + GitDirLocator locator = new GitDirLocator(project); File foundDirectory = locator.lookupGitDirectory(dotGitDir); // then From 1231d524ea448a65e264b1fd3072ccf83d91c57e Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sat, 10 Jul 2021 17:36:00 +0200 Subject: [PATCH 4/6] prettify code and use lamda expression for the BuildFileChangeListener --- src/main/java/pl/project13/maven/git/GitCommitIdMojo.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 17734e25..fe702401 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -538,11 +538,7 @@ public void execute() throws MojoExecutionException { logProperties(); if (generateGitPropertiesFile) { - BuildFileChangeListener buildFileChangeListener = new BuildFileChangeListener() { - public void changed(@Nonnull File file) { - buildContext.refresh(file); - } - }; + BuildFileChangeListener buildFileChangeListener = file -> buildContext.refresh(file); new PropertiesFileGenerator(log, buildFileChangeListener, format, prefixDot, project.getName()).maybeGeneratePropertiesFile( properties, project.getBasedir(), generateGitPropertiesFilename, sourceCharset); From b66b0553dba7d15fc986d7ce7e847362699ecba2 Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sat, 10 Jul 2021 21:49:06 +0200 Subject: [PATCH 5/6] https://github.com/git-commit-id/git-commit-id-plugin-core/issues/6: Remove custom slf4j logger bridge --- .../project13/maven/git/GitCommitIdMojo.java | 24 +- .../maven/git/PropertiesReplacer.java | 10 +- .../maven/log/MavenLoggerBridge.java | 239 ------------------ .../pl/project13/maven/log/MojoLogHelper.java | 43 ++++ .../maven/validation/ValidationMojo.java | 22 +- .../jgit/DescribeCommandIntegrationTest.java | 47 ++-- .../maven/git/GitIntegrationTest.java | 9 +- .../maven/git/PropertiesFiltererTest.java | 4 +- .../maven/git/PropertiesReplacerTest.java | 5 +- .../DescribeCommandAbbrevIntegrationTest.java | 9 +- .../DescribeCommandTagsIntegrationTest.java | 22 +- 11 files changed, 127 insertions(+), 307 deletions(-) delete mode 100644 src/main/java/pl/project13/maven/log/MavenLoggerBridge.java create mode 100644 src/main/java/pl/project13/maven/log/MojoLogHelper.java diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index fe702401..885d4f12 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -43,10 +43,9 @@ import pl.project13.core.*; import pl.project13.core.git.GitDescribeConfig; -import pl.project13.core.log.LoggerBridge; import pl.project13.core.cibuild.BuildServerDataProvider; import pl.project13.core.util.BuildFileChangeListener; -import pl.project13.maven.log.MavenLoggerBridge; +import pl.project13.maven.log.MojoLogHelper; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -412,17 +411,14 @@ public class GitCommitIdMojo extends AbstractMojo { */ private Charset sourceCharset = StandardCharsets.UTF_8; - @Nonnull - private final LoggerBridge log = new MavenLoggerBridge(this, false); - - @Nonnull - private PropertiesFilterer propertiesFilterer = new PropertiesFilterer(log); + private MojoLogHelper log; + private PropertiesFilterer propertiesFilterer; @Override public void execute() throws MojoExecutionException { try { - // Set the verbose setting: now it should be correctly loaded from maven. - log.setVerbose(verbose); + log = new MojoLogHelper(getLog(), verbose); + propertiesFilterer = new PropertiesFilterer(log); // Skip mojo execution on incremental builds. if (buildContext != null && buildContext.isIncremental()) { @@ -491,14 +487,14 @@ public void execute() throws MojoExecutionException { } if (dotGitDirectory != null) { - log.info("dotGitDirectory {}", dotGitDirectory.getAbsolutePath()); + log.info(String.format("dotGitDirectory %s", dotGitDirectory.getAbsolutePath())); } else { log.info("dotGitDirectory is null, aborting execution!"); return; } if ((evaluateOnCommit == null) || !allowedCharactersForEvaluateOnCommit.matcher(evaluateOnCommit).matches()) { - log.error("suspicious argument for evaluateOnCommit, aborting execution!"); + log.error("suspicious argument for evaluateOnCommit, aborting execution!", new IllegalStateException()); return; } @@ -651,12 +647,12 @@ private void handlePluginFailure(Exception e) throws GitCommitIdExecutionExcepti private void appendPropertiesToReactorProjects() { for (MavenProject mavenProject : reactorProjects) { - log.debug("Adding properties to project: {}", mavenProject.getName()); + log.debug(String.format("Adding properties to project: %s", mavenProject.getName())); publishPropertiesInto(mavenProject.getProperties()); mavenProject.setContextValue(CONTEXT_KEY, properties); } - log.info("Added properties to {} projects", reactorProjects.size()); + log.info(String.format("Added properties to %s projects", reactorProjects.size())); } /** @@ -671,7 +667,7 @@ private File lookupGitDirectory() throws GitCommitIdExecutionException { private void logProperties() { for (String propertyName : properties.stringPropertyNames()) { - log.info("including property {} in results", propertyName); + log.info(String.format("including property %s in results", propertyName)); } } diff --git a/src/main/java/pl/project13/maven/git/PropertiesReplacer.java b/src/main/java/pl/project13/maven/git/PropertiesReplacer.java index d7b3d612..552aeb60 100644 --- a/src/main/java/pl/project13/maven/git/PropertiesReplacer.java +++ b/src/main/java/pl/project13/maven/git/PropertiesReplacer.java @@ -18,7 +18,7 @@ package pl.project13.maven.git; import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import pl.project13.core.log.LoggerBridge; +import pl.project13.core.log.LogInterface; import java.util.*; import java.util.regex.Pattern; @@ -28,7 +28,7 @@ * For a use-case refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317. */ public class PropertiesReplacer { - private final LoggerBridge log; + private final LogInterface log; private final PluginParameterExpressionEvaluator expressionEvaluator; /** @@ -37,7 +37,7 @@ public class PropertiesReplacer { * @param expressionEvaluator Maven's PluginParameterExpressionEvaluator * (see https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/413 why it's needed) */ - public PropertiesReplacer(LoggerBridge log, PluginParameterExpressionEvaluator expressionEvaluator) { + public PropertiesReplacer(LogInterface log, PluginParameterExpressionEvaluator expressionEvaluator) { this.log = log; this.expressionEvaluator = expressionEvaluator; } @@ -127,7 +127,7 @@ private String performTransformationRules(ReplacementProperty replacementPropert private String replaceRegex(String content, String token, String value) { if (token == null) { - log.error("found replacementProperty without required token."); + log.error("found replacementProperty without required token.", new IllegalStateException()); return content; } final Pattern compiledPattern = Pattern.compile(token); @@ -136,7 +136,7 @@ private String replaceRegex(String content, String token, String value) { private String replaceNonRegex(String content, String token, String value) { if (token == null) { - log.error("found replacementProperty without required token."); + log.error("found replacementProperty without required token.", new IllegalStateException()); return content; } return content.replace(token, value == null ? "" : value); diff --git a/src/main/java/pl/project13/maven/log/MavenLoggerBridge.java b/src/main/java/pl/project13/maven/log/MavenLoggerBridge.java deleted file mode 100644 index bd890909..00000000 --- a/src/main/java/pl/project13/maven/log/MavenLoggerBridge.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski - * - * git-commit-id-maven-plugin is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * git-commit-id-maven-plugin is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with git-commit-id-maven-plugin. If not, see . - */ - -package pl.project13.maven.log; - -import org.apache.maven.plugin.Mojo; -import pl.project13.core.log.FormattingTuple; -import pl.project13.core.log.LoggerBridge; -import pl.project13.core.log.MessageFormatter; - -/** - * Bridges logging to standard Maven log adhering to verbosity level. - */ -public class MavenLoggerBridge implements LoggerBridge { - - private boolean verbose; - private final Mojo mojo; - - public MavenLoggerBridge(Mojo mojo, boolean verbose) { - this.mojo = mojo; - this.verbose = verbose; - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public boolean isDebugEnabled() { - return mojo.getLog().isDebugEnabled(); - } - - @Override - public boolean isInfoEnabled() { - return mojo.getLog().isInfoEnabled(); - } - - @Override - public boolean isWarnEnabled() { - return mojo.getLog().isWarnEnabled(); - } - - @Override - public boolean isErrorEnabled() { - return mojo.getLog().isErrorEnabled(); - } - - @Override - public void debug(String msg) { - if (verbose) { - mojo.getLog().debug(msg); - } - } - - @Override - public void debug(String format, Object arg) { - if (verbose) { - debug(MessageFormatter.format(format, arg)); - } - } - - @Override - public void debug(String format, Object arg1, Object arg2) { - if (verbose) { - debug(MessageFormatter.format(format, arg1, arg2)); - } - } - - @Override - public void debug(String format, Object... arguments) { - if (verbose) { - debug(MessageFormatter.arrayFormat(format, arguments)); - } - } - - @Override - public void debug(String msg, Throwable t) { - if (verbose) { - mojo.getLog().debug(msg, t); - } - } - - @Override - public void info(String msg) { - if (verbose) { - mojo.getLog().info(msg); - } - } - - @Override - public void info(String format, Object arg) { - if (verbose) { - info(MessageFormatter.format(format, arg)); - } - } - - @Override - public void info(String format, Object arg1, Object arg2) { - if (verbose) { - info(MessageFormatter.format(format, arg1, arg2)); - } - } - - @Override - public void info(String format, Object... arguments) { - if (verbose) { - info(MessageFormatter.arrayFormat(format, arguments)); - } - } - - @Override - public void info(String msg, Throwable t) { - if (verbose) { - mojo.getLog().info(msg, t); - } - } - - @Override - public void warn(String msg) { - if (verbose) { - mojo.getLog().warn(msg); - } - } - - @Override - public void warn(String format, Object arg) { - if (verbose) { - warn(MessageFormatter.format(format, arg)); - } - } - - @Override - public void warn(String format, Object arg1, Object arg2) { - if (verbose) { - warn(MessageFormatter.format(format, arg1, arg2)); - } - } - - @Override - public void warn(String format, Object... arguments) { - if (verbose) { - warn(MessageFormatter.arrayFormat(format, arguments)); - } - } - - @Override - public void warn(String msg, Throwable t) { - if (verbose) { - mojo.getLog().warn(msg, t); - } - } - - @Override - public void error(String msg) { - if (verbose) { - mojo.getLog().error(msg); - } - } - - @Override - public void error(String format, Object arg) { - if (verbose) { - error(MessageFormatter.format(format, arg)); - } - } - - @Override - public void error(String format, Object arg1, Object arg2) { - if (verbose) { - error(MessageFormatter.format(format, arg1, arg2)); - } - } - - @Override - public void error(String format, Object... arguments) { - if (verbose) { - error(MessageFormatter.arrayFormat(format, arguments)); - } - } - - @Override - public void error(String msg, Throwable t) { - if (verbose) { - mojo.getLog().error(msg, t); - } - } - - private void debug(FormattingTuple tuple) { - if (null == tuple.getThrowable()) { - mojo.getLog().debug(tuple.getMessage()); - } else { - mojo.getLog().debug(tuple.getMessage(), tuple.getThrowable()); - } - } - - private void info(FormattingTuple tuple) { - if (null == tuple.getThrowable()) { - mojo.getLog().info(tuple.getMessage()); - } else { - mojo.getLog().info(tuple.getMessage(), tuple.getThrowable()); - } - } - - private void warn(FormattingTuple tuple) { - if (null == tuple.getThrowable()) { - mojo.getLog().warn(tuple.getMessage()); - } else { - mojo.getLog().warn(tuple.getMessage(), tuple.getThrowable()); - } - } - - private void error(FormattingTuple tuple) { - if (null == tuple.getThrowable()) { - mojo.getLog().error(tuple.getMessage()); - } else { - mojo.getLog().error(tuple.getMessage(), tuple.getThrowable()); - } - } -} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/log/MojoLogHelper.java b/src/main/java/pl/project13/maven/log/MojoLogHelper.java new file mode 100644 index 00000000..99879d25 --- /dev/null +++ b/src/main/java/pl/project13/maven/log/MojoLogHelper.java @@ -0,0 +1,43 @@ +package pl.project13.maven.log; + +import org.apache.maven.plugin.logging.Log; +import pl.project13.core.log.LogInterface; + +import javax.annotation.Nonnull; +import java.util.Objects; + + +public final class MojoLogHelper implements LogInterface { + + private final Log log; + private final boolean isVerbose; + + public MojoLogHelper(@Nonnull Log log, boolean isVerbose) { + this.log = Objects.requireNonNull(log); + this.isVerbose = isVerbose; + } + + @Override + public void debug(String msg) { + if (isVerbose) { + log.debug(msg); + } + } + + @Override + public void info(String msg) { + if (isVerbose) { + log.info(msg); + } + } + + @Override + public void warn(String msg) { + log.warn(msg); + } + + @Override + public void error(String msg, Throwable t) { + log.error(msg, t); + } +} diff --git a/src/main/java/pl/project13/maven/validation/ValidationMojo.java b/src/main/java/pl/project13/maven/validation/ValidationMojo.java index d7f14dd1..01927808 100644 --- a/src/main/java/pl/project13/maven/validation/ValidationMojo.java +++ b/src/main/java/pl/project13/maven/validation/ValidationMojo.java @@ -22,11 +22,8 @@ import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import pl.project13.maven.log.MojoLogHelper; -import pl.project13.core.log.LoggerBridge; -import pl.project13.maven.log.MavenLoggerBridge; - -import javax.annotation.Nonnull; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -36,18 +33,17 @@ */ @Mojo(name = "validateRevision", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class ValidationMojo extends AbstractMojo { - - @Nonnull - private final LoggerBridge log = new MavenLoggerBridge(this, false); - @Parameter(defaultValue = "true") private boolean validationShouldFailIfNoMatch; + @Parameter(defaultValue = "false") + private boolean verbose; @Parameter private List validationProperties; @Override public void execute() throws MojoExecutionException { + MojoLogHelper mojoLogHelper = new MojoLogHelper(getLog(), verbose); if (validationProperties != null && validationShouldFailIfNoMatch) { for (ValidationProperty validationProperty: validationProperties) { String name = validationProperty.getName(); @@ -56,7 +52,7 @@ public void execute() throws MojoExecutionException { if ((value != null) && (shouldMatchTo != null)) { validateIfValueAndShouldMatchToMatches(name, value, shouldMatchTo); } else { - printLogMessageWhenValueOrShouldMatchToIsEmpty(name, value, shouldMatchTo); + printLogMessageWhenValueOrShouldMatchToIsEmpty(mojoLogHelper, name, value, shouldMatchTo); } } } @@ -75,12 +71,12 @@ private void validateIfValueAndShouldMatchToMatches(String name, String value, S } } - private void printLogMessageWhenValueOrShouldMatchToIsEmpty(String name, String value, String shouldMatchTo) { - String commonLogMessage = "since one of the values was null! (value = '" + value + "'; shouldMatchTo = '" + shouldMatchTo + "')."; + private void printLogMessageWhenValueOrShouldMatchToIsEmpty(MojoLogHelper mojoLogHelper, String name, String value, String shouldMatchTo) { + String commonLogMessage = String.format("since one of the values was null! (value = '%s'; shouldMatchTo = '%s').", value, shouldMatchTo); if (name != null) { - log.warn("Skipping validation '" + name + "' " + commonLogMessage); + mojoLogHelper.warn(String.format("Skipping validation '%s' %s", name, commonLogMessage)); } else { - log.warn("Skipping an unidentified validation (please set the name property-tag to be able to identify the validation) " + commonLogMessage); + mojoLogHelper.warn(String.format("Skipping an unidentified validation (please set the name property-tag to be able to identify the validation) %s", commonLogMessage)); } } diff --git a/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java b/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java index cf4e0768..f8c20dbe 100644 --- a/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java +++ b/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java @@ -23,7 +23,7 @@ import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.junit.Test; -import pl.project13.core.log.StdOutLoggerBridge; +import pl.project13.core.log.LogInterface; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; @@ -34,8 +34,7 @@ import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.*; public class DescribeCommandIntegrationTest extends GitIntegrationTest { @@ -56,11 +55,12 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT_DIRTY) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .call(); // then @@ -79,10 +79,11 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFound() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new StdOutLoggerBridge(true))); + DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, logInterface)); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -103,10 +104,11 @@ public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new StdOutLoggerBridge(true))); + DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, logInterface)); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -127,11 +129,12 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfI .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) .create(); + LogInterface logInterface = mock(LogInterface.class); int abbrevLength = 10; try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new StdOutLoggerBridge(true))); + DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, logInterface)); doReturn(false).when(command).findDirtyState(any(Repository.class)); command @@ -154,10 +157,11 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndDirtyMarker() thr .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)); + DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, logInterface); command.dirty(DIRTY_SUFFIX); DescribeResult res = command.call(); @@ -176,13 +180,14 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); + LogInterface logInterface = mock(LogInterface.class); String customDirtySuffix = "-DEV"; try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeCommand command = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .dirty(customDirtySuffix); DescribeResult res = command.call(); @@ -201,6 +206,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsId() throws Exception .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { @@ -208,7 +214,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsId() throws Exception } // when - DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)); + DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, logInterface); DescribeResult res = command.call(); // then @@ -226,13 +232,14 @@ public void shouldGiveTag() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -251,13 +258,14 @@ public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { git.checkout().setName("v1.0.0").call(); // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -278,13 +286,14 @@ public void shouldGiveTagWithCustomDirtyMarker() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { git.checkout().setName("v1.0.0").call(); // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .dirty(customDirtySuffix) .call(); @@ -304,11 +313,12 @@ public void shouldNotGiveDirtyTagByDefault() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -325,11 +335,12 @@ public void shouldGiveAnnotatedTagWithDirtyMarker() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .dirty(DIRTY_SUFFIX) .abbrev(0) .call(); @@ -349,6 +360,7 @@ public void shouldGiveLightweightTagWithDirtyMarker() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG_DIRTY) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { @@ -357,7 +369,7 @@ public void shouldGiveLightweightTagWithDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -409,6 +421,7 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { @@ -417,7 +430,7 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .abbrev(zeroAbbrev) .call(); diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index d49713c2..415e59fe 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -19,6 +19,7 @@ import org.apache.commons.io.FileUtils; import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Settings; import org.eclipse.jgit.api.Git; @@ -34,8 +35,7 @@ import java.util.Properties; import java.util.concurrent.ThreadLocalRandom; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; public abstract class GitIntegrationTest { @@ -60,7 +60,7 @@ public void setUp() throws Exception { } while (sandbox.exists()); mavenSandbox = new FileSystemMavenSandbox(currSandbox); - mojo = new GitCommitIdMojo(); + mojo = spy(GitCommitIdMojo.class); initializeMojoWithDefaults(mojo); } @@ -105,6 +105,7 @@ protected File dotGitDir(@Nonnull Optional projectDir) { public static void initializeMojoWithDefaults(GitCommitIdMojo mojo) { mojo.verbose = false; + mojo.offline = true; mojo.skipPoms = true; mojo.abbrevLength = 7; mojo.generateGitPropertiesFile = false; @@ -118,6 +119,8 @@ public static void initializeMojoWithDefaults(GitCommitIdMojo mojo) { mojo.nativeGitTimeoutInMs = (30 * 1000); mojo.session = mockSession(); mojo.settings = mockSettings(); + + when(mojo.getLog()).thenReturn(mock(Log.class)); } public void setProjectToExecuteMojoIn(@Nonnull MavenProject project) { diff --git a/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java b/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java index 7d06d10d..bda62f18 100644 --- a/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java +++ b/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java @@ -35,7 +35,7 @@ import org.mockito.junit.MockitoJUnitRunner; import pl.project13.core.PropertiesFilterer; -import pl.project13.maven.log.MavenLoggerBridge; +import pl.project13.core.log.LogInterface; @RunWith(MockitoJUnitRunner.class) public class PropertiesFiltererTest { @@ -46,7 +46,7 @@ public class PropertiesFiltererTest { private PropertiesFilterer propertiesFilterer; @Mock - private MavenLoggerBridge log; + private LogInterface log; @Mock private Properties properties; diff --git a/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java b/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java index 24b06793..77501e26 100644 --- a/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java +++ b/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java @@ -24,8 +24,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - -import pl.project13.maven.log.MavenLoggerBridge; +import pl.project13.core.log.LogInterface; import java.io.IOException; import java.util.ArrayList; @@ -53,7 +52,7 @@ public static Collection useRegexReplacement() { public void setUp() throws Throwable { PluginParameterExpressionEvaluator pluginParameterExpressionEvaluator = mock(PluginParameterExpressionEvaluator.class); when(pluginParameterExpressionEvaluator.evaluate(anyString())).then(returnsFirstArg()); - this.propertiesReplacer = new PropertiesReplacer(mock(MavenLoggerBridge.class), pluginParameterExpressionEvaluator); + this.propertiesReplacer = new PropertiesReplacer(mock(LogInterface.class), pluginParameterExpressionEvaluator); } @Test diff --git a/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java b/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java index 03749469..4e94b90a 100644 --- a/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java +++ b/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java @@ -22,7 +22,7 @@ import org.junit.Test; import pl.project13.core.jgit.DescribeCommand; import pl.project13.core.jgit.DescribeResult; -import pl.project13.core.log.StdOutLoggerBridge; +import pl.project13.core.log.LogInterface; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; @@ -30,6 +30,7 @@ import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class DescribeCommandAbbrevIntegrationTest extends GitIntegrationTest { @@ -68,11 +69,12 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .abbrev(2) // 2 is enough to be unique in this small repo .call(); @@ -92,11 +94,12 @@ public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); + LogInterface logInterface = mock(LogInterface.class); try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .abbrev(2) // way too small to be unique in git-commit-id's repo! .call(); diff --git a/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java b/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java index 960a4acd..b44550d3 100644 --- a/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java +++ b/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java @@ -24,13 +24,14 @@ import org.junit.Test; import pl.project13.core.jgit.DescribeCommand; import pl.project13.core.jgit.DescribeResult; -import pl.project13.core.log.StdOutLoggerBridge; +import pl.project13.core.log.LogInterface; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class DescribeCommandTagsIntegrationTest extends GitIntegrationTest { @@ -56,7 +57,7 @@ protected Optional projectDir() { @Test public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { // given - + LogInterface logInterface = mock(LogInterface.class); // HEAD // lightweight-tag // annotated-tag @@ -66,7 +67,7 @@ public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .call(); // then @@ -79,6 +80,7 @@ public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { @Test public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { // given + LogInterface logInterface = mock(LogInterface.class); // HEAD // lightweight-tag @@ -89,7 +91,7 @@ public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -103,6 +105,7 @@ public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { @Test public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { // given + LogInterface logInterface = mock(LogInterface.class); // HEAD // lightweight-tag @@ -113,7 +116,7 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .match("annotated*") .call(); @@ -139,6 +142,7 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { @Test public void shouldFindNewerTagWhenACommitHasTwoOrMoreTags() throws Exception { // given + LogInterface logInterface = mock(LogInterface.class); // HEAD // lightweight-tag @@ -149,7 +153,7 @@ public void shouldFindNewerTagWhenACommitHasTwoOrMoreTags() throws Exception { // when DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -168,6 +172,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); String snapshotTag = "0.0.1-SNAPSHOT"; String latestTag = "OName-0.0.1"; @@ -182,7 +187,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except wrap.tag().setName(latestTag).call(); DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); @@ -200,6 +205,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t .withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); + LogInterface logInterface = mock(LogInterface.class); String beforeTag = "OName-0.0.1"; String latestTag = "0.0.1-SNAPSHOT"; @@ -214,7 +220,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t } DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new StdOutLoggerBridge(true)) + .on(evaluateOnCommit, repo, logInterface) .tags() .call(); From a1fcb1ca5862f0eb8e5e149d7451701bd3afeede Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Thu, 15 Jul 2021 18:21:58 +0200 Subject: [PATCH 6/6] first POC to extract the core 'generate properties' logic into an interface so it can be moved into the core-plugin code --- .../project13/maven/git/GitCommitIdMojo.java | 290 +++++++++------- .../project13/maven/git/GitDataManager.java | 314 ++++++++++++++++++ .../maven/git/GitIntegrationTest.java | 1 + 3 files changed, 476 insertions(+), 129 deletions(-) create mode 100644 src/main/java/pl/project13/maven/git/GitDataManager.java diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 885d4f12..b7f8e17e 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -18,14 +18,10 @@ package pl.project13.maven.git; import java.io.File; -import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.text.DateFormat; -import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; -import java.util.function.Supplier; import java.util.regex.Pattern; import org.apache.maven.execution.MavenSession; @@ -43,7 +39,7 @@ import pl.project13.core.*; import pl.project13.core.git.GitDescribeConfig; -import pl.project13.core.cibuild.BuildServerDataProvider; +import pl.project13.core.log.LogInterface; import pl.project13.core.util.BuildFileChangeListener; import pl.project13.maven.log.MojoLogHelper; @@ -418,7 +414,6 @@ public class GitCommitIdMojo extends AbstractMojo { public void execute() throws MojoExecutionException { try { log = new MojoLogHelper(getLog(), verbose); - propertiesFilterer = new PropertiesFilterer(log); // Skip mojo execution on incremental builds. if (buildContext != null && buildContext.isIncremental()) { @@ -501,7 +496,7 @@ public void execute() throws MojoExecutionException { try { try { commitIdGenerationModeEnum = CommitIdGenerationMode.valueOf(commitIdGenerationMode.toUpperCase()); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException | NullPointerException e) { log.warn("Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat' mode!"); commitIdGenerationModeEnum = CommitIdGenerationMode.FLAT; } @@ -519,26 +514,165 @@ public void execute() throws MojoExecutionException { properties = contextProperties; } - loadGitData(properties); - loadBuildData(properties); - // first round of publication and filtering (we need to make variables available for the ParameterExpressionEvaluator - propertiesFilterer.filter(properties, includeOnlyProperties, this.prefixDot); - propertiesFilterer.filterNot(properties, excludeProperties, this.prefixDot); - publishToAllSystemEnvironments(); - - // now run replacements - PropertiesReplacer propertiesReplacer = new PropertiesReplacer( - log, new PluginParameterExpressionEvaluator(session, mojoExecution)); - propertiesReplacer.performReplacement(properties, replacementProperties); - - logProperties(); - - if (generateGitPropertiesFile) { - BuildFileChangeListener buildFileChangeListener = file -> buildContext.refresh(file); - - new PropertiesFileGenerator(log, buildFileChangeListener, format, prefixDot, project.getName()).maybeGeneratePropertiesFile( - properties, project.getBasedir(), generateGitPropertiesFilename, sourceCharset); - } + GitDataManager.DataProvider dp = new GitDataManager.DataProvider() { + @Nonnull + @Override + public LogInterface getLogInterface() { + return log; + } + + @Nullable + @Override + public String getPrefixDot() { + return prefixDot; + } + + @Nullable + @Override + public List getExcludeProperties() { + return excludeProperties; + } + + @Nullable + @Override + public List getIncludeOnlyProperties() { + return includeOnlyProperties; + } + + @Override + public boolean shouldGeneratePropertiesFile() { + return generateGitPropertiesFile; + } + + @Nonnull + @Override + public String getGenerateGitPropertiesFilename() { + return generateGitPropertiesFilename; + } + + @Nonnull + @Override + public Charset getPropertiesOutputFileSourceCharset() { + return sourceCharset; + } + + @Nonnull + @Override + public GitDataManager.PropertiesOutputFormat getPropertiesOutputFormat() { + GitDataManager.PropertiesOutputFormat propertiesOutputFormat; + try { + propertiesOutputFormat = GitDataManager.PropertiesOutputFormat.valueOf(format.toUpperCase()); + } catch (IllegalArgumentException | NullPointerException e) { + log.warn("Detected wrong setting for 'format'. Falling back to default 'properties' mode!"); + propertiesOutputFormat = GitDataManager.PropertiesOutputFormat.PROPERTIES; + } + + return propertiesOutputFormat; + } + + @Nonnull + @Override + public File getProjectBaseDir() { + return project.getBasedir(); + } + + @Nonnull + @Override + public String getProjectName() { + return project.getName(); + } + + @Nonnull + @Override + public String getProjectVersion() { + return project.getVersion(); + } + + @Nonnull + @Override + public String getProjectBuildOutputTimestamp() { + return projectBuildOutputTimestamp; + } + + @Nonnull + @Override + public void callBeforePropertiesAreWrittenToFile(Properties p) { + publishToAllSystemEnvironments(); + + // now run replacements + PropertiesReplacer propertiesReplacer = new PropertiesReplacer( + log, new PluginParameterExpressionEvaluator(session, mojoExecution)); + propertiesReplacer.performReplacement(properties, replacementProperties); + } + + @Nonnull + @Override + public BuildFileChangeListener getBuildFileChangeListener() { + return file -> { + if (buildContext != null) { + buildContext.refresh(file); + } + }; + } + + @Nonnull + @Override + public String getDateFormat() { + return dateFormat; + } + + @Nonnull + @Override + public String getDateFormatTimeZone() { + return dateFormatTimeZone; + } + + @Override + public long getNativeGitTimeoutInMs() { + return nativeGitTimeoutInMs; + } + + @Override + public int getAbbrevLength() { + return abbrevLength; + } + + @Override + public boolean shouldRunWithNativeGit() { + return useNativeGit || useNativeGitViaCommandLine; + } + + @Override + public GitDescribeConfig getGitDescribeConfig() { + return gitDescribe; + } + + @Override + public CommitIdGenerationMode getCommitIdGenerationMode() { + return commitIdGenerationModeEnum; + } + + @Override + public boolean shouldUseBranchNameFromBuildEnvironment() { + return useBranchNameFromBuildEnvironment; + } + + @Override + public boolean shouldRunOffline() { + return offline || settings.isOffline(); + } + + @Override + public String getEvaluateOnCommit() { + return evaluateOnCommit; + } + + @Override + public File getDotGitDirectory() { + return dotGitDirectory; + } + }; + properties = new GitDataManager(dp).gatherGitData(properties); // publish properties again since we might have new properties gained by the replacement publishToAllSystemEnvironments(); @@ -576,54 +710,6 @@ private Properties getContextProperties(MavenProject project) { return null; } - private void loadBuildData(Properties properties) throws GitCommitIdExecutionException { - Map> additionalProperties = Collections.singletonMap( - GitCommitPropertyConstant.BUILD_VERSION, () -> project.getVersion()); - BuildServerDataProvider buildServerDataProvider = BuildServerDataProvider.getBuildServerProvider(System.getenv(),log); - buildServerDataProvider - .setDateFormat(dateFormat) - .setDateFormatTimeZone(dateFormatTimeZone) - .setAdditionalProperties(additionalProperties) - .setPrefixDot(prefixDot) - .setExcludeProperties(excludeProperties) - .setIncludeOnlyProperties(includeOnlyProperties); - - buildServerDataProvider.loadBuildData(properties, parseOutputTimestamp(projectBuildOutputTimestamp)); - } - - /** - * Parse output timestamp configured for Reproducible Builds' archive entries - * (https://maven.apache.org/guides/mini/guide-reproducible-builds.html). - * The value from ${project.build.outputTimestamp} is either formatted as ISO 8601 - * yyyy-MM-dd'T'HH:mm:ssXXX or as an int representing seconds since the epoch (like - * SOURCE_DATE_EPOCH. - * - * Inspired by https://github.com/apache/maven-archiver/blob/a3103d99396cd8d3440b907ef932a33563225265/src/main/java/org/apache/maven/archiver/MavenArchiver.java#L765 - * - * @param outputTimestamp the value of ${project.build.outputTimestamp} (may be null) - * @return the parsed timestamp, may be null if null input or input contains only 1 - * character - */ - private Date parseOutputTimestamp(String outputTimestamp) throws GitCommitIdExecutionException { - if (outputTimestamp != null && !outputTimestamp.trim().isEmpty() && outputTimestamp.chars().allMatch(Character::isDigit)) { - return new Date(Long.parseLong(outputTimestamp) * 1000); - } - - if ((outputTimestamp == null) || (outputTimestamp.length() < 2)) { - // no timestamp configured - return null; - } - - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - try { - return df.parse(outputTimestamp); - } catch (ParseException pe) { - throw new GitCommitIdExecutionException( - "Invalid 'project.build.outputTimestamp' value '" + outputTimestamp + "'", - pe); - } - } - private void publishPropertiesInto(Properties p) { for (String propertyName : properties.stringPropertyNames()) { p.setProperty(propertyName, properties.getProperty(propertyName)); @@ -665,60 +751,6 @@ private File lookupGitDirectory() throws GitCommitIdExecutionException { return new GitDirLocator(project).lookupGitDirectory(dotGitDirectory); } - private void logProperties() { - for (String propertyName : properties.stringPropertyNames()) { - log.info(String.format("including property %s in results", propertyName)); - } - } - - private void loadGitData(@Nonnull Properties properties) throws GitCommitIdExecutionException { - if (useNativeGit || useNativeGitViaCommandLine) { - loadGitDataWithNativeGit(properties); - } else { - loadGitDataWithJGit(properties); - } - } - - private void loadGitDataWithNativeGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { - try { - final File basedir = project.getBasedir().getCanonicalFile(); - - GitDataProvider nativeGitProvider = NativeGitProvider - .on(basedir, nativeGitTimeoutInMs, log) - .setPrefixDot(prefixDot) - .setAbbrevLength(abbrevLength) - .setDateFormat(dateFormat) - .setDateFormatTimeZone(dateFormatTimeZone) - .setGitDescribe(gitDescribe) - .setCommitIdGenerationMode(commitIdGenerationModeEnum) - .setUseBranchNameFromBuildEnvironment(useBranchNameFromBuildEnvironment) - .setExcludeProperties(excludeProperties) - .setIncludeOnlyProperties(includeOnlyProperties) - .setOffline(offline || settings.isOffline()); - - nativeGitProvider.loadGitData(evaluateOnCommit, properties); - } catch (IOException e) { - throw new GitCommitIdExecutionException(e); - } - } - - private void loadGitDataWithJGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { - GitDataProvider jGitProvider = JGitProvider - .on(dotGitDirectory, log) - .setPrefixDot(prefixDot) - .setAbbrevLength(abbrevLength) - .setDateFormat(dateFormat) - .setDateFormatTimeZone(dateFormatTimeZone) - .setGitDescribe(gitDescribe) - .setCommitIdGenerationMode(commitIdGenerationModeEnum) - .setUseBranchNameFromBuildEnvironment(useBranchNameFromBuildEnvironment) - .setExcludeProperties(excludeProperties) - .setIncludeOnlyProperties(includeOnlyProperties) - .setOffline(offline || settings.isOffline()); - - jGitProvider.loadGitData(evaluateOnCommit, properties); - } - private boolean isPomProject(@Nonnull MavenProject project) { return project.getPackaging().equalsIgnoreCase("pom"); } diff --git a/src/main/java/pl/project13/maven/git/GitDataManager.java b/src/main/java/pl/project13/maven/git/GitDataManager.java new file mode 100644 index 00000000..862c7fa8 --- /dev/null +++ b/src/main/java/pl/project13/maven/git/GitDataManager.java @@ -0,0 +1,314 @@ +package pl.project13.maven.git; + +import pl.project13.core.*; +import pl.project13.core.cibuild.BuildServerDataProvider; +import pl.project13.core.git.GitDescribeConfig; +import pl.project13.core.log.LogInterface; +import pl.project13.core.util.BuildFileChangeListener; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Supplier; + + +public class GitDataManager { + public enum PropertiesOutputFormat { + + PROPERTIES, + + JSON, + } + + public interface DataProvider { + @Nonnull + LogInterface getLogInterface(); + + @Nullable + String getPrefixDot(); + + @Nullable + List getExcludeProperties(); + + @Nullable + List getIncludeOnlyProperties(); + + boolean shouldGeneratePropertiesFile(); + + @Nonnull + String getGenerateGitPropertiesFilename(); + + @Nonnull + Charset getPropertiesOutputFileSourceCharset(); + + @Nonnull + PropertiesOutputFormat getPropertiesOutputFormat(); + + @Nonnull + File getProjectBaseDir(); + + @Nonnull + String getProjectName(); + + @Nonnull + String getProjectVersion(); + + @Nonnull + String getProjectBuildOutputTimestamp(); + + @Nonnull + void callBeforePropertiesAreWrittenToFile(final Properties p); + + @Nonnull + BuildFileChangeListener getBuildFileChangeListener(); + + @Nonnull + String getDateFormat(); + + @Nonnull + String getDateFormatTimeZone(); + + long getNativeGitTimeoutInMs(); + + int getAbbrevLength(); + + boolean shouldRunWithNativeGit(); + + GitDescribeConfig getGitDescribeConfig(); + + CommitIdGenerationMode getCommitIdGenerationMode(); + + boolean shouldUseBranchNameFromBuildEnvironment(); + + boolean shouldRunOffline(); + + String getEvaluateOnCommit(); + + File getDotGitDirectory(); + } + + + private LogInterface log; + + private String prefixDot; + + private List includeOnlyProperties; + + private List excludeProperties; + + private File projectBaseDir; + + private String projectVersion; + + private String projectName; + + private String projectBuildOutputTimestamp; + + private String dateFormat; + + private String dateFormatTimeZone; + + private boolean shouldGeneratePropertiesFile; + + private BuildFileChangeListener buildFileChangeListener; + + private PropertiesOutputFormat propertiesOutputFormat; + + private String generateGitPropertiesFilename; + + private Charset propertiesOutputFileSourceCharset; + + private long nativeGitTimeoutInMs; + + private int abbrevLength; + + private boolean shouldRunWithNativeGit; + + private GitDescribeConfig gitDescribeConfig; + + private CommitIdGenerationMode commitIdGenerationMode; + + private boolean useBranchNameFromBuildEnvironment; + + private boolean shouldRunOffline; + + private String evaluateOnCommit; + + private File dotGitDirectory; + + private Consumer callbackBeforePropertiesAreWrittenToFile; + + + public GitDataManager(@Nonnull DataProvider dp) { + Objects.requireNonNull(dp); + this.log = Objects.requireNonNull(dp.getLogInterface()); + this.prefixDot = Optional.ofNullable(dp.getPrefixDot()).orElseGet(() -> ""); + this.includeOnlyProperties = Optional.ofNullable(dp.getIncludeOnlyProperties()).orElseGet(() -> new ArrayList<>()); + this.excludeProperties = Optional.ofNullable(dp.getExcludeProperties()).orElseGet(() -> new ArrayList<>()); + this.projectBaseDir = dp.getProjectBaseDir(); + this.projectVersion = dp.getProjectVersion(); + this.projectName = dp.getProjectName(); + this.dateFormat = dp.getDateFormat(); + this.dateFormatTimeZone = dp.getDateFormatTimeZone(); + this.projectBuildOutputTimestamp = dp.getProjectBuildOutputTimestamp(); + this.shouldGeneratePropertiesFile = dp.shouldGeneratePropertiesFile(); + this.buildFileChangeListener = dp.getBuildFileChangeListener(); + this.propertiesOutputFormat = dp.getPropertiesOutputFormat(); + this.generateGitPropertiesFilename = dp.getGenerateGitPropertiesFilename(); + this.propertiesOutputFileSourceCharset = dp.getPropertiesOutputFileSourceCharset(); + this.nativeGitTimeoutInMs = dp.getNativeGitTimeoutInMs(); + this.abbrevLength = dp.getAbbrevLength(); + this.shouldRunWithNativeGit = dp.shouldRunWithNativeGit(); + this.gitDescribeConfig = dp.getGitDescribeConfig(); + this.commitIdGenerationMode = dp.getCommitIdGenerationMode(); + this.useBranchNameFromBuildEnvironment = dp.shouldUseBranchNameFromBuildEnvironment(); + this.shouldRunOffline = dp.shouldRunOffline(); + this.evaluateOnCommit = dp.getEvaluateOnCommit(); + this.dotGitDirectory = dp.getDotGitDirectory(); + this.callbackBeforePropertiesAreWrittenToFile = dp::callBeforePropertiesAreWrittenToFile; + } + + public Properties gatherGitData(@Nullable Properties existingProperties) throws GitCommitIdExecutionException { + final Properties properties = Optional.ofNullable(existingProperties).orElseGet(() -> new Properties()); + + + loadGitData(properties); + loadBuildData(properties); + + PropertiesFilterer propertiesFilterer = new PropertiesFilterer(log); + // first round of publication and filtering (we need to make variables available for the ParameterExpressionEvaluator + propertiesFilterer.filter(properties, includeOnlyProperties, prefixDot); + propertiesFilterer.filterNot(properties, excludeProperties, prefixDot); + + callbackBeforePropertiesAreWrittenToFile.accept(properties); + logProperties(log, properties); + + if (shouldGeneratePropertiesFile) { + new PropertiesFileGenerator( + log, + buildFileChangeListener, + // TODO: This should be an enum + propertiesOutputFormat.toString().toLowerCase(), + prefixDot, + projectName + ).maybeGeneratePropertiesFile( + properties, + projectBaseDir, + generateGitPropertiesFilename, + propertiesOutputFileSourceCharset + ); + } + return properties; + } + + private void loadBuildData(Properties existingProperties) throws GitCommitIdExecutionException { + Map> additionalProperties = Collections.singletonMap( + GitCommitPropertyConstant.BUILD_VERSION, () -> projectVersion); + BuildServerDataProvider buildServerDataProvider = BuildServerDataProvider.getBuildServerProvider( + System.getenv(), log); + buildServerDataProvider + .setDateFormat(dateFormat) + .setDateFormatTimeZone(dateFormatTimeZone) + .setAdditionalProperties(additionalProperties) + .setPrefixDot(prefixDot) + .setExcludeProperties(excludeProperties) + .setIncludeOnlyProperties(includeOnlyProperties); + + buildServerDataProvider.loadBuildData(existingProperties, parseOutputTimestamp(projectBuildOutputTimestamp)); + } + + /** + * Parse output timestamp configured for Reproducible Builds' archive entries + * (https://maven.apache.org/guides/mini/guide-reproducible-builds.html). + * The value from ${project.build.outputTimestamp} is either formatted as ISO 8601 + * yyyy-MM-dd'T'HH:mm:ssXXX or as an int representing seconds since the epoch (like + * SOURCE_DATE_EPOCH. + * + * Inspired by https://github.com/apache/maven-archiver/blob/a3103d99396cd8d3440b907ef932a33563225265/src/main/java/org/apache/maven/archiver/MavenArchiver.java#L765 + * + * @param outputTimestamp the value of ${project.build.outputTimestamp} (may be null) + * @return the parsed timestamp, may be null if null input or input contains only 1 + * character + */ + private Date parseOutputTimestamp(String outputTimestamp) throws GitCommitIdExecutionException { + if (outputTimestamp != null && !outputTimestamp.trim().isEmpty() && outputTimestamp.chars().allMatch(Character::isDigit)) { + return new Date(Long.parseLong(outputTimestamp) * 1000); + } + + if ((outputTimestamp == null) || (outputTimestamp.length() < 2)) { + // no timestamp configured + return null; + } + + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + try { + return df.parse(outputTimestamp); + } catch (ParseException pe) { + throw new GitCommitIdExecutionException( + "Invalid 'project.build.outputTimestamp' value '" + outputTimestamp + "'", + pe); + } + } + + private void logProperties(@Nonnull LogInterface log, @Nonnull Properties properties) { + for (String propertyName : properties.stringPropertyNames()) { + log.info(String.format("including property %s in results", propertyName)); + } + } + + private void loadGitData(@Nonnull Properties properties) throws GitCommitIdExecutionException { + if (shouldRunWithNativeGit) { + loadGitDataWithNativeGit(properties); + } else { + loadGitDataWithJGit(properties); + } + } + + private void loadGitDataWithNativeGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { + try { + // TODO: I guess this should use dotGitDirectory.getParentFile().getCanonicalFile() + final File basedir = projectBaseDir.getCanonicalFile(); + + GitDataProvider nativeGitProvider = NativeGitProvider + .on(basedir, nativeGitTimeoutInMs, log) + .setPrefixDot(prefixDot) + .setAbbrevLength(abbrevLength) + .setDateFormat(dateFormat) + .setDateFormatTimeZone(dateFormatTimeZone) + .setGitDescribe(gitDescribeConfig) + .setCommitIdGenerationMode(commitIdGenerationMode) + .setUseBranchNameFromBuildEnvironment(useBranchNameFromBuildEnvironment) + .setExcludeProperties(excludeProperties) + .setIncludeOnlyProperties(includeOnlyProperties) + .setOffline(shouldRunOffline); + + nativeGitProvider.loadGitData(evaluateOnCommit, properties); + } catch (IOException e) { + throw new GitCommitIdExecutionException(e); + } + } + + private void loadGitDataWithJGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { + GitDataProvider jGitProvider = JGitProvider + .on(dotGitDirectory, log) + .setPrefixDot(prefixDot) + .setAbbrevLength(abbrevLength) + .setDateFormat(dateFormat) + .setDateFormatTimeZone(dateFormatTimeZone) + .setGitDescribe(gitDescribeConfig) + .setCommitIdGenerationMode(commitIdGenerationMode) + .setUseBranchNameFromBuildEnvironment(useBranchNameFromBuildEnvironment) + .setExcludeProperties(excludeProperties) + .setIncludeOnlyProperties(includeOnlyProperties) + .setOffline(shouldRunOffline); + + jGitProvider.loadGitData(evaluateOnCommit, properties); + } +} diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index 415e59fe..a538fe7c 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -113,6 +113,7 @@ public static void initializeMojoWithDefaults(GitCommitIdMojo mojo) { mojo.prefix = "git"; mojo.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"; mojo.failOnNoGitDirectory = true; + mojo.failOnUnableToExtractRepoInfo = true; mojo.useNativeGit = false; mojo.commitIdGenerationMode = "full"; mojo.evaluateOnCommit = evaluateOnCommit;