From 3997d60027209994d61afd8cee2a399115fc62c7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 29 Jan 2024 08:38:44 +0000 Subject: [PATCH 1/2] Bump com.puppycrawl.tools:checkstyle from 8.25 to 10.13.0 Bumps [com.puppycrawl.tools:checkstyle](https://github.com/checkstyle/checkstyle) from 8.25 to 10.13.0. - [Release notes](https://github.com/checkstyle/checkstyle/releases) - [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-8.25...checkstyle-10.13.0) --- updated-dependencies: - dependency-name: com.puppycrawl.tools:checkstyle dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6637a2b6..9090ad3d 100644 --- a/pom.xml +++ b/pom.xml @@ -490,7 +490,7 @@ 3.3.1 - 8.25 + 10.13.0 ${basedir}/.github/.checkstyle From 385773e1a7472d8fe847cbc47eb1737137a7da3f Mon Sep 17 00:00:00 2001 From: TheSnoozer Date: Sun, 11 Feb 2024 08:32:46 +0100 Subject: [PATCH 2/2] make code more checkstyle conform --- .../.checkstyle/checkstyle-suppressions.xml | 19 +- ...l => google_checks_checkstyle_10.13.0.xml} | 182 +- .github/.checkstyle/java.header | 3 +- pom.xml | 5 +- .../project13/maven/git/GitCommitIdMojo.java | 1806 ++++++++--------- .../pl/project13/maven/git/GitDirLocator.java | 46 +- .../maven/git/PropertiesReplacer.java | 115 +- .../maven/git/ReplacementProperty.java | 156 +- .../maven/git/TransformationRule.java | 58 +- .../maven/validation/ValidationMojo.java | 64 +- .../maven/validation/ValidationProperty.java | 47 +- .../jgit/DescribeCommandIntegrationTest.java | 152 +- .../core/jgit/DescribeResultTest.java | 33 +- .../project13/log/DummyTestLoggerBridge.java | 9 +- .../project13/maven/git/AheadBehindTest.java | 49 +- .../maven/git/AvailableGitTestRepo.java | 39 +- .../pl/project13/maven/git/BigDiffTest.java | 33 +- .../maven/git/ContainsKeyCondition.java | 14 +- .../maven/git/DoesNotContainKeyCondition.java | 9 +- .../maven/git/FileSystemMavenSandbox.java | 52 +- .../git/GitCommitIdMojoIntegrationTest.java | 751 ++++--- .../maven/git/GitCommitIdMojoTest.java | 45 +- .../maven/git/GitDirLocatorTest.java | 25 +- .../maven/git/GitIntegrationTest.java | 39 +- .../maven/git/GitPropertiesFileTest.java | 73 +- .../maven/git/GitSubmodulesTest.java | 17 +- .../maven/git/NaivePerformanceTest.java | 50 +- .../maven/git/NativeAndJGitProviderTest.java | 107 +- .../git/NativeProviderAheadBehindTest.java | 3 +- .../maven/git/PropertiesFiltererTest.java | 26 +- .../maven/git/PropertiesReplacerTest.java | 170 +- .../DescribeCommandAbbrevIntegrationTest.java | 39 +- .../DescribeCommandTagsIntegrationTest.java | 66 +- .../jgit/JgitProviderAheadBehindTest.java | 12 +- .../maven/validation/ValidationMojoTest.java | 25 +- 35 files changed, 2477 insertions(+), 1862 deletions(-) rename .github/.checkstyle/{google_checks_checkstyle_8.25.xml => google_checks_checkstyle_10.13.0.xml} (60%) diff --git a/.github/.checkstyle/checkstyle-suppressions.xml b/.github/.checkstyle/checkstyle-suppressions.xml index 98381106..2b965e78 100644 --- a/.github/.checkstyle/checkstyle-suppressions.xml +++ b/.github/.checkstyle/checkstyle-suppressions.xml @@ -5,24 +5,15 @@ "http://www.puppycrawl.com/dtds/suppressions_1_0.dtd"> - + + + - - - - - - - - + - - - - - + \ No newline at end of file diff --git a/.github/.checkstyle/google_checks_checkstyle_8.25.xml b/.github/.checkstyle/google_checks_checkstyle_10.13.0.xml similarity index 60% rename from .github/.checkstyle/google_checks_checkstyle_8.25.xml rename to .github/.checkstyle/google_checks_checkstyle_10.13.0.xml index afbcdfb5..917103f0 100644 --- a/.github/.checkstyle/google_checks_checkstyle_8.25.xml +++ b/.github/.checkstyle/google_checks_checkstyle_10.13.0.xml @@ -5,10 +5,10 @@ - - - - - - - + + + - + + + + + + + - + @@ -75,14 +75,26 @@ - + + + - - + + + + + + + INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF, INTERFACE_DEF, RECORD_DEF, + COMPACT_CTOR_DEF, LITERAL_SWITCH"/> + + + + + + + + @@ -102,8 +128,18 @@ + + + value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks + may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/> @@ -115,6 +151,10 @@ + @@ -128,13 +168,13 @@ - + - + @@ -150,6 +190,8 @@ value="Package name ''{0}'' must match pattern ''{1}''."/> + @@ -174,16 +216,30 @@ value="Catch parameter name ''{0}'' must match pattern ''{1}''."/> - + + + + + + + + + + + + - + @@ -215,32 +271,52 @@ - + + + + + + + - + value="COMMA, SEMI, POST_INC, POST_DEC, DOT, + LABELED_STAT, METHOD_REF"/> - + + + + LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR, METHOD_REF, + TYPE_EXTENSION_AND "/> + value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, + RECORD_DEF, COMPACT_CTOR_DEF"/> @@ -255,35 +331,63 @@ value="^@return the *|^This method returns |^A [{]@code [a-zA-Z0-9]+[}]( is a )"/> + - + - - + + + + + + + - + - - - + - + + + + + + + + + + + + + + + + + + + + + - + \ No newline at end of file diff --git a/.github/.checkstyle/java.header b/.github/.checkstyle/java.header index c8bdf753..b4239a21 100644 --- a/.github/.checkstyle/java.header +++ b/.github/.checkstyle/java.header @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 diff --git a/pom.xml b/pom.xml index 9090ad3d..7c07ac35 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,10 @@ ${checkstyle.config.path}/google_checks_checkstyle_${checkstyle.version}.xml ${checkstyle.config.path}/checkstyle-suppressions.xml - samedir=${checkstyle.config.path} + + samedir=${checkstyle.config.path} + org.checkstyle.google.suppressionfilter.config=${checkstyle.config.path}/checkstyle-suppressions.xml + true ${project.reporting.outputEncoding} true diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 68e9c218..5eae4976 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -23,9 +24,15 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Properties; import java.util.function.Supplier; - +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecution; @@ -38,15 +45,15 @@ import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Settings; import org.sonatype.plexus.build.incremental.BuildContext; - -import pl.project13.core.*; +import pl.project13.core.CommitIdGenerationMode; +import pl.project13.core.CommitIdPropertiesOutputFormat; +import pl.project13.core.GitCommitIdExecutionException; +import pl.project13.core.GitCommitIdPlugin; +import pl.project13.core.PropertiesFileGenerator; 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; - /** * Puts git build-time information into property files or maven's properties. * @@ -56,68 +63,66 @@ public class GitCommitIdMojo extends AbstractMojo { private static final String CONTEXT_KEY = GitCommitIdMojo.class.getName() + ".properties"; - // ============================================================================================================ + // =============================================================================================== // Parameter injected by maven itself can't be configured in the pom.xml! /** - * This parameter can't be configured in the {@code pom.xml} - * it represents the Maven Project that will be injected by maven itself. + * This parameter can't be configured in the {@code pom.xml} it represents the Maven Project that + * will be injected by maven itself. */ @Parameter(defaultValue = "${project}", readonly = true, required = true) MavenProject project; /** - * This parameter can't be configured in the {@code pom.xml} - * it represents the list of projects in the reactor that will be injected by maven itself. + * This parameter can't be configured in the {@code pom.xml} it represents the list of projects in + * the reactor that will be injected by maven itself. */ @Parameter(defaultValue = "${reactorProjects}", readonly = true, required = true) List reactorProjects; /** - * This parameter can't be configured in the {@code pom.xml} - * it represents the Mojo Execution that will be injected by maven itself. + * This parameter can't be configured in the {@code pom.xml} it represents the Mojo Execution that + * will be injected by maven itself. */ @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true) MojoExecution mojoExecution; /** - * This parameter can't be configured in the {@code pom.xml} - * it represents the Maven Session Object that will be injected by maven itself. + * This parameter can't be configured in the {@code pom.xml} it represents the Maven Session + * Object that will be injected by maven itself. */ @Parameter(defaultValue = "${session}", readonly = true, required = true) MavenSession session; /** - * This parameter can't be configured in the {@code pom.xml} - * it represents the Maven settings that will be injected by maven itself. + * This parameter can't be configured in the {@code pom.xml} it represents the Maven settings that + * will be injected by maven itself. */ @Parameter(defaultValue = "${settings}", readonly = true, required = true) Settings settings; - // ============================================================================================================ + // =============================================================================================== // Parameters that can be configured in the pom.xml /** - * Configuration to tell the git-commit-id-maven-plugin if the plugin should - * inject the git properties into all reactor projects not just the current one. + * Configuration to tell the git-commit-id-maven-plugin if the plugin should inject the git + * properties into all reactor projects not just the current one. * - *

The property is set to {@code false} by default to prevent the overriding of - * properties that may be unrelated to the project. If you need to expose your git properties - * to another maven module (e.g. maven-antrun-plugin) you need to set it to {@code true}.

+ *

The property is set to {@code false} by default to prevent the overriding of properties that + * may be unrelated to the project. If you need to expose your git properties to another maven + * module (e.g. maven-antrun-plugin) you need to set it to {@code true}. * - *

Inject git properties into all reactor projects, not just the current one - * may slow down the build and you don't always need this feature.

+ *

Inject git properties into all reactor projects, not just the current one may slow down the + * build and you don't always need this feature. * - *

For details about why you might want to skip this, read this issue: - * pull #65

+ *

For details about why you might want to skip this, read this issue: pull #65 * *

Example: - *

-   * {@code
-   *     false
-   * }
-   * 
- *

+ * + *
{@code
+   * false
+   * }
* * @since 2.1.4 */ @@ -125,151 +130,136 @@ public class GitCommitIdMojo extends AbstractMojo { boolean injectAllReactorProjects; /** - * Configuration to tell the git-commit-id-maven-plugin to print - * some more verbose information during the build - * (e.g. a summary of all collected properties when it's done). + * Configuration to tell the git-commit-id-maven-plugin to print some more verbose information + * during the build (e.g. a summary of all collected properties when it's done). * - *

By default this option is disabled (set to {@code false})

+ *

By default this option is disabled (set to {@code false}) * - *

Note, If enabled (set to {@code true}) the plugin may - * print information you deem sensible, so be extra cautious when you share those.

+ *

Note, If enabled (set to {@code true}) the plugin may print information you deem sensible, + * so be extra cautious when you share those. * *

Example: - *

-   * {@code
-   *     false
-   * }
-   * 
- *

+ * + *
{@code
+   * false
+   * }
*/ @Parameter(defaultValue = "false") boolean verbose; /** - * Configuration to tell the git-commit-id-maven-plugin to not run in - * a pom packaged project (e.g. {@code pom}). + * Configuration to tell the git-commit-id-maven-plugin to not run in a pom packaged + * project (e.g. {@code pom}). * - *

By default 'pom' packaged projects will be skipped (to {@code true})

+ *

By default 'pom' packaged projects will be skipped (to {@code true}) * - *

You may want to set this to {@code false}, if the plugin - * should also run inside a pom packaged project. - * Most projects won't need to override this property. - * For an use-case for this kind of behaviour see: + *

You may want to set this to {@code false}, if the plugin should also run inside a pom + * packaged project. Most projects won't need to override this property. For an use-case for this + * kind of behaviour see: * - * Issue 21 - *

+ *

Issue 21 * - *

Note: The plugin might not execute at all, if you also set {@code true}

+ *

Note: The plugin might not execute at all, if you also set {@code + * true} * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
*/ @Parameter(defaultValue = "true") boolean skipPoms; /** - * Configuration to tell the git-commit-id-maven-plugin to - * generate a {@code 'git.properties'} file. - * By default the plugin will not not generate such a file (set to {@code false}), + * Configuration to tell the git-commit-id-maven-plugin to generate a {@code 'git.properties'} + * file. By default the plugin will not not generate such a file (set to {@code false}), * and only adds properties to maven project properties. * - *

Set this to {@code 'true'} if you want an easy way to expose your git information - * into your final artifact (jar, war, ...), which will generate a properties file (with filled out values) - * that can be configured to end up in the final artifact. - * Refer to the configuration of {@link #generateGitPropertiesFilename}` - * that helps you setup that final path.

+ *

Set this to {@code 'true'} if you want an easy way to expose your git information into your + * final artifact (jar, war, ...), which will generate a properties file (with filled out values) + * that can be configured to end up in the final artifact. Refer to the configuration of {@link + * #generateGitPropertiesFilename}` that helps you setup that final path. + * + *

Such generated property file, can normally be read using during runtime. * - *

Such generated property file, can normally be read using *

    *     new Properties().load(...)
    * 
- * during runtime.

* - *

Note: - * When writing the {@code git.properties} file the value *git.build.time* will only be updated - * when things in the commit information have changed. If you only change a bit of your code - * and rebuild/rerun you will see an older timestamp that you may have expected. Essentially - * the functional meaning becomes **The latest build time when the git information was written - * to the git.properties file**. - * The reason why this was done can be found in - * [issue 151](https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/151).

+ *

Note: When writing the {@code git.properties} file the value *git.build.time* will only be + * updated when things in the commit information have changed. If you only change a bit of your + * code and rebuild/rerun you will see an older timestamp that you may have expected. Essentially + * the functional meaning becomes **The latest build time when the git information was written to + * the git.properties file**. The reason why this was done can be found in [issue + * 151](https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/151). * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
*/ @Parameter(defaultValue = "false") boolean generateGitPropertiesFile; /** - * Configuration to tell the git-commit-id-maven-plugin about the - * location where you want to generate a {@code 'git.properties'} file. + * Configuration to tell the git-commit-id-maven-plugin about the location where you want to + * generate a {@code 'git.properties'} file. * - *

By default the file would be generated under - * {@code ${project.build.outputDirectory}/git.properties}, but you would need to - * set {@link #generateGitPropertiesFile} to {@code true} first to "activate" the generation of this file. - * You can also choose the format of the generated properties by specifying it under {@link #format}.

+ *

By default the file would be generated under {@code + * ${project.build.outputDirectory}/git.properties}, but you would need to set {@link + * #generateGitPropertiesFile} to {@code true} first to "activate" the generation of this file. + * You can also choose the format of the generated properties by specifying it under {@link + * #format}. * - *

The path can be relative to {@code ${project.basedir}} (e.g. {@code target/classes/git.properties}) or - * can be a full path (e.g. {@code ${project.build.outputDirectory}/git.properties}).

+ *

The path can be relative to {@code ${project.basedir}} (e.g. {@code + * target/classes/git.properties}) or can be a full path (e.g. {@code + * ${project.build.outputDirectory}/git.properties}). * *

Note: If you plan to set the generateGitPropertiesFilename-Path to a location where usually * the source-files comes from (e.g. {@code src/main/resources}) and experience that your IDE - * (e.g. eclipse) invokes "Maven Project Builder" once every second, the chances that you - * are using an IDE where the src-folder is a watched folder for files that are only - * edited by humans is pretty high. - *
- * For further information refer to the manual for your - * specific IDE and check the workflow of "incremental project builders". - *
- * In order to fix this problem we recommend to set the generateGitPropertiesFilename-Path - * to a target folder (e.g. {@code ${project.build.outputDirectory}}) since this is - * the place where all derived/generated resources should go. - *
+ * (e.g. eclipse) invokes "Maven Project Builder" once every second, the chances that you are + * using an IDE where the src-folder is a watched folder for files that are only edited by + * humans is pretty high.
+ * For further information refer to the manual for your specific IDE and check the workflow of + * "incremental project builders".
+ * In order to fix this problem we recommend to set the generateGitPropertiesFilename-Path to a + * target folder (e.g. {@code ${project.build.outputDirectory}}) since this is the place where all + * derived/generated resources should go.
* With plugin version 3.0.0 we introduced a smarter way to counter that issue, but that might not - * be supported by your IDE. - * See: pull 385 - * for further information

+ * be supported by your IDE. See: pull 385 for + * further information * *

Example: - *

-   * {@code
-   *     ${project.build.outputDirectory}/git.properties
-   * }
-   * 
- *

* + *
{@code
+   * 
+   *   ${project.build.outputDirectory}/git.properties
+   * 
+   * }
*/ @Parameter(defaultValue = "${project.build.outputDirectory}/git.properties") String generateGitPropertiesFilename; /** - * Controls whether special characters in the properties - * within the {@link #generateGitPropertiesFilename} should be unicode escaped. - * By default properties are escaped (e.g. \\u6E2C\\u8A66\\u4E2D\\u6587). - * If you write commit messages in chinese and want to extract the message - * without any additional conversion from the generated properties - * you may want to set this to {@code false}. + * Controls whether special characters in the properties within the {@link + * #generateGitPropertiesFilename} should be unicode escaped. By default properties are escaped + * (e.g. \\u6E2C\\u8A66\\u4E2D\\u6587). If you write commit messages in chinese and want to + * extract the message without any additional conversion from the generated properties you may + * want to set this to {@code false}. * - *

See issue 590 - * for further details.

+ *

See issue + * 590 for further details. * *

Example: - *

-   * {@code
-   *    true
-   * }
-   * 
- *

+ * + *
{@code
+   * 
+   *   true
+   * 
+   * }
* * @since 6.0.0 */ @@ -277,178 +267,178 @@ public class GitCommitIdMojo extends AbstractMojo { boolean generateGitPropertiesFileWithEscapedUnicode; /** - * Configuration to tell the git-commit-id-maven-plugin about the - * root directory of the git repository we want to check. - * By default uses {@code ${project.basedir}/.git} will most probably be - * ok for single module projects, in other cases please use `../` to get higher up - * in the dir tree (e.g. {@code ${project.basedir}/../.git}). + * Configuration to tell the git-commit-id-maven-plugin about the root directory of the git + * repository we want to check. By default uses {@code ${project.basedir}/.git} will most probably + * be ok for single module projects, in other cases please use `../` to get higher up in the dir + * tree (e.g. {@code ${project.basedir}/../.git}). * *

Example: - *

-   * {@code
-   *    ${project.basedir}/.git
-   * }
-   * 
- *

+ * + *
{@code
+   * 
+   *   ${project.basedir}/.git
+   * 
+   * }
*/ @Parameter(defaultValue = "${project.basedir}/.git") File dotGitDirectory; /** - * Configuration for the {@code 'git-describe'} command. - * You can modify the dirty marker, abbrev length and other options here. - * The following `gitDescribe` configuration below is optional and can be leveraged as a - * really powerful versioning helper. If you are not familiar with - * git-describe + * Configuration for the {@code 'git-describe'} command. You can modify the dirty marker, abbrev + * length and other options here. The following `gitDescribe` configuration below is optional and + * can be leveraged as a really powerful versioning helper. If you are not familiar with git-describe * it is highly recommended to go through this part of the documentation. * - *

More advanced users can most likely skip the explanations in this section, as it just explains the - * same options that git provides. - * As a side note this plugin tries to be 1-to-1 compatible with git's plain output, even - * though the describe functionality has been reimplemented manually using JGit (you don't - * have to have a git executable to use the plugin).

+ *

More advanced users can most likely skip the explanations in this section, as it just + * explains the same options that git provides. As a side note this plugin tries to be 1-to-1 + * compatible with git's plain output, even though the describe functionality has been + * reimplemented manually using JGit (you don't have to have a git executable to use the plugin). * - * For further information refer to this. + *

For further information refer to this. * *

Example: - *

-   *     {@code
-   *         
-   *             
-   *             false
-   *
-   *             
-   *             true
-   *
-   *             
-   *             7
-   *
-   *             
-   *             -dirty
-   *
-   *             
-   *             *
-   *
-   *             
-   *             false
-   *
-   *             
-   *             false
-   *         
-   *     }
-   *     
- *

+ * + *
{@code
+   *     
+   *         
+   *         false
+   *
+   *         
+   *         true
+   *
+   *         
+   *         7
+   *
+   *         
+   *         -dirty
+   *
+   *         
+   *         *
+   *
+   *         
+   *         false
+   *
+   *         
+   *         false
+   *     
+   * }
+   *
+   * 
* * @since 2.1.0 */ - @Parameter - GitDescribeConfig gitDescribe; + @Parameter GitDescribeConfig gitDescribe; /** - *

Minimum length of {@code 'git.commit.id.abbrev'} property. - * Value must be from 2 to 40 (inclusive), other values will result in an exception.

+ * Minimum length of {@code 'git.commit.id.abbrev'} property. Value must be from 2 to 40 + * (inclusive), other values will result in an exception. * - *

Defaults to `7`

+ *

Defaults to `7` * - *

An abbreviated commit is a shorter version of commit id. However, it is guaranteed to be unique. - * To keep this contract, the plugin may decide to print an abbreviated version - * that is longer than the value specified here.

+ *

An abbreviated commit is a shorter version of commit id. However, it is guaranteed to be + * unique. To keep this contract, the plugin may decide to print an abbreviated version that is + * longer than the value specified here. * - *

Example: You have a very big repository, yet you set this value to 2. It's very probable that you'll end up - * getting a 4 or 7 char long abbrev version of the commit id. If your repository, on the other hand, - * has just 4 commits, you'll probably get a 2 char long abbreviation.

+ *

Example: You have a very big repository, yet you set this value to 2. It's very + * probable that you'll end up getting a 4 or 7 char long abbrev version of the commit id. If your + * repository, on the other hand, has just 4 commits, you'll probably get a 2 char long + * abbreviation. * *

Example: - *

-   * {@code
-   *    7
-   * }
-   * 
- *

+ * + *
{@code
+   * 7
+   * }
* * @since 2.0.4 */ @@ -456,75 +446,67 @@ public class GitCommitIdMojo extends AbstractMojo { int abbrevLength; /** - * Denotes the format to save properties of the properties file that can be configured with - * {@link #generateGitPropertiesFilename}. + * Denotes the format to save properties of the properties file that can be configured with {@link + * #generateGitPropertiesFilename}. * - *

Valid options are encoded in {@link CommitIdPropertiesOutputFormat} - * and currently would allow "properties" (default) and "json". - * Future option like yml, toml, ... might be supported at some point.

+ *

Valid options are encoded in {@link CommitIdPropertiesOutputFormat} and currently would + * allow "properties" (default) and "json". Future option like yml, toml, ... might be supported + * at some point. * - *

Note: - * If you set this to "json", you might also should checkout the documentation about - * {@link #commitIdGenerationMode} and may want to set - * {@code full}. - *

+ *

Note: If you set this to "json", you might also should checkout the documentation about + * {@link #commitIdGenerationMode} and may want to set {@code + * full}. * *

Example: - *

-   * {@code
-   *    properties
-   * }
-   * 
- *

+ * + *
{@code
+   * properties
+   * }
*/ @Parameter(defaultValue = "properties") String format; /** - * Not settable by any configuration in the {@code pom.xml}. - * For internal use only (represents the {@link #format} the user has set as enum. + * Not settable by any configuration in the {@code pom.xml}. For internal use only (represents the + * {@link #format} the user has set as enum. */ private CommitIdPropertiesOutputFormat commitIdPropertiesOutputFormat; /** - * Configuration to tell the git-commit-id-maven-plugin about the - * property that will be used as the "namespace" prefix for all exposed/generated properties. - * An example the plugin may generate the property `${configured-prefix}.commit.id`. - * Such behaviour can be used to generate properties for multiple git repositories (see - * issue 173 - * for a full example). + * Configuration to tell the git-commit-id-maven-plugin about the property that will be used as + * the "namespace" prefix for all exposed/generated properties. An example the plugin may generate + * the property `${configured-prefix}.commit.id`. Such behaviour can be used to generate + * properties for multiple git repositories (see issue + * 173 for a full example). * - *

By default is set to {@code 'git'} that for example would allow you to access {@code ${git.branch}}

+ *

By default is set to {@code 'git'} that for example would allow you to access {@code + * ${git.branch}} * *

Example: - *

-   * {@code
-   *    git
-   * }
-   * 
- *

+ * + *
{@code
+   * git
+   * }
*/ @Parameter(defaultValue = "git") String prefix; /** - * This date format will be used to format the time of any exposed/generated property - * that represents dates or times exported by this plugin (e.g. {@code git.commit.time}, {@code git.build.time}). - * It should be a valid {@link SimpleDateFormat} string. + * This date format will be used to format the time of any exposed/generated property that + * represents dates or times exported by this plugin (e.g. {@code git.commit.time}, {@code + * git.build.time}). It should be a valid {@link SimpleDateFormat} string. * - *

- * The current dateFormat is set to match maven's default {@code yyyy-MM-dd'T'HH:mm:ssZ}. - * Please note that in previous versions (2.2.0 - 2.2.2) the default dateFormat was set to: - * {@code dd.MM.yyyy '@' HH:mm:ss z}. However the {@code RFC 822 time zone} seems to give a more - * reliable option in parsing the date and it's being used in maven as default.

+ *

The current dateFormat is set to match maven's default {@code yyyy-MM-dd'T'HH:mm:ssZ}. + * Please note that in previous versions (2.2.0 - 2.2.2) the default dateFormat was set to: {@code + * dd.MM.yyyy '@' HH:mm:ss z}. However the {@code RFC 822 time zone} seems to give a more reliable + * option in parsing the date and it's being used in maven as default. * *

Example: - *

-   * {@code
-   *    yyyy-MM-dd'T'HH:mm:ssZ
-   * }
-   * 
- *

+ * + *
{@code
+   * yyyy-MM-dd'T'HH:mm:ssZ
+   * }
* * @since 2.2.0 */ @@ -532,48 +514,44 @@ public class GitCommitIdMojo extends AbstractMojo { String dateFormat; /** - *

The timezone used in the {@link #dateFormat} of dates exported by this plugin (e.g. {@code git.commit.time}, {@code git.build.time}). - * It should be a valid Timezone string such as {@code 'America/Los_Angeles'}, {@code 'GMT+10'} or {@code 'PST'}.

- * - *

As a general warning try to avoid three-letter time zone IDs because the same abbreviation are often used for multiple time zones. - * Please review https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html - * for more information on this issue.

- * - *

The default value we'll use the timezone use the timezone that's shipped with java - * ({@code java.util.TimeZone.getDefault().getID()}). - * Note: If you plan to set the java's timezone by using - * {@code MAVEN_OPTS=-Duser.timezone=UTC mvn clean package}, - * {@code mvn clean package -Duser.timezone=UTC}, - * or any other configuration keep in mind that this option will override those settings and - * will not take other configurations into account!

+ * The timezone used in the {@link #dateFormat} of dates exported by this plugin (e.g. {@code + * git.commit.time}, {@code git.build.time}). It should be a valid Timezone string such as {@code + * 'America/Los_Angeles'}, {@code 'GMT+10'} or {@code 'PST'}. + * + *

As a general warning try to avoid three-letter time zone IDs because the same abbreviation + * are often used for multiple time zones. Please review + * https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html for more information on + * this issue. + * + *

The default value we'll use the timezone use the timezone that's shipped with java ({@code + * java.util.TimeZone.getDefault().getID()}). Note: If you plan to set the java's timezone + * by using {@code MAVEN_OPTS=-Duser.timezone=UTC mvn clean package}, {@code mvn clean package + * -Duser.timezone=UTC}, or any other configuration keep in mind that this option will override + * those settings and will not take other configurations into account! * *

Example: - *

-   * {@code
-   *     ${user.timezone}
-   * }
-   * 
- *

+ * + *
{@code
+   * ${user.timezone}
+   * }
* * @since 2.2.0 */ - @Parameter - String dateFormatTimeZone; + @Parameter String dateFormatTimeZone; /** - * Specify whether the plugin should fail when a {@code '.git'} directory cannot be found. - * When set to {@code false} and no {@code .git} directory is found the plugin will skip execution. + * Specify whether the plugin should fail when a {@code '.git'} directory cannot be found. When + * set to {@code false} and no {@code .git} directory is found the plugin will skip execution. * - *

Defaults to {@code true}, so a missing {@code '.git'} directory is treated as error - * and should cause a failure in your build.

+ *

Defaults to {@code true}, so a missing {@code '.git'} directory is treated as error and + * should cause a failure in your build. * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 2.0.4 */ @@ -581,25 +559,25 @@ public class GitCommitIdMojo extends AbstractMojo { boolean failOnNoGitDirectory; /** - *

Set this to {@code false} to continue the build even if unable to get enough data for a complete run. - * This may be useful during CI builds if the CI server does weird things to the repository.

+ * Set this to {@code false} to continue the build even if unable to get enough data for a + * complete run. This may be useful during CI builds if the CI server does weird things to the + * repository. * *

Setting this value to {@code false} causes the plugin to gracefully tell you "I did my best" - * and abort its execution if unable to obtain git meta data - yet the build will continue to run without failing.

+ * and abort its execution if unable to obtain git meta data - yet the build will continue to run + * without failing. * - *

By default the plugin will fail the build (set to {@code true}) if unable to obtain enough data for a complete - * run.

+ *

By default the plugin will fail the build (set to {@code true}) if unable to obtain enough + * data for a complete run. * - *

See issue #63 - * for a rationale behind this flag.

+ *

See issue + * #63 for a rationale behind this flag. * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 2.1.5 */ @@ -607,30 +585,28 @@ public class GitCommitIdMojo extends AbstractMojo { boolean failOnUnableToExtractRepoInfo; /** - * This plugin ships with custom {@code jgit} implementation that is being used to obtain all relevant information. - * If set to {@code true} the plugin will use native git executable instead of the custom {@code jgit} implementation - * to fetch information about the repository. - * Of course if set to {@code true} will require a git executable to be installed in system. + * This plugin ships with custom {@code jgit} implementation that is being used to obtain all + * relevant information. If set to {@code true} the plugin will use native git executable instead + * of the custom {@code jgit} implementation to fetch information about the repository. Of course + * if set to {@code true} will require a git executable to be installed in system. * - *

Although setting this to {@code true} (use the native git executable) - * should usually give your build some performance boost, it may randomly - * break if you upgrade your git version and it decides to print information in a different - * format suddenly.

+ *

Although setting this to {@code true} (use the native git executable) should usually give + * your build some performance boost, it may randomly break if you upgrade your git version and it + * decides to print information in a different format suddenly. * - *

By default the plugin will use {@code jgit} implementation as a source of information about the repository. - * As rule of thumb, keep using the default {@code jgit} implementation (set to {@code false}) - * until you notice performance problems within your build (usually when you have *hundreds* of maven modules).

+ *

By default the plugin will use {@code jgit} implementation as a source of information about + * the repository. As rule of thumb, keep using the default {@code jgit} implementation (set to + * {@code false}) until you notice performance problems within your build (usually when you have + * *hundreds* of maven modules). * - *

With plugin version *3.0.2* you can also control it using the commandline option - * {@code -Dmaven.gitcommitid.nativegit=true}. See {@link #useNativeGitViaCommandLine}

+ *

With plugin version *3.0.2* you can also control it using the commandline option {@code + * -Dmaven.gitcommitid.nativegit=true}. See {@link #useNativeGitViaCommandLine} * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 2.1.9 */ @@ -641,18 +617,15 @@ public class GitCommitIdMojo extends AbstractMojo { * Option to be used in command-line to override the value of {@link #useNativeGit} specified in * the pom.xml, or its default value if it's not set explicitly. * - *

NOTE / WARNING: - * Do *NOT* set this property inside the configuration of your plugin. - * Please read issue 315 - * to find out why.

+ *

NOTE / WARNING: Do *NOT* set this property inside the configuration of your plugin. Please + * read issue + * 315 to find out why. * *

Example: - *

-   * {@code
-   *     mvn clean package -Dmaven.gitcommitid.nativegit=true
-   * }
-   * 
- *

+ * + *
{@code
+   * mvn clean package -Dmaven.gitcommitid.nativegit=true
+   * }
* * @since 3.0.2 */ @@ -660,22 +633,19 @@ public class GitCommitIdMojo extends AbstractMojo { boolean useNativeGitViaCommandLine; /** - * When set to {@code true} the plugin execution will completely skip. - * This is useful for e.g. profile activated plugin invocations or to use properties to - * enable / disable pom features. + * When set to {@code true} the plugin execution will completely skip. This is useful for e.g. + * profile activated plugin invocations or to use properties to enable / disable pom features. * - *

By default the execution is not skipped (set to {@code false})

+ *

By default the execution is not skipped (set to {@code false}) * - *

With version *2.2.3* you can also skip the plugin by using the commandline option - * {@code -Dmaven.gitcommitid.skip=true}. See {@link #skipViaCommandLine}

+ *

With version *2.2.3* you can also skip the plugin by using the commandline option {@code + * -Dmaven.gitcommitid.skip=true}. See {@link #skipViaCommandLine} * *

Example: - *

-   * {@code
-   *     false
-   * }
-   * 
- *

+ * + *
{@code
+   * false
+   * }
* * @since 2.1.8 */ @@ -683,22 +653,19 @@ public class GitCommitIdMojo extends AbstractMojo { boolean skip; /** - * Option to be used in command-line to override the value of {@link #skip} specified in - * the pom.xml, or its default value if it's not set explicitly. - * Set this to {@code true} to skip plugin execution via commandline. + * Option to be used in command-line to override the value of {@link #skip} specified in the + * pom.xml, or its default value if it's not set explicitly. Set this to {@code true} to skip + * plugin execution via commandline. * - *

NOTE / WARNING: - * Do *NOT* set this property inside the configuration of your plugin. - * Please read issue 315 - * to find out why.

+ *

NOTE / WARNING: Do *NOT* set this property inside the configuration of your plugin. Please + * read issue + * 315 to find out why. * *

Example: - *

-   * {@code
-   *     mvn clean package -Dmaven.gitcommitid.skip=true
-   * }
-   * 
- *

+ * + *
{@code
+   * mvn clean package -Dmaven.gitcommitid.skip=true
+   * }
* * @since 2.2.4 */ @@ -708,37 +675,34 @@ public class GitCommitIdMojo extends AbstractMojo { /** * Use with caution! * - *

Set this to {@code true} to only run once in a multi-module build. - * This means that the plugins effects will only execute once for the first project in the execution graph. - * If {@code skipPoms} is set to {@code true} (default) the plugin will run for the first - * non pom project in the execution graph (as listed in the reactor build order). - * This probably won't "do the right thing" if your project has more than one git repository.

+ *

Set this to {@code true} to only run once in a multi-module build. This means that the + * plugins effects will only execute once for the first project in the execution graph. If {@code + * skipPoms} is set to {@code true} (default) the plugin will run for the first non pom project in + * the execution graph (as listed in the reactor build order). This probably won't "do the right + * thing" if your project has more than one git repository. * - *

Defaults to {@code false}, so the plugin may get executed multiple times in a reactor build!

+ *

Defaults to {@code false}, so the plugin may get executed multiple times in a reactor build! * - *

Important: If you're using {@link #generateGitPropertiesFile}, setting {@code runOnlyOnce} will make - * the plugin only generate the file in the project build directory which is the first one - * based on the execution graph (!).

+ *

Important: If you're using {@link #generateGitPropertiesFile}, setting {@code runOnlyOnce} + * will make the plugin only generate the file in the project build directory which is the first + * one based on the execution graph (!). * *

Important: Please note that the git-commit-id-maven-plugin also has an option to skip pom * project ({@code pom}). If you plan to use the {@code runOnlyOnce} option - * alongside with an aggregator pom you may want to set {@code false}. - * Refer to {@link #skipPoms} for more information

+ * alongside with an aggregator pom you may want to set {@code false}. Refer + * to {@link #skipPoms} for more information * *

For multi-module build you might also want to set {@link #injectAllReactorProjects} to make - * the {@code git.*} maven properties available in all modules.

+ * the {@code git.*} maven properties available in all modules. * - *

Note: - * Prior to version 4.0.0 the plugin was simply using the execute once applied for the parent - * project (which might have skipped execution if the parent project was a pom project).

+ *

Note: Prior to version 4.0.0 the plugin was simply using the execute once applied for the + * parent project (which might have skipped execution if the parent project was a pom project). * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 2.1.12 */ @@ -746,134 +710,120 @@ public class GitCommitIdMojo extends AbstractMojo { boolean runOnlyOnce; /** - * Can be used to exclude certain properties from being emitted (e.g. filter out properties - * that you *don't* want to expose). May be useful when you want to hide - * {@code git.build.user.email} (maybe because you don't want to expose your eMail?), - * or the email of the committer? - * - *

Each value may be globbing, that is, you can write {@code git.commit.user.*} to - * exclude both the {@code name}, as well as {@code email} properties from being emitted. - * - *

Please note that the strings here are Java regexes ({@code .*} is globbing, - * not plain {@code *}). - * If you have a very long list of exclusions you may want to - * use {@link #includeOnlyProperties}. - * - *

This feature was implemented in response to issue 91, - * so if you're curious about the use-case, check that issue.

- * - *

Prior to version 3.0.0 the plugin used the 'naive' approach to ask for all properties - * and then apply filtering. However, with the growing numbers of properties each property - * eat more and more of execution time that will be filtered out afterwards. - * With 3.0.0 this behaviour was readjusted to a 'selective running' approach whereby the - * plugin will not even try to get the property when excluded. Such behaviour can result in - * an overall reduced execution time of the plugin - * (see issue 408 for details).

+ * Can be used to exclude certain properties from being emitted (e.g. filter out properties that + * you *don't* want to expose). May be useful when you want to hide {@code git.build.user.email} + * (maybe because you don't want to expose your eMail?), or the email of the committer? + * + *

Each value may be globbing, that is, you can write {@code git.commit.user.*} to exclude both + * the {@code name}, as well as {@code email} properties from being emitted. + * + *

Please note that the strings here are Java regexes ({@code .*} is globbing, not plain {@code + * *}). If you have a very long list of exclusions you may want to use {@link + * #includeOnlyProperties}. + * + *

This feature was implemented in response to issue 91, so + * if you're curious about the use-case, check that issue. + * + *

Prior to version 3.0.0 the plugin used the 'naive' approach to ask for all properties and + * then apply filtering. However, with the growing numbers of properties each property eat more + * and more of execution time that will be filtered out afterwards. With 3.0.0 this behaviour was + * readjusted to a 'selective running' approach whereby the plugin will not even try to get the + * property when excluded. Such behaviour can result in an overall reduced execution time of the + * plugin (see issue 408 for + * details). * *

Defaults to the empty list (= no properties are excluded). * *

Example: - *

-   * {@code
-   *     
-   *          git.user.*
-   *     
-   * }
-   * 
- *

+ * + *
{@code
+   * 
+   *      git.user.*
+   * 
+   * }
* * @since 2.1.9 */ - @Parameter - List excludeProperties; + @Parameter List excludeProperties; /** - * Can be used to include only certain properties into the emission (e.g. include only - * properties that you want to expose). This feature was implemented to avoid big exclude - * properties tag when we only want very few specific properties. - * - *

The inclusion rules, will be overruled by the {@link #excludeProperties} rules - * (e.g. you can write an inclusion rule that applies for multiple - * properties and then exclude a subset of them). - * You can therefor can be a bit broader in the inclusion rules and - * exclude more sensitive ones in the {@link #excludeProperties} rules. - * - *

Each value may be globbing, that is, you can write {@code git.commit.user.*} to - * exclude both the {@code name}, as well as {@code email} properties from being emitted. - * - *

Please note that the strings here are Java regexes ({@code .*} is globbing, - * not plain {@code *}). - * If you have a short list of exclusions you may want to - * use {@link #excludeProperties}. - * - *

Prior to version 3.0.0 the plugin used the 'naive' approach to ask for all properties - * and then apply filtering. However, with the growing numbers of properties each property - * eat more and more of execution time that will be filtered out afterwards. - * With 3.0.0 this behaviour was readjusted to a 'selective running' approach whereby the - * plugin will not even try to get the property when excluded. Such behaviour can result in - * an overall reduced execution time of the plugin - * (see issue 408 for details).

- * - *

Defaults to the empty list (= no properties are excluded).

+ * Can be used to include only certain properties into the emission (e.g. include only properties + * that you want to expose). This feature was implemented to avoid big exclude properties + * tag when we only want very few specific properties. + * + *

The inclusion rules, will be overruled by the {@link #excludeProperties} rules (e.g. you can + * write an inclusion rule that applies for multiple properties and then exclude a subset of + * them). You can therefor can be a bit broader in the inclusion rules and exclude more sensitive + * ones in the {@link #excludeProperties} rules. + * + *

Each value may be globbing, that is, you can write {@code git.commit.user.*} to exclude both + * the {@code name}, as well as {@code email} properties from being emitted. + * + *

Please note that the strings here are Java regexes ({@code .*} is globbing, not plain {@code + * *}). If you have a short list of exclusions you may want to use {@link #excludeProperties}. + * + *

Prior to version 3.0.0 the plugin used the 'naive' approach to ask for all properties and + * then apply filtering. However, with the growing numbers of properties each property eat more + * and more of execution time that will be filtered out afterwards. With 3.0.0 this behaviour was + * readjusted to a 'selective running' approach whereby the plugin will not even try to get the + * property when excluded. Such behaviour can result in an overall reduced execution time of the + * plugin (see issue 408 for + * details). + * + *

Defaults to the empty list (= no properties are excluded). * *

Example: - *

-   * {@code
-   *     
-   *         ^git.commit.id.full$
-   *     
-   * }
-   * 
- *

+ * + *
{@code
+   * 
+   *     ^git.commit.id.full$
+   * 
+   * }
* * @since 2.1.14 */ - @Parameter - List includeOnlyProperties; + @Parameter List includeOnlyProperties; /** - * The option can be used to tell the plugin how it should generate the {@code 'git.commit.id'} property. - * Due to some naming issues when exporting the properties as an json-object - * (issue 122) we needed to - * make it possible to export all properties as a valid json-object. - * - *

Due to the fact that this is one of the major properties the plugin is exporting we - * just don't want to change the exporting mechanism and somehow throw the backwards - * compatibility away. - * We rather provide a convenient switch where you can choose if you - * would like the properties as they always had been, or if you rather need to support - * full json-object compatibility.

- * - *

In the case you need to fully support json-object we unfortunately need to change the - * {@code 'git.commit.id'} property from {@code 'git.commit.id'} to {@code 'git.commit.id.full'} in the exporting - * mechanism to allow the generation of a fully valid json object.

+ * The option can be used to tell the plugin how it should generate the {@code 'git.commit.id'} + * property. Due to some naming issues when exporting the properties as an json-object (issue 122) we + * needed to make it possible to export all properties as a valid json-object. + * + *

Due to the fact that this is one of the major properties the plugin is exporting we just + * don't want to change the exporting mechanism and somehow throw the backwards compatibility + * away. We rather provide a convenient switch where you can choose if you would like the + * properties as they always had been, or if you rather need to support full json-object + * compatibility. + * + *

In the case you need to fully support json-object we unfortunately need to change the {@code + * 'git.commit.id'} property from {@code 'git.commit.id'} to {@code 'git.commit.id.full'} in the + * exporting mechanism to allow the generation of a fully valid json object. * *

Currently, the switch allows two different options: - *

    - *
  1. - * By default this property is set to {@code 'flat'} and will generate the formerly known - * property {@code 'git.commit.id'} as it was in the previous versions of the plugin. - * Keeping it to {@code 'flat'} by default preserve backwards compatibility and does not require further - * adjustments by the end user. - *
  2. - *
  3. - * If you set this switch to {@code 'full'} the plugin will export the formerly known property - * {@code 'git.commit.id'} as {@code 'git.commit.id.full'} and therefore will generate a fully valid - * json object in the exporting mechanism. - *
  4. - *

- * - *

Note: If you set the value to something that's not equal to {@code 'flat'} or {@code 'full'} (ignoring the case) - * the plugin will output a warning and will fallback to the default {@code 'flat'} mode.

* + *
    + *
  1. By default this property is set to {@code 'flat'} and will generate the formerly known + * property {@code 'git.commit.id'} as it was in the previous versions of the plugin. + * Keeping it to {@code 'flat'} by default preserve backwards compatibility and does not + * require further adjustments by the end user. + *
  2. If you set this switch to {@code 'full'} the plugin will export the formerly known + * property {@code 'git.commit.id'} as {@code 'git.commit.id.full'} and therefore will + * generate a fully valid json object in the exporting mechanism. + *
+ * + *

Note: If you set the value to something that's not equal to {@code 'flat'} or {@code + * 'full'} (ignoring the case) the plugin will output a warning and will fallback to the default + * {@code 'flat'} mode. * *

Example: - *

-   * {@code
-   *     flat
-   * }
-   * 
- *

+ * + *
{@code
+   * flat
+   * }
* * @since 2.2.0 */ @@ -881,134 +831,127 @@ public class GitCommitIdMojo extends AbstractMojo { String commitIdGenerationMode; /** - * Not settable by any configuration in the {@code pom.xml}. - * For internal use only (represents the {@link #commitIdGenerationMode} the user has set as enum. + * Not settable by any configuration in the {@code pom.xml}. For internal use only (represents the + * {@link #commitIdGenerationMode} the user has set as enum. */ private CommitIdGenerationMode commitIdGenerationModeEnum; /** * Can be used to replace certain characters or strings using regular expressions within the - * exposed properties. - * Replacements can be performed using regular expressions and on a configuration level - * it can be defined whether the replacement should affect all properties or just a single one. - * - * Please note that the replacement will only be applied to properties that are being generated by the plugin. - * If you want to replace properties that are being generated by other plugins you may want to use the - * maven-replacer-plugin or any other alternative. - * - * Replacements can be configured with a {@code replacementProperty}. - * A {@code replacementProperty} can have a {@code property}` and a {@code regex}-tag. - * If the {@code replacementProperty} configuration has a {@code property}-tag the - * replacement will only be performed on that specific property - * (e.g. {@code git.branch} will only be performed on {@code git.branch}). - * - * In case this specific element is not defined or left empty the replacement will be - * performed on all generated properties. - * - * The optional {@code regex}-tag can either be {@code true} to perform a replacement with regular - * expressions or {@code false} to perform a replacement with java's string.replace-function. - * - * By default the replacement will be performed with regular expressions ({@code true}). - * Furthermore each {@code replacementProperty} need to be configured with a {@code token} and a {@code value}. - * The {@code token} can be seen as the needle and the {@code value} as the text to be written over any - * found tokens. If using regular expressions the value can reference grouped regex matches - * by using $1, $2, etc. - * - * Since 2.2.4 the plugin allows to define a even more sophisticated ruleset and allows to - * set an {@code propertyOutputSuffix} within each {@code replacementProperty}. - * If this option is empty the original property will be overwritten (default behaviour in 2.2.3). - * However when this configuration is set to {@code something} and a user wants to modify the - * {@code git.branch} property the plugin will keep {@code git.branch} as the original one (w/o modifications) - * but also will be creating a new {@code git.branch.something} property with the requested replacement. - * - * Furthermore with 2.2.4 the plugin allows to perform certain types of string manipulation - * either before or after the evaluation of the replacement. - * With this feature a user can currently easily manipulate the case (e.g. lower case VS upper case) - * of the input/output property. - * This behaviour can be achieved by defining a list of {@code transformationRules} for - * the property where those rules should take effect. - * Each {@code transformationRule} consist of two required fields {@code apply} and {@code action}. - * The {@code apply}-tag controls when the rule should be applied and can be set to {@code BEFORE} - * to have the rule being applied before or it can be set to {@code AFTER} to have the - * rule being applied after the replacement. - * The {@code action}-tag determines the string conversion rule that should be applied. - * Currently supported is {@code LOWER_CASE} and {@code UPPER_CASE}. - * Potential candidates in the feature are {@code CAPITALIZATION} and {@code INVERT_CASE} - * (open a ticket if you need them...). - * - * Since 4.0.1 the plugin allows to define a {@code forceValueEvaluation}-switch which forces the - * plugin to evaluate the given value on every project. - * - * This might come handy if every project needs a unique value and a user wants to - * project specific variables like {@code ${project.artifactId}}. - * Be advised that this essentially means that the plugin must run for every child-project of a - * reactor build and thus might cause some overhead (the git properties should be cached). - * For a use-case refer to issue 457 - * - *

Defaults to the empty list / not set (= no properties are being replaced by default)

+ * exposed properties. Replacements can be performed using regular expressions and on a + * configuration level it can be defined whether the replacement should affect all properties or + * just a single one. + * + *

Please note that the replacement will only be applied to properties that are being generated + * by the plugin. If you want to replace properties that are being generated by other plugins you + * may want to use the maven-replacer-plugin or any other alternative. + * + *

Replacements can be configured with a {@code replacementProperty}. A {@code + * replacementProperty} can have a {@code property}` and a {@code regex}-tag. If the {@code + * replacementProperty} configuration has a {@code property}-tag the replacement will only be + * performed on that specific property (e.g. {@code git.branch} will only be + * performed on {@code git.branch}). + * + *

In case this specific element is not defined or left empty the replacement will be performed + * on all generated properties. + * + *

The optional {@code regex}-tag can either be {@code true} to perform a replacement with + * regular expressions or {@code false} to perform a replacement with java's + * string.replace-function. + * + *

By default the replacement will be performed with regular expressions ({@code true}). + * Furthermore each {@code replacementProperty} need to be configured with a {@code token} and a + * {@code value}. The {@code token} can be seen as the needle and the {@code value} as the text to + * be written over any found tokens. If using regular expressions the value can reference grouped + * regex matches by using $1, $2, etc. + * + *

Since 2.2.4 the plugin allows to define a even more sophisticated ruleset and allows to set + * an {@code propertyOutputSuffix} within each {@code replacementProperty}. If this option is + * empty the original property will be overwritten (default behaviour in 2.2.3). However when this + * configuration is set to {@code something} and a user wants to modify the {@code git.branch} + * property the plugin will keep {@code git.branch} as the original one (w/o modifications) but + * also will be creating a new {@code git.branch.something} property with the requested + * replacement. + * + *

Furthermore with 2.2.4 the plugin allows to perform certain types of string manipulation + * either before or after the evaluation of the replacement. With this feature a user can + * currently easily manipulate the case (e.g. lower case VS upper case) of the input/output + * property. This behaviour can be achieved by defining a list of {@code transformationRules} for + * the property where those rules should take effect. Each {@code transformationRule} consist of + * two required fields {@code apply} and {@code action}. The {@code apply}-tag controls when the + * rule should be applied and can be set to {@code BEFORE} to have the rule being applied before + * or it can be set to {@code AFTER} to have the rule being applied after the replacement. The + * {@code action}-tag determines the string conversion rule that should be applied. Currently + * supported is {@code LOWER_CASE} and {@code UPPER_CASE}. Potential candidates in the feature are + * {@code CAPITALIZATION} and {@code INVERT_CASE} (open a ticket if you need them...). + * + *

Since 4.0.1 the plugin allows to define a {@code forceValueEvaluation}-switch which forces + * the plugin to evaluate the given value on every project. + * + *

This might come handy if every project needs a unique value and a user wants to + * project specific variables like {@code ${project.artifactId}}. Be advised that this essentially + * means that the plugin must run for every child-project of a reactor build and thus might + * cause some overhead (the git properties should be cached). For a use-case refer to issue 457 + * + *

Defaults to the empty list / not set (= no properties are being replaced by default) * *

Example: - *

-   * {@code
-   *     
-   *         
-   *         
-   *             git.branch
-   *             something
-   *             ^([^\/]*)\/([^\/]*)$
-   *             $1-$2
-   *             true
-   *             false
-   *             
-   *                 
-   *                     BEFORE
-   *                     UPPER_CASE
-   *                 
-   *                 
-   *                     AFTER
-   *                     LOWER_CASE
-   *                 
-   *             
-   *         
-   *     
-   * }
-   * 
- *

+ * + *
{@code
+   * 
+   *     
+   *     
+   *         git.branch
+   *         something
+   *         ^([^\/]*)\/([^\/]*)$
+   *         $1-$2
+   *         true
+   *         false
+   *         
+   *             
+   *                 BEFORE
+   *                 UPPER_CASE
+   *             
+   *             
+   *                 AFTER
+   *                 LOWER_CASE
+   *             
+   *         
+   *     
+   * 
+   * }
* * @since 2.2.3 */ - @Parameter - List replacementProperties; + @Parameter List replacementProperties; /** - * Allow to tell the plugin what commit should be used as reference to - * generate the properties from. + * Allow to tell the plugin what commit should be used as reference to generate the properties + * from. * *

In general this property can be set to something generic like {@code HEAD^1} or point to a - * branch or tag-name. To support any kind or use-case this configuration can also be set - * to an entire commit-hash or it's abbreviated version.

+ * branch or tag-name. To support any kind or use-case this configuration can also be set to an + * entire commit-hash or it's abbreviated version. * - *

A use-case for this feature can be found in - * here.

+ *

A use-case for this feature can be found in here. * - *

Please note that for security purposes not all references might - * be allowed as configuration. If you have a specific use-case that is currently - * not white listed feel free to file an issue.

+ *

Please note that for security purposes not all references might be allowed as configuration. + * If you have a specific use-case that is currently not white listed feel free to file an issue. * *

By default this property is simply set to {@code HEAD} which should reference to the latest - * commit in your repository.

+ * commit in your repository. * *

Example: - *

-   * {@code
-   *     HEAD
-   * }
-   * 
- *

+ * + *
{@code
+   * HEAD
+   * }
* * @since 2.2.4 */ @@ -1016,22 +959,20 @@ public class GitCommitIdMojo extends AbstractMojo { String evaluateOnCommit; /** - * Allow to specify a timeout (in milliseconds) for fetching information with the native - * Git executable. This option might come in handy in cases where fetching information - * about the repository with the native Git executable does not terminate. + * Allow to specify a timeout (in milliseconds) for fetching information with the native Git + * executable. This option might come in handy in cases where fetching information about the + * repository with the native Git executable does not terminate. * - *

Note: This option will only be taken into consideration when using the native git - * executable ({@link #useNativeGit} is set to {@code true}). + *

Note: This option will only be taken into consideration when using the native git executable + * ({@link #useNativeGit} is set to {@code true}). * *

By default this timeout is set to 30000 (30 seconds). * *

Example: - *

-   * {@code
-   *     30000
-   * }
-   * 
- *

+ * + *
{@code
+   * 30000
+   * }
* * @since 3.0.0 */ @@ -1040,22 +981,20 @@ public class GitCommitIdMojo extends AbstractMojo { /** * When set to {@code true} this plugin will try to use the branch name from build environment. - * Set to {@code false} to use JGit/GIT to get current branch name which can be useful - * when using the JGitflow maven plugin. - * See https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/24#issuecomment-203285398 + * Set to {@code false} to use JGit/GIT to get current branch name which can be useful when using + * the JGitflow maven plugin. See + * https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/24#issuecomment-203285398 * - * Note: If not using "Check out to specific local branch' and setting this to false may result in getting - * detached head state and therefore a commit id as branch name. + *

Note: If not using "Check out to specific local branch' and setting this to false may result + * in getting detached head state and therefore a commit id as branch name. * - *

By default this is set to {@code true}.

+ *

By default this is set to {@code true}. * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 3.0.0 */ @@ -1064,21 +1003,19 @@ public class GitCommitIdMojo extends AbstractMojo { /** * Controls if this plugin should expose the generated properties into {@code System.properties} - * When set to {@code true} this plugin will try to expose the generated properties into - * {@code System.getProperties()}. Set to {@code false} to avoid this exposure. + * When set to {@code true} this plugin will try to expose the generated properties into {@code + * System.getProperties()}. Set to {@code false} to avoid this exposure. * - * Note that parameters provided via command-line (e.g. {@code -Dgit.commit.id=value}) still + *

Note that parameters provided via command-line (e.g. {@code -Dgit.commit.id=value}) still * have precedence. * - *

By default this is set to {@code true}.

+ *

By default this is set to {@code true}. * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 3.0.0 */ @@ -1086,32 +1023,30 @@ public class GitCommitIdMojo extends AbstractMojo { boolean injectIntoSysProperties; /** - * The plugin can generate certain properties that represents the count of commits - * that your local branch is ahead or behind in perspective to the remote branch. + * The plugin can generate certain properties that represents the count of commits that your local + * branch is ahead or behind in perspective to the remote branch. * *

When your branch is "ahead" it means your local branch has committed changes that are not - * pushed yet to the remote branch. - * When your branch is "behind" it means there are commits in the remote branch that are not yet - * integrated into your local branch.

+ * pushed yet to the remote branch. When your branch is "behind" it means there are commits in the + * remote branch that are not yet integrated into your local branch. * - *

This configuration allows you to control if the plugin should somewhat ensure - * that such properties are more accurate. More accurate means that the plugin will perform a - * {@code git fetch} before the properties are calculated. - * Certainly a {@code git fetch} is an operation that may alter your local git repository - * and thus the plugin will operate not perform such operation (offline is set to {@code true}). - * If you however desire more accurate properties you may want to set this to {@code false}.

+ *

This configuration allows you to control if the plugin should somewhat ensure that such + * properties are more accurate. More accurate means that the plugin will perform a {@code git + * fetch} before the properties are calculated. Certainly a {@code git fetch} is an operation that + * may alter your local git repository and thus the plugin will operate not perform such operation + * (offline is set to {@code true}). If you however desire more accurate properties you may want + * to set this to {@code false}. * - *

Before version 5.X.X the default was set to {@code false} causing the plugin to operate - * in online-mode by default. Now the default is set to {@code true} (offline-mode) so the plugin might generate - * inaccurate {@code git.local.branch.ahead} and {@code git.local.branch.behind} branch information. + *

Before version 5.X.X the default was set to {@code false} causing the plugin to operate in + * online-mode by default. Now the default is set to {@code true} (offline-mode) so the plugin + * might generate inaccurate {@code git.local.branch.ahead} and {@code git.local.branch.behind} + * branch information. * *

Example: - *

-   * {@code
-   *     true
-   * }
-   * 
- *

+ * + *
{@code
+   * true
+   * }
* * @since 3.0.1 */ @@ -1120,10 +1055,10 @@ public class GitCommitIdMojo extends AbstractMojo { /** * Timestamp for reproducible output 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. + * (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. * * @since 4.0.2 */ @@ -1132,17 +1067,14 @@ public class GitCommitIdMojo extends AbstractMojo { // This is now the end of parameters that can be configured in the pom.xml // Happy hacking! - // ============================================================================================================ + // =============================================================================================== /** * Injected {@link BuildContext} to recognize incremental builds. */ - @Component - private BuildContext buildContext; + @Component private BuildContext buildContext; - /** - * Charset to read-write project sources. - */ + /** Charset to read-write project sources. */ private Charset sourceCharset = StandardCharsets.UTF_8; /** @@ -1156,53 +1088,54 @@ protected Map getCustomSystemEnv() { @Override public void execute() throws MojoExecutionException { - LogInterface log = new LogInterface() { - @Override - public void debug(String msg) { - if (verbose) { - getLog().debug(msg); - } - } - - @Override - public void info(String msg) { - if (verbose) { - getLog().info(msg); - } - } + LogInterface log = + new LogInterface() { + @Override + public void debug(String msg) { + if (verbose) { + getLog().debug(msg); + } + } - @Override - public void warn(String msg) { - if (verbose) { - getLog().warn(msg); - } - } + @Override + public void info(String msg) { + if (verbose) { + getLog().info(msg); + } + } - @Override - public void error(String msg) { - // TODO: Should we truly only report errors when verbose = true? - if (verbose) { - getLog().error(msg); - } - } + @Override + public void warn(String msg) { + if (verbose) { + getLog().warn(msg); + } + } - @Override - public void error(String msg, Throwable t) { - // TODO: Should we truly only report errors when verbose = true? - if (verbose) { - getLog().error(msg, t); - } - } - }; + @Override + public void error(String msg) { + // TODO: Should we truly only report errors when verbose = true? + if (verbose) { + getLog().error(msg); + } + } + @Override + public void error(String msg, Throwable t) { + // TODO: Should we truly only report errors when verbose = true? + if (verbose) { + getLog().error(msg, t); + } + } + }; try { // Skip mojo execution on incremental builds. if (buildContext != null && buildContext.isIncremental()) { // Except if properties file is missing at all - if (!generateGitPropertiesFile || - PropertiesFileGenerator.craftPropertiesOutputFile( - project.getBasedir(), new File(generateGitPropertiesFilename)).exists()) { + if (!generateGitPropertiesFile + || PropertiesFileGenerator.craftPropertiesOutputFile( + project.getBasedir(), new File(generateGitPropertiesFilename)) + .exists()) { return; } } @@ -1222,29 +1155,40 @@ public void error(String msg, Throwable t) { if (runOnlyOnce) { List sortedProjects = - Optional.ofNullable(session.getProjectDependencyGraph()) - .map(graph -> graph.getSortedProjects()) - .orElseGet(() -> { - log.warn("Maven's dependency graph is null. Assuming project is the only one executed."); - return Collections.singletonList(session.getCurrentProject()); - }); - MavenProject firstProject = sortedProjects.stream() + Optional.ofNullable(session.getProjectDependencyGraph()) + .map(graph -> graph.getSortedProjects()) + .orElseGet( + () -> { + log.warn( + "Maven's dependency graph is null. Assuming project is the only one" + + " executed."); + return Collections.singletonList(session.getCurrentProject()); + }); + MavenProject firstProject = + sortedProjects.stream() // skipPoms == true => find first project that is not pom project - .filter(p -> { - if (skipPoms) { - return !isPomProject(p); - } else { - return true; - } - }) + .filter( + p -> { + if (skipPoms) { + return !isPomProject(p); + } else { + return true; + } + }) .findFirst() .orElse(session.getCurrentProject()); - log.info("Current project: '" + session.getCurrentProject().getName() + - "', first project to execute based on dependency graph: '" + firstProject.getName() + "'"); + log.info( + "Current project: '" + + session.getCurrentProject().getName() + + "', first project to execute based on dependency graph: '" + + firstProject.getName() + + "'"); if (!session.getCurrentProject().equals(firstProject)) { - log.info("runOnlyOnce is enabled and this project is not the first project (perhaps skipPoms is configured?), skipping execution!"); + log.info( + "runOnlyOnce is enabled and this project is not the first project (perhaps skipPoms" + + " is configured?), skipping execution!"); return; } } @@ -1256,7 +1200,9 @@ public void error(String msg, Throwable t) { dotGitDirectory = lookupGitDirectory(); if (failOnNoGitDirectory && !directoryExists(dotGitDirectory)) { - throw new GitCommitIdExecutionException(".git directory is not found! Please specify a valid [dotGitDirectory] in your pom.xml"); + throw new GitCommitIdExecutionException( + ".git directory is not found! Please specify a valid [dotGitDirectory] in your" + + " pom.xml"); } if (gitDescribe == null) { @@ -1271,182 +1217,189 @@ public void error(String msg, Throwable t) { } try { - commitIdGenerationModeEnum = CommitIdGenerationMode.valueOf(commitIdGenerationMode.toUpperCase()); + commitIdGenerationModeEnum = + CommitIdGenerationMode.valueOf(commitIdGenerationMode.toUpperCase()); } catch (IllegalArgumentException e) { - log.warn("Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat' mode!"); + log.warn( + "Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat'" + + " mode!"); commitIdGenerationModeEnum = CommitIdGenerationMode.FLAT; } try { - commitIdPropertiesOutputFormat = CommitIdPropertiesOutputFormat.valueOf(format.toUpperCase()); + commitIdPropertiesOutputFormat = + CommitIdPropertiesOutputFormat.valueOf(format.toUpperCase()); } catch (IllegalArgumentException e) { log.warn("Detected wrong setting for 'format'. Falling back to default 'properties' mode!"); commitIdPropertiesOutputFormat = CommitIdPropertiesOutputFormat.PROPERTIES; } - final GitCommitIdPlugin.Callback cb = new GitCommitIdPlugin.Callback() { - @Override - public Map getSystemEnv() { - return getCustomSystemEnv(); - } + final GitCommitIdPlugin.Callback cb = + new GitCommitIdPlugin.Callback() { + @Override + public Map getSystemEnv() { + return getCustomSystemEnv(); + } - @Override - public Supplier supplyProjectVersion() { - return () -> project.getVersion(); - } + @Override + public Supplier supplyProjectVersion() { + return () -> project.getVersion(); + } - @Nonnull - @Override - public LogInterface getLogInterface() { - return log; - } + @Nonnull + @Override + public LogInterface getLogInterface() { + return log; + } - @Nonnull - @Override - public String getDateFormat() { - return dateFormat; - } + @Nonnull + @Override + public String getDateFormat() { + return dateFormat; + } - @Nonnull - @Override - public String getDateFormatTimeZone() { - return dateFormatTimeZone; - } + @Nonnull + @Override + public String getDateFormatTimeZone() { + return dateFormatTimeZone; + } - @Nonnull - @Override - public String getPrefixDot() { - String trimmedPrefix = prefix.trim(); - return trimmedPrefix.equals("") ? "" : trimmedPrefix + "."; - } + @Nonnull + @Override + public String getPrefixDot() { + String trimmedPrefix = prefix.trim(); + return trimmedPrefix.equals("") ? "" : trimmedPrefix + "."; + } - @Override - public List getExcludeProperties() { - return excludeProperties; - } + @Override + public List getExcludeProperties() { + return excludeProperties; + } - @Override - public List getIncludeOnlyProperties() { - return includeOnlyProperties; - } + @Override + public List getIncludeOnlyProperties() { + return includeOnlyProperties; + } - @Nullable - @Override - public Date getReproducibleBuildOutputTimestamp() throws GitCommitIdExecutionException { - return parseOutputTimestamp(projectBuildOutputTimestamp); - } + @Nullable + @Override + public Date getReproducibleBuildOutputTimestamp() throws GitCommitIdExecutionException { + return parseOutputTimestamp(projectBuildOutputTimestamp); + } - @Override - public boolean useNativeGit() { - return useNativeGit || useNativeGitViaCommandLine; - } + @Override + public boolean useNativeGit() { + return useNativeGit || useNativeGitViaCommandLine; + } - @Override - public long getNativeGitTimeoutInMs() { - return nativeGitTimeoutInMs; - } + @Override + public long getNativeGitTimeoutInMs() { + return nativeGitTimeoutInMs; + } - @Override - public int getAbbrevLength() { - return abbrevLength; - } + @Override + public int getAbbrevLength() { + return abbrevLength; + } - @Override - public GitDescribeConfig getGitDescribe() { - return gitDescribe; - } + @Override + public GitDescribeConfig getGitDescribe() { + return gitDescribe; + } - @Override - public CommitIdGenerationMode getCommitIdGenerationMode() { - return commitIdGenerationModeEnum; - } + @Override + public CommitIdGenerationMode getCommitIdGenerationMode() { + return commitIdGenerationModeEnum; + } - @Override - public boolean getUseBranchNameFromBuildEnvironment() { - return useBranchNameFromBuildEnvironment; - } + @Override + public boolean getUseBranchNameFromBuildEnvironment() { + return useBranchNameFromBuildEnvironment; + } - @Override - public boolean isOffline() { - return offline || settings.isOffline(); - } + @Override + public boolean isOffline() { + return offline || settings.isOffline(); + } - @Override - public String getEvaluateOnCommit() { - return evaluateOnCommit; - } + @Override + public String getEvaluateOnCommit() { + return evaluateOnCommit; + } - @Override - public File getDotGitDirectory() { - return dotGitDirectory; - } + @Override + public File getDotGitDirectory() { + return dotGitDirectory; + } - @Override - public boolean shouldGenerateGitPropertiesFile() { - return generateGitPropertiesFile; - } + @Override + public boolean shouldGenerateGitPropertiesFile() { + return generateGitPropertiesFile; + } - @Override - public void performPublishToAllSystemEnvironments(Properties properties) { - publishToAllSystemEnvironments(getLogInterface(), properties); - } + @Override + public void performPublishToAllSystemEnvironments(Properties properties) { + publishToAllSystemEnvironments(getLogInterface(), properties); + } - @Override - public void performPropertiesReplacement(Properties properties) { - PropertiesReplacer propertiesReplacer = new PropertiesReplacer( - log, new PluginParameterExpressionEvaluator(session, mojoExecution)); - propertiesReplacer.performReplacement(properties, replacementProperties); + @Override + public void performPropertiesReplacement(Properties properties) { + PropertiesReplacer propertiesReplacer = + new PropertiesReplacer( + log, new PluginParameterExpressionEvaluator(session, mojoExecution)); + propertiesReplacer.performReplacement(properties, replacementProperties); - logProperties(getLogInterface(), properties); - } + logProperties(getLogInterface(), properties); + } - @Override - public CommitIdPropertiesOutputFormat getPropertiesOutputFormat() { - return commitIdPropertiesOutputFormat; - } + @Override + public CommitIdPropertiesOutputFormat getPropertiesOutputFormat() { + return commitIdPropertiesOutputFormat; + } - @Override - public BuildFileChangeListener getBuildFileChangeListener() { - return file -> { - // this should only be null in our tests - if (buildContext != null) { - buildContext.refresh(file); + @Override + public BuildFileChangeListener getBuildFileChangeListener() { + return file -> { + // this should only be null in our tests + if (buildContext != null) { + buildContext.refresh(file); + } + }; } - }; - } - @Override - public String getProjectName() { - return project.getName(); - } + @Override + public String getProjectName() { + return project.getName(); + } - @Override - public File getProjectBaseDir() { - return project.getBasedir(); - } + @Override + public File getProjectBaseDir() { + return project.getBasedir(); + } - @Override - public File getGenerateGitPropertiesFile() { - return new File(generateGitPropertiesFilename); - } + @Override + public File getGenerateGitPropertiesFile() { + return new File(generateGitPropertiesFilename); + } - @Override - public Charset getPropertiesSourceCharset() { - return sourceCharset; - } + @Override + public Charset getPropertiesSourceCharset() { + return sourceCharset; + } - @Override - public boolean shouldPropertiesEscapeUnicode() { - return generateGitPropertiesFileWithEscapedUnicode; - } - }; + @Override + public boolean shouldPropertiesEscapeUnicode() { + return generateGitPropertiesFileWithEscapedUnicode; + } + }; Properties properties = null; // check if properties have already been injected Properties contextProperties = getContextProperties(project); boolean alreadyInjected = injectAllReactorProjects && contextProperties != null; if (alreadyInjected) { - log.info("injectAllReactorProjects is enabled - attempting to use the already computed values"); + log.info( + "injectAllReactorProjects is enabled - attempting to use the already computed values"); properties = contextProperties; } @@ -1476,26 +1429,30 @@ private void publishToAllSystemEnvironments(LogInterface log, Properties propert private Properties getContextProperties(MavenProject project) { Object stored = project.getContextValue(CONTEXT_KEY); if (stored instanceof Properties) { - return (Properties)stored; + return (Properties) stored; } return null; } /** * 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 + * (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)) { + if (outputTimestamp != null + && !outputTimestamp.trim().isEmpty() + && outputTimestamp.chars().allMatch(Character::isDigit)) { return new Date(Long.parseLong(outputTimestamp) * 1000); } @@ -1509,8 +1466,7 @@ private Date parseOutputTimestamp(String outputTimestamp) throws GitCommitIdExec return df.parse(outputTimestamp); } catch (ParseException pe) { throw new GitCommitIdExecutionException( - "Invalid 'project.build.outputTimestamp' value '" + outputTimestamp + "'", - pe); + "Invalid 'project.build.outputTimestamp' value '" + outputTimestamp + "'", pe); } } @@ -1531,8 +1487,8 @@ private void appendPropertiesToReactorProjects(LogInterface log, Properties prop } /** - * Find the git directory of the currently used project. - * If it's not already specified, this method will try to find it. + * Find the git directory of the currently used project. If it's not already specified, this + * method will try to find it. * * @return the File representation of the .git directory */ diff --git a/src/main/java/pl/project13/maven/git/GitDirLocator.java b/src/main/java/pl/project13/maven/git/GitDirLocator.java index c8cb62ba..4926ab61 100644 --- a/src/main/java/pl/project13/maven/git/GitDirLocator.java +++ b/src/main/java/pl/project13/maven/git/GitDirLocator.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,18 +18,20 @@ package pl.project13.maven.git; -import org.apache.maven.project.MavenProject; -import org.eclipse.jgit.lib.Constants; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; import java.nio.file.Path; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import org.apache.maven.project.MavenProject; +import org.eclipse.jgit.lib.Constants; /** - * This class encapsulates logic to locate a valid .git directory of the currently used project. - * If it's not already specified, this logic will try to find it. + * This class encapsulates logic to locate a valid .git directory of the currently used project. If + * it's not already specified, this logic will try to find it. */ public class GitDirLocator { final MavenProject mavenProject; @@ -36,8 +39,10 @@ public class GitDirLocator { /** * 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. + * @param reactorProjects The list of reactor projects (sub-projects) of the current (maven) + * project. */ public GitDirLocator(MavenProject mavenProject, List reactorProjects) { this.mavenProject = mavenProject; @@ -46,10 +51,12 @@ public GitDirLocator(MavenProject mavenProject, List reactorProjec /** * Attempts to lookup a valid .git directory of the currently used project. - * @param manuallyConfiguredDir A user has the ability to configure a git-directory with the {@code dotGitDirectory} - * configuration setting. By default it should be simply {@code ${project.basedir}/.git} - * @return A valid .git directory, or {@code null} if none could be found under the user specified location or within - * the project or it's reactor projects. + * + * @param manuallyConfiguredDir A user has the ability to configure a git-directory with the + * {@code dotGitDirectory} configuration setting. By default it should be simply {@code + * ${project.basedir}/.git} + * @return A valid .git directory, or {@code null} if none could be found under the user specified + * location or within the project or it's reactor projects. */ @Nullable public File lookupGitDirectory(@Nonnull File manuallyConfiguredDir) { @@ -142,8 +149,8 @@ private File processGitDirFile(@Nonnull File file) { } /** - * If the file looks like the location of a worktree, return the .git folder of the git repository of the worktree. - * If not, return the file as is. + * If the file looks like the location of a worktree, return the .git folder of the git repository + * of the worktree. If not, return the file as is. */ static File resolveWorktree(File fileLocation) { Path parent = fileLocation.toPath().getParent(); @@ -158,8 +165,11 @@ static File resolveWorktree(File fileLocation) { /** * Helper method to validate that the specified {@code File} is an existing directory. - * @param fileLocation The {@code File} that should be checked if it's actually an existing directory. - * @return {@code true} if the specified {@code File} is an existing directory, {@false} otherwise. + * + * @param fileLocation The {@code File} that should be checked if it's actually an existing + * directory. + * @return {@code true} if the specified {@code File} is an existing directory, {@false} + * otherwise. */ private static boolean isExistingDirectory(@Nullable File fileLocation) { return fileLocation != null && fileLocation.exists() && fileLocation.isDirectory(); diff --git a/src/main/java/pl/project13/maven/git/PropertiesReplacer.java b/src/main/java/pl/project13/maven/git/PropertiesReplacer.java index 61b7389d..919ddc6d 100644 --- a/src/main/java/pl/project13/maven/git/PropertiesReplacer.java +++ b/src/main/java/pl/project13/maven/git/PropertiesReplacer.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,15 +18,16 @@ package pl.project13.maven.git; +import java.util.List; +import java.util.Optional; +import java.util.Properties; +import java.util.regex.Pattern; import org.apache.maven.plugin.PluginParameterExpressionEvaluator; import pl.project13.core.log.LogInterface; -import java.util.*; -import java.util.regex.Pattern; - /** - * This class encapsulates logic to perform property replacements. - * For a use-case refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317. + * This class encapsulates logic to perform property replacements. For a use-case refer to + * https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317. */ public class PropertiesReplacer { private final LogInterface log; @@ -33,23 +35,27 @@ public class PropertiesReplacer { /** * Constructor to encapsulates all references required to perform property replacements. + * * @param log The logger to log any messages - * @param expressionEvaluator Maven's PluginParameterExpressionEvaluator - * (see https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/413 why it's needed) + * @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(LogInterface log, PluginParameterExpressionEvaluator expressionEvaluator) { + public PropertiesReplacer( + LogInterface log, PluginParameterExpressionEvaluator expressionEvaluator) { this.log = log; this.expressionEvaluator = expressionEvaluator; } /** * Method that performs the actual property replacement. + * * @param properties all properties that are being generated by the plugin * @param replacementProperties list of all replacement actions to perform */ - public void performReplacement(Properties properties, List replacementProperties) { + public void performReplacement( + Properties properties, List replacementProperties) { if ((replacementProperties != null) && (properties != null)) { - for (ReplacementProperty replacementProperty: replacementProperties) { + for (ReplacementProperty replacementProperty : replacementProperties) { String propertyKey = replacementProperty.getProperty(); if (propertyKey == null) { performReplacementOnAllGeneratedProperties(properties, replacementProperty); @@ -60,63 +66,112 @@ public void performReplacement(Properties properties, List } } - private void performReplacementOnAllGeneratedProperties(Properties properties, ReplacementProperty replacementProperty) { + private void performReplacementOnAllGeneratedProperties( + Properties properties, ReplacementProperty replacementProperty) { for (String propertyName : properties.stringPropertyNames()) { String content = properties.getProperty(propertyName); String result = performReplacement(replacementProperty, content); - if ((replacementProperty.getPropertyOutputSuffix() != null) && (!replacementProperty.getPropertyOutputSuffix().isEmpty())) { + if ((replacementProperty.getPropertyOutputSuffix() != null) + && (!replacementProperty.getPropertyOutputSuffix().isEmpty())) { String newPropertyKey = propertyName + "." + replacementProperty.getPropertyOutputSuffix(); properties.setProperty(newPropertyKey, result); - log.info("apply replace on property " + propertyName + " and save to " + newPropertyKey + ": original value '" + content + "' with '" + result + "'"); + log.info( + "apply replace on property " + + propertyName + + " and save to " + + newPropertyKey + + ": original value '" + + content + + "' with '" + + result + + "'"); } else { properties.setProperty(propertyName, result); - log.info("apply replace on property " + propertyName + ": original value '" + content + "' with '" + result + "'"); + log.info( + "apply replace on property " + + propertyName + + ": original value '" + + content + + "' with '" + + result + + "'"); } } } - private void performReplacementOnSingleProperty(Properties properties, ReplacementProperty replacementProperty, String propertyKey) { + private void performReplacementOnSingleProperty( + Properties properties, ReplacementProperty replacementProperty, String propertyKey) { String content = properties.getProperty(propertyKey); String result = performReplacement(replacementProperty, content); - if ((replacementProperty.getPropertyOutputSuffix() != null) && (!replacementProperty.getPropertyOutputSuffix().isEmpty())) { + if ((replacementProperty.getPropertyOutputSuffix() != null) + && (!replacementProperty.getPropertyOutputSuffix().isEmpty())) { String newPropertyKey = propertyKey + "." + replacementProperty.getPropertyOutputSuffix(); properties.setProperty(newPropertyKey, result); - log.info("apply replace on property " + propertyKey + " and save to " + newPropertyKey + ": original value '" + content + "' with '" + result + "'"); + log.info( + "apply replace on property " + + propertyKey + + " and save to " + + newPropertyKey + + ": original value '" + + content + + "' with '" + + result + + "'"); } else { properties.setProperty(propertyKey, result); - log.info("apply replace on property " + propertyKey + ": original value '" + content + "' with '" + result + "'"); + log.info( + "apply replace on property " + + propertyKey + + ": original value '" + + content + + "' with '" + + result + + "'"); } } private String performReplacement(ReplacementProperty replacementProperty, String content) { String evaluationContent = content; - if (evaluationContent == null || evaluationContent.isEmpty() || replacementProperty.isForceValueEvaluation()) { + if (evaluationContent == null + || evaluationContent.isEmpty() + || replacementProperty.isForceValueEvaluation()) { evaluationContent = replacementProperty.getValue(); } String result = ""; try { - result = Optional - .ofNullable(expressionEvaluator.evaluate(evaluationContent)) - .map(x -> x.toString()).orElse(evaluationContent); + result = + Optional.ofNullable(expressionEvaluator.evaluate(evaluationContent)) + .map(x -> x.toString()) + .orElse(evaluationContent); } catch (Exception e) { log.error("Something went wrong performing the replacement.", e); } if (replacementProperty != null) { - result = performTransformationRules(replacementProperty, result, TransformationRule.ApplyEnum.BEFORE); + result = + performTransformationRules( + replacementProperty, result, TransformationRule.ApplyEnum.BEFORE); if (replacementProperty.isRegex()) { - result = replaceRegex(result, replacementProperty.getToken(), replacementProperty.getValue()); + result = + replaceRegex(result, replacementProperty.getToken(), replacementProperty.getValue()); } else { - result = replaceNonRegex(result, replacementProperty.getToken(), replacementProperty.getValue()); + result = + replaceNonRegex(result, replacementProperty.getToken(), replacementProperty.getValue()); } - result = performTransformationRules(replacementProperty, result, TransformationRule.ApplyEnum.AFTER); + result = + performTransformationRules( + replacementProperty, result, TransformationRule.ApplyEnum.AFTER); } return result; } - private String performTransformationRules(ReplacementProperty replacementProperty, String content, TransformationRule.ApplyEnum forRule) { + private String performTransformationRules( + ReplacementProperty replacementProperty, + String content, + TransformationRule.ApplyEnum forRule) { String result = content; - if ((replacementProperty.getTransformationRules() != null) && (!replacementProperty.getTransformationRules().isEmpty())) { - for (TransformationRule transformationRule: replacementProperty.getTransformationRules()) { + if ((replacementProperty.getTransformationRules() != null) + && (!replacementProperty.getTransformationRules().isEmpty())) { + for (TransformationRule transformationRule : replacementProperty.getTransformationRules()) { if (transformationRule.getApplyRule().equals(forRule)) { result = transformationRule.getActionRule().perform(result); } diff --git a/src/main/java/pl/project13/maven/git/ReplacementProperty.java b/src/main/java/pl/project13/maven/git/ReplacementProperty.java index b746f0a5..6cc67ea3 100644 --- a/src/main/java/pl/project13/maven/git/ReplacementProperty.java +++ b/src/main/java/pl/project13/maven/git/ReplacementProperty.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -19,94 +20,98 @@ import java.util.ArrayList; import java.util.List; - import org.apache.maven.plugins.annotations.Parameter; /** - * This class represents a specific property replacement the user wants to perform. - * For a use-case refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317. + * This class represents a specific property replacement the user wants to perform. For a use-case + * refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317. + * * @since 2.2.3 */ public class ReplacementProperty { /** - * Defines if a replacement should only be applied to a single property. - * If left empty the replacement will be performed on all generated properties. + * Defines if a replacement should only be applied to a single property. If left empty the + * replacement will be performed on all generated properties. */ - @Parameter - private String property; + @Parameter private String property; /** - * @since 2.2.4 * Defines an additional output property suffix. - * Note: - * this will only be *appended* to the current property key - * (e.g. when the property is set to 'sample' the property - * 'git.branch' will be transformed to 'git.branch.sample') - * - * Be advised that you might want to adjust your include - * or exclude filters which be applied after the regex validation. + * + *

Note: this will only be appended to the current property key (e.g. when the property + * is set to {@code sample} the property {@code git.branch} will be transformed to + * {@code git.branch.sample}). + * + *

Be advised that you might want to adjust your include or exclude filters which be + * applied after the regex validation. + * + * @since 2.2.4 */ - @Parameter - private String propertyOutputSuffix; + @Parameter private String propertyOutputSuffix; - /** - * Token to replace. - * This may or may not be a regular expression. - */ + /** Token to replace. This may or may not be a regular expression. */ @Parameter(required = true) private String token; /** - * Value to replace token with. - * The text to be written over any found tokens. - * You can also reference grouped regex matches made in the token here by $1, $2, etc. + * Value to replace token with. The text to be written over any found tokens. You can also + * reference grouped regex matches made in the token here by $1, $2, etc. */ @Parameter(defaultValue = "") private String value = ""; - /** - * Indicates if the token should be located with regular expressions. - */ + /** Indicates if the token should be located with regular expressions. */ @Parameter(defaultValue = "true") private boolean regex = true; /** - * Forces the plugin to evaluate the value on *every* project. - * Note that this essentially means that the plugin *must* run for every child-project of a reactor - * build and thus might cause some overhead (the git properties should be cached). + * Forces the plugin to evaluate the value on *every* project. Note that this essentially means + * that the plugin *must* run for every child-project of a reactor build and thus might cause some + * overhead (the git properties should be cached). * - * For a use-case refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/457. + *

For a use-case refer to + * https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/457. */ @Parameter(defaultValue = "false") private boolean forceValueEvaluation = false; /** + * Provides the ability to perform certain string transformations before regex + * evaluation or after. + * * @since 2.2.4 - * Provides the ability to perform certain string transformations before regex evaluation or after. */ - @Parameter - private List transformationRules = new ArrayList<>(); + @Parameter private List transformationRules = new ArrayList<>(); - /** - * Empty constructor - */ - public ReplacementProperty() { - } + /** Empty constructor. */ + public ReplacementProperty() {} /** * Constructs a specific property replacement the user wants to perform. - * @param property The source (input) property on which the replacements should be performed (e.g. {@code git.branch}) - * @param propertyOutputSuffix The property output suffix where the replacement result should be stored in (e.g. {@code git.branch-no-slashes}) - * @param token The replacement token acts as {@code needle} that will be searched in the input property (e.g. {@code ^([^\/]*)\/([^\/]*)$}) + * + * @param property The source (input) property on which the replacements should be performed (e.g. + * {@code git.branch}) + * @param propertyOutputSuffix The property output suffix where the replacement result should be + * stored in (e.g. {@code git.branch-no-slashes}) + * @param token The replacement token acts as {@code needle} that will be searched in the input + * property (e.g. {@code ^([^\/]*)\/([^\/]*)$}) * @param value The value acts as the text to be written over any found tokens ("replacement"). - * @param regex If {@code true} the replacement will be performed with regular expressions or, - * if {@code false} performs a replacement with java's string.replace-function. - * @param forceValueEvaluation If {@code true} forces the plugin to evaluate the given value on *every* project. - * This might come handy if *every* project needs a unique value and a user wants to - * project specific variables like {@code project.artifactId}. - * @param transformationRules The list of transformation-rules that should be applied during replacement. - */ - public ReplacementProperty(String property, String propertyOutputSuffix, String token, String value, boolean regex, boolean forceValueEvaluation, List transformationRules) { + * @param regex If {@code true} the replacement will be performed with regular expressions or, if + * {@code false} performs a replacement with java's string.replace-function. + * @param forceValueEvaluation If {@code true} forces the plugin to evaluate the given value on + * *every* project. This might come handy if *every* project needs a unique value and a user + * wants to project specific variables like {@code project.artifactId}. + * @param transformationRules The list of transformation-rules that should be applied during + * replacement. + */ + public ReplacementProperty( + String property, + String propertyOutputSuffix, + String token, + String value, + boolean regex, + boolean forceValueEvaluation, + List transformationRules) { this.property = property; this.propertyOutputSuffix = propertyOutputSuffix; this.token = token; @@ -117,14 +122,19 @@ public ReplacementProperty(String property, String propertyOutputSuffix, String } /** - * @return The source (input) property on which the replacements should be performed (e.g. {@code git.branch}) + * The source (input) property on which the replacements should be performed. + * + * @return The source (input) property on which the replacements should be performed (e.g. {@code + * git.branch}) */ public String getProperty() { return property; } /** - * Set the source (input) property on which the replacements should be performed (e.g. {@code git.branch}) + * Set the source (input) property on which the replacements should be performed (e.g. {@code + * git.branch}) + * * @param property The source (input) property */ public void setProperty(String property) { @@ -132,14 +142,19 @@ public void setProperty(String property) { } /** - * @return The property output suffix where the replacement result should be stored in (e.g. {@code git.branch-no-slashes}) + * The property output suffix where the replacement result should be stored in. + * + * @return The property output suffix where the replacement result should be stored in (e.g. + * {@code git.branch-no-slashes}) */ public String getPropertyOutputSuffix() { return propertyOutputSuffix; } /** - * Set the property output suffix where the replacement result should be stored in (e.g. {@code git.branch-no-slashes}) + * Set the property output suffix where the replacement result should be stored in (e.g. {@code + * git.branch-no-slashes}) + * * @param propertyOutputSuffix The property output suffix */ public void setPropertyOutputSuffix(String propertyOutputSuffix) { @@ -147,14 +162,18 @@ public void setPropertyOutputSuffix(String propertyOutputSuffix) { } /** - * @return The replacement token acts as {@code needle} that will be searched in the input property (e.g. {@code ^([^\/]*)\/([^\/]*)$}) + * The replacement token acts as {@code needle} that will be searched in the input property. + * + * @return The replacement token acts as {@code needle} that will be searched in the input + * property (e.g. {@code ^([^\/]*)\/([^\/]*)$}) */ public String getToken() { return token; } /** - * Set the replacement token + * Set the replacement token. + * * @param token The replacement token */ public void setToken(String token) { @@ -162,6 +181,8 @@ public void setToken(String token) { } /** + * The value that acts as the text to be written over any found tokens. + * * @return The value that acts as the text to be written over any found tokens ("replacement"). */ public String getValue() { @@ -170,6 +191,7 @@ public String getValue() { /** * Sets the value that acts as the text to be written over any found tokens ("replacement"). + * * @param value The replacment value */ public void setValue(String value) { @@ -177,8 +199,10 @@ public void setValue(String value) { } /** - * @return Indicator if the replacement will be performed with regular expressions ({@code true}) or, - * if a replacement with java's string.replace-function is performed ({@code false}). + * Indicator if the replacement will be performed with regular expressions. + * + * @return Indicator if the replacement will be performed with regular expressions ({@code true}) + * or, if a replacement with java's string.replace-function is performed ({@code false}). */ public boolean isRegex() { return regex; @@ -187,6 +211,7 @@ public boolean isRegex() { /** * Sets Indicator if the replacement will be performed with regular expressions ({@code true}) or, * if a replacement with java's string.replace-function is performed ({@code false}). + * * @param regex Indicator */ public void setRegex(boolean regex) { @@ -194,21 +219,27 @@ public void setRegex(boolean regex) { } /** - * @return Indicator if the plugin forces to evaluate the given value on *every* project ({@code true}). + * Indicator if the plugin forces to evaluate the given value on every project. + * + * @return Indicator if the plugin forces to evaluate the given value on every project. */ public boolean isForceValueEvaluation() { return forceValueEvaluation; } /** - * Sets Indicator if the plugin forces to evaluate the given value on *every* project ({@code true}). - * @param forceValueEvaluation Indicator if the plugin forces to evaluate the given value on *every* project ({@code true}). + * Sets Indicator if the plugin forces to evaluate the given value on every project. + * + * @param forceValueEvaluation Indicator if the plugin forces to evaluate the given value on + * every project ({@code true}). */ public void setForceValueEvaluation(boolean forceValueEvaluation) { this.forceValueEvaluation = forceValueEvaluation; } /** + * The list of transformation-rules that should be applied during replacement. + * * @return The list of transformation-rules that should be applied during replacement. */ public List getTransformationRules() { @@ -217,6 +248,7 @@ public List getTransformationRules() { /** * Sets the list of transformation-rules that should be applied during replacement. + * * @param transformationRules The list of transformation-rules */ public void setTransformationRules(List transformationRules) { diff --git a/src/main/java/pl/project13/maven/git/TransformationRule.java b/src/main/java/pl/project13/maven/git/TransformationRule.java index 53456618..4513e3d5 100644 --- a/src/main/java/pl/project13/maven/git/TransformationRule.java +++ b/src/main/java/pl/project13/maven/git/TransformationRule.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -22,50 +23,55 @@ /** * This class represents a specific transformation logic the user wants to perform. * - * Each {@code transformationRule} consist of - * two required fields {@code apply} and {@code action}. - * The {@code apply}-tag controls when the rule should - * be applied and can be set to {@code BEFORE} to have the rule being applied before or it can be - * set to {@code AFTER} to have the rule being applied after the replacement. + *

Each {@code transformationRule} consist of two required fields {@code apply} and {@code + * action}. + * The {@code apply}-tag controls when the rule should be applied and can be set to {@link + * ApplyEnum#BEFORE} to have the rule being applied before or it can be set to + * {@link ApplyEnum#AFTER} to have the rule being applied after the replacement. * The {@code action}-tag determines the string conversion rule that should be applied. * - * Refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317 for a use-case. + *

Refer to https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/317 for a + * use-case. */ public class TransformationRule { /** - * Determines when the transformation should be taken place. - * Currently supported is - * - BEFORE_REGEX - * - AFTER_REGEX + * Determines when the transformation should be taken place. Currently supported is - BEFORE_REGEX + * - AFTER_REGEX */ @Parameter(required = true) private String apply; private ApplyEnum applyRule; + /** + * Each {@code transformationRule} consist of two required fields {@code apply} and {@code + * action}. + * The {@code apply}-tag controls when the rule should be applied and can be set to {@link + * ApplyEnum#BEFORE} to have the rule being applied before or it can be set to + * {@link ApplyEnum#AFTER} to have the rule being applied after the replacement. + */ protected enum ApplyEnum { - /** - * have the rule being applied before the replacement - */ + /** have the rule being applied before the replacement. */ BEFORE, - /** - * have the rule being applied after the replacement - */ + /** have the rule being applied after the replacement. */ AFTER, ; } /** - * Determines the action that should be performed as transformation. - * Currently supported is - * - LOWER_CASE - * - UPPER_CASE + * Determines the action that should be performed as transformation. Currently supported is - + * LOWER_CASE - UPPER_CASE */ @Parameter(required = true) private String action; private ActionEnum actionRule; + /** + * Each {@code transformationRule} consist of two required fields {@code apply} and {@code + * action}. + * The {@code action}-tag determines the string conversion rule that should be applied. + */ protected enum ActionEnum { LOWER_CASE { @Override @@ -86,11 +92,11 @@ protected String perform(String input) { } }, ; + protected abstract String perform(String input); } - public TransformationRule() { - } + public TransformationRule() {} public TransformationRule(String apply, String action) { this(ApplyEnum.valueOf(apply), ActionEnum.valueOf(action)); @@ -114,7 +120,8 @@ public void setApply(String apply) { public ApplyEnum getApplyRule() { if (applyRule == null) { - throw new IllegalStateException("The parameter 'apply' for TransformationRule is missing or invalid"); + throw new IllegalStateException( + "The parameter 'apply' for TransformationRule is missing or invalid"); } return applyRule; } @@ -130,7 +137,8 @@ public void setAction(String action) { public ActionEnum getActionRule() { if (actionRule == null) { - throw new IllegalStateException("The parameter 'action' for TransformationRule is missing or invalid"); + throw new IllegalStateException( + "The parameter 'action' for TransformationRule is missing or invalid"); } return actionRule; } diff --git a/src/main/java/pl/project13/maven/validation/ValidationMojo.java b/src/main/java/pl/project13/maven/validation/ValidationMojo.java index 6e80a4cb..46e1dfb3 100644 --- a/src/main/java/pl/project13/maven/validation/ValidationMojo.java +++ b/src/main/java/pl/project13/maven/validation/ValidationMojo.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,17 +18,41 @@ package pl.project13.maven.validation; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** + * The git-commit-id-maven-plugin comes equipped with an additional + * validation utility which can be used to verify if your project properties are set as you + * would like to have them set. + * This feature ships with an additional mojo execution and for instance allows to check if + * the version is not a snapshot build. If you are interested in the config checkout the + * + * validation utility documentation. + *

+ * Each validation you may want to perform can be configured using a {@link ValidationProperty}. + * + * Note: This configuration will only be taken into account when the additional goal + * `validateRevision` is configured inside an execution like so + *

{@code
+ * 
+ *   io.github.git-commit-id
+ *   git-commit-id-maven-plugin
+ *   
+ *      
+ *        validate-the-git-infos
+ *        validateRevision
+ *        package
+ *      
+ *    
+ * }
+ * * @since 2.2.2 */ @Mojo(name = "validateRevision", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) @@ -35,13 +60,12 @@ public class ValidationMojo extends AbstractMojo { @Parameter(defaultValue = "true") private boolean validationShouldFailIfNoMatch; - @Parameter - private List validationProperties; + @Parameter private List validationProperties; @Override public void execute() throws MojoExecutionException { if (validationProperties != null && validationShouldFailIfNoMatch) { - for (ValidationProperty validationProperty: validationProperties) { + for (ValidationProperty validationProperty : validationProperties) { String name = validationProperty.getName(); String value = validationProperty.getValue(); String shouldMatchTo = validationProperty.getShouldMatchTo(); @@ -54,7 +78,8 @@ public void execute() throws MojoExecutionException { } } - private void validateIfValueAndShouldMatchToMatches(String name, String value, String shouldMatchTo) throws MojoExecutionException { + private void validateIfValueAndShouldMatchToMatches( + String name, String value, String shouldMatchTo) throws MojoExecutionException { Pattern pattern = Pattern.compile(shouldMatchTo); Matcher matcher = pattern.matcher(value); if (!matcher.find()) { @@ -62,17 +87,30 @@ private void validateIfValueAndShouldMatchToMatches(String name, String value, S if (name != null) { throw new MojoExecutionException("Validation '" + name + "' failed! " + commonLogMessage); } else { - throw new MojoExecutionException("Validation of an unidentified validation (please set the name property-tag to be able to identify the validation) failed! " + commonLogMessage); + throw new MojoExecutionException( + "Validation of an unidentified validation (please set the name property-tag to be able" + + " to identify the validation) failed! " + + commonLogMessage); } } } - 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( + String name, String value, String shouldMatchTo) { + String commonLogMessage = + "since one of the values was null! (value = '" + + value + + "'; shouldMatchTo = '" + + shouldMatchTo + + "')."; if (name != null) { getLog().warn("Skipping validation '" + name + "' " + commonLogMessage); } else { - getLog().warn("Skipping an unidentified validation (please set the name property-tag to be able to identify the validation) " + commonLogMessage); + getLog() + .warn( + "Skipping an unidentified validation (please set the name property-tag to be able to" + + " identify the validation) " + + commonLogMessage); } } diff --git a/src/main/java/pl/project13/maven/validation/ValidationProperty.java b/src/main/java/pl/project13/maven/validation/ValidationProperty.java index 3b8ac5b4..4d2ff509 100644 --- a/src/main/java/pl/project13/maven/validation/ValidationProperty.java +++ b/src/main/java/pl/project13/maven/validation/ValidationProperty.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,14 +18,26 @@ package pl.project13.maven.validation; - +/** + * Allows to configure a single validation action that shall be performed + * when running the {@link ValidationMojo}. + * A full configuration may like: + *
{@code
+ * 
+ *   
+ *     validating project version
+ *     ${project.version}
+ *     
+ *   
+ * 
+ * }
+ */ public class ValidationProperty { private String name; private String value; private String shouldMatchTo; - public ValidationProperty() { - } + public ValidationProperty() {} ValidationProperty(String name, String value, String shouldMatchTo) { this.name = name; @@ -32,26 +45,52 @@ public ValidationProperty() { this.shouldMatchTo = shouldMatchTo; } + /** + * Sets a descriptive name that will be used to be able to identify the validation that + * does not match up (will be displayed in the error message). + * + * @param name The name that shall be used to identify the validation + */ public void setName(String name) { this.name = name; } + /** + * Sets the value that needs to be validated. + * + * @param value The value that needs to be validated. + */ public void setValue(String value) { this.value = value; } + /** + * Sets the expectation what the given value should match to. + * + * @param shouldMatchTo The expectation what the given value should match to. + */ public void setShouldMatchTo(String shouldMatchTo) { this.shouldMatchTo = shouldMatchTo; } + /** + * @return A descriptive name that will be used to be able to identify the validation that + * does not match up (will be displayed in the error message). + */ public String getName() { return name; } + /** + * @return The value that needs to be validated. + */ public String getValue() { return value; } + /** + * @return The expectation what the given value should match to. + */ public String getShouldMatchTo() { return shouldMatchTo; } diff --git a/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java b/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java index d1847f54..1eb0153d 100644 --- a/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java +++ b/src/test/java/pl/project13/core/jgit/DescribeCommandIntegrationTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,6 +18,15 @@ package pl.project13.core.jgit; +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 java.util.Collections; +import java.util.Optional; +import javax.annotation.Nonnull; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.ObjectId; @@ -27,16 +37,9 @@ import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; -import javax.annotation.Nonnull; -import java.util.Collections; -import java.util.Optional; - -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; - +/** + * Testcases to verify that the {@link DescribeResult} works properly. + */ public class DescribeCommandIntegrationTest extends GitIntegrationTest { public static final int DEFAULT_ABBREV_LEN = 7; @@ -57,11 +60,11 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT_DIRTY) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).call(); // then assertThat(res).isNotNull(); @@ -80,9 +83,11 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFound() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); + DescribeCommand command = + spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -94,7 +99,7 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFound() throws Exception { assertThat(res.toString()).isEqualTo(abbrev(head.getName())); } } - + @Test public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { // given @@ -104,9 +109,11 @@ public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); + DescribeCommand command = + spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -120,7 +127,8 @@ public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { } @Test - public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfIt() throws Exception { + public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfIt() + throws Exception { // given mavenSandbox .withParentProject(PROJECT_NAME, "jar") @@ -129,13 +137,14 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfI .create(); int abbrevLength = 10; - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); + DescribeCommand command = + spy(DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge())); doReturn(false).when(command).findDirtyState(any(Repository.class)); - command - .abbrev(abbrevLength); + command.abbrev(abbrevLength); DescribeResult res = command.call(); // then @@ -155,9 +164,11 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndDirtyMarker() thr .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()); + DescribeCommand command = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()); command.dirty(DIRTY_SUFFIX); DescribeResult res = command.call(); @@ -169,7 +180,8 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndDirtyMarker() thr } @Test - public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker() throws Exception { + public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker() + throws Exception { // given mavenSandbox .withParentProject(PROJECT_NAME, "jar") @@ -179,17 +191,19 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker String customDirtySuffix = "-DEV"; - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeCommand command = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) + DescribeCommand command = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .dirty(customDirtySuffix); DescribeResult res = command.call(); // then assertThat(res).isNotNull(); RevCommit head = git.log().call().iterator().next(); - assertThat(res.toString()).isEqualTo("v2.0.4-25-g" + abbrev(head.getName()) + customDirtySuffix); + assertThat(res.toString()) + .isEqualTo("v2.0.4-25-g" + abbrev(head.getName()) + customDirtySuffix); } } @@ -202,13 +216,15 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsId() throws Exception .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { wrap.reset().setMode(ResetCommand.ResetType.HARD).call(); } // when - DescribeCommand command = DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()); + DescribeCommand command = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()); DescribeResult res = command.call(); // then @@ -227,14 +243,13 @@ public void shouldGiveTag() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res).isNotNull(); @@ -244,7 +259,8 @@ public void shouldGiveTag() throws Exception { } @Test - public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured() throws Exception { + public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured() + throws Exception { // given mavenSandbox .withParentProject(PROJECT_NAME, "jar") @@ -252,14 +268,13 @@ public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res).isNotNull(); @@ -279,12 +294,13 @@ public void shouldGiveTagWithCustomDirtyMarker() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .tags() .dirty(customDirtySuffix) .call(); @@ -305,12 +321,11 @@ public void shouldNotGiveDirtyTagByDefault() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res.toString()).isEqualTo("v1.0.0"); @@ -326,10 +341,11 @@ public void shouldGiveAnnotatedTagWithDirtyMarker() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .dirty(DIRTY_SUFFIX) .abbrev(0) .call(); @@ -350,16 +366,15 @@ public void shouldGiveLightweightTagWithDirtyMarker() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG_DIRTY) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { wrap.reset().setMode(ResetCommand.ResetType.HARD).call(); } // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res).isNotNull(); @@ -377,7 +392,8 @@ public void isATag_shouldProperlyDetectIfACommitIsATag() throws Exception { ObjectId oid = ObjectId.fromString(commitHash); // when - boolean isATag = DescribeCommand.hasTags(oid, Collections.singletonMap(oid, singletonList(tagName))); + boolean isATag = + DescribeCommand.hasTags(oid, Collections.singletonMap(oid, singletonList(tagName))); // then assertThat(isATag).isTrue(); @@ -394,7 +410,8 @@ public void isATag_shouldProperlyDetectIfACommitIsANotTag() throws Exception { ObjectId oid = ObjectId.fromString(commitHash); // when - boolean isATag = DescribeCommand.hasTags(oid, Collections.singletonMap(tagOid, singletonList(tagName))); + boolean isATag = + DescribeCommand.hasTags(oid, Collections.singletonMap(tagOid, singletonList(tagName))); // then assertThat(isATag).isTrue(); @@ -410,14 +427,15 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { try (final Git wrap = Git.wrap(repo)) { wrap.reset().setMode(ResetCommand.ResetType.HARD).call(); } // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .abbrev(zeroAbbrev) .call(); @@ -437,4 +455,4 @@ String abbrev(@Nonnull String id) { String abbrev(@Nonnull String id, int n) { return id.substring(0, n); } -} \ No newline at end of file +} diff --git a/src/test/java/pl/project13/core/jgit/DescribeResultTest.java b/src/test/java/pl/project13/core/jgit/DescribeResultTest.java index 31701615..112fee9c 100644 --- a/src/test/java/pl/project13/core/jgit/DescribeResultTest.java +++ b/src/test/java/pl/project13/core/jgit/DescribeResultTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,6 +18,9 @@ package pl.project13.core.jgit; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.ObjectId; @@ -26,10 +30,9 @@ import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the {@link DescribeResult} works properly. + */ public class DescribeResultTest extends GitIntegrationTest { static final String PROJECT_NAME = "my-jar-project"; @@ -77,10 +80,13 @@ public void shouldToStringForTag() throws Exception { @Test public void shouldToStringForDirtyTag() throws Exception { // given - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); - DescribeResult res = new DescribeResult(repo.newObjectReader(), VERSION, 2, HEAD_OBJECT_ID, true, DIRTY_MARKER); + DescribeResult res = + new DescribeResult( + repo.newObjectReader(), VERSION, 2, HEAD_OBJECT_ID, true, DIRTY_MARKER); // when String s = res.toString(); @@ -93,10 +99,12 @@ public void shouldToStringForDirtyTag() throws Exception { @Test public void shouldToStringForDirtyTagAnd10Abbrev() throws Exception { // given - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); - DescribeResult res = new DescribeResult(repo.newObjectReader(), VERSION, 2, HEAD_OBJECT_ID, true, DIRTY_MARKER) + DescribeResult res = + new DescribeResult(repo.newObjectReader(), VERSION, 2, HEAD_OBJECT_ID, true, DIRTY_MARKER) .withCommitIdAbbrev(10); String expectedHash = "gb6a73ed747"; @@ -112,7 +120,8 @@ public void shouldToStringForDirtyTagAnd10Abbrev() throws Exception { @Test public void shouldToStringFor2CommitsAwayFromTag() throws Exception { // given - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); DescribeResult res = new DescribeResult(repo.newObjectReader(), VERSION, 2, HEAD_OBJECT_ID); @@ -128,12 +137,12 @@ public void shouldToStringFor2CommitsAwayFromTag() throws Exception { @Test public void shouldToStringForNoTagJustACommit() throws Exception { // given - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { git.reset().setMode(ResetCommand.ResetType.HARD).call(); DescribeResult res = new DescribeResult(repo.newObjectReader(), HEAD_OBJECT_ID); - // when String s = res.toString(); diff --git a/src/test/java/pl/project13/log/DummyTestLoggerBridge.java b/src/test/java/pl/project13/log/DummyTestLoggerBridge.java index 36e3f852..a72450e9 100644 --- a/src/test/java/pl/project13/log/DummyTestLoggerBridge.java +++ b/src/test/java/pl/project13/log/DummyTestLoggerBridge.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,13 +18,15 @@ package pl.project13.log; -import pl.project13.core.log.LogInterface; - import java.util.AbstractMap; import java.util.ArrayList; import java.util.List; import java.util.Map; +import pl.project13.core.log.LogInterface; +/** + * A class to test any logging interaction. + */ public class DummyTestLoggerBridge implements LogInterface { private List debugs = new ArrayList<>(); private ArrayList infos = new ArrayList<>(); diff --git a/src/test/java/pl/project13/maven/git/AheadBehindTest.java b/src/test/java/pl/project13/maven/git/AheadBehindTest.java index 5757de68..877eef89 100644 --- a/src/test/java/pl/project13/maven/git/AheadBehindTest.java +++ b/src/test/java/pl/project13/maven/git/AheadBehindTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,8 +18,9 @@ package pl.project13.maven.git; -import java.io.File; +import static org.junit.Assert.assertEquals; +import java.io.File; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.lib.ConfigConstants; import org.eclipse.jgit.lib.StoredConfig; @@ -30,18 +32,16 @@ import pl.project13.core.AheadBehind; import pl.project13.core.GitProvider; -import static org.junit.Assert.assertEquals; - +/** + * Testcases to verify that the {@link AheadBehind} works properly. + */ public abstract class AheadBehindTest { - @Rule - public TemporaryFolder remoteRepository = new TemporaryFolder(); + @Rule public TemporaryFolder remoteRepository = new TemporaryFolder(); - @Rule - public TemporaryFolder localRepository = new TemporaryFolder(); + @Rule public TemporaryFolder localRepository = new TemporaryFolder(); - @Rule - public TemporaryFolder secondLocalRepository = new TemporaryFolder(); + @Rule public TemporaryFolder secondLocalRepository = new TemporaryFolder(); protected Git localRepositoryGit; @@ -96,8 +96,8 @@ public void shouldBe1Ahead() throws Exception { createLocalCommit(); AheadBehind aheadBehind = gitProvider.getAheadBehind(); - assertEquals(aheadBehind.ahead(),"1"); - assertEquals(aheadBehind.behind(),"0"); + assertEquals(aheadBehind.ahead(), "1"); + assertEquals(aheadBehind.behind(), "0"); } @Test @@ -106,8 +106,8 @@ public void shouldBe1Behind() throws Exception { createCommitInSecondRepoAndPush(); AheadBehind aheadBehind = gitProvider.getAheadBehind(); - assertEquals(aheadBehind.ahead(),"0"); - assertEquals(aheadBehind.behind(),"1"); + assertEquals(aheadBehind.ahead(), "0"); + assertEquals(aheadBehind.behind(), "1"); } @Test @@ -117,8 +117,8 @@ public void shouldBe1AheadAnd1Behind() throws Exception { createCommitInSecondRepoAndPush(); AheadBehind aheadBehind = gitProvider.getAheadBehind(); - assertEquals(aheadBehind.ahead(),"1"); - assertEquals(aheadBehind.behind(),"1"); + assertEquals(aheadBehind.ahead(), "1"); + assertEquals(aheadBehind.behind(), "1"); } protected void createLocalCommit() throws Exception { @@ -142,8 +142,12 @@ protected void createRemoteRepository() throws Exception { } protected void setupLocalRepository() throws Exception { - localRepositoryGit = Git.cloneRepository().setURI(remoteRepository.getRoot().toURI().toString()) - .setDirectory(localRepository.getRoot()).setBranch("master").call(); + localRepositoryGit = + Git.cloneRepository() + .setURI(remoteRepository.getRoot().toURI().toString()) + .setDirectory(localRepository.getRoot()) + .setBranch("master") + .call(); StoredConfig config = localRepositoryGit.getRepository().getConfig(); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, "master", "remote", "origin"); @@ -152,8 +156,12 @@ protected void setupLocalRepository() throws Exception { } protected void setupSecondLocalRepository() throws Exception { - secondLocalRepositoryGit = Git.cloneRepository().setURI(remoteRepository.getRoot().toURI().toString()) - .setDirectory(secondLocalRepository.getRoot()).setBranch("master").call(); + secondLocalRepositoryGit = + Git.cloneRepository() + .setURI(remoteRepository.getRoot().toURI().toString()) + .setDirectory(secondLocalRepository.getRoot()) + .setBranch("master") + .call(); } protected void createAndPushInitialCommit() throws Exception { @@ -163,5 +171,4 @@ protected void createAndPushInitialCommit() throws Exception { localRepositoryGit.push().call(); } - } diff --git a/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java b/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java index 0721a9c4..b994b20d 100644 --- a/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java +++ b/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,10 +18,12 @@ package pl.project13.maven.git; - -import javax.annotation.Nonnull; import java.io.File; +import javax.annotation.Nonnull; +/** + * List of available git repositories that we can use to perform tests with. + */ public enum AvailableGitTestRepo { WITH_ONE_COMMIT("src/test/resources/_git_one_commit"), WITH_ONE_COMMIT_DIRTY("src/test/resources/_git_one_commit_dirty"), @@ -28,6 +31,8 @@ public enum AvailableGitTestRepo { GIT_WITH_NO_CHANGES("src/test/resources/_git_with_no_changes"), ON_A_TAG("src/test/resources/_git_on_a_tag"), /** + * + * *
    * $ lg
    *   * b6a73ed - (HEAD, master) third addition (32 hours ago) 

Konrad Malawski

@@ -36,6 +41,7 @@ public enum AvailableGitTestRepo { *
* * Where the newest-tag was created latest: + * *
    * $ tag -v newest-tag
    * object d37a598a7a98531ad1375966642c6b1263129436
@@ -50,14 +56,19 @@ public enum AvailableGitTestRepo {
   ON_A_TAG_DIRTY("src/test/resources/_git_on_a_tag_dirty"),
   WITH_SUBMODULES("src/test/resources/_git_with_submodules"),
   /**
+   *
+   *
    * 
    * b6a73ed - (HEAD, master) third addition (4 minutes ago) 

Konrad Malawski

* d37a598 - (lightweight-tag) second line (6 minutes ago)

Konrad Malawski

* 9597545 - (annotated-tag) initial commit (6 minutes ago)

Konrad Malawski

*
*/ - WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG("src/test/resources/_git_lightweight_tag_before_annotated_tag"), + WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG( + "src/test/resources/_git_lightweight_tag_before_annotated_tag"), /** + * + * *
    * * 9cb810e - Change in tag - Fri, 29 Nov 2013 10:39:31 +0100 (tag: test_tag, branch: test)
    * | * 2343428 - Moved master - Fri, 29 Nov 2013 10:38:34 +0100 (HEAD, branch: master)
@@ -68,16 +79,18 @@ public enum AvailableGitTestRepo {
   WITH_TAG_ON_DIFFERENT_BRANCH("src/test/resources/_git_with_tag_on_different_branch"),
   WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS("src/test/resources/_git_one_commit_with_umlaut"),
   /**
-    * 
-    * b0c6d28b3b83bf7b905321bae67d9ca4c75a203f 2015-06-04 00:50:18 +0200  (HEAD, master)
-    * 0e3495783c56589213ee5f2ae8900e2dc1b776c4 2015-06-03 23:59:10 +0200  (tag: v2.0)
-    * f830b5f85cad3d33ba50d04c3d1454e1ae469057 2015-06-03 23:57:53 +0200  (tag: v1.0)
-    * 
- */ - WITH_THREE_COMMITS_AND_TWO_TAGS_CURRENTLY_ON_COMMIT_WITHOUT_TAG("src/test/resources/_git_three_commits_and_two_tags_currently_on_commit_without_tag"), + * + * + *
+   * b0c6d28b3b83bf7b905321bae67d9ca4c75a203f 2015-06-04 00:50:18 +0200  (HEAD, master)
+   * 0e3495783c56589213ee5f2ae8900e2dc1b776c4 2015-06-03 23:59:10 +0200  (tag: v2.0)
+   * f830b5f85cad3d33ba50d04c3d1454e1ae469057 2015-06-03 23:57:53 +0200  (tag: v1.0)
+   * 
+ */ + WITH_THREE_COMMITS_AND_TWO_TAGS_CURRENTLY_ON_COMMIT_WITHOUT_TAG( + "src/test/resources/_git_three_commits_and_two_tags_currently_on_commit_without_tag"), // TODO: Why do the tests get stuck when we use .git?? - MAVEN_GIT_COMMIT_ID_PLUGIN("src/test/resources/_git_one_commit_with_umlaut") - ; + MAVEN_GIT_COMMIT_ID_PLUGIN("src/test/resources/_git_one_commit_with_umlaut"); private String dir; diff --git a/src/test/java/pl/project13/maven/git/BigDiffTest.java b/src/test/java/pl/project13/maven/git/BigDiffTest.java index ec1880b1..b06d2318 100644 --- a/src/test/java/pl/project13/maven/git/BigDiffTest.java +++ b/src/test/java/pl/project13/maven/git/BigDiffTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,27 +18,25 @@ package pl.project13.maven.git; -import junitparams.JUnitParamsRunner; -import org.apache.maven.project.MavenProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import pl.project13.core.git.GitDescribeConfig; +import static org.assertj.core.api.Assertions.assertThat; import java.io.FileOutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Properties; - -import static org.assertj.core.api.Assertions.assertThat; +import junitparams.JUnitParamsRunner; +import org.apache.maven.project.MavenProject; +import org.junit.Test; +import org.junit.runner.RunWith; +import pl.project13.core.git.GitDescribeConfig; /** * Run this to simulate hanging native-git-process for repo-state with lots of changes. * - * The test case will still finish successfully because all git-related errors are cught in. + *

The test case will still finish successfully because all git-related errors are cught in. * * @author eternach - * */ @RunWith(JUnitParamsRunner.class) public class BigDiffTest extends GitIntegrationTest { @@ -46,7 +45,8 @@ public class BigDiffTest extends GitIntegrationTest { // @Ignore("Run this to simulate hanging native-git-process for repo-state with lots of changes") public void bigDiff() throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") + mavenSandbox + .withParentProject("my-pom-project", "pom") .withChildProject("my-jar-module", "jar") .withGitRepoInChild(AvailableGitTestRepo.MAVEN_GIT_COMMIT_ID_PLUGIN) .create(); @@ -62,7 +62,10 @@ public void bigDiff() throws Exception { mojo.gitDescribe = gitDescribeConfig; for (int i = 0; i < 100000; i++) { - final Path path = Paths.get(mavenSandbox.getChildProject().getBasedir().toString(), "very-long-file-name-with-id-" + Integer.toString(i) + ".txt"); + final Path path = + Paths.get( + mavenSandbox.getChildProject().getBasedir().toString(), + "very-long-file-name-with-id-" + Integer.toString(i) + ".txt"); final byte[] bytes = "for performance test\n".getBytes(); Files.createFile(path); try (FileOutputStream fos = new FileOutputStream(path.toFile())) { @@ -77,8 +80,7 @@ public void bigDiff() throws Exception { mojo.execute(); final long estimatedTime = System.currentTimeMillis() - startTime; - System.out.println( - "[***] time: " + (double) estimatedTime + " ms"); + System.out.println("[***] time: " + (double) estimatedTime + " ms"); // then assertGitPropertiesPresentInProject(targetProject.getProperties()); @@ -101,7 +103,8 @@ private void assertGitPropertiesPresentInProject(final Properties properties) { assertThat(properties).satisfies(new ContainsKeyCondition("git.remote.origin.url")); } - private GitDescribeConfig createGitDescribeConfig(final boolean forceLongFormat, final int abbrev) { + private GitDescribeConfig createGitDescribeConfig( + final boolean forceLongFormat, final int abbrev) { final GitDescribeConfig gitDescribeConfig = new GitDescribeConfig(); gitDescribeConfig.setTags(true); gitDescribeConfig.setForceLongFormat(forceLongFormat); diff --git a/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java b/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java index c4a8deea..e172a9f2 100644 --- a/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java +++ b/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,10 +18,9 @@ package pl.project13.maven.git; -import org.assertj.core.api.Condition; - -import javax.annotation.Nonnull; import java.util.Map; +import javax.annotation.Nonnull; +import org.assertj.core.api.Condition; class ContainsKeyCondition extends Condition> { @@ -34,9 +34,11 @@ public ContainsKeyCondition(String key) { public boolean matches(@Nonnull Map map) { boolean containsKey = map.containsKey(key); if (!containsKey) { - throw new RuntimeException(String.format("Map did not contain [%s] key! Map is: %s\nValue for [%s] was: %s", key, map, key, map.get(key))); + throw new RuntimeException( + String.format( + "Map did not contain [%s] key! Map is: %s\nValue for [%s] was: %s", + key, map, key, map.get(key))); } return true; } - } diff --git a/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java b/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java index 084ffdb8..49f13b0e 100644 --- a/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java +++ b/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,10 +18,9 @@ package pl.project13.maven.git; -import org.assertj.core.api.Condition; - -import javax.annotation.Nonnull; import java.util.Map; +import javax.annotation.Nonnull; +import org.assertj.core.api.Condition; class DoesNotContainKeyCondition extends Condition> { @@ -39,5 +39,4 @@ public boolean matches(@Nonnull Map map) { } return true; } - } diff --git a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java index 5165ac78..93df7e06 100644 --- a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java +++ b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,20 +18,18 @@ package pl.project13.maven.git; -import org.apache.commons.io.FileUtils; -import org.apache.maven.project.MavenProject; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import org.apache.commons.io.FileUtils; +import org.apache.maven.project.MavenProject; /** - * Quick and dirty maven projects tree structure to create on disk during integration tests. - * Can have both parent and child projects set up. - * Copies sample git repository from prototype location to newly created project. - * Has ability to set target project for storing git repository. + * Quick and dirty maven projects tree structure to create on disk during integration tests. Can + * have both parent and child projects set up. Copies sample git repository from prototype location + * to newly created project. Has ability to set target project for storing git repository. */ public class FileSystemMavenSandbox { @@ -40,13 +39,12 @@ public class FileSystemMavenSandbox { private boolean keepSandboxWhenFinishedTest = false; /** - * Sample git repository location to use as source in integration tests - * Test should copy content of this folder to ".git" in correct destination + * Sample git repository location to use as source in integration tests Test should copy content + * of this folder to ".git" in correct destination */ private File gitRepoSourceDir; - @Nullable - private File gitRepoTargetDir; + @Nullable private File gitRepoTargetDir; public FileSystemMavenSandbox(String rootSandboxPath) { this.rootSandboxPath = rootSandboxPath; @@ -54,7 +52,8 @@ public FileSystemMavenSandbox(String rootSandboxPath) { @Nonnull public FileSystemMavenSandbox withParentProject(String parentProjectDirName, String packaging) { - parentProject = createProject(new File(rootSandboxPath + File.separator + parentProjectDirName), packaging); + parentProject = + createProject(new File(rootSandboxPath + File.separator + parentProjectDirName), packaging); return this; } @@ -66,7 +65,8 @@ public FileSystemMavenSandbox withNoChildProject() { @Nonnull public FileSystemMavenSandbox withChildProject(String childProjectDirName, String packaging) { - childProject = createProject(new File(parentProject.getBasedir(), childProjectDirName), packaging); + childProject = + createProject(new File(parentProject.getBasedir(), childProjectDirName), packaging); childProject.setParent(parentProject); return this; } @@ -109,7 +109,8 @@ public FileSystemMavenSandbox create() throws RuntimeException { return this; } catch (Exception ex) { - throw new RuntimeException(String.format("Failed creating %s...", getClass().getSimpleName()), ex); + throw new RuntimeException( + String.format("Failed creating %s...", getClass().getSimpleName()), ex); } } @@ -154,15 +155,20 @@ private MavenProject createProject(File basedir, String packaging) { @Override public String toString() { - return "FileSystemMavenSandbox{" + - "gitRepoTargetDir=" + gitRepoTargetDir + - ", gitRepoSourceDir=" + gitRepoSourceDir + - ", rootSandboxPath='" + rootSandboxPath + '\'' + - '}'; + return "FileSystemMavenSandbox{" + + "gitRepoTargetDir=" + + gitRepoTargetDir + + ", gitRepoSourceDir=" + + gitRepoSourceDir + + ", rootSandboxPath='" + + rootSandboxPath + + '\'' + + '}'; } @Nonnull - public FileSystemMavenSandbox withKeepSandboxWhenFinishedTest(boolean keepSandboxWhenFinishedTest) { + public FileSystemMavenSandbox withKeepSandboxWhenFinishedTest( + boolean keepSandboxWhenFinishedTest) { // if we want to keep the generated sandbox for overwiew the content of it this.keepSandboxWhenFinishedTest = keepSandboxWhenFinishedTest; return this; diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java index aa8bd819..28d93d10 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,6 +18,22 @@ package pl.project13.maven.git; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TimeZone; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.apache.maven.plugin.MojoExecutionException; @@ -30,15 +47,6 @@ import pl.project13.core.git.GitDescribeConfig; import pl.project13.core.util.GenericFileManager; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.*; - -import static java.util.Arrays.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.entry; -import static org.mockito.Mockito.when; - @RunWith(JUnitParamsRunner.class) public class GitCommitIdMojoIntegrationTest extends GitIntegrationTest { private static final boolean UseJGit = false; @@ -56,10 +64,11 @@ public static Collection useDirty() { @Parameters(method = "useNativeGit") public void shouldIncludeExpectedProperties(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -88,10 +97,11 @@ public void shouldIncludeExpectedProperties(boolean useNativeGit) throws Excepti @Parameters(method = "useNativeGit") public void shouldExcludeAsConfiguredProperties(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -125,14 +135,16 @@ public void shouldExcludeAsConfiguredProperties(boolean useNativeGit) throws Exc @Parameters(method = "useNativeGit") public void shouldIncludeOnlyAsConfiguredProperties(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; - mojo.includeOnlyProperties = Arrays.asList("git.remote.origin.url", ".*.user.*", "^git.commit.id.full$"); + mojo.includeOnlyProperties = + Arrays.asList("git.remote.origin.url", ".*.user.*", "^git.commit.id.full$"); // when mojo.execute(); @@ -162,10 +174,11 @@ public void shouldIncludeOnlyAsConfiguredProperties(boolean useNativeGit) throws @Parameters(method = "useNativeGit") public void shouldExcludeAndIncludeAsConfiguredProperties(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -200,12 +213,14 @@ public void shouldExcludeAndIncludeAsConfiguredProperties(boolean useNativeGit) @Test @Parameters(method = "useNativeGit") - public void shouldHaveNoPrefixWhenConfiguredPrefixIsEmptyStringAsConfiguredProperties(boolean useNativeGit) throws Exception { + public void shouldHaveNoPrefixWhenConfiguredPrefixIsEmptyStringAsConfiguredProperties( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -227,10 +242,11 @@ public void shouldHaveNoPrefixWhenConfiguredPrefixIsEmptyStringAsConfiguredPrope @Parameters(method = "useNativeGit") public void shouldSkipDescribeWhenConfiguredToDoSo(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -244,16 +260,19 @@ public void shouldSkipDescribeWhenConfiguredToDoSo(boolean useNativeGit) throws mojo.execute(); // then - assertThat(targetProject.getProperties()).satisfies(new DoesNotContainKeyCondition("git.commit.id.describe")); + assertThat(targetProject.getProperties()) + .satisfies(new DoesNotContainKeyCondition("git.commit.id.describe")); } - + @Test @Parameters(method = "useNativeGit") - public void shouldNotUseBuildEnvironmentBranchInfoWhenParameterSet(boolean useNativeGit) throws Exception { - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + public void shouldNotUseBuildEnvironmentBranchInfoWhenParameterSet(boolean useNativeGit) + throws Exception { + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -268,7 +287,7 @@ public void shouldNotUseBuildEnvironmentBranchInfoWhenParameterSet(boolean useNa when(mojo.getCustomSystemEnv()).thenReturn(env); // reset repo and force detached HEAD - try (final Git git = git("my-jar-project")) { + try (final Git git = git("my-jar-project")) { git.reset().setMode(ResetCommand.ResetType.HARD).setRef("b6a73ed").call(); git.checkout().setCreateBranch(true).setName("test_branch").setForceRefUpdate(true).call(); } @@ -291,11 +310,13 @@ public void shouldUseJenkinsBranchInfoWhenAvailable(boolean useNativeGit) throws // when // in a detached head state, getBranch() will return the SHA1...standard behavior - shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(useNativeGit, env, detachedHeadSha1); + shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + useNativeGit, env, detachedHeadSha1); // again, SHA1 will be returned if we're in jenkins, but GIT_BRANCH is not set env.put("JENKINS_URL", ciUrl); - shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(useNativeGit, env, detachedHeadSha1); + shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + useNativeGit, env, detachedHeadSha1); // now set GIT_BRANCH too and see that the branch name from env var is returned env.clear(); @@ -314,28 +335,33 @@ public void shouldUseJenkinsBranchInfoWhenAvailable(boolean useNativeGit) throws env.put("JENKINS_URL", ciUrl); env.put("GIT_BRANCH", "mybranch"); env.put("GIT_LOCAL_BRANCH", "mylocalbranch"); - shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(useNativeGit, env, "mylocalbranch"); + shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + useNativeGit, env, "mylocalbranch"); // same, but for hudson env.clear(); env.put("HUDSON_URL", ciUrl); env.put("GIT_BRANCH", "mybranch"); env.put("GIT_LOCAL_BRANCH", "mylocalbranch"); - shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(useNativeGit, env, "mylocalbranch"); + shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + useNativeGit, env, "mylocalbranch"); // GIT_BRANCH but no HUDSON_URL or JENKINS_URL env.clear(); env.put("GIT_BRANCH", "mybranch"); env.put("GIT_LOCAL_BRANCH", "mylocalbranch"); - shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(useNativeGit, env, detachedHeadSha1); + shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + useNativeGit, env, detachedHeadSha1); } - private void shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(boolean useNativeGit, Map env, String expectedBranchName) throws Exception { + private void shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch( + boolean useNativeGit, Map env, String expectedBranchName) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -359,12 +385,14 @@ private void shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(boolea @Test @Parameters(method = "useNativeGit") - public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject(boolean useNativeGit) throws Exception { + public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -380,10 +408,11 @@ public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject(boolean use @Parameters(method = "useNativeGit") public void shouldNotRunWhenSkipIsSet(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-skip-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-skip-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.skip = true; @@ -398,12 +427,14 @@ public void shouldNotRunWhenSkipIsSet(boolean useNativeGit) throws Exception { @Test @Parameters(method = "useNativeGit") - public void shouldNotRunWhenPackagingPomAndDefaultSettingsApply(boolean useNativeGit) throws Exception { + public void shouldNotRunWhenPackagingPomAndDefaultSettingsApply(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.useNativeGit = useNativeGit; @@ -419,10 +450,11 @@ public void shouldNotRunWhenPackagingPomAndDefaultSettingsApply(boolean useNativ @Parameters(method = "useNativeGit") public void shouldRunWhenPackagingPomAndSkipPomsFalse(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.skipPoms = false; @@ -437,12 +469,14 @@ public void shouldRunWhenPackagingPomAndSkipPomsFalse(boolean useNativeGit) thro @Test @Parameters(method = "useNativeGit") - public void shouldUseParentProjectRepoWhenInvokedFromChild(boolean useNativeGit) throws Exception { + public void shouldUseParentProjectRepoWhenInvokedFromChild(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); mojo.skipPoms = false; @@ -459,10 +493,11 @@ public void shouldUseParentProjectRepoWhenInvokedFromChild(boolean useNativeGit) @Parameters(method = "useNativeGit") public void shouldUseChildProjectRepoIfInvokedFromChild(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); mojo.skipPoms = false; @@ -479,10 +514,11 @@ public void shouldUseChildProjectRepoIfInvokedFromChild(boolean useNativeGit) th @Parameters(method = "useNativeGit") public void shouldFailWithExceptionWhenNoGitRepoFound(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withNoGitRepoAvailable() - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withNoGitRepoAvailable() + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); mojo.skipPoms = false; @@ -495,10 +531,11 @@ public void shouldFailWithExceptionWhenNoGitRepoFound(boolean useNativeGit) thro @Parameters(method = "useNativeGit") public void shouldGenerateCustomPropertiesFileProperties(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); String targetFilePath = "target/classes/custom-git.properties"; @@ -524,10 +561,11 @@ public void shouldGenerateCustomPropertiesFileProperties(boolean useNativeGit) t @Parameters(method = "useNativeGit") public void shouldGenerateCustomPropertiesFileJson(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); String targetFilePath = "target/classes/custom-git.properties"; @@ -544,7 +582,9 @@ public void shouldGenerateCustomPropertiesFileJson(boolean useNativeGit) throws // then assertThat(expectedFile).exists(); - Properties p = GenericFileManager.readPropertiesAsUtf8(CommitIdPropertiesOutputFormat.JSON, expectedFile); + Properties p = + GenericFileManager.readPropertiesAsUtf8( + CommitIdPropertiesOutputFormat.JSON, expectedFile); assertThat(p.size() > 10); } finally { FileUtils.forceDelete(expectedFile); @@ -553,12 +593,14 @@ public void shouldGenerateCustomPropertiesFileJson(boolean useNativeGit) throws @Test @Parameters(method = "useNativeGit") - public void shouldSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoFound(boolean useNativeGit) throws Exception { + public void shouldSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoFound(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withNoGitRepoAvailable() - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withNoGitRepoAvailable() + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.failOnNoGitDirectory = false; @@ -573,12 +615,14 @@ public void shouldSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoFound(boolean useN @Test @Parameters(method = "useNativeGit") - public void shouldNotSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoIsPresent(boolean useNativeGit) throws Exception { + public void shouldNotSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoIsPresent(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); mojo.failOnNoGitDirectory = false; @@ -593,12 +637,14 @@ public void shouldNotSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoIsPresent(boole @Test @Parameters(method = "useNativeGit") - public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalse(boolean useNativeGit) throws Exception { + public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalse(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -612,17 +658,21 @@ public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalse(boolean mojo.execute(); // then - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-dirty"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-dirty"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalseAndAbbrevLengthIsNonDefault(boolean useNativeGit) throws Exception { + public void + shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalseAndAbbrevLengthIsNonDefault( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -634,19 +684,23 @@ public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalseAndAbbrev mojo.execute(); // then - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "v1.0.0"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "v1.0.0"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe-short", "v1.0.0"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe-short", "v1.0.0"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIsTrue(boolean useNativeGit) throws Exception { + public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIsTrue( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -658,17 +712,21 @@ public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIs mojo.execute(); // then - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-0-gde4db35"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-0-gde4db35"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIsTrueAndAbbrevLengthIsNonDefault(boolean useNativeGit) throws Exception { + public void + shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIsTrueAndAbbrevLengthIsNonDefault( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -680,19 +738,22 @@ public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIs mojo.execute(); // then - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-0-gde4db35917"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "v1.0.0-0-gde4db35917"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe-short", "v1.0.0-0"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe-short", "v1.0.0-0"); } @Test @Parameters(method = "useNativeGit") public void shouldGenerateCommitIdAbbrevWithDefaultLength(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -708,12 +769,14 @@ public void shouldGenerateCommitIdAbbrevWithDefaultLength(boolean useNativeGit) @Test @Parameters(method = "useNativeGit") - public void shouldGenerateCommitIdAbbrevWithNonDefaultLength(boolean useNativeGit) throws Exception { + public void shouldGenerateCommitIdAbbrevWithNonDefaultLength(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -731,10 +794,11 @@ public void shouldGenerateCommitIdAbbrevWithNonDefaultLength(boolean useNativeGi @Parameters(method = "useNativeGit") public void shouldFormatDate(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -758,10 +822,11 @@ public void shouldFormatDate(boolean useNativeGit) throws Exception { @Parameters(method = "useNativeGit") public void shouldSkipGitDescribe(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -775,17 +840,19 @@ public void shouldSkipGitDescribe(boolean useNativeGit) throws Exception { mojo.execute(); // then - assertThat(targetProject.getProperties()).satisfies(new DoesNotContainKeyCondition("git.commit.id.describe")); + assertThat(targetProject.getProperties()) + .satisfies(new DoesNotContainKeyCondition("git.commit.id.describe")); } @Test @Parameters(method = "useNativeGit") public void shouldMarkGitDescribeAsDirty(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -800,17 +867,19 @@ public void shouldMarkGitDescribeAsDirty(boolean useNativeGit) throws Exception mojo.execute(); // then - assertThat(targetProject.getProperties()).contains(entry("git.commit.id.describe", "v1.0.0-0-gde4db35" + dirtySuffix)); + assertThat(targetProject.getProperties()) + .contains(entry("git.commit.id.describe", "v1.0.0-0-gde4db35" + dirtySuffix)); } @Test @Parameters(method = "useNativeGit") public void shouldAlwaysPrintGitDescribe(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -824,17 +893,19 @@ public void shouldAlwaysPrintGitDescribe(boolean useNativeGit) throws Exception mojo.execute(); // then - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "0b0181b"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "0b0181b"); } @Test @Parameters(method = "useNativeGit") public void shouldWorkWithEmptyGitDescribe(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -854,10 +925,11 @@ public void shouldWorkWithEmptyGitDescribe(boolean useNativeGit) throws Exceptio @Parameters(method = "useNativeGit") public void shouldWorkWithNullGitDescribe(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -876,10 +948,11 @@ public void shouldWorkWithNullGitDescribe(boolean useNativeGit) throws Exception @Parameters(method = "useNativeGit") public void shouldExtractTagsOnGivenCommit(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); try (final Git git = git("my-jar-project")) { git.reset().setMode(ResetCommand.ResetType.HARD).setRef("d37a598").call(); @@ -902,18 +975,20 @@ public void shouldExtractTagsOnGivenCommit(boolean useNativeGit) throws Exceptio assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) - .containsOnly("lightweight-tag", "newest-tag"); + .containsOnly("lightweight-tag", "newest-tag"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "2"); } @Test @Parameters(method = "useNativeGit") - public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) throws Exception { + public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); try (final Git git = git("my-jar-project")) { git.reset().setMode(ResetCommand.ResetType.HARD).setRef("9597545").call(); @@ -936,7 +1011,7 @@ public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) - .containsOnly("annotated-tag", "lightweight-tag", "newest-tag"); + .containsOnly("annotated-tag", "lightweight-tag", "newest-tag"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "1"); } @@ -944,10 +1019,11 @@ public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) @Parameters(method = "useNativeGit") public void shouldExtractTagsOnHead(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -966,27 +1042,29 @@ public void shouldExtractTagsOnHead(boolean useNativeGit) throws Exception { assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) - .containsOnly("v1.0.0"); + .containsOnly("v1.0.0"); } @Test @Parameters(method = "useNativeGit") public void runGitDescribeWithMatchOption(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-plugin-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_THREE_COMMITS_AND_TWO_TAGS_CURRENTLY_ON_COMMIT_WITHOUT_TAG) - .create(); + mavenSandbox + .withParentProject("my-plugin-project", "jar") + .withNoChildProject() + .withGitRepoInParent( + AvailableGitTestRepo.WITH_THREE_COMMITS_AND_TWO_TAGS_CURRENTLY_ON_COMMIT_WITHOUT_TAG) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); String headCommitId = "b0c6d28b3b83bf7b905321bae67d9ca4c75a203f"; - Map gitTagMap = new HashMap<>(); + Map gitTagMap = new HashMap<>(); gitTagMap.put("v1.0", "f830b5f85cad3d33ba50d04c3d1454e1ae469057"); gitTagMap.put("v2.0", "0e3495783c56589213ee5f2ae8900e2dc1b776c4"); - for (Map.Entry entry : gitTagMap.entrySet()) { + for (Map.Entry entry : gitTagMap.entrySet()) { String gitDescribeMatchNeedle = entry.getKey(); String commitIdOfMatchNeedle = entry.getValue(); @@ -1001,11 +1079,15 @@ public void runGitDescribeWithMatchOption(boolean useNativeGit) throws Exception mojo.execute(); // then - assertThat(targetProject.getProperties().stringPropertyNames()).contains("git.commit.id.describe"); - assertThat(targetProject.getProperties().getProperty("git.commit.id.describe")).startsWith(gitDescribeMatchNeedle); - - assertThat(targetProject.getProperties().stringPropertyNames()).contains("git.commit.id.full"); - assertThat(targetProject.getProperties().get("git.commit.id.full")).isNotEqualTo(commitIdOfMatchNeedle); + assertThat(targetProject.getProperties().stringPropertyNames()) + .contains("git.commit.id.describe"); + assertThat(targetProject.getProperties().getProperty("git.commit.id.describe")) + .startsWith(gitDescribeMatchNeedle); + + assertThat(targetProject.getProperties().stringPropertyNames()) + .contains("git.commit.id.full"); + assertThat(targetProject.getProperties().get("git.commit.id.full")) + .isNotEqualTo(commitIdOfMatchNeedle); assertThat(targetProject.getProperties().get("git.commit.id.full")).isEqualTo(headCommitId); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "3"); } @@ -1015,10 +1097,11 @@ public void runGitDescribeWithMatchOption(boolean useNativeGit) throws Exception @Parameters(method = "useNativeGit") public void shouldGenerateClosestTagInformationWhenOnATag(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -1034,17 +1117,20 @@ public void shouldGenerateClosestTagInformationWhenOnATag(boolean useNativeGit) // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "v1.0.0"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "0"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "0"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWhenOnATagAndDirty(boolean useNativeGit) throws Exception { + public void shouldGenerateClosestTagInformationWhenOnATagAndDirty(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -1061,18 +1147,20 @@ public void shouldGenerateClosestTagInformationWhenOnATagAndDirty(boolean useNat // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "v1.0.0"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "0"); - } - + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "0"); + } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWhenCommitHasTwoTags(boolean useNativeGit) throws Exception { + public void shouldGenerateClosestTagInformationWhenCommitHasTwoTags(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); try (final Git git = git("my-jar-project")) { git.reset().setMode(ResetCommand.ResetType.HARD).setRef("d37a598").call(); @@ -1088,26 +1176,31 @@ public void shouldGenerateClosestTagInformationWhenCommitHasTwoTags(boolean useN mojo.execute(); // then - // AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS ==> Where the newest-tag was created latest - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "newest-tag"); + // AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS ==> Where the newest-tag was created + // latest + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.name", "newest-tag"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "0"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "0"); } @Test @Parameters(method = "useNativeGit") public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); // RFC 822 time zone: Sign TwoDigitHours Minutes - String dateFormat = "Z"; // we want only the timezone (formated in RFC 822) out of the dateformat (easier for asserts) + // we want only the timezone (formated in RFC 822) out of the dateformat (easier for asserts) + String dateFormat = "Z"; String expectedTimeZoneOffset = "+0200"; String executionTimeZoneOffset = "-0800"; TimeZone expectedTimeZone = TimeZone.getTimeZone("GMT" + expectedTimeZoneOffset); @@ -1140,10 +1233,11 @@ public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception { @Parameters(method = "useNativeGit") public void shouldGenerateCommitIdOldFashioned(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.ON_A_TAG_DIRTY) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -1164,10 +1258,11 @@ public void shouldGenerateCommitIdOldFashioned(boolean useNativeGit) throws Exce @Parameters(method = "useNativeGit") public void testDetectCleanWorkingDirectory(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.GIT_WITH_NO_CHANGES) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.GIT_WITH_NO_CHANGES) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -1186,17 +1281,19 @@ public void testDetectCleanWorkingDirectory(boolean useNativeGit) throws Excepti // then Properties properties = targetProject.getProperties(); assertThat(properties.get("git.dirty")).isEqualTo("false"); - assertThat(properties).contains(entry("git.commit.id.describe", "85c2888")); // assert no dirtySuffix at the end! + assertThat(properties) + .contains(entry("git.commit.id.describe", "85c2888")); // assert no dirtySuffix at the end! } @Test @Parameters(method = "useNativeGit") public void testDetectDirtyWorkingDirectory(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) // GIT_WITH_CHANGES - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT) // GIT_WITH_CHANGES + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -1215,17 +1312,23 @@ public void testDetectDirtyWorkingDirectory(boolean useNativeGit) throws Excepti // then Properties properties = targetProject.getProperties(); assertThat(properties.get("git.dirty")).isEqualTo("true"); - assertThat(properties).contains(entry("git.commit.id.describe", "0b0181b" + dirtySuffix)); // assert dirtySuffix at the end! + assertThat(properties) + .contains( + entry( + "git.commit.id.describe", + "0b0181b" + dirtySuffix)); // assert dirtySuffix at the end! } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWithExcludeLightweightTagsForClosestTag(boolean useNativeGit) throws Exception { + public void shouldGenerateClosestTagInformationWithExcludeLightweightTagsForClosestTag( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1242,23 +1345,30 @@ public void shouldGenerateClosestTagInformationWithExcludeLightweightTagsForClos // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "b6a73ed"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "annotated-tag-2-gb6a73ed74-customDirtyMark"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), + "git.commit.id.describe", + "annotated-tag-2-gb6a73ed74-customDirtyMark"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "annotated-tag"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.name", "annotated-tag"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "2"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "2"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "3"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTag(boolean useNativeGit) throws Exception { + public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTag( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1275,21 +1385,29 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "b6a73ed"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "lightweight-tag-1-gb6a73ed74-customDirtyMark"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), + "git.commit.id.describe", + "lightweight-tag-1-gb6a73ed74-customDirtyMark"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "lightweight-tag"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.name", "lightweight-tag"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "1"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "1"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTagAndPreferAnnotatedTags(boolean useNativeGit) throws Exception { + public void + shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTagAndPreferAnnotatedTags( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1306,21 +1424,28 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "b6a73ed"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "newest-tag-1-gb6a73ed74-customDirtyMark"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), + "git.commit.id.describe", + "newest-tag-1-gb6a73ed74-customDirtyMark"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "newest-tag"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.name", "newest-tag"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "1"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "1"); } @Test @Parameters(method = "useNativeGit") - public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTagAndFilter(boolean useNativeGit) throws Exception { + public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClosestTagAndFilter( + boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_COMMIT_THAT_HAS_TWO_TAGS) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1338,21 +1463,27 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "b6a73ed"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "lightweight-tag-1-gb6a73ed74-customDirtyMark"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), + "git.commit.id.describe", + "lightweight-tag-1-gb6a73ed74-customDirtyMark"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.name", "lightweight-tag"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.name", "lightweight-tag"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.closest.tag.commit.count", "1"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.closest.tag.commit.count", "1"); } @Test @Parameters(method = "useNativeGit") public void verifyEvalOnDifferentCommitWithParentOfHead(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1369,7 +1500,8 @@ public void verifyEvalOnDifferentCommitWithParentOfHead(boolean useNativeGit) th // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "e3d159d"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "e3d159dd7"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "e3d159dd7"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.tags", "test_tag"); @@ -1380,10 +1512,11 @@ public void verifyEvalOnDifferentCommitWithParentOfHead(boolean useNativeGit) th @Parameters(method = "useNativeGit") public void verifyEvalOnDifferentCommitWithBranchName(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1400,7 +1533,8 @@ public void verifyEvalOnDifferentCommitWithBranchName(boolean useNativeGit) thro // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "9cb810e"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.branch", "test"); @@ -1415,10 +1549,11 @@ public void verifyEvalOnDifferentCommitWithBranchName(boolean useNativeGit) thro @Parameters(method = "useNativeGit") public void verifyEvalOnDifferentCommitWithTagName(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1435,9 +1570,11 @@ public void verifyEvalOnDifferentCommitWithTagName(boolean useNativeGit) throws // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "9cb810e"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.branch", "9cb810e57e2994f38c7ec6a698a31de66fdd9e24"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.branch", "9cb810e57e2994f38c7ec6a698a31de66fdd9e24"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.tags", "test_tag"); @@ -1450,10 +1587,11 @@ public void verifyEvalOnDifferentCommitWithTagName(boolean useNativeGit) throws @Parameters(method = "useNativeGit") public void verifyEvalOnDifferentCommitWithCommitHash(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1470,7 +1608,8 @@ public void verifyEvalOnDifferentCommitWithCommitHash(boolean useNativeGit) thro // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "9cb810e"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.commit.id.describe", "test_tag-0-g9cb810e57"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.branch", "test"); @@ -1485,10 +1624,11 @@ public void verifyEvalOnDifferentCommitWithCommitHash(boolean useNativeGit) thro @Parameters(method = "useNativeGit") public void verifyEvalOnCommitWithTwoBranches(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1508,17 +1648,19 @@ public void verifyEvalOnCommitWithTwoBranches(boolean useNativeGit) throws Excep // then assertPropertyPresentAndEqual(targetProject.getProperties(), "git.commit.id.abbrev", "2343428"); - assertPropertyPresentAndEqual(targetProject.getProperties(), "git.branch", "another_branch,master,z_branch"); + assertPropertyPresentAndEqual( + targetProject.getProperties(), "git.branch", "another_branch,master,z_branch"); } @Test @Parameters(method = "useNativeGit") public void verifyDetachedHeadIsNotReportedAsBranch(boolean useNativeGit) throws Exception { // given - mavenSandbox.withParentProject("my-jar-project", "jar") - .withNoChildProject() - .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) - .create(); + mavenSandbox + .withParentProject("my-jar-project", "jar") + .withNoChildProject() + .withGitRepoInParent(AvailableGitTestRepo.WITH_TAG_ON_DIFFERENT_BRANCH) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); @@ -1540,12 +1682,14 @@ public void verifyDetachedHeadIsNotReportedAsBranch(boolean useNativeGit) throws @Test @Parameters(method = "useNativeGit") - public void shouldGeneratePropertiesWithMultiplePrefixesAndReactorProject(boolean useNativeGit) throws Exception { + public void shouldGeneratePropertiesWithMultiplePrefixesAndReactorProject(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) - .withChildProject("my-child-module", "jar") - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withGitRepoInParent(AvailableGitTestRepo.ON_A_TAG) + .withChildProject("my-child-module", "jar") + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); // "my-child-two-module" setProjectToExecuteMojoIn(targetProject); @@ -1559,8 +1703,9 @@ public void shouldGeneratePropertiesWithMultiplePrefixesAndReactorProject(boolea List prefixes = Arrays.asList("prefix-one", "prefix-two"); // when // simulate plugin execution with multiple prefixes - // see https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/137#issuecomment-418144756 - for (String prefix: prefixes) { + // see + // https://github.com/git-commit-id/git-commit-id-maven-plugin/issues/137#issuecomment-418144756 + for (String prefix : prefixes) { mojo.prefix = prefix; mojo.execute(); @@ -1569,7 +1714,7 @@ public void shouldGeneratePropertiesWithMultiplePrefixesAndReactorProject(boolea // then // since we inject into all reactors both projects should have both properties Properties properties = targetProject.getProperties(); - for (String prefix: prefixes) { + for (String prefix : prefixes) { assertPropertyPresentAndEqual(properties, prefix + ".commit.id.abbrev", "de4db35"); assertPropertyPresentAndEqual(properties, prefix + ".closest.tag.name", "v1.0.0"); diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java index 8b8e2467..52fcc8b8 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,36 +18,52 @@ package pl.project13.maven.git; -import org.junit.Test; -import pl.project13.core.PropertiesFileGenerator; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; +import org.junit.Test; +import pl.project13.core.PropertiesFileGenerator; -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the git-commit-id works properly. + */ public class GitCommitIdMojoTest { @Test public void testCraftPropertiesOutputFileWithRelativePath() throws IOException { File baseDir = new File("."); String targetDir = baseDir.getCanonicalPath() + File.separator; - String generateGitPropertiesFilePath = "target" + File.separator + "classes" + File.separator + "git.properties"; + String generateGitPropertiesFilePath = + "target" + File.separator + "classes" + File.separator + "git.properties"; File generateGitPropertiesFile = new File(generateGitPropertiesFilePath); - - File result = PropertiesFileGenerator.craftPropertiesOutputFile(baseDir, generateGitPropertiesFile); - assertThat(result.getCanonicalPath()).isEqualTo( - new File(targetDir).toPath().resolve(generateGitPropertiesFilePath).toFile().getCanonicalPath()); + + File result = + PropertiesFileGenerator.craftPropertiesOutputFile(baseDir, generateGitPropertiesFile); + assertThat(result.getCanonicalPath()) + .isEqualTo( + new File(targetDir) + .toPath() + .resolve(generateGitPropertiesFilePath) + .toFile() + .getCanonicalPath()); } @Test public void testCraftPropertiesOutputFileWithFullPath() throws IOException { File baseDir = new File("."); String targetDir = baseDir.getCanonicalPath() + File.separator; - String generateGitPropertiesFilePath = targetDir + "target" + File.separator + "classes" + File.separator + "git.properties"; + String generateGitPropertiesFilePath = + targetDir + "target" + File.separator + "classes" + File.separator + "git.properties"; File generateGitPropertiesFile = new File(generateGitPropertiesFilePath); - File result = PropertiesFileGenerator.craftPropertiesOutputFile(baseDir, generateGitPropertiesFile); - assertThat(result.getCanonicalPath()).isEqualTo( - new File(targetDir).toPath().resolve(generateGitPropertiesFilePath).toFile().getCanonicalPath()); + File result = + PropertiesFileGenerator.craftPropertiesOutputFile(baseDir, generateGitPropertiesFile); + assertThat(result.getCanonicalPath()) + .isEqualTo( + new File(targetDir) + .toPath() + .resolve(generateGitPropertiesFilePath) + .toFile() + .getCanonicalPath()); } } diff --git a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java index 09e86087..e4ac9e12 100644 --- a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java +++ b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,24 +18,22 @@ package pl.project13.maven.git; -import org.apache.maven.project.MavenProject; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.nio.file.Files; import java.util.Collections; import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.maven.project.MavenProject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class GitDirLocatorTest { - @Mock - MavenProject project; + @Mock MavenProject project; List reactorProjects = Collections.emptyList(); @@ -64,7 +63,9 @@ public void testWorktreeResolution() { for (String path : noopCases) { assertThat(GitDirLocator.resolveWorktree(new File(path))).isEqualTo(new File(path)); } - assertThat(GitDirLocator.resolveWorktree(new File("a/.git/worktrees/b"))).isEqualTo(new File("a/.git")); - assertThat(GitDirLocator.resolveWorktree(new File("/a/.git/worktrees/b"))).isEqualTo(new File("/a/.git")); + assertThat(GitDirLocator.resolveWorktree(new File("a/.git/worktrees/b"))) + .isEqualTo(new File("a/.git")); + assertThat(GitDirLocator.resolveWorktree(new File("/a/.git/worktrees/b"))) + .isEqualTo(new File("/a/.git")); } } diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index 506cc56b..0beca07d 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,16 +18,10 @@ package pl.project13.maven.git; -import org.apache.commons.io.FileUtils; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; -import org.eclipse.jgit.api.Git; -import org.junit.After; -import org.junit.Before; -import pl.project13.core.CommitIdPropertiesOutputFormat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -34,17 +29,25 @@ import java.util.Optional; import java.util.Properties; import java.util.concurrent.ThreadLocalRandom; +import javax.annotation.Nonnull; +import org.apache.commons.io.FileUtils; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Settings; +import org.eclipse.jgit.api.Git; +import org.junit.After; +import org.junit.Before; +import pl.project13.core.CommitIdPropertiesOutputFormat; -import static org.mockito.Mockito.*; - +/** + * Base class for various Testcases to verify that the git-commit-id-plugin works properly. + */ public abstract class GitIntegrationTest { private static final String SANDBOX_DIR = "target" + File.separator + "sandbox" + File.separator; protected static final String evaluateOnCommit = "HEAD"; - /** - * Sandbox directory with unique name for current test. - */ + /** Sandbox directory with unique name for current test. */ private String currSandbox; protected GitCommitIdMojo mojo; @@ -55,7 +58,10 @@ public void setUp() throws Exception { // generate unique sandbox for this test File sandbox; do { - currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); + currSandbox = + SANDBOX_DIR + + "sandbox" + + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); sandbox = new File(currSandbox); } while (sandbox.exists()); @@ -150,5 +156,4 @@ private static List getReactorProjects(@Nonnull MavenProject proje } return reactorProjects; } - } diff --git a/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java b/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java index 6e792c02..bc463ad8 100644 --- a/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java +++ b/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,22 +18,25 @@ package pl.project13.maven.git; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.FileUtils; -import org.junit.Test; +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Collection; +import java.util.Properties; import junitparams.JUnitParamsRunner; import junitparams.Parameters; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.FileUtils; +import org.junit.Test; import org.junit.runner.RunWith; import pl.project13.core.CommitIdPropertiesOutputFormat; import pl.project13.core.util.GenericFileManager; -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the git-commit-id works properly. + */ @RunWith(JUnitParamsRunner.class) public class GitPropertiesFileTest extends GitIntegrationTest { @@ -45,13 +49,16 @@ public static Collection useNativeGit() { @Test @Parameters(method = "useNativeGit") - public void shouldConformPropertiesFileWhenSpecialCharactersInValueString(boolean useNativeGit) throws Exception { + public void shouldConformPropertiesFileWhenSpecialCharactersInValueString(boolean useNativeGit) + throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) - .withKeepSandboxWhenFinishedTest(false) // set true if you want to overview the result in the generated sandbox - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.WITH_ONE_COMMIT_WITH_SPECIAL_CHARACTERS) + .withKeepSandboxWhenFinishedTest( + false) // set true if you want to overview the result in the generated sandbox + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); @@ -69,27 +76,31 @@ public void shouldConformPropertiesFileWhenSpecialCharactersInValueString(boolea // then assertThat(expectedFile).exists(); - + // the git.properties should exist also among the mojo.project properties Properties propertiesInProject = mojo.project.getProperties(); assertGitPropertiesPresentInProject(propertiesInProject); - // when the properties file is conform - // it does not matter if we read as UTF-8 or ISO-8859-1 - { - Properties propertiesFromFile = GenericFileManager.readProperties( - CommitIdPropertiesOutputFormat.PROPERTIES, expectedFile, StandardCharsets.UTF_8); - assertGitPropertiesPresentInProject(propertiesFromFile); - assertThat(propertiesFromFile.get("git.commit.message.full")) - .isEqualTo(propertiesInProject.get("git.commit.message.full")); - } - { - Properties propertiesFromFile = GenericFileManager.readProperties( - CommitIdPropertiesOutputFormat.PROPERTIES, expectedFile, StandardCharsets.ISO_8859_1); - assertGitPropertiesPresentInProject(propertiesFromFile); - assertThat(propertiesFromFile.get("git.commit.message.full")) - .isEqualTo(propertiesInProject.get("git.commit.message.full")); - } + // when the properties file is conform + // it does not matter if we read as UTF-8 or ISO-8859-1 + { + Properties propertiesFromFile = + GenericFileManager.readProperties( + CommitIdPropertiesOutputFormat.PROPERTIES, expectedFile, StandardCharsets.UTF_8); + assertGitPropertiesPresentInProject(propertiesFromFile); + assertThat(propertiesFromFile.get("git.commit.message.full")) + .isEqualTo(propertiesInProject.get("git.commit.message.full")); + } + { + Properties propertiesFromFile = + GenericFileManager.readProperties( + CommitIdPropertiesOutputFormat.PROPERTIES, + expectedFile, + StandardCharsets.ISO_8859_1); + assertGitPropertiesPresentInProject(propertiesFromFile); + assertThat(propertiesFromFile.get("git.commit.message.full")) + .isEqualTo(propertiesInProject.get("git.commit.message.full")); + } } finally { if (!mavenSandbox.isKeepSandboxWhenFinishedTest()) { diff --git a/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java b/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java index 729d5b5a..b2990a6e 100644 --- a/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java +++ b/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,15 +18,18 @@ package pl.project13.maven.git; -import org.apache.maven.project.MavenProject; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; -import javax.annotation.Nonnull; import java.io.File; import java.util.Properties; +import javax.annotation.Nonnull; +import org.apache.maven.project.MavenProject; +import org.junit.Test; +import pl.project13.core.jgit.DescribeCommand; -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the git-commit-id-plugin works properly. + */ public class GitSubmodulesTest extends GitIntegrationTest { @Test @@ -66,5 +70,4 @@ private void assertGitPropertiesPresentInProject(Properties properties) { assertThat(properties).satisfies(new ContainsKeyCondition("git.commit.time")); assertThat(properties).satisfies(new ContainsKeyCondition("git.remote.origin.url")); } - } diff --git a/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java b/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java index 7b37e210..e9de42ed 100644 --- a/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java +++ b/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,20 +18,22 @@ package pl.project13.maven.git; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Properties; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.apache.maven.project.MavenProject; -import org.junit.Test; import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import pl.project13.core.git.GitDescribeConfig; -import java.util.Arrays; -import java.util.Collection; -import java.util.Properties; - -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the git-commit-id works properly. + */ @RunWith(JUnitParamsRunner.class) public class NaivePerformanceTest extends GitIntegrationTest { @@ -38,12 +41,13 @@ public class NaivePerformanceTest extends GitIntegrationTest { static final boolean UseNativeGit = true; public static Collection performanceParameter() { - return Arrays.asList(new Object[][]{ - {UseJGit, 10}, - {UseNativeGit, 10}, - {UseJGit, 100}, - {UseNativeGit, 100} - }); + return Arrays.asList( + new Object[][] { + {UseJGit, 10}, + {UseNativeGit, 10}, + {UseJGit, 100}, + {UseNativeGit, 100} + }); } @Test @@ -51,10 +55,11 @@ public static Collection performanceParameter() { @Ignore("Naive performance test - run this locally") public void performance(boolean useNativeGit, int iterations) throws Exception { // given - mavenSandbox.withParentProject("my-pom-project", "pom") - .withChildProject("my-jar-module", "jar") - .withGitRepoInChild(AvailableGitTestRepo.MAVEN_GIT_COMMIT_ID_PLUGIN) - .create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInChild(AvailableGitTestRepo.MAVEN_GIT_COMMIT_ID_PLUGIN) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); @@ -70,13 +75,18 @@ public void performance(boolean useNativeGit, int iterations) throws Exception { mojo.execute(); } long estimatedTime = System.currentTimeMillis() - startTime; - System.out.println("[***] Iterations: " + iterations + " Avg. time: " + ((double) estimatedTime) + " ms for useNativeGit=" + useNativeGit); + System.out.println( + "[***] Iterations: " + + iterations + + " Avg. time: " + + ((double) estimatedTime) + + " ms for useNativeGit=" + + useNativeGit); // then assertGitPropertiesPresentInProject(targetProject.getProperties()); } - private GitDescribeConfig createGitDescribeConfig(boolean forceLongFormat, int abbrev) { GitDescribeConfig gitDescribeConfig = new GitDescribeConfig(); gitDescribeConfig.setTags(true); diff --git a/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java b/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java index a52b17bd..f0ec603b 100644 --- a/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java +++ b/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -23,35 +24,39 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Properties; - import org.apache.maven.project.MavenProject; import org.junit.Assert; import org.junit.Test; +import pl.project13.core.jgit.DescribeResult; +/** + * Testcases to verify that the {@link DescribeResult} works properly. + */ public class NativeAndJGitProviderTest extends GitIntegrationTest { - private static final String[] GIT_KEYS = new String[] { - "git.build.time", - "git.build.host", - "git.branch", - "git.commit.id.full", - "git.commit.id.abbrev", - "git.commit.id.describe", - "git.build.user.name", - "git.build.user.email", - "git.commit.user.name", - "git.commit.user.email", - "git.commit.message.full", - "git.commit.message.short", - "git.commit.time", - "git.commit.author.time", - "git.commit.committer.time", - "git.total.commit.count", - "git.remote.origin.url", - "git.local.branch.ahead", - "git.local.branch.behind", - }; - - private static final String DEFAULT_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZ"; + private static final String[] GIT_KEYS = + new String[] { + "git.build.time", + "git.build.host", + "git.branch", + "git.commit.id.full", + "git.commit.id.abbrev", + "git.commit.id.describe", + "git.build.user.name", + "git.build.user.email", + "git.commit.user.name", + "git.commit.user.email", + "git.commit.message.full", + "git.commit.message.short", + "git.commit.time", + "git.commit.author.time", + "git.commit.committer.time", + "git.total.commit.count", + "git.remote.origin.url", + "git.local.branch.ahead", + "git.local.branch.behind", + }; + + private static final String DEFAULT_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZ"; private static final String ISO8601_FORMAT_STRING = "yyyy-MM-dd'T'HH:mm:ssZZ"; @Test @@ -59,7 +64,11 @@ public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { - mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); + mavenSandbox + .withParentProject("my-basic-project", "jar") + .withNoChildProject() + .withGitRepoInParent(testRepo) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } @@ -71,7 +80,11 @@ public void testCompareSubrepoInRoot() throws Exception { for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { // Don't create a subrepo based on the plugin repo itself. - mavenSandbox.withParentProject("my-pom-project", "pom").withChildProject("my-jar-module", "jar").withGitRepoInParent(testRepo).create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInParent(testRepo) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } @@ -83,7 +96,11 @@ public void testCompareSubrepoInChild() throws Exception { for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { // Don't create a subrepo based on the plugin repo itself. - mavenSandbox.withParentProject("my-pom-project", "pom").withChildProject("my-jar-module", "jar").withGitRepoInParent(testRepo).create(); + mavenSandbox + .withParentProject("my-pom-project", "pom") + .withChildProject("my-jar-module", "jar") + .withGitRepoInParent(testRepo) + .create(); MavenProject targetProject = mavenSandbox.getChildProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } @@ -95,14 +112,19 @@ public void testCompareIso8601Time() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { - mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); + mavenSandbox + .withParentProject("my-basic-project", "jar") + .withNoChildProject() + .withGitRepoInParent(testRepo) + .create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, ISO8601_FORMAT_STRING); } } } - private void verifyNativeAndJGit(AvailableGitTestRepo repo, MavenProject targetProject, String formatString) throws Exception { + private void verifyNativeAndJGit( + AvailableGitTestRepo repo, MavenProject targetProject, String formatString) throws Exception { setProjectToExecuteMojoIn(targetProject); mojo.skipPoms = false; @@ -122,17 +144,28 @@ private void verifyNativeAndJGit(AvailableGitTestRepo repo, MavenProject targetP assertGitPropertiesPresentInProject(nativeProps); for (String key : GIT_KEYS) { - if (!key.equals("git.build.time")) { // git.build.time is excused because the two runs happened at different times. + if (!key.equals("git.build.time")) { + // git.build.time is excused because the two runs happened at different times. String jGitKey = jgitProps.getProperty(key); String nativeKey = nativeProps.getProperty(key); - assertEquals("Key difference for key: '" + key + "'; jgit=" + jGitKey + "; nativeKey=" + nativeKey + "; for " + repo.getDir(), jGitKey, nativeKey); + assertEquals( + "Key difference for key: '" + key + "'; jgit=" + jGitKey + + "; nativeKey=" + nativeKey + "; for " + repo.getDir(), + jGitKey, + nativeKey); } else { - // Ensure that the date formats are parseable and within reason. If running all the git commands on the + // Ensure that the date formats are parseable and within reason. If running all the git + // commands on the // native provider takes more than 60 seconds, then something is seriously wrong. long jGitBuildTimeInMs = format.parse(jgitProps.getProperty(key)).getTime(); long nativeBuildTimeInMs = format.parse(nativeProps.getProperty(key)).getTime(); - Assert.assertTrue("Time ran backwards, jgitTime after nativeTime!", jGitBuildTimeInMs <= nativeBuildTimeInMs); - Assert.assertTrue("Build ran too slow.", (nativeBuildTimeInMs - jGitBuildTimeInMs) < 60000L); // If native takes more than 1 minute, something is wrong. + Assert.assertTrue( + "Time ran backwards, jgitTime after nativeTime!", + jGitBuildTimeInMs <= nativeBuildTimeInMs); + Assert.assertTrue( + "Build ran too slow.", + (nativeBuildTimeInMs - jGitBuildTimeInMs) + < 60000L); // If native takes more than 1 minute, something is wrong. } } @@ -140,7 +173,9 @@ private void verifyNativeAndJGit(AvailableGitTestRepo repo, MavenProject targetP long jGitCommitTimeInMs = format.parse(jgitProps.getProperty("git.commit.time")).getTime(); long nativeCommitTimeInMs = format.parse(nativeProps.getProperty("git.commit.time")).getTime(); - assertEquals("commit times parse to different time stamps", jGitCommitTimeInMs, nativeCommitTimeInMs); + assertEquals( + "commit times parse to different time stamps", + jGitCommitTimeInMs, nativeCommitTimeInMs); } private Properties createCopy(Properties orig) { diff --git a/src/test/java/pl/project13/maven/git/NativeProviderAheadBehindTest.java b/src/test/java/pl/project13/maven/git/NativeProviderAheadBehindTest.java index a5f0809d..9bbf05b3 100644 --- a/src/test/java/pl/project13/maven/git/NativeProviderAheadBehindTest.java +++ b/src/test/java/pl/project13/maven/git/NativeProviderAheadBehindTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 diff --git a/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java b/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java index bda62f18..909fb9aa 100644 --- a/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java +++ b/src/test/java/pl/project13/maven/git/PropertiesFiltererTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -26,14 +27,12 @@ import java.util.HashSet; import java.util.List; import java.util.Properties; - import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; - import pl.project13.core.PropertiesFilterer; import pl.project13.core.log.LogInterface; @@ -42,14 +41,11 @@ public class PropertiesFiltererTest { private static final String PREFIX_DOT = "prefix."; - @InjectMocks - private PropertiesFilterer propertiesFilterer; + @InjectMocks private PropertiesFilterer propertiesFilterer; - @Mock - private LogInterface log; + @Mock private LogInterface log; - @Mock - private Properties properties; + @Mock private Properties properties; @Test public void filterNotWithoutExclusions() { @@ -72,7 +68,10 @@ public void filterNotWithEmptyExclusions() { @Test public void filterNotRemovesOwnPropertyInExclusionAndSkipsOtherOnes() { List inclusions = Arrays.asList("^prefix\\.exclude1.*$", "^prefix\\.exclude2.*$"); - when(properties.stringPropertyNames()).thenReturn(new HashSet<>(Arrays.asList("prefix.include", "prefix.exclude1", "prefix.exclude2", "global"))); + when(properties.stringPropertyNames()) + .thenReturn( + new HashSet<>( + Arrays.asList("prefix.include", "prefix.exclude1", "prefix.exclude2", "global"))); propertiesFilterer.filterNot(properties, inclusions, PREFIX_DOT); @@ -103,7 +102,10 @@ public void filterWithEmptyInclusions() { @Test public void filterRemovesOwnPropertyNotInInclusionAndSkipsOtherOnes() { List inclusions = Arrays.asList("^prefix\\.include1.*$", "^prefix\\.include2.*$"); - when(properties.stringPropertyNames()).thenReturn(new HashSet<>(Arrays.asList("prefix.include1", "prefix.include2", "prefix.exclude", "global"))); + when(properties.stringPropertyNames()) + .thenReturn( + new HashSet<>( + Arrays.asList("prefix.include1", "prefix.include2", "prefix.exclude", "global"))); propertiesFilterer.filter(properties, inclusions, PREFIX_DOT); @@ -111,4 +113,4 @@ public void filterRemovesOwnPropertyNotInInclusionAndSkipsOtherOnes() { verify(properties).remove("prefix.exclude"); verifyNoMoreInteractions(properties); } -} \ No newline at end of file +} diff --git a/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java b/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java index e605f171..cc07ad40 100644 --- a/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java +++ b/src/test/java/pl/project13/maven/git/PropertiesReplacerTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,15 +18,11 @@ package pl.project13.maven.git; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.apache.maven.plugin.PluginParameterExpressionEvaluator; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import pl.project13.core.log.LogInterface; +import static java.util.Arrays.asList; +import static org.mockito.AdditionalAnswers.returnsFirstArg; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; @@ -34,13 +31,18 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.apache.maven.plugin.PluginParameterExpressionEvaluator; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import pl.project13.core.log.LogInterface; -import static java.util.Arrays.asList; -import static org.mockito.AdditionalAnswers.returnsFirstArg; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - +/** + * Testcases to verify that the {@link PropertiesReplacer} works properly. + */ @RunWith(JUnitParamsRunner.class) public class PropertiesReplacerTest { public static Collection useRegexReplacement() { @@ -51,9 +53,11 @@ public static Collection useRegexReplacement() { @Before public void setUp() throws Throwable { - PluginParameterExpressionEvaluator pluginParameterExpressionEvaluator = mock(PluginParameterExpressionEvaluator.class); + PluginParameterExpressionEvaluator pluginParameterExpressionEvaluator = + mock(PluginParameterExpressionEvaluator.class); when(pluginParameterExpressionEvaluator.evaluate(anyString())).then(returnsFirstArg()); - this.propertiesReplacer = new PropertiesReplacer(mock(LogInterface.class), pluginParameterExpressionEvaluator); + this.propertiesReplacer = + new PropertiesReplacer(mock(LogInterface.class), pluginParameterExpressionEvaluator); } @Test @@ -69,7 +73,8 @@ public void testPerformReplacementWithInvalidReplacement(boolean regex) throws I Properties actualProperties = build("key1", "value1", "key2", "value2"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("key1", null, null, null, regex, false, null)); + replacementProperties.add( + new ReplacementProperty("key1", null, null, null, regex, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); } @@ -80,21 +85,23 @@ public void testPerformReplacementWithSingleProperty(boolean regex) throws IOExc Properties actualProperties = build("key1", "value1", "key2", "value2"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("key1", null, "value", "another", regex, false, null)); + replacementProperties.add( + new ReplacementProperty("key1", null, "value", "another", regex, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); Properties exptecedProperties = build("key1", "another1", "key2", "value2"); assertEquals(exptecedProperties, actualProperties); } - + @Test @Parameters(method = "useRegexReplacement") public void testPerformReplacementWithSinglePropertyEmptyValue(boolean regex) throws IOException { Properties actualProperties = build("key1", "value1", "key2", "value2"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("key1", null, "value", null, regex, false, null)); + replacementProperties.add( + new ReplacementProperty("key1", null, "value", null, regex, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); @@ -108,21 +115,24 @@ public void testPerformReplacementWithMultipleProperties(boolean regex) throws I Properties actualProperties = build("key1", "value1", "key2", "value2"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty(null, null, "value", "another", regex, false, null)); + replacementProperties.add( + new ReplacementProperty(null, null, "value", "another", regex, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); Properties exptecedProperties = build("key1", "another1", "key2", "another2"); assertEquals(exptecedProperties, actualProperties); } - + @Test @Parameters(method = "useRegexReplacement") - public void testPerformReplacementWithMultiplePropertiesEmptyValue(boolean regex) throws IOException { + public void testPerformReplacementWithMultiplePropertiesEmptyValue(boolean regex) + throws IOException { Properties actualProperties = build("key1", "value1", "key2", "value2"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty(null, null, "value", null, regex, false, null)); + replacementProperties.add( + new ReplacementProperty(null, null, "value", null, regex, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); @@ -132,75 +142,136 @@ public void testPerformReplacementWithMultiplePropertiesEmptyValue(boolean regex @Test public void testPerformReplacementWithPatternGroupAndMatching() throws IOException { - Properties actualProperties = build("git.branch", "feature/feature_name", "git.commit.author", "author/name"); + Properties actualProperties = + build("git.branch", "feature/feature_name", "git.commit.author", "author/name"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("git.branch", null, "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); + replacementProperties.add( + new ReplacementProperty( + "git.branch", null, "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); - Properties exptecedProperties = build("git.branch", "feature-feature_name", "git.commit.author", "author/name"); + Properties exptecedProperties = + build("git.branch", "feature-feature_name", "git.commit.author", "author/name"); assertEquals(exptecedProperties, actualProperties); } @Test public void testPerformReplacementWithPatternGroupAndNoMatch() throws IOException { - Properties actualProperties = build("git.branch", "feature#feature_name", "git.commit.author", "author#"); + Properties actualProperties = + build("git.branch", "feature#feature_name", "git.commit.author", "author#"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("git.branch", null, "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); + replacementProperties.add( + new ReplacementProperty( + "git.branch", null, "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); - Properties exptecedProperties = build("git.branch", "feature#feature_name", "git.commit.author", "author#"); + Properties exptecedProperties = + build("git.branch", "feature#feature_name", "git.commit.author", "author#"); assertEquals(exptecedProperties, actualProperties); } @Test public void testPerformReplacementOnSinglePropertyAndExpectNewPropertyGenerated() { - Properties actualProperties = build("git.branch", "feature/feature_name", "git.commit.author", "author#"); + Properties actualProperties = + build("git.branch", "feature/feature_name", "git.commit.author", "author#"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty("git.branch", "something", "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); + replacementProperties.add( + new ReplacementProperty( + "git.branch", "something", "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); - Properties exptecedProperties = build("git.branch", "feature/feature_name", "git.branch.something", "feature-feature_name", "git.commit.author", "author#"); + Properties exptecedProperties = + build( + "git.branch", + "feature/feature_name", + "git.branch.something", + "feature-feature_name", + "git.commit.author", + "author#"); assertEquals(exptecedProperties, actualProperties); } @Test public void testPerformReplacementOnEveryPropertyAndExpectNewPropertyGenerated() { - Properties actualProperties = build("git.branch", "feature/feature_name", "git.commit.author", "author#"); + Properties actualProperties = + build("git.branch", "feature/feature_name", "git.commit.author", "author#"); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty(null, "something", "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); + replacementProperties.add( + new ReplacementProperty( + null, "something", "^([^\\/]*)\\/([^\\/]*)$", "$1-$2", true, false, null)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); - Properties exptecedProperties = build("git.branch", "feature/feature_name", "git.branch.something", "feature-feature_name", "git.commit.author", "author#", "git.commit.author.something", "author#"); + Properties exptecedProperties = + build( + "git.branch", + "feature/feature_name", + "git.branch.something", + "feature-feature_name", + "git.commit.author", + "author#", + "git.commit.author.something", + "author#"); assertEquals(exptecedProperties, actualProperties); } public static Collection testPerformReplacementWithTransformationRule() { - return Arrays.asList(new Object[][] { - { "feature/AbCdEfGh0123456789", "[^/a-z0-9\\-]", TransformationRule.ApplyEnum.BEFORE, TransformationRule.ActionEnum.LOWER_CASE, "feature/abcdefgh0123456789" }, - { "feature/AbCdEfGh0123456789", "[^/a-z0-9\\-]", TransformationRule.ApplyEnum.AFTER, TransformationRule.ActionEnum.LOWER_CASE, "feature/-b-d-f-h0123456789" }, - { "feature/AbCdEfGh0123456789", "[^/A-Z0-9\\-]", TransformationRule.ApplyEnum.BEFORE, TransformationRule.ActionEnum.UPPER_CASE, "FEATURE/ABCDEFGH0123456789" }, - { "feature/AbCdEfGh0123456789", "[^/A-Z0-9\\-]", TransformationRule.ApplyEnum.AFTER, TransformationRule.ActionEnum.UPPER_CASE, "-------/A-C-E-G-0123456789" }, - }); + return Arrays.asList( + new Object[][] { + { + "feature/AbCdEfGh0123456789", + "[^/a-z0-9\\-]", + TransformationRule.ApplyEnum.BEFORE, + TransformationRule.ActionEnum.LOWER_CASE, + "feature/abcdefgh0123456789" + }, + { + "feature/AbCdEfGh0123456789", + "[^/a-z0-9\\-]", + TransformationRule.ApplyEnum.AFTER, + TransformationRule.ActionEnum.LOWER_CASE, + "feature/-b-d-f-h0123456789" + }, + { + "feature/AbCdEfGh0123456789", + "[^/A-Z0-9\\-]", + TransformationRule.ApplyEnum.BEFORE, + TransformationRule.ActionEnum.UPPER_CASE, + "FEATURE/ABCDEFGH0123456789" + }, + { + "feature/AbCdEfGh0123456789", + "[^/A-Z0-9\\-]", + TransformationRule.ApplyEnum.AFTER, + TransformationRule.ActionEnum.UPPER_CASE, + "-------/A-C-E-G-0123456789" + }, + }); } @Test @Parameters(method = "testPerformReplacementWithTransformationRule") - public void runTransformationTestHelper(String input, String regex, TransformationRule.ApplyEnum applyRule, TransformationRule.ActionEnum actionRule, String expectedOutput) { + public void runTransformationTestHelper( + String input, + String regex, + TransformationRule.ApplyEnum applyRule, + TransformationRule.ActionEnum actionRule, + String expectedOutput) { Properties actualProperties = build("git.branch", input); List transformationRules = new ArrayList<>(); transformationRules.add(new TransformationRule(applyRule, actionRule)); List replacementProperties = new ArrayList<>(); - replacementProperties.add(new ReplacementProperty(null, null, regex, "-", true, false, transformationRules)); + replacementProperties.add( + new ReplacementProperty(null, null, regex, "-", true, false, transformationRules)); propertiesReplacer.performReplacement(actualProperties, replacementProperties); @@ -228,14 +299,13 @@ private void assertEquals(Properties expected, Properties actual) { Assert.assertNull(expected); } else { Assert.assertEquals(expected.size(), actual.size()); - for (Map.Entry expectedElementEntry: expected.entrySet()) { - String expectedKey = (String)expectedElementEntry.getKey(); - String expectedValue = (String)expectedElementEntry.getValue(); + for (Map.Entry expectedElementEntry : expected.entrySet()) { + String expectedKey = (String) expectedElementEntry.getKey(); + String expectedValue = (String) expectedElementEntry.getValue(); Assert.assertTrue(actual.containsKey(expectedKey)); String actualValue = actual.getProperty(expectedKey); Assert.assertEquals(expectedValue, actualValue); } } } - } diff --git a/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java b/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java index cb6537d5..74e48301 100644 --- a/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java +++ b/src/test/java/pl/project13/maven/jgit/DescribeCommandAbbrevIntegrationTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,6 +18,10 @@ package pl.project13.maven.jgit; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; +import javax.annotation.Nonnull; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.lib.Repository; import org.junit.Test; @@ -26,11 +31,9 @@ import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; -import javax.annotation.Nonnull; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the {@link DescribeCommand} works properly. + */ public class DescribeCommandAbbrevIntegrationTest extends GitIntegrationTest { static final String PROJECT_NAME = "my-jar-project"; @@ -42,6 +45,7 @@ protected Optional projectDir() { /** * Test for such situation: + * *

    * master!tag-test$ lg
    *   b6a73ed - (HEAD, master) third addition (8 hours ago) 

Konrad Malawski

@@ -55,10 +59,8 @@ protected Optional projectDir() { * annotated-tag-2-gb6a7 *
* - *

- * Notice that git will not use less than 4 chars for the abbrev, and in large repositories, - * it will use the abbrev so long that it's guaranteed to be unique. - *

+ *

Notice that git will not use less than 4 chars for the abbrev, and in large repositories, it + * will use the abbrev so long that it's guaranteed to be unique. */ @Test public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throws Exception { @@ -69,10 +71,11 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .abbrev(2) // 2 is enough to be unique in this small repo .call(); @@ -85,7 +88,8 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw } @Test - public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse4CharsInstead() throws Exception { + public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse4CharsInstead() + throws Exception { // given mavenSandbox .withParentProject(PROJECT_NAME, "jar") @@ -93,10 +97,11 @@ public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse .withGitRepoInParent(AvailableGitTestRepo.GIT_COMMIT_ID) .create(); - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { // when - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .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 e49c85a9..d50588c3 100644 --- a/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java +++ b/src/test/java/pl/project13/maven/jgit/DescribeCommandTagsIntegrationTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,6 +18,9 @@ package pl.project13.maven.jgit; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Optional; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.Repository; @@ -28,10 +32,9 @@ import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - +/** + * Testcases to verify that the {@link DescribeCommand} works properly. + */ public class DescribeCommandTagsIntegrationTest extends GitIntegrationTest { static final String PROJECT_NAME = "my-jar-project"; @@ -61,13 +64,13 @@ public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { // lightweight-tag // annotated-tag - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).call(); // then assertThat(res).isNotNull(); @@ -84,14 +87,13 @@ public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { // lightweight-tag // annotated-tag - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res).isNotNull(); @@ -108,12 +110,13 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { // lightweight-tag // annotated-tag - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) .tags() .match("annotated*") .call(); @@ -126,6 +129,8 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { } /** + * + * *

    * $ lg
    *   * b6a73ed - (HEAD, master) third addition (32 hours ago) 

Konrad Malawski

@@ -144,14 +149,13 @@ public void shouldFindNewerTagWhenACommitHasTwoOrMoreTags() throws Exception { // lightweight-tag // annotated-tag - try (final Git git = git(); final Repository repo = git.getRepository()) { + 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 DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res).isNotNull(); @@ -172,7 +176,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except String snapshotTag = "0.0.1-SNAPSHOT"; String latestTag = "OName-0.0.1"; - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { try (Git wrap = Git.wrap(repo)) { wrap.reset().setMode(ResetCommand.ResetType.HARD).call(); @@ -181,10 +186,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except Thread.sleep(2000); wrap.tag().setName(latestTag).call(); - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res.toString()).isEqualTo(latestTag); @@ -204,7 +207,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t String beforeTag = "OName-0.0.1"; String latestTag = "0.0.1-SNAPSHOT"; - try (final Git git = git(); final Repository repo = git.getRepository()) { + try (final Git git = git(); + final Repository repo = git.getRepository()) { try (Git wrap = Git.wrap(repo)) { wrap.reset().setMode(ResetCommand.ResetType.HARD).call(); @@ -213,10 +217,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t wrap.tag().setName(latestTag).call(); } - DescribeResult res = DescribeCommand - .on(evaluateOnCommit, repo, new DummyTestLoggerBridge()) - .tags() - .call(); + DescribeResult res = + DescribeCommand.on(evaluateOnCommit, repo, new DummyTestLoggerBridge()).tags().call(); // then assertThat(res.toString()).isEqualTo(latestTag); diff --git a/src/test/java/pl/project13/maven/jgit/JgitProviderAheadBehindTest.java b/src/test/java/pl/project13/maven/jgit/JgitProviderAheadBehindTest.java index c48b2d53..7ee220bb 100644 --- a/src/test/java/pl/project13/maven/jgit/JgitProviderAheadBehindTest.java +++ b/src/test/java/pl/project13/maven/jgit/JgitProviderAheadBehindTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,11 +18,13 @@ package pl.project13.maven.jgit; +import java.nio.file.Paths; import pl.project13.core.JGitProvider; import pl.project13.maven.git.AheadBehindTest; -import java.nio.file.Paths; - +/** + * Testcases to verify that the {@link JGitProvider} works properly. + */ public class JgitProviderAheadBehindTest extends AheadBehindTest { @Override @@ -31,6 +34,7 @@ public void extraSetup() { @Override protected JGitProvider gitProvider() { - return JGitProvider.on(Paths.get(localRepository.getRoot().getAbsolutePath(), ".git").toFile(), null); + return JGitProvider.on( + Paths.get(localRepository.getRoot().getAbsolutePath(), ".git").toFile(), null); } } diff --git a/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java b/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java index 7fef318a..33596284 100644 --- a/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java +++ b/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java @@ -1,5 +1,6 @@ /* - * This file is part of git-commit-id-maven-plugin by Konrad 'ktoso' Malawski + * This file is part of git-commit-id-maven-plugin + * Originally invented 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 @@ -17,22 +18,25 @@ package pl.project13.maven.validation; -import org.apache.maven.plugin.MojoExecutionException; - -import org.junit.Test; - import java.util.ArrayList; import java.util.List; +import org.apache.maven.plugin.MojoExecutionException; +import org.junit.Test; +/** + * Test cases to verify the {@link ValidationMojo} works properly. + */ public class ValidationMojoTest { @Test(expected = MojoExecutionException.class) - public void validationNotMatchingAndValidationShouldFailIfNoMatch() throws MojoExecutionException { + public void validationNotMatchingAndValidationShouldFailIfNoMatch() + throws MojoExecutionException { List validationProperties = getNonMatchingValidationProperties(); executeMojo(validationProperties, true); } @Test - public void validationNotMatchingAndValidationShouldNotFailIfNoMatch() throws MojoExecutionException { + public void validationNotMatchingAndValidationShouldNotFailIfNoMatch() + throws MojoExecutionException { List validationProperties = getNonMatchingValidationProperties(); executeMojo(validationProperties, false); } @@ -61,14 +65,17 @@ public void nullTests() throws MojoExecutionException { executeMojo(getListValidationProperty(null, null, ""), validationShouldFailIfNoMatch); } - private void executeMojo(List validationProperties, boolean validationShouldFailIfNoMatch) throws MojoExecutionException { + private void executeMojo( + List validationProperties, boolean validationShouldFailIfNoMatch) + throws MojoExecutionException { ValidationMojo cut = new ValidationMojo(); cut.setValidationProperties(validationProperties); cut.setValidationShouldFailIfNoMatch(validationShouldFailIfNoMatch); cut.execute(); } - private List getListValidationProperty(String name, String value, String shouldMatchTo) { + private List getListValidationProperty( + String name, String value, String shouldMatchTo) { List list = new ArrayList<>(); list.add(new ValidationProperty(name, value, shouldMatchTo)); return list;