diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index d3e2ce1f..cfc8d761 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,27 +1,17 @@ - +### Description +Please provide a brief summary of the issue and provide a summarised description in the title above. - +### Expected behavior +- Please provide a description of what you expected to happen. -### Expected Behavior - - +### Additional context +For reproducibility please provide the following: -### Current Behavior - - +- the plugin version is being used (if not included in the configuration) +- the Java-Version is being used (output of ``java -version`` and also include details about oracle-jdk VS open-jdk) +- the Maven-Version is being used (output of ``mvn --version``) +- on what Operating System you experience the bug (on Linux run ``lsb_release -a`` or ``cat /etc/*release*``) +- in what context maven is being executed (e.g. inside Windows Terminal, Powershell, Git Bash, /bin/bash, ...) +- how maven is being executed (e.g. ``mvn clean deploy`` VS ``mvn deploy:deploy``) - - - -### Steps to Reproduce (for bugs only) - - - - -### Environment (for bugs only) - - - - - - +Feel free to add any other context or screenshots about the bug. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..d272d967 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,35 @@ +--- +name: Bug report +about: Create a bug report to help us fix an issue + +--- + +### Describe the bug +Please provide a brief summary of the issue and provide a summarised description in the title above. + +### Steps to Reproduce +- Please include the **full** configuration of the plugin + +```xml + +... + +``` + +- Is there a (public) project where this issue can be reproduced? If so please provide a link. +- Include any stack-traces or any error messages + +### Expected behavior +- Please provide a description of what you expected to happen. + +### Additional context +For reproducibility please provide the following: + +- the plugin version is being used (if not included in the configuration) +- the Java-Version is being used (output of ``java -version`` and also include details about oracle-jdk VS open-jdk) +- the Maven-Version is being used (output of ``mvn --version``) +- on what Operating System you experience the bug (on Linux run ``lsb_release -a`` or ``cat /etc/*release*``) +- in what context maven is being executed (e.g. inside Windows Terminal, Powershell, Git Bash, /bin/bash, ...) +- how maven is being executed (e.g. ``mvn clean deploy`` VS ``mvn deploy:deploy``) + +Feel free to add any other context or screenshots about the bug. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..b778e852 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,16 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +### Describe your idea +Please provide a brief summary of your idea and provide a summarised description in the title above. + +### Expected Behavior +If you're suggesting a change/improvement, tell us a bit more about the problem you attempt to solve and how you idea helps to solve it. +Include a brief description of what you think should happen, maybe even how it should work and how you plan on using it. +Ex. I'm always frustrated when [...] + +### Additional context +Add any other context or screenshots about the feature request. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..91501322 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,10 @@ +### Context + + + + +### Contributor Checklist +- [ ] Added relevant integration or unit tests to verify the changes +- [ ] Update the Readme or any other documentation (including relevant Javadoc) +- [ ] Ensured that tests pass locally: `mvn clean package` +- [ ] Ensured that the code meets the current `checkstyle` coding style definition: `mvn clean verify -Pcheckstyle -Dmaven.test.skip=true -B` diff --git a/.travis.yml b/.travis.yml index c25ed9be..09b5bfe6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: java -sudo: false +sudo: true dist: trusty stages: @@ -12,20 +12,19 @@ jdk: - oraclejdk10 - oraclejdk9 - oraclejdk8 - - openjdk7 matrix: include: - stage: Integration Test - jdk: openjdk7 + jdk: oraclejdk8 env: CUSTOM_MVN_VERION="3.0" - - jdk: openjdk7 + - jdk: oraclejdk8 env: CUSTOM_MVN_VERION="3.0.5" - - jdk: openjdk7 + - jdk: oraclejdk8 env: CUSTOM_MVN_VERION="3.1.1" - - jdk: openjdk7 + - jdk: oraclejdk8 env: CUSTOM_MVN_VERION="3.2.5" - - jdk: openjdk7 + - jdk: oraclejdk8 env: CUSTOM_MVN_VERION="3.3.9" - jdk: oraclejdk9 env: CUSTOM_MVN_VERION="3.5.0" @@ -36,9 +35,9 @@ matrix: script: mvn clean verify -Pcheckstyle -Dcheckstyle.version=8.2 -Dmaven.test.skip=true -B env: CHECKSTYLE=8.2 - stage: checkstyle - jdk: openjdk7 + jdk: oraclejdk8 script: mvn clean verify -Pcheckstyle -Dmaven.test.skip=true -B - env: CHECKSTYLE=6.11.2 + env: CHECKSTYLE=8.2 install: - if [[ -n "${CUSTOM_MVN_VERION}" ]]; then diff --git a/README.md b/README.md index cef094a2..9ac7b789 100644 --- a/README.md +++ b/README.md @@ -32,13 +32,13 @@ Validate if properties are set as expected --------------------------------------------- Since version **2.2.2** the maven-git-commit-id-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. The validation can be used for *any* property that is visible inside the pom.xml and therefore can be used for a various amount of different use cases. -In order to understand the ideology and intention here are some pretty usefull ideas you could achive by using the validation: +In order to understand the ideology and intention here are some pretty useful ideas you could achieve by using the validation: * validate if the version of your project does not end with SNAPSHOT * validate if you are currently on a tag * ensure that your repository is not dirty * may other's :-) -With the current version of the validation the user can decide if the build should fail if *at least one* of the defined criterias do not match with the desired values. +With the current version of the validation the user can decide if the build should fail if *at least one* of the defined criteria do not match with the desired values. For flexibility and due to the fact that this validation has a different scope than the maven-git-commit-id-plugin this validation needs to be configured as additional execution inside the configuration of the pom.xml. Once configured, the validation is executed during the verification-phase. However since the validation is done in a separate execution the phase can easily be changed by adding the desired phase to the execution configuration. @@ -108,13 +108,18 @@ A detailed description of using the plugin is available in the Eclipse Marketplace -> Search` after restarting eclipse it should pick-up the rules automatically. If this does not work out of the box checkout the [official integration guide](http://checkstyle.sourceforge.net/eclipse.html) or use google to trace down your error message. -* IntelliJ IDEA -- for IntelliJ you would need to install the `CheckStyle-IDEA` via `File -> Settings -> Plugins -> Search`. After restarting IntelliJ you would need to import the `checkstyle` rules manually via `File -> Settings -> Checkstyle`. As checkstyle version you may choose `6.11.2` or `8.2` and then click on the plus-sign on the right. As description you may choose `maven-git-commit-id-plugin` and as local checkstyle file you may choose one of the checkstyle rule residing in `src/test/resources/checks`. Please note that the rule-file depend on the version you have selected in the previous step and thus it is essential to ensure that the version numbers match up. As next-step you unfortunately will be prompted to enter the **full directory** of the `checkstyle-suppressions.xml`-File. If this does not work out of the box checkout the [official integration guide](http://checkstyle.sourceforge.net/idea.html) or use google to trace down your error message. +* IntelliJ IDEA -- for IntelliJ you would need to install the `CheckStyle-IDEA` via `File -> Settings -> Plugins -> Search`. After restarting IntelliJ you would need to import the `checkstyle` rules manually via `File -> Settings -> Checkstyle`. As checkstyle version you may choose `8.2` and then click on the plus-sign on the right. As description you may choose `maven-git-commit-id-plugin` and as local checkstyle file you may choose one of the checkstyle rule residing in `src/test/resources/checks`. Please note that the rule-file depend on the version you have selected in the previous step and thus it is essential to ensure that the version numbers match up. As next-step you unfortunately will be prompted to enter the **full directory** of the `checkstyle-suppressions.xml`-File. If this does not work out of the box checkout the [official integration guide](http://checkstyle.sourceforge.net/idea.html) or use google to trace down your error message. * Netbeans -- feel free to open a ticket and share your installation guide :-) You can also check out the [official integration guide](http://checkstyle.sourceforge.net/netbeans.html) or use google to get any addtional help. -* Maven -- if you want to run `checkstyle` via maven you simply can execute `mvn clean verify -Pcheckstyle -Dmaven.test.skip=true -B`. If you are using java9 you may want to run `mvn clean verify -Pcheckstyle -Dcheckstyle.version=8.2 -Dmaven.test.skip=true -B` that uses a more recent checkstyle version. - -**Note**: -If you run into -``` -[ERROR] Failed to execute goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check (validate) on project git-commit-id-plugin: Execution validate of goal org.apache.maven.plugins:maven-checkstyle-plugin:2.17:check failed: Plugin org.apache.maven.plugins:maven-checkstyle-plugin:2.17 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:1.7.0 at specified path /usr/lib/jvm/java-9-oracle/../lib/tools.jar -> [Help 1] -``` -you may want to check that your ``JAVA_HOME``-Path is set correctly and that your are running `mvn clean verify -Pcheckstyle -Dcheckstyle.version=8.2 -Dmaven.test.skip=true -B`. +* Maven -- if you want to run `checkstyle` via maven you simply can execute `mvn clean verify -Pcheckstyle -Dmaven.test.skip=true -B`. Maintainers =========== diff --git a/pom.xml b/pom.xml index 16d91f21..6e786f58 100644 --- a/pom.xml +++ b/pom.xml @@ -52,14 +52,14 @@ UTF-8 UTF-8 - 1.7 + 1.8 3.0 3.5 - 4.5.4.201711221230-r - 4.12 - 2.19.0 + 5.0.2.201807311906-r + 5.2.0 + 2.21.0 1.4 @@ -102,14 +102,7 @@ com.google.guava guava - 19.0 - - - - - com.intellij - annotations - 12.0 + 26.0-jre @@ -121,8 +114,8 @@ - junit - junit + org.junit.jupiter + junit-jupiter-api ${junit.version} test @@ -209,11 +202,11 @@ maven-assembly-plugin - 2.6 + 3.1.0 maven-dependency-plugin - 2.10 + 3.1.1 maven-release-plugin @@ -225,7 +218,7 @@ maven-compiler-plugin - 3.3 + 3.8.0 maven-gpg-plugin @@ -233,15 +226,15 @@ maven-clean-plugin - 3.0.0 + 3.1.0 maven-resources-plugin - 2.7 + 3.1.0 maven-jar-plugin - 3.0.2 + 3.1.0 maven-plugin-plugin @@ -249,7 +242,7 @@ maven-surefire-plugin - 2.19.1 + 2.22.0 maven-install-plugin @@ -261,7 +254,7 @@ maven-site-plugin - 3.4 + 3.7.1 @@ -275,6 +268,7 @@ ${java.target} ${java.target} + -Xlint:deprecation @@ -429,9 +423,9 @@ checkstyle - 2.17 + 3.0.0 - 6.11.2 + 8.2 diff --git a/src/main/java/pl/project13/jgit/DescribeCommand.java b/src/main/java/pl/project13/jgit/DescribeCommand.java index effb5638..172b995e 100644 --- a/src/main/java/pl/project13/jgit/DescribeCommand.java +++ b/src/main/java/pl/project13/jgit/DescribeCommand.java @@ -18,7 +18,6 @@ package pl.project13.jgit; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import org.eclipse.jgit.api.GitCommand; @@ -27,12 +26,13 @@ import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import pl.project13.maven.git.GitDescribeConfig; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.util.Pair; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.util.*; /** @@ -51,7 +51,7 @@ public class DescribeCommand extends GitCommand { // private Optional candidatesOption = Optional.of(10); // private boolean exactMatchFlag = false; - private Optional matchOption = Optional.absent(); + private Optional matchOption = Optional.empty(); /** * How many chars of the commit hash should be displayed? 7 is the default used by git. @@ -74,7 +74,7 @@ public class DescribeCommand extends GitCommand { /** * The string marker (such as "DEV") to be suffixed to the describe result when the working directory is dirty */ - private Optional dirtyOption = Optional.absent(); + private Optional dirtyOption = Optional.empty(); /** * Creates a new describe command which interacts with a single repository @@ -82,7 +82,7 @@ public class DescribeCommand extends GitCommand { * @param repo the {@link Repository} this command should interact with * @param log logger bridge to direct logs to */ - @NotNull + @Nonnull public static DescribeCommand on(String evaluateOnCommit, Repository repo, LoggerBridge log) { return new DescribeCommand(evaluateOnCommit, repo, log); } @@ -92,7 +92,7 @@ public static DescribeCommand on(String evaluateOnCommit, Repository repo, Logge * * @param repo the {@link org.eclipse.jgit.lib.Repository} this command should interact with */ - private DescribeCommand(@NotNull String evaluateOnCommit, @NotNull Repository repo, @NotNull LoggerBridge log) { + private DescribeCommand(@Nonnull String evaluateOnCommit, @Nonnull Repository repo, @Nonnull LoggerBridge log) { super(repo); this.evaluateOnCommit = evaluateOnCommit; this.jGitCommon = new JGitCommon(log); @@ -106,7 +106,7 @@ private DescribeCommand(@NotNull String evaluateOnCommit, @NotNull Repository re * *
true
by default. */ - @NotNull + @Nonnull public DescribeCommand always(boolean always) { this.alwaysFlag = always; log.info("--always = {}", always); @@ -124,7 +124,7 @@ public DescribeCommand always(boolean always) { * *
false
by default. */ - @NotNull + @Nonnull public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) { if (forceLongFormat != null && forceLongFormat) { this.forceLongFormat = true; @@ -141,7 +141,7 @@ public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) { * * An `n` of 0 will suppress long format, only showing the closest tag. */ - @NotNull + @Nonnull public DescribeCommand abbrev(@Nullable Integer n) { if (n != null) { Preconditions.checkArgument(n < 41, String.format("N (commit abbrev length) must be < 41. (Was:[%s])", n)); @@ -180,7 +180,7 @@ public DescribeCommand abbrev(@Nullable Integer n) { * tags to be included in the search, enable this option. *

*/ - @NotNull + @Nonnull public DescribeCommand tags(@Nullable Boolean includeLightweightTagsInSearch) { if (includeLightweightTagsInSearch != null && includeLightweightTagsInSearch) { tagsFlag = includeLightweightTagsInSearch; @@ -202,7 +202,7 @@ public DescribeCommand tags() { * * @return itself, after applying the settings */ - @NotNull + @Nonnull public DescribeCommand apply(@Nullable GitDescribeConfig config) { if (config != null) { always(config.isAlways()); @@ -223,10 +223,10 @@ public DescribeCommand apply(@Nullable GitDescribeConfig config) { * @param dirtyMarker the marker name to be appended to the describe output when the workspace is dirty * @return itself, to allow fluent configuration */ - @NotNull + @Nonnull public DescribeCommand dirty(@Nullable String dirtyMarker) { - Optional option = Optional.fromNullable(dirtyMarker); - log.info("--dirty = {}", option.or("")); + Optional option = Optional.ofNullable(dirtyMarker); + log.info("--dirty = {}", option.orElse("")); this.dirtyOption = option; return this; } @@ -238,11 +238,11 @@ public DescribeCommand dirty(@Nullable String dirtyMarker) { * @param pattern the glob style pattern to match against the tag names * @return itself, to allow fluent configuration */ - @NotNull + @Nonnull public DescribeCommand match(@Nullable String pattern) { if (!"*".equals(pattern)) { - matchOption = Optional.fromNullable(pattern); - log.info("--match = {}", matchOption.or("")); + matchOption = Optional.ofNullable(pattern); + log.info("--match = {}", matchOption.orElse("")); } return this; } @@ -328,7 +328,7 @@ private DescribeResult createDescribeResult(ObjectReader objectReader, ObjectId } } - private static boolean foundZeroTags(@NotNull Map> tags) { + private static boolean foundZeroTags(@Nonnull Map> tags) { return tags.isEmpty(); } @@ -338,11 +338,11 @@ boolean findDirtyState(Repository repo) throws GitAPIException { } @VisibleForTesting - static boolean hasTags(ObjectId headCommit, @NotNull Map> tagObjectIdToName) { + static boolean hasTags(ObjectId headCommit, @Nonnull Map> tagObjectIdToName) { return tagObjectIdToName.containsKey(headCommit); } - RevCommit findEvalCommitObjectId(@NotNull String evaluateOnCommit, @NotNull Repository repo) throws RuntimeException { + RevCommit findEvalCommitObjectId(@Nonnull String evaluateOnCommit, @Nonnull Repository repo) throws RuntimeException { return jGitCommon.findEvalCommitObjectId(evaluateOnCommit, repo); } diff --git a/src/main/java/pl/project13/jgit/DescribeResult.java b/src/main/java/pl/project13/jgit/DescribeResult.java index 7faf8567..69b98991 100644 --- a/src/main/java/pl/project13/jgit/DescribeResult.java +++ b/src/main/java/pl/project13/jgit/DescribeResult.java @@ -17,19 +17,16 @@ package pl.project13.jgit; -import com.google.common.base.Joiner; -import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; + import org.eclipse.jgit.lib.AbbreviatedObjectId; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectReader; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; /** * Represents the result of a git describe command. @@ -38,10 +35,10 @@ */ public class DescribeResult { - private Optional tagName = Optional.absent(); + private Optional tagName = Optional.empty(); - private Optional commitId = Optional.absent(); - private Optional abbreviatedObjectId = Optional.absent(); + private Optional commitId = Optional.empty(); + private Optional abbreviatedObjectId = Optional.empty(); private int abbrev = 7; private int commitsAwayFromTag; @@ -55,49 +52,49 @@ public class DescribeResult { public static final DescribeResult EMPTY = new DescribeResult(""); - public DescribeResult(@NotNull String tagName) { - this(tagName, false, Optional.absent()); + public DescribeResult(@Nonnull String tagName) { + this(tagName, false, Optional.empty()); } - public DescribeResult(@NotNull ObjectReader objectReader, String tagName, int commitsAwayFromTag, @NotNull ObjectId commitId) { - this(objectReader, tagName, commitsAwayFromTag, commitId, false, Optional.absent(), false); + public DescribeResult(@Nonnull ObjectReader objectReader, String tagName, int commitsAwayFromTag, @Nonnull ObjectId commitId) { + this(objectReader, tagName, commitsAwayFromTag, commitId, false, Optional.empty(), false); } - public DescribeResult(@NotNull ObjectReader objectReader, @NotNull ObjectId commitId) { + public DescribeResult(@Nonnull ObjectReader objectReader, @Nonnull ObjectId commitId) { this.objectReader = objectReader; this.commitId = Optional.of(commitId); this.abbreviatedObjectId = createAbbreviatedCommitId(objectReader, commitId, this.abbrev); } - public DescribeResult(@NotNull ObjectReader objectReader, String tagName, int commitsAwayFromTag, ObjectId commitId, boolean dirty, String dirtyMarker) { + public DescribeResult(@Nonnull ObjectReader objectReader, String tagName, int commitsAwayFromTag, ObjectId commitId, boolean dirty, String dirtyMarker) { this(objectReader, tagName, commitsAwayFromTag, commitId, dirty, Optional.of(dirtyMarker), false); } - public DescribeResult(@NotNull ObjectReader objectReader, String tagName, int commitsAwayFromTag, ObjectId commitId, boolean dirty, Optional dirtyMarker, boolean forceLongFormat) { + public DescribeResult(@Nonnull ObjectReader objectReader, String tagName, int commitsAwayFromTag, ObjectId commitId, boolean dirty, Optional dirtyMarker, boolean forceLongFormat) { this(objectReader, commitId, dirty, dirtyMarker); this.tagName = Optional.of(tagName); this.commitsAwayFromTag = commitsAwayFromTag; this.forceLongFormat = forceLongFormat; } - public DescribeResult(@NotNull ObjectReader objectReader, @NotNull ObjectId commitId, boolean dirty, @NotNull Optional dirtyMarker) { + public DescribeResult(@Nonnull ObjectReader objectReader, @Nonnull ObjectId commitId, boolean dirty, @Nonnull Optional dirtyMarker) { this.objectReader = objectReader; this.commitId = Optional.of(commitId); this.abbreviatedObjectId = createAbbreviatedCommitId(objectReader, commitId, this.abbrev); this.dirty = dirty; - this.dirtyMarker = dirtyMarker.or(""); + this.dirtyMarker = dirtyMarker.orElse(""); } - public DescribeResult(@NotNull String tagName, boolean dirty, @NotNull Optional dirtyMarker) { + public DescribeResult(@Nonnull String tagName, boolean dirty, @Nonnull Optional dirtyMarker) { this.tagName = Optional.of(tagName); this.dirty = dirty; - this.dirtyMarker = dirtyMarker.or(""); + this.dirtyMarker = dirtyMarker.orElse(""); } - @NotNull + @Nonnull public DescribeResult withCommitIdAbbrev(int n) { Preconditions.checkArgument(n >= 0, String.format("The --abbrev parameter must be >= 0, but it was: [%s]", n)); this.abbrev = n; @@ -139,7 +136,9 @@ public String toString() { parts = new ArrayList<>(Arrays.asList(tag(), commitsAwayFromTag(), prefixedCommitId())); } - return Joiner.on("-").skipNulls().join(parts) + dirtyMarker(); // like in the describe spec the entire "-dirty" is configurable (incl. "-") + final StringJoiner sj = new StringJoiner("-"); + parts.stream().filter(Objects::nonNull).forEach(sj::add); + return sj.toString() + dirtyMarker(); // like in the describe spec the entire "-dirty" is configurable (incl. "-") } private boolean abbrevZeroHidesCommitsPartOfDescribe() { @@ -208,17 +207,17 @@ private String gPrefixedCommitId(String name) { * * @return the abbreviated commit id, possibly longer than the requested len (if it wouldn't be unique) */ - private static Optional createAbbreviatedCommitId(@NotNull ObjectReader objectReader, ObjectId commitId, int requestedLength) { + private static Optional createAbbreviatedCommitId(@Nonnull ObjectReader objectReader, ObjectId commitId, int requestedLength) { if (requestedLength < 2) { // 0 means we don't want to print commit id's at all - return Optional.absent(); + return Optional.empty(); } try { AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(commitId, requestedLength); return Optional.of(abbreviatedObjectId); } catch (IOException e) { - return Optional.absent(); + return Optional.empty(); } } @@ -233,6 +232,6 @@ public ObjectId commitObjectId() { @Nullable public String tag() { - return tagName.orNull(); + return tagName.orElse(null); } } diff --git a/src/main/java/pl/project13/jgit/JGitCommon.java b/src/main/java/pl/project13/jgit/JGitCommon.java index 62e91768..a60ad218 100644 --- a/src/main/java/pl/project13/jgit/JGitCommon.java +++ b/src/main/java/pl/project13/jgit/JGitCommon.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.*; import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Status; @@ -31,19 +32,16 @@ import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTag; import org.eclipse.jgit.revwalk.RevWalk; -import org.jetbrains.annotations.NotNull; import pl.project13.jgit.dummy.DatedRevTag; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Lists; import pl.project13.maven.git.GitDescribeConfig; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.util.Pair; +import javax.annotation.Nonnull; + public class JGitCommon { private final LoggerBridge log; @@ -63,38 +61,32 @@ public Collection getTags(Repository repo, final ObjectId objectId) thro } private Collection getTags(final Git git, final ObjectId objectId, final RevWalk finalWalk) throws GitAPIException { - List tagRefs = git.tagList().call(); - Collection tagsForHeadCommit = Collections2.filter(tagRefs, new Predicate() { - @Override - public boolean apply(Ref tagRef) { - try { - final RevCommit tagCommit = finalWalk.parseCommit(tagRef.getObjectId()); - final RevCommit objectCommit = finalWalk.parseCommit(objectId); - if (finalWalk.isMergedInto(objectCommit, tagCommit)) { - return true; - } - } catch (Exception ignored) { - log.debug("Failed while getTags [{}] -- ", tagRef, ignored); - } - return false; - } - }); - Collection tags = Collections2.transform(tagsForHeadCommit, new Function() { - @Override public String apply(Ref input) { - return input.getName().replaceAll("refs/tags/", ""); - } - }); - return tags; + return git.tagList().call() + .stream() + .filter(tagRef -> { + try { + final RevCommit tagCommit = finalWalk.parseCommit(tagRef.getObjectId()); + final RevCommit objectCommit = finalWalk.parseCommit(objectId); + if (finalWalk.isMergedInto(objectCommit, tagCommit)) { + return true; + } + } catch (Exception ignored) { + log.debug("Failed while getTags [{}] -- ", tagRef, ignored); + } + return false; + }) + .map(tagRef -> trimFullTagName(tagRef.getName())) + .collect(Collectors.toList()); } - public String getClosestTagName(@NotNull String evaluateOnCommit, @NotNull Repository repo, GitDescribeConfig gitDescribe) { + public String getClosestTagName(@Nonnull String evaluateOnCommit, @Nonnull Repository repo, GitDescribeConfig gitDescribe) { // TODO: Why does some tests fail when it gets headCommit from JGitprovider? RevCommit headCommit = findEvalCommitObjectId(evaluateOnCommit, repo); Pair pair = getClosestRevCommit(repo, headCommit, gitDescribe); return pair.second; } - public String getClosestTagCommitCount(@NotNull String evaluateOnCommit, @NotNull Repository repo, GitDescribeConfig gitDescribe) { + public String getClosestTagCommitCount(@Nonnull String evaluateOnCommit, @Nonnull Repository repo, GitDescribeConfig gitDescribe) { // TODO: Why does some tests fail when it gets headCommit from JGitprovider? RevCommit headCommit = findEvalCommitObjectId(evaluateOnCommit, repo); Pair pair = getClosestRevCommit(repo, headCommit, gitDescribe); @@ -103,7 +95,7 @@ public String getClosestTagCommitCount(@NotNull String evaluateOnCommit, @NotNul return String.valueOf(distance); } - private Pair getClosestRevCommit(@NotNull Repository repo, RevCommit headCommit, GitDescribeConfig gitDescribe) { + private Pair getClosestRevCommit(@Nonnull Repository repo, RevCommit headCommit, GitDescribeConfig gitDescribe) { boolean includeLightweightTags = false; String matchPattern = ".*"; if (gitDescribe != null) { @@ -130,7 +122,7 @@ protected String createMatchPattern(String pattern) { "\\E$"; } - protected Map> findTagObjectIds(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern) { + protected Map> findTagObjectIds(@Nonnull Repository repo, boolean includeLightweightTags, String matchPattern) { Map> commitIdsToTags = getCommitIdsToTags(repo, includeLightweightTags, matchPattern); Map> commitIdsToTagNames = transformRevTagsMapToDateSortedTagNames(commitIdsToTags); log.info("Created map: [{}]", commitIdsToTagNames); @@ -138,7 +130,7 @@ protected Map> findTagObjectIds(@NotNull Repository repo, return commitIdsToTagNames; } - protected RevCommit findEvalCommitObjectId(@NotNull String evaluateOnCommit, @NotNull Repository repo) throws RuntimeException { + protected RevCommit findEvalCommitObjectId(@Nonnull String evaluateOnCommit, @Nonnull Repository repo) throws RuntimeException { try { ObjectId evalCommitId = repo.resolve(evaluateOnCommit); @@ -154,7 +146,7 @@ protected RevCommit findEvalCommitObjectId(@NotNull String evaluateOnCommit, @No } } - protected Map> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern) { + protected Map> getCommitIdsToTags(@Nonnull Repository repo, boolean includeLightweightTags, String matchPattern) { Map> commitIdsToTags = new HashMap<>(); try (RevWalk walk = new RevWalk(repo)) { @@ -235,35 +227,23 @@ protected HashMap> transformRevTagsMapToDateSortedTagName } private List transformRevTagsMapEntryToDateSortedTagNames(Map.Entry> objectIdListEntry) { - List tags = objectIdListEntry.getValue(); - - List newTags = new ArrayList<>(tags); - Collections.sort(newTags, datedRevTagComparator()); - - List tagNames = Lists.transform(newTags, new Function() { - @Override - public String apply(DatedRevTag input) { - return trimFullTagName(input.tagName); - } - }); - return tagNames; + return objectIdListEntry.getValue() + .stream() + .sorted(datedRevTagComparator()) + .map(datedRevTag -> trimFullTagName(datedRevTag.tagName)) + .collect(Collectors.toList()); } private Comparator datedRevTagComparator() { - return new Comparator() { - @Override - public int compare(DatedRevTag revTag, DatedRevTag revTag2) { - return revTag2.date.compareTo(revTag.date); - } - }; + return (revTag, revTag2) -> revTag2.date.compareTo(revTag.date); } @VisibleForTesting - protected String trimFullTagName(@NotNull String tagName) { + protected String trimFullTagName(@Nonnull String tagName) { return tagName.replaceFirst("refs/tags/", ""); } - public List findCommitsUntilSomeTag(Repository repo, RevCommit head, @NotNull Map> tagObjectIdToName) { + public List findCommitsUntilSomeTag(Repository repo, RevCommit head, @Nonnull Map> tagObjectIdToName) { try (RevWalk revWalk = new RevWalk(repo)) { revWalk.markStart(head); @@ -289,7 +269,7 @@ public List findCommitsUntilSomeTag(Repository repo, RevCommit head, * @return distance (number of commits) between the given commits * @see
mdonoughe/jgit-describe/blob/master/src/org/mdonoughe/JGitDescribeTask.java */ - protected int distanceBetween(@NotNull Repository repo, @NotNull RevCommit child, @NotNull RevCommit parent) { + protected int distanceBetween(@Nonnull Repository repo, @Nonnull RevCommit child, @Nonnull RevCommit parent) { try (RevWalk revWalk = new RevWalk(repo)) { revWalk.markStart(child); @@ -336,7 +316,7 @@ protected int distanceBetween(@NotNull Repository repo, @NotNull RevCommit child } } - private void seeAllParents(@NotNull RevWalk revWalk, RevCommit child, @NotNull Set seen) throws IOException { + private void seeAllParents(@Nonnull RevWalk revWalk, RevCommit child, @Nonnull Set seen) throws IOException { Queue q = new ArrayDeque<>(); q.add(child); diff --git a/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java b/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java index f59634d0..bde8fb72 100644 --- a/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java +++ b/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java @@ -19,5 +19,5 @@ public enum CommitIdGenerationMode { FULL, - FLAT; + FLAT } diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 70453489..fa294f2c 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -17,7 +17,6 @@ package pl.project13.maven.git; -import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -41,22 +40,20 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.io.Closeables; import com.google.common.io.Files; import java.io.OutputStream; import pl.project13.maven.git.build.BuildServerDataProvider; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.log.MavenLoggerBridge; -import pl.project13.maven.git.util.PropertyManager; import pl.project13.maven.git.util.SortedProperties; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * Puts git build-time information into property files or maven's properties. * @@ -64,7 +61,6 @@ */ @Mojo(name = "revision", defaultPhase = LifecyclePhase.INITIALIZE, threadSafe = true) public class GitCommitIdMojo extends AbstractMojo { - // TODO fix access modifier /** * The Maven Project. */ @@ -75,13 +71,13 @@ public class GitCommitIdMojo extends AbstractMojo { * The list of projects in the reactor. */ @Parameter(defaultValue = "${reactorProjects}", readonly = true) - private List reactorProjects; + List reactorProjects; /** * The Maven Session Object. */ @Parameter(property = "session", required = true, readonly = true) - private MavenSession session; + MavenSession session; /** *

Set this to {@code 'true'} to inject git properties into all reactor projects, not just the current one.

@@ -91,27 +87,27 @@ public class GitCommitIdMojo extends AbstractMojo { *

*/ @Parameter(defaultValue = "false") - private boolean injectAllReactorProjects; + boolean injectAllReactorProjects; /** * Set this to {@code 'true'} to print more info while scanning for paths. * It will make git-commit-id "eat its own dog food" :-) */ @Parameter(defaultValue = "false") - private boolean verbose; + boolean verbose; /** * Set this to {@code 'false'} to execute plugin in 'pom' packaged projects. */ @Parameter(defaultValue = "true") - private boolean skipPoms; + boolean skipPoms; /** * Set this to {@code 'true'} to generate {@code 'git.properties'} file. * By default plugin only adds properties to maven project properties. */ @Parameter(defaultValue = "false") - private boolean generateGitPropertiesFile; + boolean generateGitPropertiesFile; /** *

The location of {@code 'git.properties'} file. Set {@code 'generateGitPropertiesFile'} to {@code 'true'} @@ -120,20 +116,20 @@ public class GitCommitIdMojo extends AbstractMojo { *

The path here is relative to your project src directory.

*/ @Parameter(defaultValue = "${project.build.outputDirectory}/git.properties") - private String generateGitPropertiesFilename; + String generateGitPropertiesFilename; /** * The root directory of the repository we want to check. */ @Parameter(defaultValue = "${project.basedir}/.git") - private File dotGitDirectory; + File dotGitDirectory; /** * Configuration for the {@code 'git-describe'} command. * You can modify the dirty marker, abbrev length and other options here. */ @Parameter - private GitDescribeConfig gitDescribe; + GitDescribeConfig gitDescribe; /** *

Minimum length of {@code 'git.commit.id.abbrev'} property. @@ -149,19 +145,19 @@ public class GitCommitIdMojo extends AbstractMojo { * */ @Parameter(defaultValue = "7") - private int abbrevLength; + int abbrevLength; /** * The format to save properties in: {@code 'properties'} or {@code 'json'}. */ @Parameter(defaultValue = "properties") - private String format; + String format; /** * The prefix to expose the properties on. For example {@code 'git'} would allow you to access {@code ${git.branch}}. */ @Parameter(defaultValue = "git") - private String prefix; + String prefix; // prefix with dot appended if needed private String prefixDot = ""; @@ -169,7 +165,7 @@ public class GitCommitIdMojo extends AbstractMojo { * The date format to be used for any dates exported by this plugin. It should be a valid {@link SimpleDateFormat} string. */ @Parameter(defaultValue = "yyyy-MM-dd'T'HH:mm:ssZ") - private String dateFormat; + String dateFormat; /** *

The timezone used in the date format of dates exported by this plugin. @@ -179,13 +175,13 @@ public class GitCommitIdMojo extends AbstractMojo { * Please review https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html for more information on this issue.

*/ @Parameter - private String dateFormatTimeZone; + String dateFormatTimeZone; /** * Set this to {@code 'false'} to continue the build on missing {@code '.git'} directory. */ @Parameter(defaultValue = "true") - private boolean failOnNoGitDirectory; + boolean failOnNoGitDirectory; /** *

Set this to {@code 'false'} to continue the build even if unable to get enough data for a complete run. @@ -198,7 +194,7 @@ public class GitCommitIdMojo extends AbstractMojo { * for a rationale behind this flag.

*/ @Parameter(defaultValue = "true") - private boolean failOnUnableToExtractRepoInfo; + boolean failOnUnableToExtractRepoInfo; /** * Set this to {@code 'true'} to use native Git executable to fetch information about the repository. @@ -207,14 +203,14 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.1.9 */ @Parameter(defaultValue = "false") - private boolean useNativeGit; + boolean useNativeGit; /** * Set this to {@code 'true'} to skip plugin execution. * @since 2.1.8 */ @Parameter(defaultValue = "false") - private boolean skip; + boolean skip; /** @@ -238,7 +234,7 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.1.12 */ @Parameter(defaultValue = "false") - private boolean runOnlyOnce; + boolean runOnlyOnce; /** *

List of properties to exclude from the resulting file. @@ -252,7 +248,7 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.1.9 */ @Parameter - private List excludeProperties; + List excludeProperties; /** *

List of properties to include into the resulting file. Only properties specified here will be included. @@ -265,7 +261,7 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.1.14 */ @Parameter - private List includeOnlyProperties; + List includeOnlyProperties; /** *

The mode of {@code 'git.commit.id'} property generation.

@@ -288,7 +284,7 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.2.0 */ @Parameter(defaultValue = "flat") - private String commitIdGenerationMode; + String commitIdGenerationMode; private CommitIdGenerationMode commitIdGenerationModeEnum; /** @@ -300,7 +296,7 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.2.3 */ @Parameter - @VisibleForTesting List replacementProperties; + List replacementProperties; /** * Allow to tell the plugin what commit should be used as reference to generate the properties from. @@ -316,9 +312,17 @@ public class GitCommitIdMojo extends AbstractMojo { * @since 2.2.4 */ @Parameter(defaultValue = "HEAD") - private String evaluateOnCommit; + String evaluateOnCommit; protected static final Pattern allowedCharactersForEvaluateOnCommit = Pattern.compile("[a-zA-Z0-9\\_\\-\\^\\/\\.]+"); + /** + * Allow to specify a timeout (in milliseconds) for fetching information with the native Git executable. + * Note that {@code useNativeGit} needs to be set to {@code 'true'} to use native Git executable. + * @since 3.0.0 + */ + @Parameter(defaultValue = "30000") + long nativeGitTimeoutInMs; + /** * The properties we store our data in and then expose them. */ @@ -329,13 +333,14 @@ public class GitCommitIdMojo extends AbstractMojo { */ private Charset sourceCharset = StandardCharsets.UTF_8; - @NotNull + @Nonnull private final LoggerBridge log = new MavenLoggerBridge(this, false); - @NotNull + @Nonnull private PropertiesFilterer propertiesFilterer = new PropertiesFilterer(log); - @NotNull @VisibleForTesting PropertiesReplacer propertiesReplacer = new PropertiesReplacer(log); + @Nonnull + PropertiesReplacer propertiesReplacer = new PropertiesReplacer(log); @Override public void execute() throws MojoExecutionException { @@ -404,7 +409,6 @@ public void execute() throws MojoExecutionException { loadGitData(properties); loadBuildData(properties); - loadShortDescribe(properties); propertiesReplacer.performReplacement(properties, replacementProperties); propertiesFilterer.filter(properties, includeOnlyProperties, this.prefixDot); propertiesFilterer.filterNot(properties, excludeProperties, this.prefixDot); @@ -472,7 +476,7 @@ private void appendPropertiesToReactorProjects() { * * @return the File representation of the .git directory */ - @VisibleForTesting File lookupGitDirectory() throws GitCommitIdExecutionException { + private File lookupGitDirectory() throws GitCommitIdExecutionException { return new GitDirLocator(project, reactorProjects).lookupGitDirectory(dotGitDirectory); } @@ -483,28 +487,7 @@ private void logProperties() { } } - void loadShortDescribe(@NotNull Properties properties) { - //removes git hash part from describe - String commitDescribe = properties.getProperty(prefixDot + GitCommitPropertyConstant.COMMIT_DESCRIBE); - - if (commitDescribe != null) { - int startPos = commitDescribe.indexOf("-g"); - if (startPos > 0) { - String commitShortDescribe; - int endPos = commitDescribe.indexOf('-', startPos + 1); - if (endPos < 0) { - commitShortDescribe = commitDescribe.substring(0, startPos); - } else { - commitShortDescribe = commitDescribe.substring(0, startPos) + commitDescribe.substring(endPos); - } - put(properties, GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE, commitShortDescribe); - } else { - put(properties, GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE, commitDescribe); - } - } - } - - void loadGitData(@NotNull Properties properties) throws GitCommitIdExecutionException { + private void loadGitData(@Nonnull Properties properties) throws GitCommitIdExecutionException { if (useNativeGit) { loadGitDataWithNativeGit(properties); } else { @@ -512,12 +495,12 @@ void loadGitData(@NotNull Properties properties) throws GitCommitIdExecutionExce } } - void loadGitDataWithNativeGit(@NotNull Properties properties) throws GitCommitIdExecutionException { + private void loadGitDataWithNativeGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { try { final File basedir = project.getBasedir().getCanonicalFile(); GitDataProvider nativeGitProvider = NativeGitProvider - .on(basedir, log) + .on(basedir, nativeGitTimeoutInMs, log) .setPrefixDot(prefixDot) .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) @@ -531,7 +514,7 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws GitCommitId } } - void loadGitDataWithJGit(@NotNull Properties properties) throws GitCommitIdExecutionException { + private void loadGitDataWithJGit(@Nonnull Properties properties) throws GitCommitIdExecutionException { GitDataProvider jGitProvider = JGitProvider .on(dotGitDirectory, log) .setPrefixDot(prefixDot) @@ -544,7 +527,7 @@ void loadGitDataWithJGit(@NotNull Properties properties) throws GitCommitIdExecu jGitProvider.loadGitData(evaluateOnCommit, properties); } - void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, String propertiesFilename) throws GitCommitIdExecutionException { + private void maybeGeneratePropertiesFile(@Nonnull Properties localProperties, File base, String propertiesFilename) throws GitCommitIdExecutionException { try { final File gitPropsFile = craftPropertiesOutputFile(base, propertiesFilename); final boolean isJsonFormat = "json".equalsIgnoreCase(format); @@ -582,33 +565,22 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, if (shouldGenerate) { Files.createParentDirs(gitPropsFile); - Writer outputWriter = null; - OutputStream outputStream = null; - boolean threw = true; - - try { - outputStream = new FileOutputStream(gitPropsFile); + try (OutputStream outputStream = new FileOutputStream(gitPropsFile)) { SortedProperties sortedLocalProperties = new SortedProperties(); sortedLocalProperties.putAll(localProperties); if (isJsonFormat) { - outputWriter = new OutputStreamWriter(outputStream, sourceCharset); - log.info("Writing json file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); - ObjectMapper mapper = new ObjectMapper(); - mapper.writerWithDefaultPrettyPrinter().writeValue(outputWriter, sortedLocalProperties); + try (Writer outputWriter = new OutputStreamWriter(outputStream, sourceCharset)) { + log.info("Writing json file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); + ObjectMapper mapper = new ObjectMapper(); + mapper.writerWithDefaultPrettyPrinter().writeValue(outputWriter, sortedLocalProperties); + } } else { log.info("Writing properties file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); // using outputStream directly instead of outputWriter this way the UTF-8 characters appears in unicode escaped form sortedLocalProperties.store(outputStream, "Generated by Git-Commit-Id-Plugin"); } - threw = false; } catch (final IOException ex) { throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex); - } finally { - if (outputWriter == null) { - Closeables.close(outputStream, threw); - } else { - Closeables.close(outputWriter, threw); - } } } else { log.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); @@ -618,7 +590,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } } - @VisibleForTesting File craftPropertiesOutputFile(File base, String propertiesFilename) { + File craftPropertiesOutputFile(File base, String propertiesFilename) { File returnPath = new File(base, propertiesFilename); File currentPropertiesFilepath = new File(propertiesFilename); @@ -630,43 +602,24 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } - boolean isPomProject(@NotNull MavenProject project) { + private boolean isPomProject(@Nonnull MavenProject project) { return project.getPackaging().equalsIgnoreCase("pom"); } - private void put(@NotNull Properties properties, String key, String value) { - String keyWithPrefix = prefixDot + key; - log.info(keyWithPrefix + " " + value); - PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value); - } - private boolean directoryExists(@Nullable File fileLocation) { return fileLocation != null && fileLocation.exists() && fileLocation.isDirectory(); } - @SuppressWarnings("resource") - private Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFileException { + private Properties readJsonProperties(@Nonnull File jsonFile) throws CannotReadFileException { final HashMap propertiesMap; - Closeable closeable = null; - - try { - boolean threw = true; - try { - final FileInputStream fis = new FileInputStream(jsonFile); - closeable = fis; - - final InputStreamReader reader = new InputStreamReader(fis, sourceCharset); - closeable = reader; - + try (final FileInputStream fis = new FileInputStream(jsonFile)) { + try (final InputStreamReader reader = new InputStreamReader(fis, sourceCharset)) { final ObjectMapper mapper = new ObjectMapper(); final TypeReference> mapTypeRef = new TypeReference>() {}; propertiesMap = mapper.readValue(reader, mapTypeRef); - threw = false; - } finally { - Closeables.close(closeable, threw); } } catch (final Exception ex) { throw new CannotReadFileException(ex); @@ -681,27 +634,12 @@ private Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadF return retVal; } - @SuppressWarnings("resource") - private Properties readProperties(@NotNull File propertiesFile) throws CannotReadFileException { - Closeable closeable = null; - - try { - boolean threw = true; - try { - final FileInputStream fis = new FileInputStream(propertiesFile); - closeable = fis; - - final InputStreamReader reader = new InputStreamReader(fis, sourceCharset); - closeable = reader; - + private Properties readProperties(@Nonnull File propertiesFile) throws CannotReadFileException { + try (final FileInputStream fis = new FileInputStream(propertiesFile)) { + try (final InputStreamReader reader = new InputStreamReader(fis, sourceCharset)) { final Properties retVal = new Properties(); - retVal.load(reader); - threw = false; - return retVal; - } finally { - Closeables.close(closeable, threw); } } catch (final Exception ex) { throw new CannotReadFileException(ex); @@ -715,94 +653,4 @@ static class CannotReadFileException extends Exception { super(cause); } } - - // SETTERS FOR TESTS ---------------------------------------------------- - - @VisibleForTesting void setFormat(String format) { - this.format = format; - } - - @VisibleForTesting void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @VisibleForTesting void setProject(MavenProject project) { - this.project = project; - } - - @VisibleForTesting void setDotGitDirectory(File dotGitDirectory) { - this.dotGitDirectory = dotGitDirectory; - } - - @VisibleForTesting void setPrefix(String prefix) { - this.prefix = prefix; - } - - @VisibleForTesting void setDateFormat(String dateFormat) { - this.dateFormat = dateFormat; - } - - @VisibleForTesting Properties getProperties() { - return properties; - } - - @VisibleForTesting void setGitDescribe(GitDescribeConfig gitDescribe) { - this.gitDescribe = gitDescribe; - } - - @VisibleForTesting void setAbbrevLength(int abbrevLength) { - this.abbrevLength = abbrevLength; - } - - @VisibleForTesting void setExcludeProperties(List excludeProperties) { - this.excludeProperties = excludeProperties; - } - - @VisibleForTesting void setIncludeOnlyProperties(List includeOnlyProperties) { - this.includeOnlyProperties = includeOnlyProperties; - } - - @VisibleForTesting void setUseNativeGit(boolean useNativeGit) { - this.useNativeGit = useNativeGit; - } - - @VisibleForTesting void setCommitIdGenerationMode(String commitIdGenerationMode) { - this.commitIdGenerationMode = commitIdGenerationMode; - } - - @VisibleForTesting void setSkip(boolean skip) { - this.skip = skip; - } - - @VisibleForTesting void setSkipPoms(boolean skipPoms) { - this.skipPoms = skipPoms; - } - - @VisibleForTesting void setGenerateGitPropertiesFile(boolean generateGitPropertiesFile) { - this.generateGitPropertiesFile = generateGitPropertiesFile; - } - - @VisibleForTesting void setGenerateGitPropertiesFilename(String generateGitPropertiesFilename) { - this.generateGitPropertiesFilename = generateGitPropertiesFilename; - } - - @VisibleForTesting void setDateFormatTimeZone(String dateFormatTimeZone) { - this.dateFormatTimeZone = dateFormatTimeZone; - } - - @VisibleForTesting void setFailOnNoGitDirectory(boolean failOnNoGitDirectory) { - this.failOnNoGitDirectory = failOnNoGitDirectory; - } - - @VisibleForTesting void setFailOnUnableToExtractRepoInfo(boolean failOnUnableToExtractRepoInfo) { - this.failOnUnableToExtractRepoInfo = failOnUnableToExtractRepoInfo; - } - - @VisibleForTesting String getEvaluateOnCommit() { - return evaluateOnCommit; - } - - @VisibleForTesting void setEvaluateOnCommit(String evaluateOnCommit) { - this.evaluateOnCommit = evaluateOnCommit; - } } diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java index bdae0eba..2b676d63 100644 --- a/src/main/java/pl/project13/maven/git/GitDataProvider.java +++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java @@ -18,12 +18,12 @@ package pl.project13.maven.git; import org.apache.http.client.utils.URIBuilder; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.build.BuildServerDataProvider; import pl.project13.maven.git.build.UnknownBuildServerData; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.util.PropertyManager; +import javax.annotation.Nonnull; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; @@ -36,7 +36,7 @@ public abstract class GitDataProvider implements GitProvider { - @NotNull + @Nonnull protected final LoggerBridge log; protected String prefixDot; @@ -53,7 +53,7 @@ public abstract class GitDataProvider implements GitProvider { protected String evaluateOnCommit; - public GitDataProvider(@NotNull LoggerBridge log) { + public GitDataProvider(@Nonnull LoggerBridge log) { this.log = log; } @@ -87,7 +87,7 @@ public GitDataProvider setDateFormatTimeZone(String dateFormatTimeZone) { return this; } - public void loadGitData(@NotNull String evaluateOnCommit, @NotNull Properties properties) throws GitCommitIdExecutionException { + public void loadGitData(@Nonnull String evaluateOnCommit, @Nonnull Properties properties) throws GitCommitIdExecutionException { this.evaluateOnCommit = evaluateOnCommit; init(); // git.user.name @@ -103,6 +103,7 @@ public void loadGitData(@NotNull String evaluateOnCommit, @NotNull Properties pr put(properties, GitCommitPropertyConstant.BRANCH, determineBranchName(System.getenv())); // git.commit.id.describe maybePutGitDescribe(properties); + loadShortDescribe(properties); // git.commit.id switch (commitIdGenerationMode) { case FULL: { @@ -146,7 +147,7 @@ public void loadGitData(@NotNull String evaluateOnCommit, @NotNull Properties pr } } - private void maybePutGitDescribe(@NotNull Properties properties) throws GitCommitIdExecutionException { + private void maybePutGitDescribe(@Nonnull Properties properties) throws GitCommitIdExecutionException { boolean isGitDescribeOptOutByDefault = (gitDescribe == null); boolean isGitDescribeOptOutByConfiguration = (gitDescribe != null && !gitDescribe.isSkip()); @@ -155,6 +156,27 @@ private void maybePutGitDescribe(@NotNull Properties properties) throws GitCommi } } + protected void loadShortDescribe(@Nonnull Properties properties) { + //removes git hash part from describe + String commitDescribe = properties.getProperty(prefixDot + GitCommitPropertyConstant.COMMIT_DESCRIBE); + + if (commitDescribe != null) { + int startPos = commitDescribe.indexOf("-g"); + if (startPos > 0) { + String commitShortDescribe; + int endPos = commitDescribe.indexOf('-', startPos + 1); + if (endPos < 0) { + commitShortDescribe = commitDescribe.substring(0, startPos); + } else { + commitShortDescribe = commitDescribe.substring(0, startPos) + commitDescribe.substring(endPos); + } + put(properties, GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE, commitShortDescribe); + } else { + put(properties, GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE, commitDescribe); + } + } + } + void validateAbbrevLength(int abbrevLength) throws GitCommitIdExecutionException { if (abbrevLength < 2 || abbrevLength > 40) { throw new GitCommitIdExecutionException(String.format("Abbreviated commit id length must be between 2 and 40, inclusive! Was [%s]. ", abbrevLength) + @@ -169,7 +191,7 @@ void validateAbbrevLength(int abbrevLength) throws GitCommitIdExecutionException * @param env environment settings * @return results of getBranchName() or, if in Jenkins/Hudson, value of GIT_BRANCH */ - protected String determineBranchName(@NotNull Map env) throws GitCommitIdExecutionException { + protected String determineBranchName(@Nonnull Map env) throws GitCommitIdExecutionException { BuildServerDataProvider buildServerDataProvider = BuildServerDataProvider.getBuildServerProvider(env,log); if (!(buildServerDataProvider instanceof UnknownBuildServerData)) { String branchName = buildServerDataProvider.getBuildBranch(); @@ -191,7 +213,7 @@ protected SimpleDateFormat getSimpleDateFormatWithTimeZone() { return smf; } - protected void put(@NotNull Properties properties, String key, String value) { + protected void put(@Nonnull Properties properties, String key, String value) { String keyWithPrefix = prefixDot + key; log.info("{} {}", keyWithPrefix, value); PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value); diff --git a/src/main/java/pl/project13/maven/git/GitDirLocator.java b/src/main/java/pl/project13/maven/git/GitDirLocator.java index e1a4077b..834386f6 100644 --- a/src/main/java/pl/project13/maven/git/GitDirLocator.java +++ b/src/main/java/pl/project13/maven/git/GitDirLocator.java @@ -19,9 +19,9 @@ import org.apache.maven.project.MavenProject; import org.eclipse.jgit.lib.Constants; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.*; import java.util.List; @@ -39,7 +39,7 @@ public GitDirLocator(MavenProject mavenProject, List reactorProjec } @Nullable - public File lookupGitDirectory(@NotNull File manuallyConfiguredDir) { + public File lookupGitDirectory(@Nonnull File manuallyConfiguredDir) { if (manuallyConfiguredDir.exists()) { // If manuallyConfiguredDir is a directory then we can use it as the git path. @@ -98,42 +98,30 @@ private File findProjectGitDirectory() { * * @return File object with path loaded or null */ - private File processGitDirFile(@NotNull File file) { - try { - BufferedReader reader = null; - - try { - reader = new BufferedReader(new FileReader(file)); - - // There should be just one line in the file, e.g. - // "gitdir: /usr/local/src/parentproject/.git/modules/submodule" - String line = reader.readLine(); - if (line == null) { - return null; - } - // Separate the key and the value in the string. - String[] parts = line.split(": "); - - // If we don't have 2 parts or if the key is not gitdir then give up. - if (parts.length != 2 || !parts[0].equals("gitdir")) { - return null; - } + private File processGitDirFile(@Nonnull File file) { + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + // There should be just one line in the file, e.g. + // "gitdir: /usr/local/src/parentproject/.git/modules/submodule" + String line = reader.readLine(); + if (line == null) { + return null; + } + // Separate the key and the value in the string. + String[] parts = line.split(": "); - // All seems ok so return the "gitdir" value read from the file. - File gitDir = new File(parts[1]); - if (gitDir.isAbsolute()) { - // gitdir value is an absolute path. Return as-is - return gitDir; - } else { - // gitdir value is relative. - return new File(file.getParentFile(), parts[1]); - } - } catch (FileNotFoundException e) { + // If we don't have 2 parts or if the key is not gitdir then give up. + if (parts.length != 2 || !parts[0].equals("gitdir")) { return null; - } finally { - if (reader != null) { - reader.close(); - } + } + + // All seems ok so return the "gitdir" value read from the file. + File gitDir = new File(parts[1]); + if (gitDir.isAbsolute()) { + // gitdir value is an absolute path. Return as-is + return gitDir; + } else { + // gitdir value is relative. + return new File(file.getParentFile(), parts[1]); } } catch (IOException e) { return null; diff --git a/src/main/java/pl/project13/maven/git/GitProvider.java b/src/main/java/pl/project13/maven/git/GitProvider.java index cc4b875c..918d1b8b 100644 --- a/src/main/java/pl/project13/maven/git/GitProvider.java +++ b/src/main/java/pl/project13/maven/git/GitProvider.java @@ -1,44 +1,44 @@ package pl.project13.maven.git; public interface GitProvider { - public void init() throws GitCommitIdExecutionException; + void init() throws GitCommitIdExecutionException; - public String getBuildAuthorName() throws GitCommitIdExecutionException; + String getBuildAuthorName() throws GitCommitIdExecutionException; - public String getBuildAuthorEmail() throws GitCommitIdExecutionException; + String getBuildAuthorEmail() throws GitCommitIdExecutionException; - public void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdExecutionException; + void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdExecutionException; - public String getBranchName() throws GitCommitIdExecutionException; + String getBranchName() throws GitCommitIdExecutionException; - public String getGitDescribe() throws GitCommitIdExecutionException; + String getGitDescribe() throws GitCommitIdExecutionException; - public String getCommitId() throws GitCommitIdExecutionException; + String getCommitId() throws GitCommitIdExecutionException; - public String getAbbrevCommitId() throws GitCommitIdExecutionException; + String getAbbrevCommitId() throws GitCommitIdExecutionException; - public boolean isDirty() throws GitCommitIdExecutionException; + boolean isDirty() throws GitCommitIdExecutionException; - public String getCommitAuthorName() throws GitCommitIdExecutionException; + String getCommitAuthorName() throws GitCommitIdExecutionException; - public String getCommitAuthorEmail() throws GitCommitIdExecutionException; + String getCommitAuthorEmail() throws GitCommitIdExecutionException; - public String getCommitMessageFull() throws GitCommitIdExecutionException; + String getCommitMessageFull() throws GitCommitIdExecutionException; - public String getCommitMessageShort() throws GitCommitIdExecutionException; + String getCommitMessageShort() throws GitCommitIdExecutionException; - public String getCommitTime() throws GitCommitIdExecutionException; + String getCommitTime() throws GitCommitIdExecutionException; - public String getRemoteOriginUrl() throws GitCommitIdExecutionException; + String getRemoteOriginUrl() throws GitCommitIdExecutionException; - public String getTags() throws GitCommitIdExecutionException; + String getTags() throws GitCommitIdExecutionException; - public String getClosestTagName() throws GitCommitIdExecutionException; + String getClosestTagName() throws GitCommitIdExecutionException; - public String getClosestTagCommitCount() throws GitCommitIdExecutionException; + String getClosestTagCommitCount() throws GitCommitIdExecutionException; - public String getTotalCommitCount() throws GitCommitIdExecutionException; + String getTotalCommitCount() throws GitCommitIdExecutionException; - public void finalCleanUp() throws GitCommitIdExecutionException; + void finalCleanUp() throws GitCommitIdExecutionException; } diff --git a/src/main/java/pl/project13/maven/git/GitRepositoryState.java b/src/main/java/pl/project13/maven/git/GitRepositoryState.java index c00b70dd..3f0a1351 100644 --- a/src/main/java/pl/project13/maven/git/GitRepositoryState.java +++ b/src/main/java/pl/project13/maven/git/GitRepositoryState.java @@ -17,9 +17,7 @@ package pl.project13.maven.git; -import com.google.common.base.Joiner; -import org.jetbrains.annotations.NotNull; - +import javax.annotation.Nonnull; import java.util.Set; /** @@ -173,14 +171,14 @@ public String toJson() { appendProperty(sb, "buildUserName", buildUserName); appendProperty(sb, "buildUserEmail", buildUserEmail); - appendProperty(sb, "tags", Joiner.on(",").join(tags)); + appendProperty(sb, "tags", String.join(",", tags)); appendProperty(sb, "mavenProjectVersion", mavenProjectVersion); return sb.append("}").toString(); } - private void appendProperty(@NotNull StringBuilder sb, String label, String value) { + private void appendProperty(@Nonnull StringBuilder sb, String label, String value) { sb.append(String.format("\"%s\": \"%s\",", label, value)); } diff --git a/src/main/java/pl/project13/maven/git/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java index 7dc05383..0e9e5624 100644 --- a/src/main/java/pl/project13/maven/git/JGitProvider.java +++ b/src/main/java/pl/project13/maven/git/JGitProvider.java @@ -18,8 +18,6 @@ package pl.project13.maven.git; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.AbbreviatedObjectId; @@ -31,7 +29,6 @@ import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.RevWalkUtils; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.jetbrains.annotations.NotNull; import pl.project13.jgit.DescribeCommand; import pl.project13.jgit.DescribeResult; @@ -43,8 +40,12 @@ import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; +import java.util.Optional; + import org.eclipse.jgit.storage.file.WindowCacheConfig; +import javax.annotation.Nonnull; + public class JGitProvider extends GitDataProvider { private File dotGitDirectory; @@ -54,12 +55,12 @@ public class JGitProvider extends GitDataProvider { private RevCommit evalCommit; private JGitCommon jGitCommon; - @NotNull - public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + @Nonnull + public static JGitProvider on(@Nonnull File dotGitDirectory, @Nonnull LoggerBridge log) { return new JGitProvider(dotGitDirectory, log); } - JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + JGitProvider(@Nonnull File dotGitDirectory, @Nonnull LoggerBridge log) { super(log); this.dotGitDirectory = dotGitDirectory; this.jGitCommon = new JGitCommon(log); @@ -74,13 +75,13 @@ public void init() throws GitCommitIdExecutionException { @Override public String getBuildAuthorName() throws GitCommitIdExecutionException { String userName = git.getConfig().getString("user", null, "name"); - return MoreObjects.firstNonNull(userName, ""); + return Optional.ofNullable(userName).orElse(""); } @Override public String getBuildAuthorEmail() throws GitCommitIdExecutionException { String userEmail = git.getConfig().getString("user", null, "email"); - return MoreObjects.firstNonNull(userEmail, ""); + return Optional.ofNullable(userEmail).orElse(""); } @Override @@ -94,7 +95,7 @@ public void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdE throw new GitCommitIdExecutionException("Could not get " + evaluateOnCommit + " Ref, are you sure you have set the dotGitDirectory property of this plugin to a valid path?"); } revWalk = new RevWalk(git); - ObjectId headObjectId = null; + ObjectId headObjectId; if (evaluateOnCommitReference != null) { headObjectId = evaluateOnCommitReference.getObjectId(); } else { @@ -184,7 +185,7 @@ public String getTags() throws GitCommitIdExecutionException { Repository repo = getGitRepository(); ObjectId headId = evalCommit.toObjectId(); Collection tags = jGitCommon.getTags(repo, headId); - return Joiner.on(",").join(tags); + return String.join(",", tags); } catch (GitAPIException e) { log.error("Unable to extract tags from commit: {} ({})", evalCommit.getName(), e.getClass().getName()); return ""; @@ -240,7 +241,7 @@ public void finalCleanUp() { } } - @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws GitCommitIdExecutionException { + @VisibleForTesting String getGitDescribe(@Nonnull Repository repository) throws GitCommitIdExecutionException { try { DescribeResult describeResult = DescribeCommand .on(evaluateOnCommit, repository, log) @@ -264,7 +265,7 @@ private String getAbbrevCommitId(ObjectReader objectReader, RevCommit headCommit } } - @NotNull + @Nonnull private Repository getGitRepository() throws GitCommitIdExecutionException { Repository repository; diff --git a/src/main/java/pl/project13/maven/git/NativeGitProvider.java b/src/main/java/pl/project13/maven/git/NativeGitProvider.java index 439133a4..875f2241 100644 --- a/src/main/java/pl/project13/maven/git/NativeGitProvider.java +++ b/src/main/java/pl/project13/maven/git/NativeGitProvider.java @@ -19,13 +19,13 @@ import static java.lang.String.format; -import com.google.common.base.Throwables; - -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.io.*; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; +import java.util.concurrent.TimeUnit; public class NativeGitProvider extends GitDataProvider { @@ -34,16 +34,19 @@ public class NativeGitProvider extends GitDataProvider { final File dotGitDirectory; + final long nativeGitTimeoutInMs; + final File canonical; - @NotNull - public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { - return new NativeGitProvider(dotGitDirectory, log); + @Nonnull + public static NativeGitProvider on(@Nonnull File dotGitDirectory, long nativeGitTimeoutInMs, @Nonnull LoggerBridge log) { + return new NativeGitProvider(dotGitDirectory, nativeGitTimeoutInMs, log); } - NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + NativeGitProvider(@Nonnull File dotGitDirectory, long nativeGitTimeoutInMs, @Nonnull LoggerBridge log) { super(log); this.dotGitDirectory = dotGitDirectory; + this.nativeGitTimeoutInMs = nativeGitTimeoutInMs; try { this.canonical = dotGitDirectory.getCanonicalFile(); } catch (IOException ex) { @@ -59,24 +62,24 @@ public void init() throws GitCommitIdExecutionException { @Override public String getBuildAuthorName() throws GitCommitIdExecutionException { try { - return runGitCommand(canonical, "config --get user.name"); + return runGitCommand(canonical, nativeGitTimeoutInMs, "config --get user.name"); } catch (NativeCommandException e) { if (e.getExitCode() == 1) { // No config file found return ""; } - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @Override public String getBuildAuthorEmail() throws GitCommitIdExecutionException { try { - return runGitCommand(canonical, "config --get user.email"); + return runGitCommand(canonical, nativeGitTimeoutInMs, "config --get user.email"); } catch (NativeCommandException e) { if (e.getExitCode() == 1) { // No config file found return ""; } - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -92,7 +95,7 @@ public String getBranchName() throws GitCommitIdExecutionException { private String getBranch(File canonical) throws GitCommitIdExecutionException { String branch; try { - branch = runGitCommand(canonical, "symbolic-ref " + evaluateOnCommit); + branch = runGitCommand(canonical, nativeGitTimeoutInMs, "symbolic-ref " + evaluateOnCommit); if (branch != null) { branch = branch.replace("refs/heads/", ""); } @@ -105,10 +108,10 @@ private String getBranch(File canonical) throws GitCommitIdExecutionException { if (noSymbolicRef || noSuchRef) { branch = getCommitId(); } else { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } else { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } return branch; @@ -117,7 +120,7 @@ private String getBranch(File canonical) throws GitCommitIdExecutionException { @Override public String getGitDescribe() throws GitCommitIdExecutionException { final String argumentsForGitDescribe = getArgumentsForGitDescribe(gitDescribe); - return runQuietGitCommand(canonical, "describe" + argumentsForGitDescribe); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "describe" + argumentsForGitDescribe); } private String getArgumentsForGitDescribe(GitDescribeConfig describeConfig) { @@ -170,10 +173,10 @@ public String getCommitId() throws GitCommitIdExecutionException { // in case evaluateOnCommit is not a reference rev-list will just return the argument given // and thus it's always safe(r) to unwrap it // however when evaluateOnCommit is not set we don't want to waste calls to the native binary - String actualCommitId = runQuietGitCommand(canonical, "rev-list -n 1 " + evaluateOnCommit); - return runQuietGitCommand(canonical, "rev-parse " + actualCommitId); + String actualCommitId = runQuietGitCommand(canonical, nativeGitTimeoutInMs, "rev-list -n 1 " + evaluateOnCommit); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "rev-parse " + actualCommitId); } else { - return runQuietGitCommand(canonical, "rev-parse HEAD"); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "rev-parse HEAD"); } } @@ -193,45 +196,45 @@ public String getAbbrevCommitId() throws GitCommitIdExecutionException { @Override public boolean isDirty() throws GitCommitIdExecutionException { - return !tryCheckEmptyRunGitCommand(canonical, "status -s"); + return !tryCheckEmptyRunGitCommand(canonical, nativeGitTimeoutInMs, "status -s"); } @Override public String getCommitAuthorName() throws GitCommitIdExecutionException { - return runQuietGitCommand(canonical, "log -1 --pretty=format:%an " + evaluateOnCommit); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "log -1 --pretty=format:%an " + evaluateOnCommit); } @Override public String getCommitAuthorEmail() throws GitCommitIdExecutionException { - return runQuietGitCommand(canonical, "log -1 --pretty=format:%ae " + evaluateOnCommit); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "log -1 --pretty=format:%ae " + evaluateOnCommit); } @Override public String getCommitMessageFull() throws GitCommitIdExecutionException { - return runQuietGitCommand(canonical, "log -1 --pretty=format:%B " + evaluateOnCommit); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "log -1 --pretty=format:%B " + evaluateOnCommit); } @Override public String getCommitMessageShort() throws GitCommitIdExecutionException { - return runQuietGitCommand(canonical, "log -1 --pretty=format:%s " + evaluateOnCommit); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "log -1 --pretty=format:%s " + evaluateOnCommit); } @Override public String getCommitTime() throws GitCommitIdExecutionException { - String value = runQuietGitCommand(canonical, "log -1 --pretty=format:%ct " + evaluateOnCommit); + String value = runQuietGitCommand(canonical, nativeGitTimeoutInMs, "log -1 --pretty=format:%ct " + evaluateOnCommit); SimpleDateFormat smf = getSimpleDateFormatWithTimeZone(); return smf.format(Long.parseLong(value) * 1000L); } @Override public String getTags() throws GitCommitIdExecutionException { - final String result = runQuietGitCommand(canonical, "tag --contains " + evaluateOnCommit); + final String result = runQuietGitCommand(canonical, nativeGitTimeoutInMs, "tag --contains " + evaluateOnCommit); return result.replace('\n', ','); } @Override public String getRemoteOriginUrl() throws GitCommitIdExecutionException { - return getOriginRemote(canonical); + return getOriginRemote(canonical, nativeGitTimeoutInMs); } @Override @@ -249,7 +252,7 @@ public String getClosestTagName() throws GitCommitIdExecutionException { argumentsForGitDescribe.append(" --match=").append(matchOption); } } - return runGitCommand(canonical, argumentsForGitDescribe.toString()); + return runGitCommand(canonical, nativeGitTimeoutInMs, argumentsForGitDescribe.toString()); } catch (NativeCommandException ignore) { // could not find any tags to describe } @@ -260,23 +263,23 @@ public String getClosestTagName() throws GitCommitIdExecutionException { public String getClosestTagCommitCount() throws GitCommitIdExecutionException { String closestTagName = getClosestTagName(); if (closestTagName != null && !closestTagName.trim().isEmpty()) { - return runQuietGitCommand(canonical, "rev-list " + closestTagName + ".." + evaluateOnCommit + " --count"); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "rev-list " + closestTagName + ".." + evaluateOnCommit + " --count"); } return ""; } @Override public String getTotalCommitCount() throws GitCommitIdExecutionException { - return runQuietGitCommand(canonical, "rev-list " + evaluateOnCommit + " --count"); + return runQuietGitCommand(canonical, nativeGitTimeoutInMs, "rev-list " + evaluateOnCommit + " --count"); } @Override public void finalCleanUp() throws GitCommitIdExecutionException { } - private String getOriginRemote(File directory) throws GitCommitIdExecutionException { + private String getOriginRemote(File directory, long nativeGitTimeoutInMs) throws GitCommitIdExecutionException { try { - String remoteUrl = runGitCommand(directory, "ls-remote --get-url"); + String remoteUrl = runGitCommand(directory, nativeGitTimeoutInMs, "ls-remote --get-url"); return stripCredentialsFromOriginUrl(remoteUrl); } catch (NativeCommandException ignore) { @@ -292,13 +295,13 @@ private String getOriginRemote(File directory) throws GitCommitIdExecutionExcept * Return true if the result is empty. * **/ - private boolean tryCheckEmptyRunGitCommand(File directory, String gitCommand) { + private boolean tryCheckEmptyRunGitCommand(File directory, long nativeGitTimeoutInMs, String gitCommand) { try { String env = System.getenv("GIT_PATH"); String exec = (env == null) ? "git" : env; String command = String.format("%s %s", exec, gitCommand); - return getRunner().runEmpty(directory, command); + return getRunner().runEmpty(directory, nativeGitTimeoutInMs, command); } catch (IOException ex) { // Error means "non-empty" return false; @@ -306,29 +309,29 @@ private boolean tryCheckEmptyRunGitCommand(File directory, String gitCommand) { } } - private String runQuietGitCommand(File directory, String gitCommand) { + private String runQuietGitCommand(File directory, long nativeGitTimeoutInMs, String gitCommand) { final String env = System.getenv("GIT_PATH"); final String exec = (env == null) ? "git" : env; final String command = String.format("%s %s", exec, gitCommand); try { - return getRunner().run(directory, command.trim()).trim(); + return getRunner().run(directory, nativeGitTimeoutInMs, command.trim()).trim(); } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } - private String runGitCommand(File directory, String gitCommand) throws NativeCommandException { + private String runGitCommand(File directory, long nativeGitTimeoutInMs, String gitCommand) throws NativeCommandException { final String env = System.getenv("GIT_PATH"); final String exec = (env == null) ? "git" : env; final String command = String.format("%s %s", exec, gitCommand); try { - return getRunner().run(directory, command.trim()).trim(); + return getRunner().run(directory, nativeGitTimeoutInMs, command.trim()).trim(); } catch (NativeCommandException e) { throw e; } catch (IOException e) { - throw Throwables.propagate(e); + throw new RuntimeException(e); } } @@ -341,10 +344,10 @@ private ProcessRunner getRunner() { public interface ProcessRunner { /** Run a command and return the entire output as a String - naive, we know. */ - String run(File directory, String command) throws IOException; + String run(File directory, long nativeGitTimeoutInMs, String command) throws IOException; /** Run a command and return false if it contains at least one output line*/ - boolean runEmpty(File directory, String command) throws IOException; + boolean runEmpty(File directory, long nativeGitTimeoutInMs, String command) throws IOException; } public static class NativeCommandException extends IOException { @@ -395,7 +398,7 @@ public String getMessage() { protected static class JavaProcessRunner implements ProcessRunner { @Override - public String run(File directory, String command) throws IOException { + public String run(File directory, long nativeGitTimeoutInMs, String command) throws IOException { String output = ""; try { ProcessBuilder builder = new ProcessBuilder(command.split("\\s")); @@ -403,7 +406,7 @@ public String run(File directory, String command) throws IOException { final InputStream is = proc.getInputStream(); final InputStream err = proc.getErrorStream(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); + final BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); final StringBuilder commandResult = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { @@ -411,12 +414,12 @@ public String run(File directory, String command) throws IOException { } final StringBuilder errMsg = readStderr(err); - proc.waitFor(); + proc.waitFor(nativeGitTimeoutInMs, TimeUnit.MILLISECONDS); if (proc.exitValue() != 0) { throw new NativeCommandException(proc.exitValue(), command, directory, output, errMsg.toString()); } output = commandResult.toString(); - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { throw new IOException(ex); } return output; @@ -433,7 +436,7 @@ private StringBuilder readStderr(InputStream err) throws IOException { } @Override - public boolean runEmpty(File directory, String command) throws IOException { + public boolean runEmpty(File directory, long nativeGitTimeoutInMs, String command) throws IOException { boolean empty = true; try { @@ -451,12 +454,12 @@ public boolean runEmpty(File directory, String command) throws IOException { } final StringBuilder errMsg = readStderr(err); - proc.waitFor(); + proc.waitFor(nativeGitTimeoutInMs, TimeUnit.MILLISECONDS); if (proc.exitValue() != 0) { throw new NativeCommandException(proc.exitValue(), command, directory, "", errMsg.toString()); } - } catch (InterruptedException ex) { + } catch (final InterruptedException ex) { throw new IOException(ex); } return empty; // was non-empty diff --git a/src/main/java/pl/project13/maven/git/PropertiesFilterer.java b/src/main/java/pl/project13/maven/git/PropertiesFilterer.java index fa3ab792..f421c99c 100644 --- a/src/main/java/pl/project13/maven/git/PropertiesFilterer.java +++ b/src/main/java/pl/project13/maven/git/PropertiesFilterer.java @@ -20,15 +20,10 @@ import java.util.List; import java.util.Properties; -import org.jetbrains.annotations.Nullable; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Lists; - import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nullable; + public class PropertiesFilterer { private LoggerBridge log; @@ -42,25 +37,16 @@ public void filterNot(Properties properties, @Nullable List exclusions, return; } - List> excludePredicates = Lists.transform(exclusions, - new Function>() { - @Override - public Predicate apply(String exclude) { - return Predicates.containsPattern(exclude); - } - }); - - Predicate shouldExclude = Predicates.alwaysFalse(); - for (Predicate predicate : excludePredicates) { - shouldExclude = Predicates.or(shouldExclude, predicate); - } - - for (String key : properties.stringPropertyNames()) { - if (isOurProperty(key, prefixDot) && shouldExclude.apply(key)) { - log.debug("shouldExclude.apply({}) = {}", key, shouldExclude.apply(key)); - properties.remove(key); - } - } + properties.stringPropertyNames() + .stream() + .filter(key -> isOurProperty(key, prefixDot)) + .forEach(key -> { + if (exclusions.stream() + .anyMatch(key::matches)) { + log.debug("shouldExclude.apply({})", key); + properties.remove(key); + } + }); } public void filter(Properties properties, @Nullable List inclusions, String prefixDot) { @@ -68,25 +54,16 @@ public void filter(Properties properties, @Nullable List inclusions, Str return; } - List> includePredicates = Lists.transform(inclusions, - new Function>() { - @Override - public Predicate apply(String exclude) { - return Predicates.containsPattern(exclude); - } - }); - - Predicate shouldInclude = Predicates.alwaysFalse(); - for (Predicate predicate : includePredicates) { - shouldInclude = Predicates.or(shouldInclude, predicate); - } - - for (String key : properties.stringPropertyNames()) { - if (isOurProperty(key, prefixDot) && !shouldInclude.apply(key)) { - log.debug("!shouldInclude.apply({}) = {}", key, shouldInclude.apply(key)); - properties.remove(key); - } - } + properties.stringPropertyNames() + .stream() + .filter(key -> isOurProperty(key, prefixDot)) + .forEach(key -> { + if (inclusions.stream() + .noneMatch(key::matches)) { + log.debug("!shouldInclude.apply({})", key); + properties.remove(key); + } + }); } private boolean isOurProperty(String key, String prefixDot) { diff --git a/src/main/java/pl/project13/maven/git/build/BambooBuildServerData.java b/src/main/java/pl/project13/maven/git/build/BambooBuildServerData.java index 122ef88c..f60f4ad2 100644 --- a/src/main/java/pl/project13/maven/git/build/BambooBuildServerData.java +++ b/src/main/java/pl/project13/maven/git/build/BambooBuildServerData.java @@ -1,15 +1,15 @@ package pl.project13.maven.git.build; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.GitCommitPropertyConstant; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.util.Map; import java.util.Properties; public class BambooBuildServerData extends BuildServerDataProvider { - BambooBuildServerData(LoggerBridge log, @NotNull Map env) { + BambooBuildServerData(LoggerBridge log, @Nonnull Map env) { super(log, env); } @@ -18,7 +18,7 @@ public static boolean isActiveServer(Map env) { } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { String buildNumber = env.get("BAMBOO_BUILDNUMBER"); put(properties, GitCommitPropertyConstant.BUILD_NUMBER, buildNumber == null ? "" : buildNumber); diff --git a/src/main/java/pl/project13/maven/git/build/BuildServerDataProvider.java b/src/main/java/pl/project13/maven/git/build/BuildServerDataProvider.java index 81e8810d..86b17991 100644 --- a/src/main/java/pl/project13/maven/git/build/BuildServerDataProvider.java +++ b/src/main/java/pl/project13/maven/git/build/BuildServerDataProvider.java @@ -1,11 +1,11 @@ package pl.project13.maven.git.build; import org.apache.maven.project.MavenProject; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.GitCommitPropertyConstant; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.util.PropertyManager; +import javax.annotation.Nonnull; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; @@ -23,27 +23,27 @@ public abstract class BuildServerDataProvider { private String prefixDot = ""; private MavenProject project = null; - BuildServerDataProvider(@NotNull LoggerBridge log, @NotNull Map env) { + BuildServerDataProvider(@Nonnull LoggerBridge log, @Nonnull Map env) { this.log = log; this.env = env; } - public BuildServerDataProvider setDateFormat(@NotNull String dateFormat) { + public BuildServerDataProvider setDateFormat(@Nonnull String dateFormat) { this.dateFormat = dateFormat; return this; } - public BuildServerDataProvider setDateFormatTimeZone(@NotNull String dateFormatTimeZone) { + public BuildServerDataProvider setDateFormatTimeZone(@Nonnull String dateFormatTimeZone) { this.dateFormatTimeZone = dateFormatTimeZone; return this; } - public BuildServerDataProvider setProject(@NotNull MavenProject project) { + public BuildServerDataProvider setProject(@Nonnull MavenProject project) { this.project = project; return this; } - public BuildServerDataProvider setPrefixDot(@NotNull String prefixDot) { + public BuildServerDataProvider setPrefixDot(@Nonnull String prefixDot) { this.prefixDot = prefixDot; return this; } @@ -55,7 +55,7 @@ public BuildServerDataProvider setPrefixDot(@NotNull String prefixDot) { * @param log logging provider which will be used to log events * @return the corresponding {@link BuildServerDataProvider} for your environment or {@link UnknownBuildServerData} */ - public static BuildServerDataProvider getBuildServerProvider(@NotNull Map env, @NotNull LoggerBridge log) { + public static BuildServerDataProvider getBuildServerProvider(@Nonnull Map env, @Nonnull LoggerBridge log) { if (BambooBuildServerData.isActiveServer(env)) { return new BambooBuildServerData(log, env); } @@ -74,7 +74,7 @@ public static BuildServerDataProvider getBuildServerProvider(@NotNull Map env) { + GitlabBuildServerData(LoggerBridge log, @Nonnull Map env) { super(log,env); } @@ -21,7 +21,7 @@ public static boolean isActiveServer(Map env) { } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { // GITLAB CI // CI_PIPELINE_ID will be present if in a Gitlab CI environment (Gitlab >8.10 & Gitlab CI >0.5) and contains a server wide unique ID for a pipeline run String uniqueBuildNumber = env.get("CI_PIPELINE_ID"); diff --git a/src/main/java/pl/project13/maven/git/build/HudsonJenkinsBuildServerData.java b/src/main/java/pl/project13/maven/git/build/HudsonJenkinsBuildServerData.java index d42a6da4..5d577e87 100644 --- a/src/main/java/pl/project13/maven/git/build/HudsonJenkinsBuildServerData.java +++ b/src/main/java/pl/project13/maven/git/build/HudsonJenkinsBuildServerData.java @@ -1,9 +1,9 @@ package pl.project13.maven.git.build; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.GitCommitPropertyConstant; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.util.Map; import java.util.Properties; @@ -11,20 +11,20 @@ public class HudsonJenkinsBuildServerData extends BuildServerDataProvider { - HudsonJenkinsBuildServerData(@NotNull LoggerBridge log, @NotNull Map env) { + HudsonJenkinsBuildServerData(@Nonnull LoggerBridge log, @Nonnull Map env) { super(log, env); } /** * @see JenkinsSetEnvironmentVariables */ - public static boolean isActiveServer(@NotNull Map env) { + public static boolean isActiveServer(@Nonnull Map env) { return env.containsKey("JENKINS_URL") || env.containsKey("JENKINS_HOME") || env.containsKey("HUDSON_URL") || env.containsKey("HUDSON_HOME"); } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { String buildNumber = env.get("BUILD_NUMBER"); put(properties, GitCommitPropertyConstant.BUILD_NUMBER, buildNumber == null ? "" : buildNumber); diff --git a/src/main/java/pl/project13/maven/git/build/TeamCityBuildServerData.java b/src/main/java/pl/project13/maven/git/build/TeamCityBuildServerData.java index a358c097..187f7382 100644 --- a/src/main/java/pl/project13/maven/git/build/TeamCityBuildServerData.java +++ b/src/main/java/pl/project13/maven/git/build/TeamCityBuildServerData.java @@ -1,9 +1,9 @@ package pl.project13.maven.git.build; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.GitCommitPropertyConstant; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; @@ -13,7 +13,7 @@ public class TeamCityBuildServerData extends BuildServerDataProvider { private final Properties teamcitySystemProperties = new Properties(); - TeamCityBuildServerData(@NotNull LoggerBridge log, @NotNull Map env) { + TeamCityBuildServerData(@Nonnull LoggerBridge log, @Nonnull Map env) { super(log, env); if (isActiveServer(env)) { //https://confluence.jetbrains.com/display/TCD18/Predefined+Build+Parameters @@ -28,12 +28,12 @@ public class TeamCityBuildServerData extends BuildServerDataProvider { /** * @see TeamCity */ - public static boolean isActiveServer(@NotNull Map env) { + public static boolean isActiveServer(@Nonnull Map env) { return env.containsKey("TEAMCITY_VERSION"); } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { String buildNumber = env.get("BUILD_NUMBER"); String buildNumberUnique = teamcitySystemProperties.getProperty("teamcity.build.id"); diff --git a/src/main/java/pl/project13/maven/git/build/TravisBuildServerData.java b/src/main/java/pl/project13/maven/git/build/TravisBuildServerData.java index a36b1f29..f2f9d74e 100644 --- a/src/main/java/pl/project13/maven/git/build/TravisBuildServerData.java +++ b/src/main/java/pl/project13/maven/git/build/TravisBuildServerData.java @@ -1,27 +1,27 @@ package pl.project13.maven.git.build; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.GitCommitPropertyConstant; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.util.Map; import java.util.Properties; public class TravisBuildServerData extends BuildServerDataProvider { - TravisBuildServerData(LoggerBridge log, @NotNull Map env) { + TravisBuildServerData(LoggerBridge log, @Nonnull Map env) { super(log, env); } /** * @see Travis */ - public static boolean isActiveServer(@NotNull Map env) { + public static boolean isActiveServer(@Nonnull Map env) { return env.containsKey("TRAVIS"); } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { String buildNumber = env.get("TRAVIS_BUILD_NUMBER"); String uniqueBuildNumber = env.get("TRAVIS_BUILD_ID"); diff --git a/src/main/java/pl/project13/maven/git/build/UnknownBuildServerData.java b/src/main/java/pl/project13/maven/git/build/UnknownBuildServerData.java index ec8da4ac..2523a0d7 100644 --- a/src/main/java/pl/project13/maven/git/build/UnknownBuildServerData.java +++ b/src/main/java/pl/project13/maven/git/build/UnknownBuildServerData.java @@ -1,18 +1,18 @@ package pl.project13.maven.git.build; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.log.LoggerBridge; +import javax.annotation.Nonnull; import java.util.Map; import java.util.Properties; public class UnknownBuildServerData extends BuildServerDataProvider { - public UnknownBuildServerData(@NotNull LoggerBridge log, @NotNull Map env) { + public UnknownBuildServerData(@Nonnull LoggerBridge log, @Nonnull Map env) { super(log, env); } @Override - void loadBuildNumber(@NotNull Properties properties) { + void loadBuildNumber(@Nonnull Properties properties) { } @Override diff --git a/src/main/java/pl/project13/maven/git/log/MessageFormatter.java b/src/main/java/pl/project13/maven/git/log/MessageFormatter.java index 2149f38e..4cef47b6 100644 --- a/src/main/java/pl/project13/maven/git/log/MessageFormatter.java +++ b/src/main/java/pl/project13/maven/git/log/MessageFormatter.java @@ -138,7 +138,7 @@ public final class MessageFormatter { * The argument to be substituted in place of the formatting anchor * @return The formatted message */ - public static final FormattingTuple format(String messagePattern, Object arg) { + public static FormattingTuple format(String messagePattern, Object arg) { return arrayFormat(messagePattern, new Object[] { arg }); } @@ -165,11 +165,11 @@ public static final FormattingTuple format(String messagePattern, Object arg) { * anchor * @return The formatted message */ - public static final FormattingTuple format(final String messagePattern, Object arg1, Object arg2) { + public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) { return arrayFormat(messagePattern, new Object[] { arg1, arg2 }); } - static final Throwable getThrowableCandidate(Object[] argArray) { + static Throwable getThrowableCandidate(Object[] argArray) { if (argArray == null || argArray.length == 0) { return null; } @@ -193,7 +193,7 @@ static final Throwable getThrowableCandidate(Object[] argArray) { * anchors * @return The formatted message */ - public static final FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { + public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) { Throwable throwableCandidate = getThrowableCandidate(argArray); @@ -236,13 +236,13 @@ public static final FormattingTuple arrayFormat(final String messagePattern, fin // itself escaped: "abc x:\\{}" // we have to consume one backward slash sbuf.append(messagePattern, i, j - 1); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + deeplyAppendParameter(sbuf, argArray[L], new HashMap<>()); i = j + 2; } } else { // normal case sbuf.append(messagePattern, i, j); - deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + deeplyAppendParameter(sbuf, argArray[L], new HashMap<>()); i = j + 2; } } @@ -256,7 +256,7 @@ public static final FormattingTuple arrayFormat(final String messagePattern, fin } } - static final boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { + static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex == 0) { return false; } @@ -268,7 +268,7 @@ static final boolean isEscapedDelimeter(String messagePattern, int delimeterStar } } - static final boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { + static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { return true; } else { diff --git a/src/main/java/pl/project13/maven/git/util/Pair.java b/src/main/java/pl/project13/maven/git/util/Pair.java index 7a578cad..df1bdd61 100644 --- a/src/main/java/pl/project13/maven/git/util/Pair.java +++ b/src/main/java/pl/project13/maven/git/util/Pair.java @@ -17,28 +17,28 @@ package pl.project13.maven.git.util; -import com.google.common.base.Preconditions; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; public class Pair { - @NotNull + @Nonnull public final A first; - @NotNull + @Nonnull public final B second; @SuppressWarnings("ConstantConditions") public Pair(A first, B second) { - Preconditions.checkArgument(first != null, "The first parameter must not be null."); - Preconditions.checkArgument(second != null, "The second parameter must not be null."); + Objects.requireNonNull(first, "The first parameter must not be null."); + Objects.requireNonNull(second, "The second parameter must not be null."); this.first = first; this.second = second; } - @NotNull + @Nonnull public static Pair of(A first, B second) { return new Pair<>(first, second); } @@ -72,7 +72,7 @@ public int hashCode() { return result; } - @NotNull + @Nonnull @Override public String toString() { return String.format("Pair(%s, %s)", first, second); diff --git a/src/main/java/pl/project13/maven/git/util/PropertyManager.java b/src/main/java/pl/project13/maven/git/util/PropertyManager.java index 68010640..848a4141 100644 --- a/src/main/java/pl/project13/maven/git/util/PropertyManager.java +++ b/src/main/java/pl/project13/maven/git/util/PropertyManager.java @@ -17,15 +17,16 @@ package pl.project13.maven.git.util; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; +import java.nio.charset.Charset; import java.util.Properties; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class PropertyManager { - public static void putWithoutPrefix(@NotNull Properties properties, String key, String value) { + public static void putWithoutPrefix(@Nonnull Properties properties, String key, String value) { if (!isNotEmpty(value)) { value = "Unknown"; } @@ -36,7 +37,7 @@ private static boolean isNotEmpty(@Nullable String value) { return null != value && !" ".equals(value.trim().replaceAll(" ", "")); } - public static Properties readProperties(@NotNull File propertiesFile, @NotNull String sourceCharset) throws Exception { + public static Properties readProperties(@Nonnull File propertiesFile, @Nonnull Charset sourceCharset) throws Exception { try (FileInputStream fis = new FileInputStream(propertiesFile); InputStreamReader reader = new InputStreamReader(fis, sourceCharset)) { final Properties retVal = new Properties(); diff --git a/src/main/java/pl/project13/maven/git/util/SortedProperties.java b/src/main/java/pl/project13/maven/git/util/SortedProperties.java index 953d34e3..eb36e8d5 100644 --- a/src/main/java/pl/project13/maven/git/util/SortedProperties.java +++ b/src/main/java/pl/project13/maven/git/util/SortedProperties.java @@ -32,7 +32,7 @@ public class SortedProperties extends Properties { @Override public Enumeration keys() { Enumeration keysEnum = super.keys(); - Vector keyList = new Vector(); + Vector keyList = new Vector<>(); while (keysEnum.hasMoreElements()) { keyList.add((String)keysEnum.nextElement()); } diff --git a/src/main/java/pl/project13/maven/validation/ValidationMojo.java b/src/main/java/pl/project13/maven/validation/ValidationMojo.java index cc138c00..b16a1f1f 100644 --- a/src/main/java/pl/project13/maven/validation/ValidationMojo.java +++ b/src/main/java/pl/project13/maven/validation/ValidationMojo.java @@ -22,11 +22,11 @@ import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; -import org.jetbrains.annotations.NotNull; import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.log.MavenLoggerBridge; +import javax.annotation.Nonnull; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -37,7 +37,7 @@ @Mojo(name = "validateRevision", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) public class ValidationMojo extends AbstractMojo { - @NotNull + @Nonnull private final LoggerBridge log = new MavenLoggerBridge(this, false); @Parameter(defaultValue = "true") diff --git a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java index 4f75e753..a1b1a30c 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java @@ -17,15 +17,16 @@ package pl.project13.jgit; -import com.google.common.base.Optional; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.lib.Repository; -import org.jetbrains.annotations.NotNull; import org.junit.Test; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; import pl.project13.maven.git.log.StdOutLoggerBridge; +import javax.annotation.Nonnull; +import java.util.Optional; + import static org.fest.assertions.Assertions.assertThat; public class DescribeCommandAbbrevIntegrationTest extends GitIntegrationTest { @@ -105,7 +106,7 @@ public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse } } - String abbrev(@NotNull String id, int n) { + String abbrev(@Nonnull String id, int n) { return id.substring(0, n); } } diff --git a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java index 5004c608..c265adc4 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java @@ -17,22 +17,23 @@ package pl.project13.jgit; -import com.google.common.base.Optional; -import com.google.common.collect.ImmutableMap; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; -import org.jetbrains.annotations.NotNull; import org.junit.Test; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; import pl.project13.maven.git.log.StdOutLoggerBridge; +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.Optional; + import static java.util.Collections.singletonList; import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; @@ -376,7 +377,7 @@ public void isATag_shouldProperlyDetectIfACommitIsATag() throws Exception { ObjectId oid = ObjectId.fromString(commitHash); // when - boolean isATag = DescribeCommand.hasTags(oid, ImmutableMap.of(oid, singletonList(tagName))); + boolean isATag = DescribeCommand.hasTags(oid, Collections.singletonMap(oid, singletonList(tagName))); // then assertThat(isATag).isTrue(); @@ -393,7 +394,7 @@ public void isATag_shouldProperlyDetectIfACommitIsANotTag() throws Exception { ObjectId oid = ObjectId.fromString(commitHash); // when - boolean isATag = DescribeCommand.hasTags(oid, ImmutableMap.of(tagOid, singletonList(tagName))); + boolean isATag = DescribeCommand.hasTags(oid, Collections.singletonMap(tagOid, singletonList(tagName))); // then assertThat(isATag).isTrue(); @@ -429,11 +430,11 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { } } - String abbrev(@NotNull String id) { + String abbrev(@Nonnull String id) { return abbrev(id, DEFAULT_ABBREV_LEN); } - String abbrev(@NotNull String id, int n) { + 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/jgit/DescribeCommandTagsIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java index ab32519f..e633bc43 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java @@ -17,7 +17,6 @@ package pl.project13.jgit; -import com.google.common.base.Optional; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.Repository; @@ -27,6 +26,8 @@ import pl.project13.maven.git.GitIntegrationTest; import pl.project13.maven.git.log.StdOutLoggerBridge; +import java.util.Optional; + import static org.fest.assertions.Assertions.assertThat; public class DescribeCommandTagsIntegrationTest extends GitIntegrationTest { diff --git a/src/test/java/pl/project13/jgit/DescribeResultTest.java b/src/test/java/pl/project13/jgit/DescribeResultTest.java index ba4511bc..a43d3f08 100644 --- a/src/test/java/pl/project13/jgit/DescribeResultTest.java +++ b/src/test/java/pl/project13/jgit/DescribeResultTest.java @@ -17,7 +17,6 @@ package pl.project13.jgit; -import com.google.common.base.Optional; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.lib.ObjectId; @@ -27,6 +26,8 @@ import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; +import java.util.Optional; + import static org.fest.assertions.Assertions.assertThat; public class DescribeResultTest extends GitIntegrationTest { diff --git a/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java b/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java index f514794d..a6cbac40 100644 --- a/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java +++ b/src/test/java/pl/project13/maven/git/AvailableGitTestRepo.java @@ -17,8 +17,8 @@ package pl.project13.maven.git; -import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; import java.io.File; public enum AvailableGitTestRepo { @@ -85,7 +85,7 @@ public enum AvailableGitTestRepo { this.dir = dir; } - @NotNull + @Nonnull public File getDir() { return new File(dir); } diff --git a/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java b/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java index 252fbe89..61c83faa 100644 --- a/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java +++ b/src/test/java/pl/project13/maven/git/ContainsKeyCondition.java @@ -18,8 +18,8 @@ package pl.project13.maven.git; import org.fest.assertions.Condition; -import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; import java.util.Map; class ContainsKeyCondition extends Condition> { @@ -31,7 +31,7 @@ public ContainsKeyCondition(String key) { } @Override - public boolean matches(@NotNull Map map) { + 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))); diff --git a/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java b/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java index fd149280..4e125423 100644 --- a/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java +++ b/src/test/java/pl/project13/maven/git/DoesNotContainKeyCondition.java @@ -18,8 +18,8 @@ package pl.project13.maven.git; import org.fest.assertions.Condition; -import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; import java.util.Map; class DoesNotContainKeyCondition extends Condition> { @@ -31,7 +31,7 @@ public DoesNotContainKeyCondition(String key) { } @Override - public boolean matches(@NotNull Map map) { + public boolean matches(@Nonnull Map map) { boolean containsKey = map.containsKey(key); if (containsKey) { System.out.println(String.format("Map contained [%s] key! Map is: %s", key, map)); diff --git a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java index 451923dc..baa76a5d 100644 --- a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java +++ b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java @@ -17,16 +17,15 @@ package pl.project13.maven.git; +import com.google.common.io.Files; import org.apache.commons.io.FileUtils; import org.apache.maven.project.MavenProject; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import java.io.File; import java.io.IOException; -import com.google.common.io.Files; - /** * Quick and dirty maven projects tree structure to create on disk during integration tests. * Can have both parent and child projects set up. @@ -53,27 +52,27 @@ public FileSystemMavenSandbox(String rootSandboxPath) { this.rootSandboxPath = rootSandboxPath; } - @NotNull + @Nonnull public FileSystemMavenSandbox withParentProject(String parentProjectDirName, String packaging) { parentProject = createProject(new File(rootSandboxPath + File.separator + parentProjectDirName), packaging); return this; } - @NotNull + @Nonnull public FileSystemMavenSandbox withNoChildProject() { // no-op: marker for better tests readability return this; } - @NotNull + @Nonnull public FileSystemMavenSandbox withChildProject(String childProjectDirName, String packaging) { childProject = createProject(new File(parentProject.getBasedir(), childProjectDirName), packaging); childProject.setParent(parentProject); return this; } - @NotNull - public FileSystemMavenSandbox withGitRepoInParent(@NotNull AvailableGitTestRepo repo) { + @Nonnull + public FileSystemMavenSandbox withGitRepoInParent(@Nonnull AvailableGitTestRepo repo) { System.out.println("TEST: Will prepare sandbox repository based on: [" + repo.getDir() + "]"); gitRepoSourceDir = repo.getDir(); @@ -81,27 +80,27 @@ public FileSystemMavenSandbox withGitRepoInParent(@NotNull AvailableGitTestRepo return this; } - @NotNull - public FileSystemMavenSandbox withGitRepoInChild(@NotNull AvailableGitTestRepo repo) { + @Nonnull + public FileSystemMavenSandbox withGitRepoInChild(@Nonnull AvailableGitTestRepo repo) { gitRepoSourceDir = repo.getDir(); gitRepoTargetDir = childProject.getBasedir(); return this; } - @NotNull - public FileSystemMavenSandbox withGitRepoAboveParent(@NotNull AvailableGitTestRepo repo) { + @Nonnull + public FileSystemMavenSandbox withGitRepoAboveParent(@Nonnull AvailableGitTestRepo repo) { gitRepoSourceDir = repo.getDir(); gitRepoTargetDir = new File(rootSandboxPath); return this; } - @NotNull + @Nonnull public FileSystemMavenSandbox withNoGitRepoAvailable() { gitRepoTargetDir = null; return this; } - @NotNull + @Nonnull public FileSystemMavenSandbox create() throws RuntimeException { try { createParentDir(); @@ -145,7 +144,7 @@ public MavenProject getChildProject() { return childProject; } - @NotNull + @Nonnull private MavenProject createProject(File basedir, String packaging) { MavenProject project = new MavenProject(); project.setFile(new File(basedir + File.separator + "pom.xml")); @@ -162,7 +161,7 @@ public String toString() { '}'; } - @NotNull + @Nonnull public FileSystemMavenSandbox withKeepSandboxWhenFinishedTest(boolean keepSandboxWhenFinishedTest) { // if we want to keep the generated sandbox for overwiew the content of it this.keepSandboxWhenFinishedTest = keepSandboxWhenFinishedTest; diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java index 6ba0889d..af9f6108 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java @@ -18,10 +18,6 @@ package pl.project13.maven.git; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import com.google.common.io.Files; import junitparams.JUnitParamsRunner; import junitparams.Parameters; @@ -37,7 +33,8 @@ import org.junit.runner.RunWith; import java.io.File; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.*; @@ -51,8 +48,8 @@ public class GitCommitIdMojoIntegrationTest extends GitIntegrationTest { @Rule public final EnvironmentVariables environmentVariablesMock = new EnvironmentVariables(); - static final boolean UseJGit = false; - static final boolean UseNativeGit = true; + private static final boolean UseJGit = false; + private static final boolean UseNativeGit = true; public static Collection useNativeGit() { return asList(UseJGit, UseNativeGit); @@ -72,7 +69,7 @@ public void shouldIncludeExpectedProperties(boolean useNativeGit) throws Excepti .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -104,8 +101,8 @@ public void shouldExcludeAsConfiguredProperties(boolean useNativeGit) throws Exc .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); - mojo.setExcludeProperties(ImmutableList.of("git.remote.origin.url", ".*.user.*")); + mojo.useNativeGit = useNativeGit; + mojo.excludeProperties = Arrays.asList("git.remote.origin.url", ".*.user.*"); // when mojo.execute(); @@ -141,8 +138,8 @@ public void shouldIncludeOnlyAsConfiguredProperties(boolean useNativeGit) throws .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); - mojo.setIncludeOnlyProperties(ImmutableList.of("git.remote.origin.url", ".*.user.*", "^git.commit.id.full$")); + mojo.useNativeGit = useNativeGit; + mojo.includeOnlyProperties = Arrays.asList("git.remote.origin.url", ".*.user.*", "^git.commit.id.full$"); // when mojo.execute(); @@ -178,9 +175,9 @@ public void shouldExcludeAndIncludeAsConfiguredProperties(boolean useNativeGit) .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); - mojo.setIncludeOnlyProperties(ImmutableList.of("git.remote.origin.url", ".*.user.*")); - mojo.setExcludeProperties(ImmutableList.of("git.build.user.email")); + mojo.useNativeGit = useNativeGit; + mojo.includeOnlyProperties = Arrays.asList("git.remote.origin.url", ".*.user.*"); + mojo.excludeProperties = Arrays.asList("git.build.user.email"); // when mojo.execute(); @@ -218,8 +215,8 @@ public void shouldHaveNoPrefixWhenConfiguredPrefixIsEmptyStringAsConfiguredPrope .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); - mojo.setPrefix(""); + mojo.useNativeGit = useNativeGit; + mojo.prefix = ""; // when mojo.execute(); @@ -247,8 +244,10 @@ public void shouldSkipDescribeWhenConfiguredToDoSo(boolean useNativeGit) throws GitDescribeConfig config = new GitDescribeConfig(); config.setSkip(true); + mojo.useNativeGit = useNativeGit; + mojo.gitDescribe = config; + // when - mojo.setGitDescribe(config); mojo.execute(); // then @@ -259,7 +258,7 @@ public void shouldSkipDescribeWhenConfiguredToDoSo(boolean useNativeGit) throws @Parameters(method = "useNativeGit") public void shouldUseJenkinsBranchInfoWhenAvailable(boolean useNativeGit) throws Exception { // given - Map env = Maps.newHashMap(); + Map env = new HashMap<>(); String detachedHeadSha1 = "b6a73ed747dd8dc98642d731ddbf09824efb9d48"; String ciUrl = "http://myciserver.com"; @@ -314,6 +313,8 @@ private void shouldUseJenkinsBranchInfoWhenAvailableHelperAndAssertBranch(boolea MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); + mojo.useNativeGit = useNativeGit; + // remove all keys from System.getenv() List keySet = new ArrayList<>(System.getenv().keySet()); for (String key: keySet) { @@ -350,7 +351,7 @@ public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject(boolean use .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -369,8 +370,8 @@ public void shouldNotRunWhenSkipIsSet(boolean useNativeGit) throws Exception { .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setSkip(true); - mojo.setUseNativeGit(useNativeGit); + mojo.skip = true; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -389,7 +390,7 @@ public void shouldNotRunWhenPackagingPomAndDefaultSettingsApply(boolean useNativ .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -408,8 +409,8 @@ public void shouldRunWhenPackagingPomAndSkipPomsFalse(boolean useNativeGit) thro .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setSkipPoms(false); - mojo.setUseNativeGit(useNativeGit); + mojo.skipPoms = false; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -428,8 +429,8 @@ public void shouldUseParentProjectRepoWhenInvokedFromChild(boolean useNativeGit) .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setSkipPoms(false); - mojo.setUseNativeGit(useNativeGit); + mojo.skipPoms = false; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -448,8 +449,8 @@ public void shouldUseChildProjectRepoIfInvokedFromChild(boolean useNativeGit) th .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setSkipPoms(false); - mojo.setUseNativeGit(useNativeGit); + mojo.skipPoms = false; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -468,8 +469,8 @@ public void shouldFailWithExceptionWhenNoGitRepoFound(boolean useNativeGit) thro .create(); MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setSkipPoms(false); - mojo.setUseNativeGit(useNativeGit); + mojo.skipPoms = false; + mojo.useNativeGit = useNativeGit; mojo.execute(); } @@ -488,9 +489,9 @@ public void shouldGenerateCustomPropertiesFileProperties(boolean useNativeGit) t File expectedFile = new File(targetProject.getBasedir(), targetFilePath); setProjectToExecuteMojoIn(targetProject); - mojo.setGenerateGitPropertiesFile(true); - mojo.setGenerateGitPropertiesFilename(targetFilePath); - mojo.setUseNativeGit(useNativeGit); + mojo.generateGitPropertiesFile = true; + mojo.generateGitPropertiesFilename = targetFilePath; + mojo.useNativeGit = useNativeGit; // when try { @@ -517,17 +518,17 @@ public void shouldGenerateCustomPropertiesFileJson(boolean useNativeGit) throws File expectedFile = new File(targetProject.getBasedir(), targetFilePath); setProjectToExecuteMojoIn(targetProject); - mojo.setGenerateGitPropertiesFile(true); - mojo.setGenerateGitPropertiesFilename(targetFilePath); - mojo.setFormat("json"); - mojo.setUseNativeGit(useNativeGit); + mojo.generateGitPropertiesFile = true; + mojo.generateGitPropertiesFilename = targetFilePath; + mojo.format = "json"; + mojo.useNativeGit = useNativeGit; // when try { mojo.execute(); // then assertThat(expectedFile).exists(); - String json = Files.toString(expectedFile, Charset.forName("UTF-8")); + String json = new String(Files.readAllBytes(expectedFile.toPath()), StandardCharsets.UTF_8); ObjectMapper om = new ObjectMapper(); Map map = new HashMap<>(); map = om.readValue(json, map.getClass()); @@ -547,8 +548,8 @@ public void shouldSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoFound(boolean useN .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setFailOnNoGitDirectory(false); - mojo.setUseNativeGit(useNativeGit); + mojo.failOnNoGitDirectory = false; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -567,8 +568,8 @@ public void shouldNotSkipWithoutFailOnNoGitDirectoryWhenNoGitRepoIsPresent(boole .create(); MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setFailOnNoGitDirectory(false); - mojo.setUseNativeGit(useNativeGit); + mojo.failOnNoGitDirectory = false; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -591,8 +592,8 @@ public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalse(boolean GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(false, 7); gitDescribeConfig.setDirty("-dirty"); // checking if dirty works as expected - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -613,8 +614,8 @@ public void shouldGenerateDescribeWithTagOnlyWhenForceLongFormatIsFalseAndAbbrev setProjectToExecuteMojoIn(targetProject); GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(false, 10); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -637,8 +638,8 @@ public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIs setProjectToExecuteMojoIn(targetProject); GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -659,8 +660,8 @@ public void shouldGenerateDescribeWithTagAndZeroAndCommitIdWhenForceLongFormatIs setProjectToExecuteMojoIn(targetProject); GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 10); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -682,8 +683,8 @@ public void shouldGenerateCommitIdAbbrevWithDefaultLength(boolean useNativeGit) MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setAbbrevLength(7); - mojo.setUseNativeGit(useNativeGit); + mojo.abbrevLength = 7; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -703,8 +704,8 @@ public void shouldGenerateCommitIdAbbrevWithNonDefaultLength(boolean useNativeGi MavenProject targetProject = mavenSandbox.getChildProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setAbbrevLength(10); - mojo.setUseNativeGit(useNativeGit); + mojo.abbrevLength = 10; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -725,8 +726,8 @@ public void shouldFormatDate(boolean useNativeGit) throws Exception { setProjectToExecuteMojoIn(targetProject); String dateFormat = "MM/dd/yyyy"; - mojo.setDateFormat(dateFormat); - mojo.setUseNativeGit(useNativeGit); + mojo.dateFormat = dateFormat; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -753,8 +754,8 @@ public void shouldSkipGitDescribe(boolean useNativeGit) throws Exception { GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); gitDescribeConfig.setSkip(true); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -778,8 +779,8 @@ public void shouldMarkGitDescribeAsDirty(boolean useNativeGit) throws Exception GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); String dirtySuffix = "-dirtyTest"; gitDescribeConfig.setDirty(dirtySuffix); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -802,8 +803,8 @@ public void shouldAlwaysPrintGitDescribe(boolean useNativeGit) throws Exception GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); gitDescribeConfig.setAlways(true); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -825,8 +826,8 @@ public void shouldWorkWithEmptyGitDescribe(boolean useNativeGit) throws Exceptio setProjectToExecuteMojoIn(targetProject); GitDescribeConfig gitDescribeConfig = new GitDescribeConfig(); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -847,8 +848,8 @@ public void shouldWorkWithNullGitDescribe(boolean useNativeGit) throws Exception setProjectToExecuteMojoIn(targetProject); - mojo.setGitDescribe(null); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = null; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -873,8 +874,8 @@ public void shouldExtractTagsOnGivenCommit(boolean useNativeGit) throws Exceptio MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setGitDescribe(null); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = null; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -886,7 +887,7 @@ public void shouldExtractTagsOnGivenCommit(boolean useNativeGit) throws Exceptio assertThat(properties).satisfies(new ContainsKeyCondition("git.tags")); assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); - assertThat(Splitter.on(",").split(properties.get("git.tags").toString())) + assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) .containsOnly("lightweight-tag", "newest-tag"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "2"); } @@ -907,8 +908,8 @@ public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setGitDescribe(null); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = null; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -920,7 +921,7 @@ public void shouldExtractTagsOnGivenCommitWithOldestCommit(boolean useNativeGit) assertThat(properties).satisfies(new ContainsKeyCondition("git.tags")); assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); - assertThat(Splitter.on(",").split(properties.get("git.tags").toString())) + assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) .containsOnly("annotated-tag", "lightweight-tag", "newest-tag"); assertPropertyPresentAndEqual(targetProject.getProperties(), "git.total.commit.count", "1"); } @@ -937,8 +938,8 @@ public void shouldExtractTagsOnHead(boolean useNativeGit) throws Exception { MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setGitDescribe(null); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = null; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -950,7 +951,7 @@ public void shouldExtractTagsOnHead(boolean useNativeGit) throws Exception { assertThat(properties).satisfies(new ContainsKeyCondition("git.tags")); assertThat(properties.get("git.tags").toString()).doesNotContain("refs/tags/"); - assertThat(Splitter.on(",").split(properties.get("git.tags").toString())) + assertThat(Arrays.asList(properties.get("git.tags").toString().split(","))) .containsOnly("v1.0.0"); } @@ -979,8 +980,8 @@ public void runGitDescribeWithMatchOption(boolean useNativeGit) throws Exception gitDescribeConfig.setMatch(gitDescribeMatchNeedle); gitDescribeConfig.setAlways(false); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1010,8 +1011,8 @@ public void shouldGenerateClosestTagInformationWhenOnATag(boolean useNativeGit) GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(false, 7); gitDescribeConfig.setDirty("-dirty"); // checking if dirty works as expected - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1037,8 +1038,8 @@ public void shouldGenerateClosestTagInformationWhenOnATagAndDirty(boolean useNat GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); String dirtySuffix = "-dirtyTest"; gitDescribeConfig.setDirty(dirtySuffix); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1066,8 +1067,8 @@ public void shouldGenerateClosestTagInformationWhenCommitHasTwoTags(boolean useN MavenProject targetProject = mavenSandbox.getParentProject(); setProjectToExecuteMojoIn(targetProject); - mojo.setGitDescribe(null); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = null; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1099,10 +1100,10 @@ public void shouldUseDateFormatTimeZone(boolean useNativeGit) throws Exception { TimeZone executionTimeZone = TimeZone.getTimeZone("GMT" + executionTimeZoneOffset); GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); - mojo.setDateFormat(dateFormat); - mojo.setDateFormatTimeZone(expectedTimeZone.getID()); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; + mojo.dateFormat = dateFormat; + mojo.dateFormatTimeZone = expectedTimeZone.getID(); // override the default timezone for execution and testing TimeZone currentDefaultTimeZone = TimeZone.getDefault(); @@ -1133,8 +1134,8 @@ public void shouldGenerateCommitIdOldFashioned(boolean useNativeGit) throws Exce setProjectToExecuteMojoIn(targetProject); - mojo.setUseNativeGit(useNativeGit); - mojo.setCommitIdGenerationMode("flat"); + mojo.useNativeGit = useNativeGit; + mojo.commitIdGenerationMode = "flat"; // when mojo.execute(); @@ -1160,10 +1161,10 @@ public void testDetectCleanWorkingDirectory(boolean useNativeGit) throws Excepti GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); String dirtySuffix = "-dirtyTest"; gitDescribeConfig.setDirty(dirtySuffix); - mojo.setGitDescribe(gitDescribeConfig); + mojo.gitDescribe = gitDescribeConfig; - mojo.setUseNativeGit(useNativeGit); - mojo.setCommitIdGenerationMode("flat"); + mojo.useNativeGit = useNativeGit; + mojo.commitIdGenerationMode = "flat"; // when mojo.execute(); @@ -1189,10 +1190,10 @@ public void testDetectDirtyWorkingDirectory(boolean useNativeGit) throws Excepti GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); String dirtySuffix = "-dirtyTest"; gitDescribeConfig.setDirty(dirtySuffix); - mojo.setGitDescribe(gitDescribeConfig); + mojo.gitDescribe = gitDescribeConfig; - mojo.setUseNativeGit(useNativeGit); - mojo.setCommitIdGenerationMode("flat"); + mojo.useNativeGit = useNativeGit; + mojo.commitIdGenerationMode = "flat"; // when mojo.execute(); @@ -1218,8 +1219,8 @@ public void shouldGenerateClosestTagInformationWithExcludeLightweightTagsForClos gitDescribe.setDirty("-customDirtyMark"); gitDescribe.setTags(false); // exclude lightweight tags - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1251,8 +1252,8 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos gitDescribe.setDirty("-customDirtyMark"); gitDescribe.setTags(true); // include lightweight tags - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1282,8 +1283,8 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos gitDescribe.setDirty("-customDirtyMark"); gitDescribe.setTags(true); // include lightweight tags - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1314,8 +1315,8 @@ public void shouldGenerateClosestTagInformationWithIncludeLightweightTagsForClos gitDescribe.setTags(true); // include lightweight tags gitDescribe.setMatch("light*"); - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; // when mojo.execute(); @@ -1344,9 +1345,9 @@ public void verifyEvalOnDifferentCommitWithParentOfHead(boolean useNativeGit) th GitDescribeConfig gitDescribe = createGitDescribeConfig(true, 9); gitDescribe.setDirty(null); - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); - mojo.setEvaluateOnCommit("HEAD^1"); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; + mojo.evaluateOnCommit = "HEAD^1"; // when mojo.execute(); @@ -1375,9 +1376,9 @@ public void verifyEvalOnDifferentCommitWithBranchName(boolean useNativeGit) thro GitDescribeConfig gitDescribe = createGitDescribeConfig(true, 9); gitDescribe.setDirty(null); - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); - mojo.setEvaluateOnCommit("test"); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; + mojo.evaluateOnCommit = "test"; // when mojo.execute(); @@ -1408,9 +1409,9 @@ public void verifyEvalOnDifferentCommitWithTagName(boolean useNativeGit) throws GitDescribeConfig gitDescribe = createGitDescribeConfig(true, 9); gitDescribe.setDirty(null); - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); - mojo.setEvaluateOnCommit("test_tag"); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; + mojo.evaluateOnCommit = "test_tag"; // when mojo.execute(); @@ -1441,9 +1442,9 @@ public void verifyEvalOnDifferentCommitWithCommitHash(boolean useNativeGit) thro GitDescribeConfig gitDescribe = createGitDescribeConfig(true, 9); gitDescribe.setDirty(null); - mojo.setGitDescribe(gitDescribe); - mojo.setUseNativeGit(useNativeGit); - mojo.setEvaluateOnCommit("9cb810e"); + mojo.gitDescribe = gitDescribe; + mojo.useNativeGit = useNativeGit; + mojo.evaluateOnCommit = "9cb810e"; // when mojo.execute(); diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java index dc0fb571..ef06543d 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java @@ -23,7 +23,6 @@ import java.io.File; import java.io.IOException; -import java.util.Properties; import java.util.regex.Pattern; import static org.fest.assertions.Assertions.assertThat; @@ -31,30 +30,6 @@ import static org.junit.Assert.assertTrue; public class GitCommitIdMojoTest { - - @Test - public void loadShortDescribe() { - assertShortDescribe("1.0.2-12-g19471", "1.0.2-12"); - assertShortDescribe("v1.0.0-0-gde4db35917", "v1.0.0-0"); - assertShortDescribe("1.0.2-12-g19471-DEV", "1.0.2-12-DEV"); - assertShortDescribe("V-1.0.2-12-g19471-DEV", "V-1.0.2-12-DEV"); - - assertShortDescribe(null, null); - assertShortDescribe("12.4.0-1432", "12.4.0-1432"); - assertShortDescribe("12.6.0", "12.6.0"); - assertShortDescribe("", ""); - } - - private void assertShortDescribe(String commitDescribe, String expectedShortDescribe) { - GitCommitIdMojo commitIdMojo = new GitCommitIdMojo(); - Properties prop = new Properties(); - if (commitDescribe != null) { - prop.put(GitCommitPropertyConstant.COMMIT_DESCRIBE, commitDescribe); - } - commitIdMojo.loadShortDescribe(prop); - assertThat(prop.getProperty(GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE)).isEqualTo(expectedShortDescribe); - } - @Test public void testCraftPropertiesOutputFileWithRelativePath() throws IOException { GitCommitIdMojo commitIdMojo = new GitCommitIdMojo(); diff --git a/src/test/java/pl/project13/maven/git/GitDataProviderTest.java b/src/test/java/pl/project13/maven/git/GitDataProviderTest.java new file mode 100644 index 00000000..9abbd234 --- /dev/null +++ b/src/test/java/pl/project13/maven/git/GitDataProviderTest.java @@ -0,0 +1,60 @@ +/* + * This file is part of git-commit-id-plugin by Konrad 'ktoso' Malawski + * + * git-commit-id-plugin is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * git-commit-id-plugin is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with git-commit-id-plugin. If not, see . + */ + +package pl.project13.maven.git; + +import org.junit.Test; +import pl.project13.maven.git.log.LoggerBridge; + +import java.util.Properties; + +import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +public class GitDataProviderTest { + @Test + public void loadShortDescribe() { + assertShortDescribe("1.0.2-12-g19471", "1.0.2-12"); + assertShortDescribe("v1.0.0-0-gde4db35917", "v1.0.0-0"); + assertShortDescribe("1.0.2-12-g19471-DEV", "1.0.2-12-DEV"); + assertShortDescribe("V-1.0.2-12-g19471-DEV", "V-1.0.2-12-DEV"); + + assertShortDescribe(null, null); + assertShortDescribe("12.4.0-1432", "12.4.0-1432"); + assertShortDescribe("12.6.0", "12.6.0"); + assertShortDescribe("", ""); + } + + private void assertShortDescribe(String commitDescribe, String expectedShortDescribe) { + Properties prop = new Properties(); + if (commitDescribe != null) { + prop.put(GitCommitPropertyConstant.COMMIT_DESCRIBE, commitDescribe); + } + + TestGitDataProvider gitDataProvider = spy(TestGitDataProvider.class); + gitDataProvider.loadShortDescribe(prop); + assertThat(prop.getProperty(GitCommitPropertyConstant.COMMIT_SHORT_DESCRIBE)).isEqualTo(expectedShortDescribe); + } + + private abstract static class TestGitDataProvider extends GitDataProvider { + TestGitDataProvider() { + super(mock(LoggerBridge.class)); + setPrefixDot(""); + } + } +} diff --git a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java index 7026b50f..de6e7e7b 100644 --- a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java +++ b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java @@ -17,7 +17,6 @@ package pl.project13.maven.git; -import com.google.common.io.Files; import org.apache.maven.project.MavenProject; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,6 +24,7 @@ import org.mockito.junit.MockitoJUnitRunner; import java.io.File; +import java.nio.file.Files; import java.util.Collections; import java.util.List; @@ -41,7 +41,7 @@ public class GitDirLocatorTest { @Test public void shouldUseTheManuallySpecifiedDirectory() throws Exception { // given - File dotGitDir = Files.createTempDir(); + File dotGitDir = Files.createTempDirectory("temp").toFile(); try { // when diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index 4a0227e9..16a1a9cc 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -17,16 +17,16 @@ package pl.project13.maven.git; -import com.google.common.base.Optional; import org.apache.commons.io.FileUtils; import org.apache.maven.project.MavenProject; import org.eclipse.jgit.api.Git; -import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; +import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; +import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; public abstract class GitIntegrationTest { @@ -83,11 +83,11 @@ protected Git git() throws IOException, InterruptedException { } protected Optional projectDir() { - return Optional.absent(); + return Optional.empty(); } - @NotNull - protected File dotGitDir(@NotNull Optional projectDir) { + @Nonnull + protected File dotGitDir(@Nonnull Optional projectDir) { if (projectDir.isPresent()) { return new File(currSandbox + File.separator + projectDir.get() + File.separator + ".git"); } else { @@ -96,22 +96,23 @@ protected File dotGitDir(@NotNull Optional projectDir) { } public static void initializeMojoWithDefaults(GitCommitIdMojo mojo) { - mojo.setVerbose(false); - mojo.setSkipPoms(true); - mojo.setAbbrevLength(7); - mojo.setGenerateGitPropertiesFile(false); - mojo.setGenerateGitPropertiesFilename("src/main/resources/git.properties"); - mojo.setPrefix("git"); - mojo.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); - mojo.setFailOnNoGitDirectory(true); - mojo.setUseNativeGit(false); - mojo.setCommitIdGenerationMode("full"); - mojo.setEvaluateOnCommit(evaluateOnCommit); + mojo.verbose = false; + mojo.skipPoms = true; + mojo.abbrevLength = 7; + mojo.generateGitPropertiesFile = false; + mojo.generateGitPropertiesFilename = "src/main/resources/git.properties"; + mojo.prefix = "git"; + mojo.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"; + mojo.failOnNoGitDirectory = true; + mojo.useNativeGit = false; + mojo.commitIdGenerationMode = "full"; + mojo.evaluateOnCommit = evaluateOnCommit; + mojo.nativeGitTimeoutInMs = (30 * 1000); } - public void setProjectToExecuteMojoIn(@NotNull MavenProject project) { - mojo.setProject(project); - mojo.setDotGitDirectory(new File(project.getBasedir(), ".git")); + public void setProjectToExecuteMojoIn(@Nonnull MavenProject project) { + mojo.project = project; + mojo.dotGitDirectory = new File(project.getBasedir(), ".git"); } } diff --git a/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java b/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java index d04ee004..e38286b6 100644 --- a/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java +++ b/src/test/java/pl/project13/maven/git/GitPropertiesFileTest.java @@ -22,6 +22,7 @@ import org.junit.Test; import java.io.File; +import java.nio.charset.StandardCharsets; import java.util.*; import junitparams.JUnitParamsRunner; import junitparams.Parameters; @@ -57,9 +58,9 @@ public void shouldConformPropertiesFileWhenSpecialCharactersInValueString(boolea File expectedFile = new File(targetProject.getBasedir(), targetFilePath); setProjectToExecuteMojoIn(targetProject); - mojo.setGenerateGitPropertiesFile(true); - mojo.setGenerateGitPropertiesFilename(targetFilePath); - mojo.setUseNativeGit(useNativeGit); + mojo.generateGitPropertiesFile = true; + mojo.generateGitPropertiesFilename = targetFilePath; + mojo.useNativeGit = useNativeGit; // when try { @@ -75,13 +76,14 @@ public void shouldConformPropertiesFileWhenSpecialCharactersInValueString(boolea // when the properties file is conform // it does not matter if we read as UTF8 or ISO-8859-1 { - Properties propertiesFromFile = PropertyManager.readProperties(expectedFile, "UTF-8"); + + Properties propertiesFromFile = PropertyManager.readProperties(expectedFile, StandardCharsets.UTF_8); assertGitPropertiesPresentInProject(propertiesFromFile); assertThat(propertiesFromFile.get("git.commit.message.full")) .isEqualTo(propertiesInProject.get("git.commit.message.full")); } { - Properties propertiesFromFile = PropertyManager.readProperties(expectedFile, "ISO-8859-1"); + Properties propertiesFromFile = PropertyManager.readProperties(expectedFile, StandardCharsets.ISO_8859_1); assertGitPropertiesPresentInProject(propertiesFromFile); assertThat(propertiesFromFile.get("git.commit.message.full")) .isEqualTo(propertiesInProject.get("git.commit.message.full")); diff --git a/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java b/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java index 8188c07e..e7373df2 100644 --- a/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java +++ b/src/test/java/pl/project13/maven/git/GitSubmodulesTest.java @@ -18,9 +18,9 @@ package pl.project13.maven.git; import org.apache.maven.project.MavenProject; -import org.jetbrains.annotations.NotNull; import org.junit.Test; +import javax.annotation.Nonnull; import java.io.File; import java.util.Properties; @@ -46,9 +46,9 @@ public void shouldResolvePropertiesOnDefaultSettingsForNonPomProject() throws Ex assertGitPropertiesPresentInProject(targetProject.getProperties()); } - public void setProjectToExecuteMojoIn(@NotNull MavenProject project) { - mojo.setProject(project); - mojo.setDotGitDirectory(new File(project.getBasedir(), ".git")); + public void setProjectToExecuteMojoIn(@Nonnull MavenProject project) { + mojo.project = project; + mojo.dotGitDirectory = new File(project.getBasedir(), ".git"); } private void assertGitPropertiesPresentInProject(Properties properties) { diff --git a/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java b/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java index 2a8e4ba9..6edc5c22 100644 --- a/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java +++ b/src/test/java/pl/project13/maven/git/NaivePerformanceTest.java @@ -60,8 +60,8 @@ public void performance(boolean useNativeGit, int iterations) throws Exception { GitDescribeConfig gitDescribeConfig = createGitDescribeConfig(true, 7); gitDescribeConfig.setAlways(true); - mojo.setGitDescribe(gitDescribeConfig); - mojo.setUseNativeGit(useNativeGit); + mojo.gitDescribe = gitDescribeConfig; + mojo.useNativeGit = useNativeGit; // when long startTime = System.currentTimeMillis(); diff --git a/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java b/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java index 48f3dd1d..f4c07144 100644 --- a/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java +++ b/src/test/java/pl/project13/maven/git/NativeAndJGitProviderTest.java @@ -101,16 +101,16 @@ public void testCompareISO8601Time() throws Exception { private void verifyNativeAndJGit(AvailableGitTestRepo repo, MavenProject targetProject, String formatString) throws Exception { setProjectToExecuteMojoIn(targetProject); - mojo.setSkipPoms(false); - mojo.setDateFormat(formatString); + mojo.skipPoms = false; + mojo.dateFormat = formatString; DateFormat format = new SimpleDateFormat(formatString); - mojo.setUseNativeGit(false); + mojo.useNativeGit = false; mojo.execute(); Properties jgitProps = createCopy(targetProject.getProperties()); - mojo.setUseNativeGit(true); + mojo.useNativeGit = true; mojo.execute(); Properties nativeProps = createCopy(targetProject.getProperties()); diff --git a/src/test/java/pl/project13/maven/git/UriUserInfoRemoverTest.java b/src/test/java/pl/project13/maven/git/UriUserInfoRemoverTest.java index 4343bb02..a7570a50 100644 --- a/src/test/java/pl/project13/maven/git/UriUserInfoRemoverTest.java +++ b/src/test/java/pl/project13/maven/git/UriUserInfoRemoverTest.java @@ -58,7 +58,7 @@ public static Collection parameters() { @Parameters(method = "parameters") public void testStripCrecentialsFromOriginUrl(String input, String expected) throws GitCommitIdExecutionException { GitDataProvider gitDataProvider = mock(GitDataProvider.class); - when(gitDataProvider.stripCredentialsFromOriginUrl(ArgumentMatchers.any())).thenCallRealMethod(); + when(gitDataProvider.stripCredentialsFromOriginUrl(ArgumentMatchers.any())).thenCallRealMethod(); String result = gitDataProvider.stripCredentialsFromOriginUrl(input); assertEquals(expected, result); } diff --git a/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java b/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java index 0c6751e1..b04dad08 100644 --- a/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java +++ b/src/test/java/pl/project13/maven/validation/ValidationMojoTest.java @@ -69,7 +69,7 @@ private void executeMojo(List validationProperties, boolean } private List getListValidationProperty(String name, String value, String shouldMatchTo) { - List list = new ArrayList(); + List list = new ArrayList<>(); list.add(new ValidationProperty(name, value, shouldMatchTo)); return list; } diff --git a/src/test/resources/checks/google_checks_checkstyle_6.11.2.xml b/src/test/resources/checks/google_checks_checkstyle_6.11.2.xml deleted file mode 100644 index 14c811ba..00000000 --- a/src/test/resources/checks/google_checks_checkstyle_6.11.2.xml +++ /dev/null @@ -1,221 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -