diff --git a/README.md b/README.md
index f356d5c5..a2213bf7 100644
--- a/README.md
+++ b/README.md
@@ -118,7 +118,7 @@ It's really simple to setup this plugin; below is a sample pom that you may base
${project.basedir}/.git
@@ -207,7 +207,7 @@ It's really simple to setup this plugin; below is a sample pom that you may base
+
+ org.apache.maven.plugin-tools
+ maven-plugin-annotations
+ ${maven-plugin-plugin.version}
+ provided
+
+
com.fasterxml.jackson.corejackson-databind
- 2.5.1
+ 2.6.4joda-timejoda-time
- 2.7
+ 2.9.1com.google.guavaguava
- 18.0
+ 19.0
@@ -129,18 +118,6 @@
${jgit.version}
-
- org.slf4j
- slf4j-api
- ${slf4j.version}
-
-
-
- org.slf4j
- slf4j-simple
- ${slf4j.version}
-
-
junit
@@ -159,7 +136,7 @@
org.codehaus.plexusplexus-utils
- 3.0.21
+ 3.0.22test
@@ -184,6 +161,14 @@
1.0.4test
+
+
+
+ org.slf4j
+ slf4j-simple
+ 1.7.13
+ test
+
@@ -198,6 +183,80 @@
+
+
+ src/test/resources
+
+ _git_*/**
+ README.md
+
+
+
+
+
+
+
+ maven-antrun-plugin
+ 1.8
+
+
+ maven-assembly-plugin
+ 2.6
+
+
+ maven-dependency-plugin
+ 2.10
+
+
+ maven-release-plugin
+ 2.5.3
+
+
+ maven-enforcer-plugin
+ 1.4.1
+
+
+ maven-compiler-plugin
+ 3.3
+
+
+ maven-gpg-plugin
+ 1.6
+
+
+ maven-clean-plugin
+ 3.0.0
+
+
+ maven-resources-plugin
+ 2.7
+
+
+ maven-jar-plugin
+ 2.6
+
+
+ maven-plugin-plugin
+ ${maven-plugin-plugin.version}
+
+
+ maven-surefire-plugin
+ 2.19
+
+
+ maven-install-plugin
+ 2.5.2
+
+
+ maven-deploy-plugin
+ 2.8.2
+
+
+ maven-site-plugin
+ 3.4
+
+
+
@@ -205,57 +264,34 @@
org.apache.maven.pluginsmaven-compiler-plugin
- 2.5.1
- UTF-8${java.target}${java.target}
-
+
org.apache.maven.plugins
- maven-shade-plugin
- 2.3
+ maven-plugin-plugin
- package
+ default-descriptor
+ process-classes
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -339,5 +375,4 @@
-
-
+
\ No newline at end of file
diff --git a/src/main/java/pl/project13/jgit/DescribeCommand.java b/src/main/java/pl/project13/jgit/DescribeCommand.java
index a9fd2ee0..82554225 100644
--- a/src/main/java/pl/project13/jgit/DescribeCommand.java
+++ b/src/main/java/pl/project13/jgit/DescribeCommand.java
@@ -36,7 +36,6 @@
import pl.project13.jgit.dummy.DatedRevTag;
import pl.project13.maven.git.GitDescribeConfig;
import pl.project13.maven.git.log.LoggerBridge;
-import pl.project13.maven.git.log.StdOutLoggerBridge;
import pl.project13.maven.git.util.Pair;
import java.io.IOException;
@@ -47,7 +46,7 @@
*/
public class DescribeCommand extends GitCommand {
- private LoggerBridge loggerBridge;
+ private LoggerBridge log;
private JGitCommon jGitCommon;
// TODO not yet implemented options:
@@ -85,11 +84,12 @@ public class DescribeCommand extends GitCommand {
/**
* Creates a new describe command which interacts with a single repository
*
- * @param repo the {@link org.eclipse.jgit.lib.Repository} this command should interact with
+ * @param repo the {@link Repository} this command should interact with
+ * @param log logger bridge to direct logs to
*/
@NotNull
- public static DescribeCommand on(Repository repo) {
- return new DescribeCommand(repo);
+ public static DescribeCommand on(Repository repo, LoggerBridge log) {
+ return new DescribeCommand(repo, log);
}
/**
@@ -97,31 +97,10 @@ public static DescribeCommand on(Repository repo) {
*
* @param repo the {@link org.eclipse.jgit.lib.Repository} this command should interact with
*/
- private DescribeCommand(Repository repo) {
- this(repo, true);
- }
-
- private DescribeCommand(Repository repo, boolean verbose) {
+ private DescribeCommand(Repository repo, @NotNull LoggerBridge log) {
super(repo);
- initDefaultLoggerBridge(verbose);
- setVerbose(verbose);
- this.jGitCommon = new JGitCommon();
- }
-
- private void initDefaultLoggerBridge(boolean verbose) {
- loggerBridge = new StdOutLoggerBridge(verbose);
- }
-
- @NotNull
- public DescribeCommand setVerbose(boolean verbose) {
- loggerBridge.setVerbose(verbose);
- return this;
- }
-
- @NotNull
- public DescribeCommand withLoggerBridge(LoggerBridge bridge) {
- this.loggerBridge = bridge;
- return this;
+ this.jGitCommon = new JGitCommon(log);
+ this.log = log;
}
/**
@@ -134,7 +113,7 @@ public DescribeCommand withLoggerBridge(LoggerBridge bridge) {
@NotNull
public DescribeCommand always(boolean always) {
this.alwaysFlag = always;
- log("--always =", always);
+ log.info("--always = {}", always);
return this;
}
@@ -153,7 +132,7 @@ public DescribeCommand always(boolean always) {
public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) {
if (forceLongFormat != null && forceLongFormat) {
this.forceLongFormat = true;
- log("--long =", true);
+ log.info("--long = {}", true);
}
return this;
}
@@ -169,9 +148,9 @@ public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) {
@NotNull
public DescribeCommand abbrev(@Nullable Integer n) {
if (n != null) {
- Preconditions.checkArgument(n < 41, String.format("N (commit abbres length) must be < 41. (Was:[%s])", n));
+ Preconditions.checkArgument(n < 41, String.format("N (commit abbrev length) must be < 41. (Was:[%s])", n));
Preconditions.checkArgument(n >= 0, String.format("N (commit abbrev length) must be positive! (Was [%s])", n));
- log("--abbrev =", n);
+ log.info("--abbrev = {}", n);
abbrev = n;
}
return this;
@@ -209,7 +188,7 @@ public DescribeCommand abbrev(@Nullable Integer n) {
public DescribeCommand tags(@Nullable Boolean includeLightweightTagsInSearch) {
if (includeLightweightTagsInSearch != null && includeLightweightTagsInSearch) {
tagsFlag = includeLightweightTagsInSearch;
- log("--tags =", includeLightweightTagsInSearch);
+ log.info("--tags = {}", includeLightweightTagsInSearch);
}
return this;
}
@@ -251,7 +230,7 @@ public DescribeCommand apply(@Nullable GitDescribeConfig config) {
@NotNull
public DescribeCommand dirty(@Nullable String dirtyMarker) {
Optional option = Optional.fromNullable(dirtyMarker);
- log("--dirty =", option.or(""));
+ log.info("--dirty = {}", option.or(""));
this.dirtyOption = option;
return this;
}
@@ -267,7 +246,7 @@ public DescribeCommand dirty(@Nullable String dirtyMarker) {
public DescribeCommand match(@Nullable String pattern) {
if (!"*".equals(pattern)) {
matchOption = Optional.fromNullable(pattern);
- log("--match =", matchOption.or(""));
+ log.info("--match = {}", matchOption.or(""));
}
return this;
}
@@ -289,7 +268,7 @@ public DescribeResult call() throws GitAPIException {
if (hasTags(headCommit, tagObjectIdToName) && !forceLongFormat) {
String tagName = tagObjectIdToName.get(headCommit).iterator().next();
- log("The commit we're on is a Tag ([",tagName,"]) and forceLongFormat == false, returning.");
+ log.info("The commit we're on is a Tag ([{}]) and forceLongFormat == false, returning.", tagName);
return new DescribeResult(tagName, dirty, dirtyOption);
}
@@ -362,7 +341,7 @@ boolean findDirtyState(Repository repo) throws GitAPIException {
&& status.getModified().isEmpty()
&& status.getConflicting().isEmpty());
- log("Repo is in dirty state [", isDirty, "]");
+ log.info("Repo is in dirty state [{}]", isDirty);
return isDirty;
}
@@ -379,7 +358,7 @@ RevCommit findHeadObjectId(@NotNull Repository repo) throws RuntimeException {
RevCommit headCommit = walk.lookupCommit(headId);
walk.dispose();
- log("HEAD is [",headCommit.getName(),"] ");
+ log.info("HEAD is [{}]", headCommit.getName());
return headCommit;
} catch (IOException ex) {
throw new RuntimeException("Unable to obtain HEAD commit!", ex);
@@ -389,9 +368,9 @@ RevCommit findHeadObjectId(@NotNull Repository repo) throws RuntimeException {
// git commit id -> its tag (or tags)
private Map> findTagObjectIds(@NotNull Repository repo, boolean tagsFlag) {
String matchPattern = createMatchPattern();
- Map> commitIdsToTags = jGitCommon.getCommitIdsToTags(loggerBridge, repo, tagsFlag, matchPattern);
+ Map> commitIdsToTags = jGitCommon.getCommitIdsToTags(repo, tagsFlag, matchPattern);
Map> commitIdsToTagNames = jGitCommon.transformRevTagsMapToDateSortedTagNames(commitIdsToTags);
- log("Created map: [",commitIdsToTagNames,"] ");
+ log.info("Created map: [{}]", commitIdsToTagNames);
return commitIdsToTagNames;
}
@@ -401,15 +380,8 @@ private String createMatchPattern() {
return ".*";
}
- StringBuffer buf = new StringBuffer();
- buf.append("^refs/tags/\\Q");
- buf.append(matchOption.get().replace("*", "\\E.*\\Q").replace("?", "\\E.\\Q"));
- buf.append("\\E$");
- return buf.toString();
- }
-
- private void log(Object... parts) {
- loggerBridge.log(parts);
+ return "^refs/tags/\\Q" +
+ matchOption.get().replace("*", "\\E.*\\Q").replace("?", "\\E.\\Q") +
+ "\\E$";
}
-}
-
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/jgit/DescribeResult.java b/src/main/java/pl/project13/jgit/DescribeResult.java
index ba3f0647..285a2cc2 100644
--- a/src/main/java/pl/project13/jgit/DescribeResult.java
+++ b/src/main/java/pl/project13/jgit/DescribeResult.java
@@ -27,10 +27,11 @@
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
-import static com.google.common.collect.Lists.newArrayList;
-
/**
* Represents the result of a git describe command.
*
@@ -134,9 +135,9 @@ public String toString() {
List parts;
if (abbrevZeroHidesCommitsPartOfDescribe()) {
- parts = newArrayList(tag());
+ parts = new ArrayList<>(Collections.singletonList(tag()));
} else {
- parts = newArrayList(tag(), commitsAwayFromTag(), prefixedCommitId());
+ 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. "-")
@@ -160,7 +161,7 @@ public String dirtyMarker() {
}
/**
- *
The (possibly) "g" prefixed abbriverated object id of a commit.
+ *
The (possibly) "g" prefixed abbreviated object id of a commit.
*
* The "g" prefix is prepended to be compatible with git's describe output, please refer to
* man git-describe to check why it's included.
@@ -170,8 +171,8 @@ public String dirtyMarker() {
* This is following git's behaviour - so any git tooling should be happy with this output.
*
*
- * Notes about the abbriverated object id:
- * Git will try to use your given abbrev lenght, but when it's to short to guarantee uniqueness -
+ * Notes about the abbreviated object id:
+ * Git will try to use your given abbrev length, but when it's too short to guarantee uniqueness -
* a longer one will be used (which WILL guarantee uniqueness).
* If you need the full commit id, it's always available via {@link pl.project13.jgit.DescribeResult#commitObjectId()}.
*
@@ -208,14 +209,14 @@ 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 requestedLenght) {
- if(requestedLenght < 2) {
+ private static Optional createAbbreviatedCommitId(@NotNull 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();
}
try {
- AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(commitId, requestedLenght);
+ AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(commitId, requestedLength);
return Optional.of(abbreviatedObjectId);
} catch (IOException e) {
return Optional.absent();
diff --git a/src/main/java/pl/project13/jgit/JGitCommon.java b/src/main/java/pl/project13/jgit/JGitCommon.java
index a991ca7e..725549ae 100644
--- a/src/main/java/pl/project13/jgit/JGitCommon.java
+++ b/src/main/java/pl/project13/jgit/JGitCommon.java
@@ -17,20 +17,8 @@
package pl.project13.jgit;
-import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.collect.Maps.newHashMap;
-
import java.io.IOException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-import java.util.Set;
+import java.util.*;
import java.util.regex.Pattern;
import org.eclipse.jgit.api.Git;
@@ -45,21 +33,22 @@
import org.jetbrains.annotations.NotNull;
import pl.project13.jgit.dummy.DatedRevTag;
-import pl.project13.maven.git.log.LoggerBridge;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
-import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.collect.Lists.newLinkedList;
-import static com.google.common.collect.Maps.newHashMap;
-import static com.google.common.collect.Sets.newHashSet;
+import pl.project13.maven.git.log.LoggerBridge;
public class JGitCommon {
+
+ private final LoggerBridge log;
+
+ public JGitCommon(LoggerBridge log) {
+ this.log = log;
+ }
+
public Collection getTags(Repository repo, final ObjectId headId) throws GitAPIException{
RevWalk walk = null;
try {
@@ -88,8 +77,6 @@ public Collection getTags(Repository repo, final ObjectId headId) throws
});
return tags;
- } catch (GitAPIException e) {
- throw e;
} finally {
if (walk != null) {
walk.dispose();
@@ -97,16 +84,16 @@ public Collection getTags(Repository repo, final ObjectId headId) throws
}
}
- public String getClosestTagName(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo){
- Map> map = getClosestTagAsMap(loggerBridge,repo);
+ public String getClosestTagName(@NotNull Repository repo){
+ Map> map = getClosestTagAsMap(repo);
for(Map.Entry> entry : map.entrySet()){
return trimFullTagName(entry.getValue().get(0).tagName);
}
return "";
}
- public String getClosestTagCommitCount(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo, RevCommit headCommit){
- HashMap> map = transformRevTagsMapToDateSortedTagNames(getClosestTagAsMap(loggerBridge,repo));
+ public String getClosestTagCommitCount(@NotNull Repository repo, RevCommit headCommit){
+ HashMap> map = transformRevTagsMapToDateSortedTagNames(getClosestTagAsMap(repo));
ObjectId obj = (ObjectId) map.keySet().toArray()[0];
RevWalk walk = new RevWalk(repo);
@@ -117,14 +104,13 @@ public String getClosestTagCommitCount(@NotNull LoggerBridge loggerBridge,@NotNu
return String.valueOf(distance);
}
- private Map> getClosestTagAsMap(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo){
- Map> mapWithClosestTagOnly = newHashMap();
- boolean includeLightweightTags = true;
+ private Map> getClosestTagAsMap(@NotNull Repository repo){
+ Map> mapWithClosestTagOnly = new HashMap<>();
String matchPattern = ".*";
- Map> commitIdsToTags = getCommitIdsToTags(loggerBridge,repo,includeLightweightTags,matchPattern);
+ Map> commitIdsToTags = getCommitIdsToTags(repo, true, matchPattern);
LinkedHashMap> sortedCommitIdsToTags = sortByDatedRevTag(commitIdsToTags);
- for(Map.Entry> entry: sortedCommitIdsToTags.entrySet()){
+ for (Map.Entry> entry: sortedCommitIdsToTags.entrySet()){
mapWithClosestTagOnly.put(entry.getKey(), entry.getValue());
break;
}
@@ -133,7 +119,7 @@ private Map> getClosestTagAsMap(@NotNull LoggerBridg
}
private LinkedHashMap> sortByDatedRevTag(Map> map) {
- List>> list = new LinkedList>>(map.entrySet());
+ List>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator>>() {
public int compare(Map.Entry> m1, Map.Entry> m2) {
@@ -147,29 +133,28 @@ public int compare(Map.Entry> m1, Map.Entry> result = new LinkedHashMap>();
+ LinkedHashMap> result = new LinkedHashMap<>();
for (Map.Entry> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
- protected Map> getCommitIdsToTags(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo, boolean includeLightweightTags, String matchPattern){
- Map> commitIdsToTags = newHashMap();
+ protected Map> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern){
+ Map> commitIdsToTags = new HashMap<>();
- RevWalk walk = new RevWalk(repo);
- try {
+ try (RevWalk walk = new RevWalk(repo)) {
walk.markStart(walk.parseCommit(repo.resolve("HEAD")));
List tagRefs = Git.wrap(repo).tagList().call();
Pattern regex = Pattern.compile(matchPattern);
- loggerBridge.log("Tag refs [", tagRefs, "]");
+ log.info("Tag refs [{}]", tagRefs);
for (Ref tagRef : tagRefs) {
walk.reset();
String name = tagRef.getName();
if (!regex.matcher(name).matches()) {
- loggerBridge.log("Skipping tagRef with name [", name, "] as it doesn't match [", matchPattern, "]");
+ log.info("Skipping tagRef with name [{}] as it doesn't match [{}]", name, matchPattern);
continue;
}
ObjectId resolvedCommitId = repo.resolve(name);
@@ -178,7 +163,7 @@ protected Map> getCommitIdsToTags(@NotNull LoggerBri
try {
final RevTag revTag = walk.parseTag(resolvedCommitId);
ObjectId taggedCommitId = revTag.getObject().getId();
- loggerBridge.log("Resolved tag [",revTag.getTagName(),"] [",revTag.getTaggerIdent(),"], points at [",taggedCommitId,"] ");
+ log.info("Resolved tag [{}] [{}], points at [{}] ", revTag.getTagName(), revTag.getTaggerIdent(), taggedCommitId);
// sometimes a tag, may point to another tag, so we need to unpack it
while (isTagId(taggedCommitId)) {
@@ -188,36 +173,34 @@ protected Map> getCommitIdsToTags(@NotNull LoggerBri
if (commitIdsToTags.containsKey(taggedCommitId)) {
commitIdsToTags.get(taggedCommitId).add(new DatedRevTag(revTag));
} else {
- commitIdsToTags.put(taggedCommitId, newArrayList(new DatedRevTag(revTag)));
+ commitIdsToTags.put(taggedCommitId, new ArrayList<>(Collections.singletonList(new DatedRevTag(revTag))));
}
} catch (IncorrectObjectTypeException ex) {
// it's an lightweight tag! (yeah, really)
if (includeLightweightTags) {
// --tags means "include lightweight tags"
- loggerBridge.log("Including lightweight tag [", name, "]");
+ log.info("Including lightweight tag [{}]", name);
DatedRevTag datedRevTag = new DatedRevTag(resolvedCommitId, name);
if (commitIdsToTags.containsKey(resolvedCommitId)) {
commitIdsToTags.get(resolvedCommitId).add(datedRevTag);
} else {
- commitIdsToTags.put(resolvedCommitId, newArrayList(datedRevTag));
+ commitIdsToTags.put(resolvedCommitId, new ArrayList<>(Collections.singletonList(datedRevTag)));
}
}
} catch (Exception ignored) {
- loggerBridge.error("Failed while parsing [",tagRef,"] -- ", Throwables.getStackTraceAsString(ignored));
+ log.info("Failed while parsing [{}] -- ", tagRef, ignored);
}
}
for (Map.Entry> entry : commitIdsToTags.entrySet()) {
- loggerBridge.log("key [",entry.getKey(),"], tags => [",entry.getValue(),"] ");
+ log.info("key [{}], tags => [{}] ", entry.getKey(), entry.getValue());
}
- return commitIdsToTags;
+ return commitIdsToTags;
} catch (Exception e) {
- loggerBridge.log("Unable to locate tags\n[",Throwables.getStackTraceAsString(e),"]");
- } finally {
- walk.close();
+ log.info("Unable to locate tags", e);
}
return Collections.emptyMap();
}
@@ -228,7 +211,7 @@ private boolean isTagId(ObjectId objectId) {
}
protected HashMap> transformRevTagsMapToDateSortedTagNames(Map> commitIdsToTags) {
- HashMap> commitIdsToTagNames = newHashMap();
+ HashMap> commitIdsToTagNames = new HashMap<>();
for (Map.Entry> objectIdListEntry : commitIdsToTags.entrySet()) {
List tagNames = transformRevTagsMapEntryToDateSortedTagNames(objectIdListEntry);
@@ -240,7 +223,7 @@ protected HashMap> transformRevTagsMapToDateSortedTagName
private List transformRevTagsMapEntryToDateSortedTagNames(Map.Entry> objectIdListEntry) {
List tags = objectIdListEntry.getValue();
- List newTags = newArrayList(tags);
+ List newTags = new ArrayList<>(tags);
Collections.sort(newTags, datedRevTagComparator());
List tagNames = Lists.transform(newTags, new Function() {
@@ -267,8 +250,7 @@ protected String trimFullTagName(@NotNull String tagName) {
}
public List findCommitsUntilSomeTag(Repository repo, RevCommit head, @NotNull Map> tagObjectIdToName) {
- RevWalk revWalk = new RevWalk(repo);
- try {
+ try (RevWalk revWalk = new RevWalk(repo)) {
revWalk.markStart(head);
for (RevCommit commit : revWalk) {
@@ -294,14 +276,12 @@ public List findCommitsUntilSomeTag(Repository repo, RevCommit head,
* @see mdonoughe/jgit-describe/blob/master/src/org/mdonoughe/JGitDescribeTask.java
*/
protected int distanceBetween(@NotNull Repository repo, @NotNull RevCommit child, @NotNull RevCommit parent) {
- RevWalk revWalk = new RevWalk(repo);
-
- try {
+ try (RevWalk revWalk = new RevWalk(repo)) {
revWalk.markStart(child);
- Set seena = newHashSet();
- Set seenb = newHashSet();
- Queue q = newLinkedList();
+ Set seena = new HashSet<>();
+ Set seenb = new HashSet<>();
+ Queue q = new ArrayDeque<>();
q.add(revWalk.parseCommit(child));
int distance = 0;
@@ -339,13 +319,11 @@ protected int distanceBetween(@NotNull Repository repo, @NotNull RevCommit child
return distance;
} catch (Exception e) {
throw new RuntimeException(String.format("Unable to calculate distance between [%s] and [%s]", child, parent), e);
- } finally {
- revWalk.dispose();
}
}
private void seeAllParents(@NotNull RevWalk revWalk, RevCommit child, @NotNull Set seen) throws IOException {
- Queue q = newLinkedList();
+ Queue q = new ArrayDeque<>();
q.add(child);
while (q.size() > 0) {
@@ -360,4 +338,4 @@ private void seeAllParents(@NotNull RevWalk revWalk, RevCommit child, @NotNull S
}
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/CommitIdGenerationModeEnum.java b/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java
similarity index 70%
rename from src/main/java/pl/project13/maven/git/CommitIdGenerationModeEnum.java
rename to src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java
index 3dc0168c..df76e6f0 100644
--- a/src/main/java/pl/project13/maven/git/CommitIdGenerationModeEnum.java
+++ b/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java
@@ -16,19 +16,7 @@
*/
package pl.project13.maven.git;
-public enum CommitIdGenerationModeEnum{
+public enum CommitIdGenerationMode {
FULL,
- FLAT,
- UNKNOWN;
-
- public static CommitIdGenerationModeEnum getValue(String o){
- if(o != null){
- for(CommitIdGenerationModeEnum v : values()){
- if(v.name().toString().equalsIgnoreCase(o)){
- return v;
- }
- }
- }
- return CommitIdGenerationModeEnum.UNKNOWN;
- }
+ FLAT;
}
diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdExecutionException.java b/src/main/java/pl/project13/maven/git/GitCommitIdExecutionException.java
new file mode 100644
index 00000000..e278aad4
--- /dev/null
+++ b/src/main/java/pl/project13/maven/git/GitCommitIdExecutionException.java
@@ -0,0 +1,45 @@
+/*
+ * 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;
+
+/**
+ * Exception used by plugin. Plugin code should operate using this exception, which can then be wrapped into
+ * build-tool specific exception at the top level.
+ */
+public class GitCommitIdExecutionException extends Exception {
+
+ public GitCommitIdExecutionException() {
+ super();
+ }
+
+ public GitCommitIdExecutionException(String message) {
+ super(message);
+ }
+
+ public GitCommitIdExecutionException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public GitCommitIdExecutionException(Throwable cause) {
+ super(cause);
+ }
+
+ public GitCommitIdExecutionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
+ super(message, cause, enableSuppression, writableStackTrace);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java
index 525ad929..a14c33e5 100644
--- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java
+++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java
@@ -20,7 +20,6 @@
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
@@ -31,6 +30,9 @@
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugins.annotations.LifecyclePhase;
+import org.apache.maven.plugins.annotations.Mojo;
+import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -42,8 +44,9 @@
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
-import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -52,24 +55,19 @@
import java.util.TimeZone;
/**
- * Goal which puts git build-time information into property files or maven's properties.
+ * Puts git build-time information into property files or maven's properties.
*
- * @goal revision
- * @phase initialize
- * @requiresProject
- * @threadSafe true
* @since 1.0
*/
-@SuppressWarnings({"JavaDoc"})
+@Mojo(name = "revision", defaultPhase = LifecyclePhase.INITIALIZE, threadSafe = true)
public class GitCommitIdMojo extends AbstractMojo {
// these properties will be exposed to maven
public static final String BRANCH = "branch";
public static final String DIRTY = "dirty";
+ // only one of the following two will be exposed, depending on the commitIdGenerationMode
public static final String COMMIT_ID_FLAT = "commit.id";
public static final String COMMIT_ID_FULL = "commit.id.full";
- public static String COMMIT_ID = COMMIT_ID_FLAT;
-
public static final String COMMIT_ID_ABBREV = "commit.id.abbrev";
public static final String COMMIT_DESCRIBE = "commit.id.describe";
public static final String COMMIT_SHORT_DESCRIBE = "commit.id.describe-short";
@@ -88,358 +86,314 @@ public class GitCommitIdMojo extends AbstractMojo {
public static final String CLOSEST_TAG_NAME = "closest.tag.name";
public static final String CLOSEST_TAG_COMMIT_COUNT = "closest.tag.commit.count";
+ // TODO fix access modifier
/**
- * The maven project.
- *
- * @parameter property="project" default-value="${project}"
- * @readonly
+ * The Maven Project.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "${project}", readonly = true, required = true)
MavenProject project;
/**
- * Contains the full list of projects in the reactor.
- *
- * @parameter property="reactorProjects" default-value="${reactorProjects}"
- * @readonly
+ * The list of projects in the reactor.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "${reactorProjects}", readonly = true)
private List reactorProjects;
/**
- * Tell git-commit-id to inject the git properties into all
- * reactor projects not just the current one.
- *
- * For details about why you might want to skip this, read this issue: https://github.com/ktoso/maven-git-commit-id-plugin/pull/65
- * Basically, injecting into all projects may slow down the build and you don't always need this feature.
+ * The Maven Session Object.
+ */
+ @Parameter(property = "session", required = true, readonly = true)
+ private MavenSession session;
+
+ /**
+ *
Set this to {@code 'true'} to inject git properties into all reactor projects, not just the current one.
*
- * @parameter default-value="false"
+ *
Injecting into all projects may slow down the build and you don't always need this feature.
+ * See pull #65 for details about why you might want to skip this.
+ *
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "false")
private boolean injectAllReactorProjects;
/**
- * Specifies whether the goal runs in verbose mode.
- * To be more specific, this means more info being printed out while scanning for paths and also
- * it will make git-commit-id "eat it's own dog food" :-)
- *
- * @parameter default-value="false"
+ * Set this to {@code 'true'} to print more info while scanning for paths.
+ * It will make git-commit-id "eat its own dog food" :-)
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "false")
private boolean verbose;
/**
- * Specifies whether the execution in pom projects should be skipped.
- * Override this value to false if you want to force the plugin to run on 'pom' packaged projects.
- *
- * @parameter parameter="git.skipPoms" default-value="true"
+ * Set this to {@code 'false'} to execute plugin in 'pom' packaged projects.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "true")
private boolean skipPoms;
/**
- * Specifies whether plugin should generate properties file.
- * By default it will not generate any additional file,
- * and only add properties to maven project's properties for further filtering
- *
- * If set to "true" properties will be fully generated with no placeholders inside.
- *
- * @parameter default-value="false"
+ * Set this to {@code 'true'} to generate {@code 'git.properties'} file.
+ * By default plugin only adds properties to maven project properties.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "false")
private boolean generateGitPropertiesFile;
/**
- * Decide where to generate the git.properties file. By default, the ${project.build.outputDirectory}/git.properties
- * file will be updated - of course you must first set generateGitPropertiesFile = true to force git-commit-id
- * into generateFile mode.
- *
- * The path here is relative to your projects src directory.
+ *
The location of {@code 'git.properties'} file. Set {@code 'generateGitPropertiesFile'} to {@code 'true'}
+ * to generate this file.
The path here is relative to your project src directory.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "${project.build.outputDirectory}/git.properties")
private String generateGitPropertiesFilename;
/**
- * The root directory of the repository we want to check
- *
- * @parameter default-value="${project.basedir}/.git"
+ * The root directory of the repository we want to check.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "${project.basedir}/.git")
private File dotGitDirectory;
/**
- * Configuration for the
git-describe
command.
+ * Configuration for the {@code 'git-describe'} command.
* You can modify the dirty marker, abbrev length and other options here.
- *
- * If not specified, default values will be used.
- *
- * @parameter
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter
private GitDescribeConfig gitDescribe;
/**
- *
- * Configure the "git.commit.id.abbrev" property to be at least of length N.
- * N must be in the range of 2 to 40 (inclusive), other values will result in an Exception.
- *
+ *
Minimum length of {@code 'git.commit.id.abbrev'} property.
+ * Value must be from 2 to 40 (inclusive), other values will result in an exception.
*
- *
- * An Abbreviated commit is a shorter version of the commit id, it is guaranteed to be unique though.
- * To keep this contract, the plugin may decide to print an abbrev version that is longer than the value specified here.
- *
+ *
An abbreviated commit is a shorter version of commit id. However, it is guaranteed to be unique.
+ * To keep this contract, the plugin may decide to print an abbreviated version
+ * that is longer than the value specified here.
*
- * Example:
- *
- * You have a very big repository, yet you set this value to 2. It's very probable that you'll end up getting a 4 or 7 char
- * long abbrev version of the commit id. If your repository, on the other hand, has just 4 commits, you'll probably get a 2 char long abbrev.
- *
+ *
Example: You have a very big repository, yet you set this value to 2. It's very probable that you'll end up
+ * getting a 4 or 7 char long abbrev version of the commit id. If your repository, on the other hand,
+ * has just 4 commits, you'll probably get a 2 char long abbreviation.
*
- * @parameter default-value=7
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "7")
private int abbrevLength;
/**
- * The format to save properties in. Valid options are "properties" (default) and "json".
- *
- * @parameter default-value="properties"
+ * The format to save properties in: {@code 'properties'} or {@code 'json'}.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "properties")
private String format;
/**
- * The prefix to expose the properties on, for example 'git' would allow you to access '${git.branch}'
- *
- * @parameter default-value="git"
+ * The prefix to expose the properties on. For example {@code 'git'} would allow you to access {@code ${git.branch}}.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "git")
private String prefix;
+ // prefix with dot appended if needed
private String prefixDot = "";
/**
- * The date format to be used for any dates exported by this plugin.
- * It should be a valid SimpleDateFormat string.
- *
- * @parameter default-value="dd.MM.yyyy '@' HH:mm:ss z"
+ * The date format to be used for any dates exported by this plugin. It should be a valid {@link SimpleDateFormat} string.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "dd.MM.yyyy '@' HH:mm:ss z")
private String dateFormat;
/**
- * The timezone used in the date format that's used for any dates exported by this plugin.
- * It should be a valid Timezone string (e.g. 'America/Los_Angeles', 'GMT+10', 'PST').
- * As a general warning try to avoid three-letter time zone IDs because the same abbreviation are often used for multiple time zones.
- * Please review https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html for more information on this issue.
- * will use the timezone that's shipped with java as a default (java.util.TimeZone.getDefault().getID())
- *
- * @parameter
+ *
The timezone used in the date format of dates exported by this plugin.
+ * It should be a valid Timezone string such as {@code 'America/Los_Angeles'}, {@code 'GMT+10'} or {@code 'PST'}.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter
private String dateFormatTimeZone;
-
-
/**
- * Specifies whether the plugin should fail if it can't find the .git directory. The default
- * value is true.
- *
- * @parameter default-value="true"
+ * Set this to {@code 'false'} to continue the build on missing {@code '.git'} directory.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "true")
private boolean failOnNoGitDirectory;
/**
- * By default the plugin will fail the build if unable to obtain enough data for a complete run,
- * if you don't care about this - for example it's not needed during your CI builds and the CI server does weird
- * things to the repository, you may want to set this value to false.
+ *
Set this to {@code 'false'} to continue the build even if unable to get enough data for a complete run.
+ * This may be useful during CI builds if the CI server does weird things to the repository.
*
- * Setting this value to `false`, causes the plugin to gracefully tell you "I did my best" and abort it's execution
- * if unable to obtain git meta data - yet the build will continue to run (without failing).
+ *
Setting this value to {@code 'false'} causes the plugin to gracefully tell you "I did my best"
+ * and abort its execution if unable to obtain git meta data - yet the build will continue to run without failing.
*
- * See https://github.com/ktoso/maven-git-commit-id-plugin/issues/63 for a rationale behing this flag.
- *
- * @parameter default-value="true"
+ *
See issue #63
+ * for a rationale behind this flag.
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "true")
private boolean failOnUnableToExtractRepoInfo;
/**
- * By default the plugin will use a jgit implementation as a source of a information about the repository. You can
- * use a native GIT executable to fetch information about the repository, witch is in most cases faster but requires
- * a git executable to be installed in system.
- *
- * @parameter default-value="false"
+ * Set this to {@code 'true'} to use native Git executable to fetch information about the repository.
+ * It is in most cases faster but requires a git executable to be installed in system.
+ * By default the plugin will use jGit implementation as a source of information about the repository.
* @since 2.1.9
*/
- @SuppressWarnings("UnusedDeclaration")
+ @Parameter(defaultValue = "false")
private boolean useNativeGit;
/**
- * Skip the plugin execution.
- *
- * @parameter default-value="false"
+ * Set this to {@code 'true'} to skip plugin execution.
* @since 2.1.8
*/
- @SuppressWarnings("UnusedDeclaration")
- private boolean skip = false;
+ @Parameter(defaultValue = "false")
+ private boolean skip;
/**
- * In a multi-module build, only run once. This probably won't "do the right thing" if your project has more than
- * one git repository. If you use this with the option 'generateGitPropertiesFile', it will only generate (or update)
- * the file in the directory where you started your build.
- *
- * The git.* maven properties are available in all modules.
+ *
Set this to {@code 'true'} to only run once in a multi-module build. This probably won't "do the right thing"
+ * if your project has more than one git repository. If you use this with {@code 'generateGitPropertiesFile'},
+ * it will only generate (or update) the file in the directory where you started your build.
*
- * @parameter default-value="false"
+ *
The git.* maven properties are available in all modules.
* @since 2.1.12
*/
- @SuppressWarnings("UnusedDeclaration")
- private boolean runOnlyOnce = false;
+ @Parameter(defaultValue = "false")
+ private boolean runOnlyOnce;
/**
- * Can be used to exclude certain properties from being emited into the resulting file.
- * May be useful when you want to hide {@code git.remote.origin.url} (maybe because it contains your repo password?),
- * or the email of the committer etc.
+ *
List of properties to exclude from the resulting file.
+ * May be useful when you want to hide {@code 'git.remote.origin.url'} (maybe because it contains your repo password?)
+ * or the email of the committer.
*
- * Each value may be globbing, that is, you can write {@code git.commit.user.*} to exclude both, the {@code name},
- * as well as {@code email} properties from being emitted into the resulting files.
+ *
Supports wildcards: you can write {@code 'git.commit.user.*'} to exclude both the {@code 'name'}
+ * as well as {@code 'email'} properties from being emitted into the resulting files.
*
- * Please note that the strings here are Java regexes ({@code .*} is globbing, not plain {@code *}).
- *
- * @parameter
+ *
Note: The strings here are Java regular expressions: {@code '.*'} is a wildcard, not plain {@code '*'}.
* @since 2.1.9
*/
- @SuppressWarnings("UnusedDeclaration")
- private List excludeProperties = Collections.emptyList();
+ @Parameter
+ private List excludeProperties;
/**
- * Can be used to include only certain properties into the resulting file.
- * Will be overruled by the exclude properties.
- *
- * Each value may be globbing, that is, you can write {@code git.commit.user.*} to include both, the {@code name},
- * as well as {@code email} properties into the resulting files.
+ *
List of properties to include into the resulting file. Only properties specified here will be included.
+ * This list will be overruled by the {@code 'excludeProperties'}.
*
- * Please note that the strings here are Java regexes ({@code .*} is globbing, not plain {@code *}).
+ *
Supports wildcards: you can write {@code 'git.commit.user.*'} to include both the {@code 'name'}
+ * as well as {@code 'email'} properties into the resulting files.
*
- * @parameter
+ *
Note: The strings here are Java regular expressions: {@code '.*'} is a wildcard, not plain {@code '*'}.
* @since 2.1.14
*/
- @SuppressWarnings("UnusedDeclaration")
- private List includeOnlyProperties = Collections.emptyList();
+ @Parameter
+ private List includeOnlyProperties;
/**
- * The option can be used to tell the plugin how it should generate the 'git.commit.id' property. Due to some naming issues when exporting the properties as an json-object (https://github.com/ktoso/maven-git-commit-id-plugin/issues/122) we needed to make it possible to export all properties as a valid json-object.
- * Due to the fact that this is one of the major properties the plugin is exporting we just don't want to change the exporting mechanism and somehow throw the backwards compatibility away.
- * We rather provide a convient switch where you can choose if you would like the properties as they always had been, or if you rather need to support full json-object compatibility.
- * In the case you need to fully support json-object we unfortunately need to change the 'git.commit.id' property from 'git.commit.id' to 'git.commit.id.full' in the exporting mechanism to allow the generation of a fully valid json object.
+ *
The mode of {@code 'git.commit.id'} property generation.
*
- * Currently the switch allows two different options:
- * 1. By default this property is set to 'flat' and will generate the formerly known property 'git.commit.id' as it was in the previous versions of the plugin. Keeping it to 'flat' by default preserve backwards compatibility and does not require further adjustments by the end user.
- * 2. If you set this switch to 'full' the plugin will export the formerly known property 'git.commit.id' as 'git.commit.id.full' and therefore will generate a fully valid json object in the exporting mechanism.
+ *
{@code 'git.commit.id'} property name is incompatible with json export
+ * (see issue #122).
+ * This property allows one either to preserve backward compatibility or to enable fully valid json export:
*
- * *Note*: Depending on your plugin configuration you obviously can choose the 'prefix' of your properties by setting it accordingly in the plugin's configuration. As a result this is therefore only an illustration what the switch means when the 'prefix' is set to it's default value.
- * *Note*: If you set the value to something that's not equal to 'flat' or 'full' (ignoring the case) the plugin will output a warning and will fallback to the default 'flat' mode.
+ *
Note: Depending on your plugin configuration you obviously can choose the `prefix` of your properties
+ * by setting it accordingly in the plugin's configuration. As a result this is therefore only an illustration
+ * what the switch means when the 'prefix' is set to it's default value.
+ *
Note: If you set the value to something that's not equal to {@code 'flat'} or {@code 'full'} (ignoring the case)
+ * the plugin will output a warning and will fallback to the default {@code 'flat'} mode.
* @since 2.2.0
*/
+ @Parameter(defaultValue = "flat")
private String commitIdGenerationMode;
+ private CommitIdGenerationMode commitIdGenerationModeEnum;
/**
- * The Maven Session Object
- *
- * @parameter property="session"
- * @required
- * @readonly
+ * The properties we store our data in and then expose them.
*/
- @SuppressWarnings("UnusedDeclaration")
- protected MavenSession session;
+ private Properties properties;
/**
- * The properties we store our data in and then expose them
+ * Charset to read-write project sources.
*/
- private Properties properties;
-
- boolean runningTests = false;
+ private Charset sourceCharset = StandardCharsets.UTF_8;
@NotNull
- LoggerBridge loggerBridge = new MavenLoggerBridge(getLog(), true);
+ private final LoggerBridge log = new MavenLoggerBridge(this, false);
+ @Override
public void execute() throws MojoExecutionException {
- // Set the verbose setting now it should be correctly loaded from maven.
- loggerBridge.setVerbose(verbose);
+ try {
+ // Set the verbose setting: now it should be correctly loaded from maven.
+ log.setVerbose(verbose);
- if (skip) {
- log("skip is enabled, skipping execution!");
- return;
- }
+ // read source encoding from project properties for those who still doesn't use UTF-8
+ String sourceEncoding = project.getProperties().getProperty("project.build.sourceEncoding");
+ if (null != sourceEncoding) {
+ sourceCharset = Charset.forName(sourceEncoding);
+ } else {
+ sourceCharset = Charset.defaultCharset();
+ }
- if (runOnlyOnce) {
- if (!session.getExecutionRootDirectory().equals(session.getCurrentProject().getBasedir().getAbsolutePath())) {
- log("runOnlyOnce is enabled and this project is not the top level project, skipping execution!");
+ if (skip) {
+ log.info("skip is enabled, skipping execution!");
return;
}
- }
- if (isPomProject(project) && skipPoms) {
- log("isPomProject is true and skipPoms is true, return");
- return;
- }
+ if (runOnlyOnce) {
+ if (!session.getExecutionRootDirectory().equals(session.getCurrentProject().getBasedir().getAbsolutePath())) {
+ log.info("runOnlyOnce is enabled and this project is not the top level project, skipping execution!");
+ return;
+ }
+ }
- dotGitDirectory = lookupGitDirectory();
- throwWhenRequiredDirectoryNotFound(dotGitDirectory, failOnNoGitDirectory, ".git directory could not be found! Please specify a valid [dotGitDirectory] in your pom.xml");
+ if (isPomProject(project) && skipPoms) {
+ log.info("isPomProject is true and skipPoms is true, return");
+ return;
+ }
- if (gitDescribe == null) {
- gitDescribe = new GitDescribeConfig();
- }
+ dotGitDirectory = lookupGitDirectory();
+ if (failOnNoGitDirectory && !directoryExists(dotGitDirectory)) {
+ throw new GitCommitIdExecutionException(".git directory is not found! Please specify a valid [dotGitDirectory] in your pom.xml");
+ }
- if (dotGitDirectory != null) {
- log("dotGitDirectory", dotGitDirectory.getAbsolutePath());
- } else {
- log("dotGitDirectory is null, aborting execution!");
- return;
- }
+ if (gitDescribe == null) {
+ gitDescribe = new GitDescribeConfig();
+ }
- try {
- switch(CommitIdGenerationModeEnum.getValue(commitIdGenerationMode)){
- default:
- loggerBridge.warn("Detected wrong setting for 'commitIdGenerationMode' will fallback to default 'flat'-Mode!");
- case FLAT:
- COMMIT_ID = COMMIT_ID_FLAT;
- break;
- case FULL:
- COMMIT_ID = COMMIT_ID_FULL;
- break;
+ if (dotGitDirectory != null) {
+ log.info("dotGitDirectory {}", dotGitDirectory.getAbsolutePath());
+ } else {
+ log.info("dotGitDirectory is null, aborting execution!");
+ return;
}
- properties = initProperties();
+ try {
+ try {
+ commitIdGenerationModeEnum = CommitIdGenerationMode.valueOf(commitIdGenerationMode.toUpperCase());
+ } catch (IllegalArgumentException e) {
+ log.warn("Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat' mode!");
+ commitIdGenerationModeEnum = CommitIdGenerationMode.FLAT;
+ }
- String trimmedPrefix = prefix.trim();
- prefixDot = trimmedPrefix.equals("") ? "" : trimmedPrefix + ".";
+ properties = initProperties();
- loadGitData(properties);
- loadBuildVersionAndTimeData(properties);
- loadBuildHostData(properties);
- loadShortDescribe(properties);
- filter(properties, includeOnlyProperties);
- filterNot(properties, excludeProperties);
- logProperties(properties);
+ String trimmedPrefix = prefix.trim();
+ prefixDot = trimmedPrefix.equals("") ? "" : trimmedPrefix + ".";
- if (generateGitPropertiesFile) {
- maybeGeneratePropertiesFile(properties, project.getBasedir(), generateGitPropertiesFilename);
- }
+ loadGitData(properties);
+ loadBuildVersionAndTimeData(properties);
+ loadBuildHostData(properties);
+ loadShortDescribe(properties);
+ filter(properties, includeOnlyProperties);
+ filterNot(properties, excludeProperties);
+ logProperties(properties);
- if (injectAllReactorProjects) {
- appendPropertiesToReactorProjects(properties, prefixDot);
+ if (generateGitPropertiesFile) {
+ maybeGeneratePropertiesFile(properties, project.getBasedir(), generateGitPropertiesFilename);
+ }
+
+ if (injectAllReactorProjects) {
+ appendPropertiesToReactorProjects(properties, prefixDot);
+ }
+ } catch (Exception e) {
+ handlePluginFailure(e);
}
- } catch (Exception e) {
- e.printStackTrace();
- handlePluginFailure(e);
+ } catch (GitCommitIdExecutionException e) {
+ throw new MojoExecutionException(e.getMessage(), e);
}
-
}
private void filterNot(Properties properties, @Nullable List exclusions) {
@@ -461,7 +415,7 @@ public Predicate apply(String exclude) {
for (String key : properties.stringPropertyNames()) {
if (shouldExclude.apply(key)) {
- loggerBridge.debug("shouldExclude.apply(" + key + ") = " + shouldExclude.apply(key));
+ log.debug("shouldExclude.apply({}) = {}", key, shouldExclude.apply(key));
properties.remove(key);
}
}
@@ -486,7 +440,7 @@ public Predicate apply(String exclude) {
for (String key : properties.stringPropertyNames()) {
if (!shouldInclude.apply(key)) {
- loggerBridge.debug("!shouldInclude.apply(" + key + ") = " + shouldInclude.apply(key));
+ log.debug("!shouldInclude.apply({}) = {}", key, shouldInclude.apply(key));
properties.remove(key);
}
}
@@ -494,16 +448,16 @@ public Predicate apply(String exclude) {
/**
* Reacts to an exception based on the {@code failOnUnableToExtractRepoInfo} setting.
- * If it's true, an MojoExecutionException will be throw, otherwise we just log an error message.
+ * If it's true, an GitCommitIdExecutionException will be thrown, otherwise we just log an error message.
*
- * @throws MojoExecutionException which will be should be throw within an MojoException in case the
+ * @throws GitCommitIdExecutionException which will be thrown in case the
* {@code failOnUnableToExtractRepoInfo} setting was set to true.
*/
- private void handlePluginFailure(Exception e) throws MojoExecutionException {
+ private void handlePluginFailure(Exception e) throws GitCommitIdExecutionException {
if (failOnUnableToExtractRepoInfo) {
- throw new MojoExecutionException("Could not complete Mojo execution...", e);
+ throw new GitCommitIdExecutionException("Could not complete Mojo execution...", e);
} else {
- loggerBridge.error(e.getMessage(), com.google.common.base.Throwables.getStackTraceAsString(e));
+ log.error(e.getMessage(), e);
}
}
@@ -511,7 +465,8 @@ private void appendPropertiesToReactorProjects(@NotNull Properties properties, @
for (MavenProject mavenProject : reactorProjects) {
Properties mavenProperties = mavenProject.getProperties();
- log(mavenProject.getName(), "] project", mavenProject.getName());
+ // TODO check message
+ log.info("{}] project {}", mavenProject.getName(), mavenProject.getName());
for (Object key : properties.keySet()) {
if (key.toString().startsWith(trimmedPrefixWithDot)) {
@@ -521,29 +476,21 @@ private void appendPropertiesToReactorProjects(@NotNull Properties properties, @
}
}
- private void throwWhenRequiredDirectoryNotFound(File dotGitDirectory, Boolean required, String message) throws MojoExecutionException {
- if (required && directoryDoesNotExits(dotGitDirectory)) {
- throw new MojoExecutionException(message);
- }
- }
-
/**
* Find the git directory of the currently used project.
* If it's not already specified, this method will try to find it.
*
* @return the File representation of the .git directory
*/
- @VisibleForTesting File lookupGitDirectory() throws MojoExecutionException {
+ @VisibleForTesting File lookupGitDirectory() throws GitCommitIdExecutionException {
return new GitDirLocator(project, reactorProjects).lookupGitDirectory(dotGitDirectory);
}
- private Properties initProperties() throws MojoExecutionException {
+ private Properties initProperties() throws GitCommitIdExecutionException {
if (generateGitPropertiesFile) {
return properties = new Properties();
- } else if (!runningTests) {
- return properties = project.getProperties();
} else {
- return properties = new Properties(); // that's ok for unit tests
+ return properties = project.getProperties();
}
}
@@ -551,7 +498,7 @@ private void logProperties(@NotNull Properties properties) {
for (Object key : properties.keySet()) {
String keyString = key.toString();
if (isOurProperty(keyString)) {
- log("found property", keyString);
+ log.info("found property {}", keyString);
}
}
}
@@ -575,7 +522,7 @@ void loadBuildHostData(@NotNull Properties properties) {
try {
buildHost = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
- log("Unable to get build host, skipping property " + BUILD_HOST + ". Error message was: " + e.getMessage());
+ log.info("Unable to get build host, skipping property {}. Error message: {}", BUILD_HOST, e.getMessage());
}
put(properties, BUILD_HOST, buildHost);
}
@@ -601,7 +548,7 @@ void loadShortDescribe(@NotNull Properties properties) {
}
}
- void loadGitData(@NotNull Properties properties) throws IOException, MojoExecutionException {
+ void loadGitData(@NotNull Properties properties) throws GitCommitIdExecutionException {
if (useNativeGit) {
loadGitDataWithNativeGit(properties);
} else {
@@ -609,95 +556,100 @@ void loadGitData(@NotNull Properties properties) throws IOException, MojoExecuti
}
}
- void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException, MojoExecutionException {
- final File basedir = project.getBasedir().getCanonicalFile();
-
- GitDataProvider nativeGitProvider = NativeGitProvider
- .on(basedir, loggerBridge)
- .setVerbose(verbose)
- .setPrefixDot(prefixDot)
- .setAbbrevLength(abbrevLength)
- .setDateFormat(dateFormat)
- .setDateFormatTimeZone(dateFormatTimeZone)
- .setGitDescribe(gitDescribe);
-
- nativeGitProvider.loadGitData(properties);
+ void loadGitDataWithNativeGit(@NotNull Properties properties) throws GitCommitIdExecutionException {
+ try {
+ final File basedir = project.getBasedir().getCanonicalFile();
+
+ GitDataProvider nativeGitProvider = NativeGitProvider
+ .on(basedir, log)
+ .setPrefixDot(prefixDot)
+ .setAbbrevLength(abbrevLength)
+ .setDateFormat(dateFormat)
+ .setDateFormatTimeZone(dateFormatTimeZone)
+ .setGitDescribe(gitDescribe)
+ .setCommitIdGenerationMode(commitIdGenerationModeEnum);
+
+ nativeGitProvider.loadGitData(properties);
+ } catch (IOException e) {
+ throw new GitCommitIdExecutionException(e);
+ }
}
- void loadGitDataWithJGit(@NotNull Properties properties) throws IOException, MojoExecutionException {
+ void loadGitDataWithJGit(@NotNull Properties properties) throws GitCommitIdExecutionException {
GitDataProvider jGitProvider = JGitProvider
- .on(dotGitDirectory, loggerBridge)
- .setVerbose(verbose)
+ .on(dotGitDirectory, log)
.setPrefixDot(prefixDot)
.setAbbrevLength(abbrevLength)
.setDateFormat(dateFormat)
.setDateFormatTimeZone(dateFormatTimeZone)
- .setGitDescribe(gitDescribe);
+ .setGitDescribe(gitDescribe)
+ .setCommitIdGenerationMode(commitIdGenerationModeEnum);
jGitProvider.loadGitData(properties);
}
- void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, String propertiesFilename) throws IOException {
- final File gitPropsFile = craftPropertiesOutputFile(base, propertiesFilename);
- final boolean isJsonFormat = "json".equalsIgnoreCase( format );
+ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, String propertiesFilename) throws GitCommitIdExecutionException {
+ try {
+ final File gitPropsFile = craftPropertiesOutputFile(base, propertiesFilename);
+ final boolean isJsonFormat = "json".equalsIgnoreCase(format);
- boolean shouldGenerate = true;
+ boolean shouldGenerate = true;
- if (gitPropsFile.exists( )) {
- final Properties persistedProperties;
+ if (gitPropsFile.exists()) {
+ final Properties persistedProperties;
- try {
- if (isJsonFormat) {
- log("Reading exising json file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")...");
+ try {
+ if (isJsonFormat) {
+ log.info("Reading existing json file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
- persistedProperties = readJsonProperties( gitPropsFile );
- }
- else {
- log("Reading exising properties file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")...");
+ persistedProperties = readJsonProperties(gitPropsFile);
+ } else {
+ log.info("Reading existing properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
- persistedProperties = readProperties( gitPropsFile );
- }
+ persistedProperties = readProperties(gitPropsFile);
+ }
- final Properties propertiesCopy = (Properties) localProperties.clone( );
+ final Properties propertiesCopy = (Properties) localProperties.clone();
- final String buildTimeProperty = prefixDot + BUILD_TIME;
+ final String buildTimeProperty = prefixDot + BUILD_TIME;
- propertiesCopy.remove( buildTimeProperty );
- persistedProperties.remove( buildTimeProperty );
+ propertiesCopy.remove(buildTimeProperty);
+ persistedProperties.remove(buildTimeProperty);
- shouldGenerate = ! propertiesCopy.equals( persistedProperties );
- }
- catch ( CannotReadFileException ex ) {
- // Read has failed, regenerate file
- log("Cannot read properties file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")...");
- shouldGenerate = true;
+ shouldGenerate = !propertiesCopy.equals(persistedProperties);
+ } catch (CannotReadFileException ex) {
+ // Read has failed, regenerate file
+ log.info("Cannot read properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
+ shouldGenerate = true;
+ }
}
- }
- if (shouldGenerate) {
- Files.createParentDirs(gitPropsFile);
- Writer outputWriter = null;
- boolean threw = true;
+ if (shouldGenerate) {
+ Files.createParentDirs(gitPropsFile);
+ Writer outputWriter = null;
+ boolean threw = true;
- try {
- outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), Charsets.UTF_8);
- if (isJsonFormat) {
- log("Writing json file to [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")...");
- ObjectMapper mapper = new ObjectMapper();
- mapper.writeValue(outputWriter, localProperties);
- } else {
- log("Writing properties file to [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")...");
- localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin");
+ try {
+ outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), sourceCharset);
+ if (isJsonFormat) {
+ log.info("Writing json file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.writeValue(outputWriter, localProperties);
+ } else {
+ log.info("Writing properties file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
+ localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin");
+ }
+ threw = false;
+ } catch (final IOException ex) {
+ throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
+ } finally {
+ Closeables.close(outputWriter, threw);
}
- threw = false;
- } catch (final IOException ex) {
- throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
- } finally {
- Closeables.close(outputWriter, threw);
+ } else {
+ log.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(), project.getName());
}
- }
- else {
- log("Properties file [", gitPropsFile.getAbsolutePath(), "] is up-to-date (for module ", project.getName(), ")...");
+ } catch (IOException e) {
+ throw new GitCommitIdExecutionException(e);
}
}
@@ -719,24 +671,16 @@ boolean isPomProject(@NotNull MavenProject project) {
private void put(@NotNull Properties properties, String key, String value) {
String keyWithPrefix = prefixDot + key;
- log(keyWithPrefix, value);
+ log.info(keyWithPrefix + " " + value);
PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value);
}
- void log(String... parts) {
- loggerBridge.log((Object[]) parts);
- }
-
private boolean directoryExists(@Nullable File fileLocation) {
return fileLocation != null && fileLocation.exists() && fileLocation.isDirectory();
}
- private boolean directoryDoesNotExits(File fileLocation) {
- return !directoryExists(fileLocation);
- }
-
@SuppressWarnings( "resource" )
- static Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFileException {
+ private Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFileException {
final HashMap propertiesMap;
{
@@ -748,7 +692,7 @@ static Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFi
final FileInputStream fis = new FileInputStream(jsonFile);
closeable = fis;
- final InputStreamReader reader = new InputStreamReader(fis, Charsets.UTF_8);
+ final InputStreamReader reader = new InputStreamReader(fis, sourceCharset);
closeable = reader;
final ObjectMapper mapper = new ObjectMapper();
@@ -776,7 +720,7 @@ static Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFi
}
@SuppressWarnings( "resource" )
- static Properties readProperties(@NotNull File propertiesFile) throws CannotReadFileException {
+ private Properties readProperties(@NotNull File propertiesFile) throws CannotReadFileException {
Closeable closeable = null;
try {
@@ -785,7 +729,7 @@ static Properties readProperties(@NotNull File propertiesFile) throws CannotRead
final FileInputStream fis = new FileInputStream(propertiesFile);
closeable = fis;
- final InputStreamReader reader = new InputStreamReader(fis, Charsets.UTF_8);
+ final InputStreamReader reader = new InputStreamReader(fis, sourceCharset);
closeable = reader;
final Properties retVal = new Properties();
@@ -803,9 +747,7 @@ static Properties readProperties(@NotNull File propertiesFile) throws CannotRead
}
}
- static class CannotReadFileException
- extends Exception
- {
+ static class CannotReadFileException extends Exception {
private static final long serialVersionUID = -6290782570018307756L;
CannotReadFileException( Throwable cause )
@@ -863,8 +805,4 @@ public void useNativeGit(boolean useNativeGit) {
public void setCommitIdGenerationMode(String commitIdGenerationMode){
this.commitIdGenerationMode = commitIdGenerationMode;
}
-
- public LoggerBridge getLoggerBridge() {
- return loggerBridge;
- }
-}
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java
index 8bc515a1..81abf684 100644
--- a/src/main/java/pl/project13/maven/git/GitDataProvider.java
+++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java
@@ -17,7 +17,6 @@
package pl.project13.maven.git;
-import org.apache.maven.plugin.MojoExecutionException;
import org.jetbrains.annotations.NotNull;
import pl.project13.maven.git.log.LoggerBridge;
import pl.project13.maven.git.util.PropertyManager;
@@ -33,9 +32,7 @@
public abstract class GitDataProvider {
@NotNull
- protected LoggerBridge loggerBridge;
-
- protected boolean verbose;
+ protected final LoggerBridge log;
protected String prefixDot;
@@ -47,8 +44,10 @@ public abstract class GitDataProvider {
protected GitDescribeConfig gitDescribe = new GitDescribeConfig();
- public GitDataProvider(@NotNull LoggerBridge loggerBridge) {
- this.loggerBridge = loggerBridge;
+ protected CommitIdGenerationMode commitIdGenerationMode;
+
+ public GitDataProvider(@NotNull LoggerBridge log) {
+ this.log = log;
}
public GitDataProvider setGitDescribe(GitDescribeConfig gitDescribe) {
@@ -71,32 +70,37 @@ public GitDataProvider setDateFormat(String dateFormat) {
return this;
}
+ public GitDataProvider setCommitIdGenerationMode(CommitIdGenerationMode commitIdGenerationMode) {
+ this.commitIdGenerationMode = commitIdGenerationMode;
+ return this;
+ }
+
public GitDataProvider setDateFormatTimeZone(String dateFormatTimeZone){
this.dateFormatTimeZone = dateFormatTimeZone;
return this;
}
- protected abstract void init() throws MojoExecutionException;
- protected abstract String getBuildAuthorName();
- protected abstract String getBuildAuthorEmail();
- protected abstract void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException;
- protected abstract String getBranchName() throws IOException;
- protected abstract String getGitDescribe() throws MojoExecutionException;
- protected abstract String getCommitId();
- protected abstract String getAbbrevCommitId() throws MojoExecutionException;
- protected abstract boolean isDirty() throws MojoExecutionException;
- protected abstract String getCommitAuthorName();
- protected abstract String getCommitAuthorEmail();
- protected abstract String getCommitMessageFull();
- protected abstract String getCommitMessageShort();
- protected abstract String getCommitTime();
- protected abstract String getRemoteOriginUrl() throws MojoExecutionException;
- protected abstract String getTags() throws MojoExecutionException;
- protected abstract String getClosestTagName() throws MojoExecutionException;
- protected abstract String getClosestTagCommitCount() throws MojoExecutionException;
- protected abstract void finalCleanUp();
-
- public void loadGitData(@NotNull Properties properties) throws IOException, MojoExecutionException{
+ protected abstract void init() throws GitCommitIdExecutionException;
+ protected abstract String getBuildAuthorName() throws GitCommitIdExecutionException;
+ protected abstract String getBuildAuthorEmail() throws GitCommitIdExecutionException;
+ protected abstract void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdExecutionException;
+ protected abstract String getBranchName() throws GitCommitIdExecutionException;
+ protected abstract String getGitDescribe() throws GitCommitIdExecutionException;
+ protected abstract String getCommitId() throws GitCommitIdExecutionException;
+ protected abstract String getAbbrevCommitId() throws GitCommitIdExecutionException;
+ protected abstract boolean isDirty() throws GitCommitIdExecutionException;
+ protected abstract String getCommitAuthorName() throws GitCommitIdExecutionException;
+ protected abstract String getCommitAuthorEmail() throws GitCommitIdExecutionException;
+ protected abstract String getCommitMessageFull() throws GitCommitIdExecutionException;
+ protected abstract String getCommitMessageShort() throws GitCommitIdExecutionException;
+ protected abstract String getCommitTime() throws GitCommitIdExecutionException;
+ protected abstract String getRemoteOriginUrl() throws GitCommitIdExecutionException;
+ protected abstract String getTags() throws GitCommitIdExecutionException;
+ protected abstract String getClosestTagName() throws GitCommitIdExecutionException;
+ protected abstract String getClosestTagCommitCount() throws GitCommitIdExecutionException;
+ protected abstract void finalCleanUp() throws GitCommitIdExecutionException;
+
+ public void loadGitData(@NotNull Properties properties) throws GitCommitIdExecutionException {
init();
// git.user.name
put(properties, GitCommitIdMojo.BUILD_AUTHOR_NAME, getBuildAuthorName());
@@ -104,7 +108,7 @@ public void loadGitData(@NotNull Properties properties) throws IOException, Mojo
put(properties, GitCommitIdMojo.BUILD_AUTHOR_EMAIL, getBuildAuthorEmail());
try {
- prepareGitToExtractMoreDetailedReproInformation();
+ prepareGitToExtractMoreDetailedRepoInformation();
validateAbbrevLength(abbrevLength);
// git.branch
@@ -112,8 +116,20 @@ public void loadGitData(@NotNull Properties properties) throws IOException, Mojo
// git.commit.id.describe
maybePutGitDescribe(properties);
// git.commit.id
- put(properties, GitCommitIdMojo.COMMIT_ID, getCommitId());
- // git.commit.id.abbrev
+ switch (commitIdGenerationMode) {
+ case FULL: {
+ put(properties, GitCommitIdMojo.COMMIT_ID_FULL, getCommitId());
+ break;
+ }
+ case FLAT: {
+ put(properties, GitCommitIdMojo.COMMIT_ID_FLAT, getCommitId());
+ break;
+ }
+ default: {
+ throw new GitCommitIdExecutionException("Unsupported commitIdGenerationMode: " + commitIdGenerationMode);
+ }
+ }
+ // git.commit.id.abbrev
put(properties, GitCommitIdMojo.COMMIT_ID_ABBREV, getAbbrevCommitId());
// git.dirty
put(properties, GitCommitIdMojo.DIRTY, Boolean.toString(isDirty()));
@@ -140,7 +156,7 @@ public void loadGitData(@NotNull Properties properties) throws IOException, Mojo
}
}
- private void maybePutGitDescribe(@NotNull Properties properties) throws MojoExecutionException{
+ private void maybePutGitDescribe(@NotNull Properties properties) throws GitCommitIdExecutionException{
boolean isGitDescribeOptOutByDefault = (gitDescribe == null);
boolean isGitDescribeOptOutByConfiguration = (gitDescribe != null && !gitDescribe.isSkip());
@@ -149,21 +165,21 @@ private void maybePutGitDescribe(@NotNull Properties properties) throws MojoExec
}
}
- void validateAbbrevLength(int abbrevLength) throws MojoExecutionException {
+ void validateAbbrevLength(int abbrevLength) throws GitCommitIdExecutionException {
if (abbrevLength < 2 || abbrevLength > 40) {
- throw new MojoExecutionException("Abbreviated commit id lenght must be between 2 and 40, inclusive! Was [%s]. ".codePointBefore(abbrevLength) +
+ throw new GitCommitIdExecutionException(String.format("Abbreviated commit id length must be between 2 and 40, inclusive! Was [%s]. ", abbrevLength) +
"Please fix your configuration (the element).");
}
}
/**
- * If running within Jenkins/Hudosn, honor the branch name passed via GIT_BRANCH env var. This
- * is necessary because Jenkins/Hudson alwways invoke build in a detached head state.
+ * If running within Jenkins/Hudson, honor the branch name passed via GIT_BRANCH env var.
+ * This is necessary because Jenkins/Hudson always invoke build in a detached head state.
*
* @param env environment settings
* @return results of getBranchName() or, if in Jenkins/Hudson, value of GIT_BRANCH
*/
- protected String determineBranchName(Map env) throws IOException {
+ protected String determineBranchName(Map env) throws GitCommitIdExecutionException {
if (runningOnBuildServer(env)) {
return determineBranchNameOnBuildServer(env);
} else {
@@ -185,35 +201,31 @@ private boolean runningOnBuildServer(Map env) {
}
/**
- * Is "Jenkins aware", and prefers {@code GIT_BRANCH} to getting the branch via git if that enviroment variable is set.
+ * Is "Jenkins aware", and prefers {@code GIT_BRANCH} to getting the branch via git if that environment variable is set.
* The {@code GIT_BRANCH} variable is set by Jenkins/Hudson when put in detached HEAD state, but it still knows which branch was cloned.
*/
- protected String determineBranchNameOnBuildServer(Map env) throws IOException {
- String enviromentBasedBranch = env.get("GIT_BRANCH");
- if(isNullOrEmpty(enviromentBasedBranch)) {
- log("Detected that running on CI enviroment, but using repository branch, no GIT_BRANCH detected.");
+ protected String determineBranchNameOnBuildServer(Map env) throws GitCommitIdExecutionException {
+ String environmentBasedBranch = env.get("GIT_BRANCH");
+ if (isNullOrEmpty(environmentBasedBranch)) {
+ log.info("Detected that running on CI environment, but using repository branch, no GIT_BRANCH detected.");
return getBranchName();
- }else {
- log("Using environment variable based branch name.", "GIT_BRANCH =", enviromentBasedBranch);
- return enviromentBasedBranch;
+ } else {
+ log.info("Using environment variable based branch name. GIT_BRANCH = {}", environmentBasedBranch);
+ return environmentBasedBranch;
}
}
protected SimpleDateFormat getSimpleDateFormatWithTimeZone(){
SimpleDateFormat smf = new SimpleDateFormat(dateFormat);
- if(dateFormatTimeZone != null){
+ if (dateFormatTimeZone != null){
smf.setTimeZone(TimeZone.getTimeZone(dateFormatTimeZone));
}
return smf;
}
- void log(String... parts) {
- loggerBridge.log((Object[]) parts);
- }
-
protected void put(@NotNull Properties properties, String key, String value) {
String keyWithPrefix = prefixDot + key;
- log(keyWithPrefix, value);
+ log.info("{} {}", keyWithPrefix, value);
PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value);
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/GitDescribeConfig.java b/src/main/java/pl/project13/maven/git/GitDescribeConfig.java
index 34bf4581..063bf60b 100644
--- a/src/main/java/pl/project13/maven/git/GitDescribeConfig.java
+++ b/src/main/java/pl/project13/maven/git/GitDescribeConfig.java
@@ -28,7 +28,7 @@ public class GitDescribeConfig {
* If you don't use describe, you can always disable it and make the build a bit faster.
*
* Although it's highly recommended to use
git-describe
to identify your build state,
- * so think twice before disabeling it.
+ * so think twice before disabling it.
*
* @parameter default-value=false
*/
@@ -80,7 +80,7 @@ public class GitDescribeConfig {
* 0 - will suppress long format, only showing the closest tag. (Won't show anything about the commit's id).
*
*
- * 1 - is invalid. Git's minimal abbrev lenght is 2 chars.
+ * 1 - is invalid. Git's minimal abbrev length is 2 chars.
* This will be silently ignored and you'll get a full commit id.
*
*
diff --git a/src/main/java/pl/project13/maven/git/GitDirLocator.java b/src/main/java/pl/project13/maven/git/GitDirLocator.java
index d707c582..34a60538 100644
--- a/src/main/java/pl/project13/maven/git/GitDirLocator.java
+++ b/src/main/java/pl/project13/maven/git/GitDirLocator.java
@@ -66,8 +66,7 @@ public File lookupGitDirectory(@NotNull File manuallyConfiguredDir) {
}
/**
- * Search up all the maven parent project heirarchy until a .git
- * directory is found.
+ * Search up all the maven parent project hierarchy until a .git directory is found.
*
* @return File which represents the location of the .git directory or NULL if none found.
*/
@@ -80,7 +79,7 @@ private File findProjectGitDirectory() {
File basedir = mavenProject.getBasedir();
while (basedir != null) {
File gitdir = new File(basedir, Constants.DOT_GIT);
- if (gitdir != null && gitdir.exists()) {
+ if (gitdir.exists()) {
if (gitdir.isDirectory()) {
return gitdir;
} else if (gitdir.isFile()) {
diff --git a/src/main/java/pl/project13/maven/git/GitRepositoryState.java b/src/main/java/pl/project13/maven/git/GitRepositoryState.java
index 43c52fb6..0aa9b7b3 100644
--- a/src/main/java/pl/project13/maven/git/GitRepositoryState.java
+++ b/src/main/java/pl/project13/maven/git/GitRepositoryState.java
@@ -16,8 +16,6 @@
*/
package pl.project13.maven.git;
-//import org.codehaus.jackson.annotate.JsonWriteNullProperties;
-
import com.google.common.base.Joiner;
import org.jetbrains.annotations.NotNull;
@@ -30,7 +28,6 @@
*
* @since 1.0
*/
-//@JsonWriteNullProperties(true)
public class GitRepositoryState {
String branch; // =${git.branch}
String commitId; // =${git.commit.id}
diff --git a/src/main/java/pl/project13/maven/git/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java
index 9158b510..bc04f4fa 100644
--- a/src/main/java/pl/project13/maven/git/JGitProvider.java
+++ b/src/main/java/pl/project13/maven/git/JGitProvider.java
@@ -21,7 +21,6 @@
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
-import org.apache.maven.plugin.MojoExecutionException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.AbbreviatedObjectId;
@@ -45,7 +44,6 @@
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
-import java.util.List;
public class JGitProvider extends GitDataProvider {
@@ -57,123 +55,110 @@ public class JGitProvider extends GitDataProvider {
private JGitCommon jGitCommon;
@NotNull
- public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
- return new JGitProvider(dotGitDirectory, loggerBridge);
+ public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) {
+ return new JGitProvider(dotGitDirectory, log);
}
- JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
- super(loggerBridge);
+ JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) {
+ super(log);
this.dotGitDirectory = dotGitDirectory;
- this.jGitCommon = new JGitCommon();
- }
-
- @NotNull
- public JGitProvider setVerbose(boolean verbose) {
- super.verbose = verbose;
- super.loggerBridge.setVerbose(verbose);
- return this;
+ this.jGitCommon = new JGitCommon(log);
}
@Override
- protected void init() throws MojoExecutionException {
+ protected void init() throws GitCommitIdExecutionException {
git = getGitRepository();
objectReader = git.newObjectReader();
}
@Override
- protected String getBuildAuthorName() {
+ protected String getBuildAuthorName() throws GitCommitIdExecutionException {
String userName = git.getConfig().getString("user", null, "name");
return MoreObjects.firstNonNull(userName, "");
}
@Override
- protected String getBuildAuthorEmail() {
+ protected String getBuildAuthorEmail() throws GitCommitIdExecutionException {
String userEmail = git.getConfig().getString("user", null, "email");
return MoreObjects.firstNonNull(userEmail, "");
}
@Override
- protected void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException {
+ protected void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdExecutionException {
try {
// more details parsed out bellow
Ref head = git.getRef(Constants.HEAD);
if (head == null) {
- throw new MojoExecutionException("Could not get HEAD Ref, are you sure you have set the dotGitDirectory property of this plugin to a valid path?");
+ throw new GitCommitIdExecutionException("Could not get HEAD Ref, are you sure you have set the dotGitDirectory property of this plugin to a valid path?");
}
revWalk = new RevWalk(git);
ObjectId headObjectId = head.getObjectId();
if(headObjectId == null){
- throw new MojoExecutionException("Could not get HEAD Ref, are you sure you have some commits in the dotGitDirectory?");
+ throw new GitCommitIdExecutionException("Could not get HEAD Ref, are you sure you have some commits in the dotGitDirectory?");
}
headCommit = revWalk.parseCommit(headObjectId);
revWalk.markStart(headCommit);
- } catch (MojoExecutionException e) {
- throw e;
} catch (Exception e) {
- throw new MojoExecutionException("Error", e);
+ throw new GitCommitIdExecutionException("Error", e);
}
}
@Override
- protected String getBranchName() throws IOException {
- String branch = git.getBranch();
- return branch;
+ protected String getBranchName() throws GitCommitIdExecutionException {
+ try {
+ return git.getBranch();
+ } catch (IOException e) {
+ throw new GitCommitIdExecutionException(e);
+ }
}
@Override
- protected String getGitDescribe() throws MojoExecutionException {
- String gitDescribe = getGitDescribe(git);
- return gitDescribe;
+ protected String getGitDescribe() throws GitCommitIdExecutionException {
+ return getGitDescribe(git);
}
@Override
- protected String getCommitId() {
- String commitId = headCommit.getName();
- return commitId;
+ protected String getCommitId() throws GitCommitIdExecutionException {
+ return headCommit.getName();
}
@Override
- protected String getAbbrevCommitId() throws MojoExecutionException {
- String abbrevCommitId = getAbbrevCommitId(objectReader, headCommit, abbrevLength);
- return abbrevCommitId;
+ protected String getAbbrevCommitId() throws GitCommitIdExecutionException {
+ return getAbbrevCommitId(objectReader, headCommit, abbrevLength);
}
@Override
- protected boolean isDirty() throws MojoExecutionException {
+ protected boolean isDirty() throws GitCommitIdExecutionException {
Git gitObject = Git.wrap(git);
try {
return !gitObject.status().call().isClean();
} catch (GitAPIException e) {
- throw new MojoExecutionException("Failed to get git status: " + e.getMessage(), e);
+ throw new GitCommitIdExecutionException("Failed to get git status: " + e.getMessage(), e);
}
}
@Override
- protected String getCommitAuthorName() {
- String commitAuthor = headCommit.getAuthorIdent().getName();
- return commitAuthor;
+ protected String getCommitAuthorName() throws GitCommitIdExecutionException {
+ return headCommit.getAuthorIdent().getName();
}
@Override
- protected String getCommitAuthorEmail() {
- String commitEmail = headCommit.getAuthorIdent().getEmailAddress();
- return commitEmail;
+ protected String getCommitAuthorEmail() throws GitCommitIdExecutionException {
+ return headCommit.getAuthorIdent().getEmailAddress();
}
@Override
- protected String getCommitMessageFull() {
- String fullMessage = headCommit.getFullMessage();
- return fullMessage.trim();
+ protected String getCommitMessageFull() throws GitCommitIdExecutionException {
+ return headCommit.getFullMessage().trim();
}
@Override
- protected String getCommitMessageShort() {
- String shortMessage = headCommit.getShortMessage();
- return shortMessage.trim();
+ protected String getCommitMessageShort() throws GitCommitIdExecutionException {
+ return headCommit.getShortMessage().trim();
}
@Override
- protected String getCommitTime() {
+ protected String getCommitTime() throws GitCommitIdExecutionException {
long timeSinceEpoch = headCommit.getCommitTime();
Date commitDate = new Date(timeSinceEpoch * 1000); // git is "by sec" and java is "by ms"
SimpleDateFormat smf = getSimpleDateFormatWithTimeZone();
@@ -181,29 +166,28 @@ protected String getCommitTime() {
}
@Override
- protected String getRemoteOriginUrl() throws MojoExecutionException {
- String remoteOriginUrl = git.getConfig().getString("remote", "origin", "url");
- return remoteOriginUrl;
+ protected String getRemoteOriginUrl() throws GitCommitIdExecutionException {
+ return git.getConfig().getString("remote", "origin", "url");
}
@Override
- protected String getTags() throws MojoExecutionException {
+ protected String getTags() throws GitCommitIdExecutionException {
try {
Repository repo = getGitRepository();
ObjectId headId = headCommit.toObjectId();
Collection tags = jGitCommon.getTags(repo,headId);
return Joiner.on(",").join(tags);
} catch (GitAPIException e) {
- loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")");
+ log.error("Unable to extract tags from commit: {} ({})", headCommit.getName(), e.getClass().getName());
return "";
}
}
@Override
- protected String getClosestTagName() throws MojoExecutionException {
+ protected String getClosestTagName() throws GitCommitIdExecutionException {
Repository repo = getGitRepository();
try {
- return jGitCommon.getClosestTagName(loggerBridge,repo);
+ return jGitCommon.getClosestTagName(repo);
} catch (Throwable t) {
// could not find any tags to describe
}
@@ -211,10 +195,10 @@ protected String getClosestTagName() throws MojoExecutionException {
}
@Override
- protected String getClosestTagCommitCount() throws MojoExecutionException {
+ protected String getClosestTagCommitCount() throws GitCommitIdExecutionException {
Repository repo = getGitRepository();
try {
- return jGitCommon.getClosestTagCommitCount(loggerBridge,repo,headCommit);
+ return jGitCommon.getClosestTagCommitCount(repo, headCommit);
} catch (Throwable t) {
// could not find any tags to describe
}
@@ -228,36 +212,32 @@ protected void finalCleanUp() {
}
}
-
- @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws MojoExecutionException {
+ @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws GitCommitIdExecutionException {
try {
DescribeResult describeResult = DescribeCommand
- .on(repository)
- .withLoggerBridge(super.loggerBridge)
- .setVerbose(super.verbose)
+ .on(repository, log)
.apply(super.gitDescribe)
.call();
return describeResult.toString();
} catch (GitAPIException ex) {
ex.printStackTrace();
- throw new MojoExecutionException("Unable to obtain git.commit.id.describe information", ex);
+ throw new GitCommitIdExecutionException("Unable to obtain git.commit.id.describe information", ex);
}
}
- private String getAbbrevCommitId(ObjectReader objectReader, RevCommit headCommit, int abbrevLength) throws MojoExecutionException {
+ private String getAbbrevCommitId(ObjectReader objectReader, RevCommit headCommit, int abbrevLength) throws GitCommitIdExecutionException {
try {
AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(headCommit, abbrevLength);
return abbreviatedObjectId.name();
} catch (IOException e) {
- throw new MojoExecutionException("Unable to abbreviate commit id! " +
+ throw new GitCommitIdExecutionException("Unable to abbreviate commit id! " +
"You may want to investigate the element in your configuration.", e);
}
}
-
@NotNull
- private Repository getGitRepository() throws MojoExecutionException {
+ private Repository getGitRepository() throws GitCommitIdExecutionException {
Repository repository;
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
@@ -268,11 +248,11 @@ private Repository getGitRepository() throws MojoExecutionException {
.findGitDir() // scan up the file system tree
.build();
} catch (IOException e) {
- throw new MojoExecutionException("Could not initialize repository...", e);
+ throw new GitCommitIdExecutionException("Could not initialize repository...", e);
}
if (repository == null) {
- throw new MojoExecutionException("Could not create git repository. Are you sure '" + dotGitDirectory + "' is the valid Git root for your project?");
+ throw new GitCommitIdExecutionException("Could not create git repository. Are you sure '" + dotGitDirectory + "' is the valid Git root for your project?");
}
return repository;
@@ -284,4 +264,4 @@ private Repository getGitRepository() throws MojoExecutionException {
public void setRepository(Repository git) {
this.git = git;
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/NativeGitProvider.java b/src/main/java/pl/project13/maven/git/NativeGitProvider.java
index c27b43a9..660cb629 100644
--- a/src/main/java/pl/project13/maven/git/NativeGitProvider.java
+++ b/src/main/java/pl/project13/maven/git/NativeGitProvider.java
@@ -22,9 +22,7 @@
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
-import org.apache.maven.plugin.MojoExecutionException;
import org.jetbrains.annotations.NotNull;
-
import pl.project13.maven.git.log.LoggerBridge;
import java.io.*;
@@ -42,35 +40,27 @@ public class NativeGitProvider extends GitDataProvider {
private static final int REMOTE_COLS = 3;
@NotNull
- public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
- return new NativeGitProvider(dotGitDirectory, loggerBridge);
+ public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) {
+ return new NativeGitProvider(dotGitDirectory, log);
}
- NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
- super(loggerBridge);
+ NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) {
+ super(log);
this.dotGitDirectory = dotGitDirectory;
try {
this.canonical = dotGitDirectory.getCanonicalFile();
} catch (Exception ex) {
- throw new RuntimeException(new MojoExecutionException("Passed a invalid directory, not a GIT repository: " + dotGitDirectory, ex));
+ throw new RuntimeException(new GitCommitIdExecutionException("Passed a invalid directory, not a GIT repository: " + dotGitDirectory, ex));
}
}
-
- @NotNull
- public NativeGitProvider setVerbose(boolean verbose) {
- super.verbose = verbose;
- super.loggerBridge.setVerbose(verbose);
- return this;
- }
-
@Override
- protected void init() throws MojoExecutionException {
+ protected void init() throws GitCommitIdExecutionException {
// noop ...
}
@Override
- protected String getBuildAuthorName() {
+ protected String getBuildAuthorName() throws GitCommitIdExecutionException {
try {
return runGitCommand(canonical, "config --get user.name");
} catch (NativeCommandException e) {
@@ -82,7 +72,7 @@ protected String getBuildAuthorName() {
}
@Override
- protected String getBuildAuthorEmail() {
+ protected String getBuildAuthorEmail() throws GitCommitIdExecutionException {
try {
return runGitCommand(canonical, "config --get user.email");
} catch (NativeCommandException e) {
@@ -94,23 +84,23 @@ protected String getBuildAuthorEmail() {
}
@Override
- protected void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException {
+ protected void prepareGitToExtractMoreDetailedRepoInformation() throws GitCommitIdExecutionException {
}
@Override
- protected String getBranchName() throws IOException {
+ protected String getBranchName() throws GitCommitIdExecutionException {
return getBranch(canonical);
}
- private String getBranch(File canonical) {
- String branch = null;
+ private String getBranch(File canonical) throws GitCommitIdExecutionException {
+ String branch;
try{
branch = runGitCommand(canonical, "symbolic-ref HEAD");
if (branch != null) {
branch = branch.replace("refs/heads/", "");
}
- } catch(NativeCommandException e) {
- // it seems that git repro is in 'DETACHED HEAD'-State, using Commid-Id as Branch
+ } catch (NativeCommandException e) {
+ // it seems that git repo is in 'DETACHED HEAD'-State, using Commit-Id as Branch
String err = e.getStderr();
if (err != null && err.contains("ref HEAD is not a symbolic ref")) {
branch = getCommitId();
@@ -122,10 +112,9 @@ private String getBranch(File canonical) {
}
@Override
- protected String getGitDescribe() {
+ protected String getGitDescribe() throws GitCommitIdExecutionException {
final String argumentsForGitDescribe = getArgumentsForGitDescribe(gitDescribe);
- final String gitDescribe = runQuietGitCommand(canonical, "describe" + argumentsForGitDescribe);
- return gitDescribe;
+ return runQuietGitCommand(canonical, "describe" + argumentsForGitDescribe);
}
private String getArgumentsForGitDescribe(GitDescribeConfig describeConfig) {
@@ -139,15 +128,15 @@ private String getArgumentsForGitDescribe(GitDescribeConfig describeConfig) {
final String dirtyMark = describeConfig.getDirty();
if (dirtyMark != null && !dirtyMark.isEmpty()) {
- argumentsForGitDescribe.append(" --dirty=" + dirtyMark);
+ argumentsForGitDescribe.append(" --dirty=").append(dirtyMark);
}
final String matchOption = describeConfig.getMatch();
if (matchOption != null && !matchOption.isEmpty()) {
- argumentsForGitDescribe.append(" --match=" + matchOption);
+ argumentsForGitDescribe.append(" --match=").append(matchOption);
}
- argumentsForGitDescribe.append(" --abbrev=" + describeConfig.getAbbrev());
+ argumentsForGitDescribe.append(" --abbrev=").append(describeConfig.getAbbrev());
if (describeConfig.getTags()) {
argumentsForGitDescribe.append(" --tags");
@@ -160,12 +149,12 @@ private String getArgumentsForGitDescribe(GitDescribeConfig describeConfig) {
}
@Override
- protected String getCommitId() {
+ protected String getCommitId() throws GitCommitIdExecutionException {
return runQuietGitCommand(canonical, "rev-parse HEAD");
}
@Override
- protected String getAbbrevCommitId() {
+ protected String getAbbrevCommitId() throws GitCommitIdExecutionException {
// we could run: tryToRunGitCommand(canonical, "rev-parse --short="+abbrevLength+" HEAD");
// but minimum length for --short is 4, our abbrevLength could be 2
String commitId = getCommitId();
@@ -179,50 +168,50 @@ protected String getAbbrevCommitId() {
}
@Override
- protected boolean isDirty() throws MojoExecutionException {
+ protected boolean isDirty() throws GitCommitIdExecutionException {
return !tryCheckEmptyRunGitCommand(canonical, "status -s");
}
@Override
- protected String getCommitAuthorName() {
+ protected String getCommitAuthorName() throws GitCommitIdExecutionException {
return runQuietGitCommand(canonical, "log -1 --pretty=format:%an");
}
@Override
- protected String getCommitAuthorEmail() {
+ protected String getCommitAuthorEmail() throws GitCommitIdExecutionException {
return runQuietGitCommand(canonical, "log -1 --pretty=format:%ae");
}
@Override
- protected String getCommitMessageFull() {
+ protected String getCommitMessageFull() throws GitCommitIdExecutionException {
return runQuietGitCommand(canonical, "log -1 --pretty=format:%B");
}
@Override
- protected String getCommitMessageShort() {
+ protected String getCommitMessageShort() throws GitCommitIdExecutionException {
return runQuietGitCommand(canonical, "log -1 --pretty=format:%s");
}
@Override
- protected String getCommitTime() {
+ protected String getCommitTime() throws GitCommitIdExecutionException {
String value = runQuietGitCommand(canonical, "log -1 --pretty=format:%ct");
SimpleDateFormat smf = getSimpleDateFormatWithTimeZone();
return smf.format(Long.parseLong(value)*1000L);
}
@Override
- protected String getTags() {
+ protected String getTags() throws GitCommitIdExecutionException {
final String result = runQuietGitCommand(canonical, "tag --contains");
return result.replace('\n', ',');
}
@Override
- protected String getRemoteOriginUrl() throws MojoExecutionException {
+ protected String getRemoteOriginUrl() throws GitCommitIdExecutionException {
return getOriginRemote(canonical);
}
@Override
- protected String getClosestTagName(){
+ protected String getClosestTagName() throws GitCommitIdExecutionException {
try {
return runGitCommand(canonical, "describe --abbrev=0 --tags");
} catch (NativeCommandException ignore) {
@@ -232,7 +221,7 @@ protected String getClosestTagName(){
}
@Override
- protected String getClosestTagCommitCount(){
+ protected String getClosestTagCommitCount() throws GitCommitIdExecutionException {
String closestTagName = getClosestTagName();
if(closestTagName != null && !closestTagName.trim().isEmpty()){
return runQuietGitCommand(canonical, "rev-list "+closestTagName+"..HEAD --count");
@@ -241,10 +230,10 @@ protected String getClosestTagCommitCount(){
}
@Override
- protected void finalCleanUp() {
+ protected void finalCleanUp() throws GitCommitIdExecutionException {
}
- private String getOriginRemote(File directory) throws MojoExecutionException {
+ private String getOriginRemote(File directory) throws GitCommitIdExecutionException {
String remoteUrl = null;
String remotes = runQuietGitCommand(directory, "remote -v");
@@ -253,11 +242,11 @@ private String getOriginRemote(File directory) throws MojoExecutionException {
String trimmed = line.trim();
if (trimmed.startsWith("origin")) {
- String[] splited = trimmed.split("\\s+");
- if (splited.length != REMOTE_COLS - 1) { // because (fetch/push) was trimmed
- throw new MojoExecutionException("Unsupported GIT output (verbose remote address): " + line);
+ String[] split = trimmed.split("\\s+");
+ if (split.length != REMOTE_COLS - 1) { // because (fetch/push) was trimmed
+ throw new GitCommitIdExecutionException("Unsupported GIT output (verbose remote address): " + line);
}
- remoteUrl = splited[1];
+ remoteUrl = split[1];
}
}
return remoteUrl;
@@ -409,34 +398,6 @@ private StringBuilder readStderr(InputStream err) throws IOException {
return errMsg;
}
-// @Override
-// public String run(File directory, String command) throws IOException {
-// String output;
-// try {
-// final ProcessBuilder builder = new ProcessBuilder(command.split("\\s"));
-// final Process proc = builder.directory(directory).start();
-// proc.waitFor();
-// InputStream is = proc.getInputStream();
-// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
-// final StringBuilder commandResult = new StringBuilder();
-//
-// String line;
-// while ((line = reader.readLine()) != null) {
-// commandResult.append(line);
-// }
-//
-// output = commandResult.toString();
-//
-// if (proc.exitValue() != 0) {
-// String message = String.format("Git command exited with invalid status [%d]: `%s`", proc.exitValue(), output);
-// throw new IOException(message);
-// }
-// } catch (InterruptedException e) {
-// throw new RuntimeException("Unable to attach to git process!", e);
-// }
-// return output;
-// }
-
@Override
public boolean runEmpty(File directory, String command) throws IOException {
boolean empty = true;
@@ -458,4 +419,4 @@ public boolean runEmpty(File directory, String command) throws IOException {
return empty; // was non-empty
}
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/log/FormattingTuple.java b/src/main/java/pl/project13/maven/git/log/FormattingTuple.java
new file mode 100644
index 00000000..dda205b3
--- /dev/null
+++ b/src/main/java/pl/project13/maven/git/log/FormattingTuple.java
@@ -0,0 +1,93 @@
+/*
+ * 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.log;
+
+/**
+ * Copyright (c) 2004-2011 QOS.ch
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+/**
+ * Holds the results of formatting done by {@link MessageFormatter}.
+ *
+ * @author Joern Huxhorn
+ */
+public class FormattingTuple {
+
+ static public FormattingTuple NULL = new FormattingTuple(null);
+
+ private String message;
+ private Throwable throwable;
+ private Object[] argArray;
+
+ public FormattingTuple(String message) {
+ this(message, null, null);
+ }
+
+ public FormattingTuple(String message, Object[] argArray, Throwable throwable) {
+ this.message = message;
+ this.throwable = throwable;
+ if (throwable == null) {
+ this.argArray = argArray;
+ } else {
+ this.argArray = trimmedCopy(argArray);
+ }
+ }
+
+ static Object[] trimmedCopy(Object[] argArray) {
+ if (argArray == null || argArray.length == 0) {
+ throw new IllegalStateException("non-sensical empty or null argument array");
+ }
+ final int trimmedLen = argArray.length - 1;
+ Object[] trimmed = new Object[trimmedLen];
+ System.arraycopy(argArray, 0, trimmed, 0, trimmedLen);
+ return trimmed;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public Object[] getArgArray() {
+ return argArray;
+ }
+
+ public Throwable getThrowable() {
+ return throwable;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/log/LoggerBridge.java b/src/main/java/pl/project13/maven/git/log/LoggerBridge.java
index 53126ca1..23fb9b61 100644
--- a/src/main/java/pl/project13/maven/git/log/LoggerBridge.java
+++ b/src/main/java/pl/project13/maven/git/log/LoggerBridge.java
@@ -17,10 +17,312 @@
package pl.project13.maven.git.log;
+/**
+ * Interface for logging in git-commit-id plugin. Isolates logging to enable future possible code reuse in other tools.
+ * Adds verbosity flag. Given SLF4J popularity and recent internal Maven adoption, follows SLF4J interfaces.
+ */
public interface LoggerBridge {
- void log(Object... parts);
- void error(Object... parts);
- void warn(Object... parts);
- void debug(Object... parts);
- void setVerbose(boolean verbose);
-}
+
+ /**
+ * Returns true if plugin does verbose logging.
+ *
+ * @return true if plugin does verbose logging
+ */
+ boolean isVerbose();
+
+ /**
+ * Sets plugin to verbose mode.
+ *
+ * @param verbose plugin verbosity flag
+ */
+ void setVerbose(boolean verbose);
+
+/*
+ The following borrowed from SLF4J Logger.java
+*/
+
+/**
+ * Copyright (c) 2004-2011 QOS.ch
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+ /**
+ * Is the logger instance enabled for the DEBUG level?
+ *
+ * @return True if this Logger is enabled for the DEBUG level,
+ * false otherwise.
+ */
+ boolean isDebugEnabled();
+
+ /**
+ * Log a message at the DEBUG level.
+ *
+ * @param msg the message string to be logged
+ */
+ void debug(String msg);
+
+ /**
+ * Log a message at the DEBUG level according to the specified format
+ * and argument.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the DEBUG level.
+ *
+ * @param format the format string
+ * @param arg the argument
+ */
+ void debug(String format, Object arg);
+
+ /**
+ * Log a message at the DEBUG level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the DEBUG level.
+ *
+ * @param format the format string
+ * @param arg1 the first argument
+ * @param arg2 the second argument
+ */
+ void debug(String format, Object arg1, Object arg2);
+
+ /**
+ * Log a message at the DEBUG level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous string concatenation when the logger
+ * is disabled for the DEBUG level. However, this variant incurs the hidden
+ * (and relatively small) cost of creating an Object[] before invoking the method,
+ * even if this logger is disabled for DEBUG. The variants taking
+ * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
+ * arguments exist solely in order to avoid this hidden cost.
+ *
+ * @param format the format string
+ * @param arguments a list of 3 or more arguments
+ */
+ void debug(String format, Object... arguments);
+
+ /**
+ * Log an exception (throwable) at the DEBUG level with an
+ * accompanying message.
+ *
+ * @param msg the message accompanying the exception
+ * @param t the exception (throwable) to log
+ */
+ void debug(String msg, Throwable t);
+
+ /**
+ * Is the logger instance enabled for the INFO level?
+ *
+ * @return True if this Logger is enabled for the INFO level,
+ * false otherwise.
+ */
+ boolean isInfoEnabled();
+
+ /**
+ * Log a message at the INFO level.
+ *
+ * @param msg the message string to be logged
+ */
+ void info(String msg);
+
+ /**
+ * Log a message at the INFO level according to the specified format
+ * and argument.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the INFO level.
+ *
+ * @param format the format string
+ * @param arg the argument
+ */
+ void info(String format, Object arg);
+
+ /**
+ * Log a message at the INFO level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the INFO level.
+ *
+ * @param format the format string
+ * @param arg1 the first argument
+ * @param arg2 the second argument
+ */
+ void info(String format, Object arg1, Object arg2);
+
+ /**
+ * Log a message at the INFO level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous string concatenation when the logger
+ * is disabled for the INFO level. However, this variant incurs the hidden
+ * (and relatively small) cost of creating an Object[] before invoking the method,
+ * even if this logger is disabled for INFO. The variants taking
+ * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two}
+ * arguments exist solely in order to avoid this hidden cost.
+ *
+ * @param format the format string
+ * @param arguments a list of 3 or more arguments
+ */
+ void info(String format, Object... arguments);
+
+ /**
+ * Log an exception (throwable) at the INFO level with an
+ * accompanying message.
+ *
+ * @param msg the message accompanying the exception
+ * @param t the exception (throwable) to log
+ */
+ void info(String msg, Throwable t);
+
+ /**
+ * Is the logger instance enabled for the WARN level?
+ *
+ * @return True if this Logger is enabled for the WARN level,
+ * false otherwise.
+ */
+ boolean isWarnEnabled();
+
+ /**
+ * Log a message at the WARN level.
+ *
+ * @param msg the message string to be logged
+ */
+ void warn(String msg);
+
+ /**
+ * Log a message at the WARN level according to the specified format
+ * and argument.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the WARN level.
+ *
+ * @param format the format string
+ * @param arg the argument
+ */
+ void warn(String format, Object arg);
+
+ /**
+ * Log a message at the WARN level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the WARN level.
+ *
+ * @param format the format string
+ * @param arg1 the first argument
+ * @param arg2 the second argument
+ */
+ void warn(String format, Object arg1, Object arg2);
+
+ /**
+ * Log a message at the WARN level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous string concatenation when the logger
+ * is disabled for the WARN level. However, this variant incurs the hidden
+ * (and relatively small) cost of creating an Object[] before invoking the method,
+ * even if this logger is disabled for WARN. The variants taking
+ * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two}
+ * arguments exist solely in order to avoid this hidden cost.
+ *
+ * @param format the format string
+ * @param arguments a list of 3 or more arguments
+ */
+ void warn(String format, Object... arguments);
+
+ /**
+ * Log an exception (throwable) at the WARN level with an
+ * accompanying message.
+ *
+ * @param msg the message accompanying the exception
+ * @param t the exception (throwable) to log
+ */
+ void warn(String msg, Throwable t);
+
+ /**
+ * Is the logger instance enabled for the ERROR level?
+ *
+ * @return True if this Logger is enabled for the ERROR level,
+ * false otherwise.
+ */
+ boolean isErrorEnabled();
+
+ /**
+ * Log a message at the ERROR level.
+ *
+ * @param msg the message string to be logged
+ */
+ void error(String msg);
+
+ /**
+ * Log a message at the ERROR level according to the specified format
+ * and argument.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the ERROR level.
+ *
+ * @param format the format string
+ * @param arg the argument
+ */
+ void error(String format, Object arg);
+
+ /**
+ * Log a message at the ERROR level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous object creation when the logger
+ * is disabled for the ERROR level.
+ *
+ * @param format the format string
+ * @param arg1 the first argument
+ * @param arg2 the second argument
+ */
+ void error(String format, Object arg1, Object arg2);
+
+ /**
+ * Log a message at the ERROR level according to the specified format
+ * and arguments.
+ *
+ *
This form avoids superfluous string concatenation when the logger
+ * is disabled for the ERROR level. However, this variant incurs the hidden
+ * (and relatively small) cost of creating an Object[] before invoking the method,
+ * even if this logger is disabled for ERROR. The variants taking
+ * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two}
+ * arguments exist solely in order to avoid this hidden cost.
+ *
+ * @param format the format string
+ * @param arguments a list of 3 or more arguments
+ */
+ void error(String format, Object... arguments);
+
+ /**
+ * Log an exception (throwable) at the ERROR level with an
+ * accompanying message.
+ *
+ * @param msg the message accompanying the exception
+ * @param t the exception (throwable) to log
+ */
+ void error(String msg, Throwable t);
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java b/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java
index b35109af..49f100d5 100644
--- a/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java
+++ b/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java
@@ -17,71 +17,220 @@
package pl.project13.maven.git.log;
-import java.util.Properties;
+import org.apache.maven.plugin.Mojo;
-import com.google.common.base.Joiner;
+/**
+ * Bridges logging to standard Maven log adhering to verbosity level.
+ */
+public class MavenLoggerBridge implements LoggerBridge {
-import org.apache.maven.plugin.logging.Log;
-import org.slf4j.Logger;
-import org.slf4j.impl.SimpleLogger;
-import org.slf4j.impl.SimpleLoggerFactory;
+ private boolean verbose;
+ private final Mojo mojo;
-public class MavenLoggerBridge implements LoggerBridge {
+ public MavenLoggerBridge(Mojo mojo, boolean verbose) {
+ this.mojo = mojo;
+ this.verbose = verbose;
+ }
+
+ @Override
+ public void setVerbose(boolean verbose) {
+ this.verbose = verbose;
+ }
+
+ @Override
+ public boolean isVerbose() {
+ return verbose;
+ }
+
+ @Override
+ public boolean isDebugEnabled() {
+ return mojo.getLog().isDebugEnabled();
+ }
+
+ @Override
+ public boolean isInfoEnabled() {
+ return mojo.getLog().isInfoEnabled();
+ }
- private Logger logger;
- private boolean verbose;
+ @Override
+ public boolean isWarnEnabled() {
+ return mojo.getLog().isWarnEnabled();
+ }
+
+ @Override
+ public boolean isErrorEnabled() {
+ return mojo.getLog().isErrorEnabled();
+ }
+
+ @Override
+ public void debug(String msg) {
+ if (verbose) {
+ mojo.getLog().debug(msg);
+ }
+ }
+
+ @Override
+ public void debug(String format, Object arg) {
+ if (verbose) {
+ debug(MessageFormatter.format(format, arg));
+ }
+ }
- public MavenLoggerBridge(Log log, boolean verbose) {
- setSimpleLoggerPorperties();
- this.logger = new SimpleLoggerFactory().getLogger(getClass().getName());
- this.verbose = verbose;
- }
+ @Override
+ public void debug(String format, Object arg1, Object arg2) {
+ if (verbose) {
+ debug(MessageFormatter.format(format, arg1, arg2));
+ }
+ }
- private void setSimpleLoggerPorperties() {
- Properties sysProperties = System.getProperties();
- if(!sysProperties.containsKey(SimpleLogger.SHOW_THREAD_NAME_KEY)){
- System.setProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, String.valueOf(false));
+ @Override
+ public void debug(String format, Object... arguments) {
+ if (verbose) {
+ debug(MessageFormatter.arrayFormat(format, arguments));
+ }
}
- if(!sysProperties.containsKey(SimpleLogger.LEVEL_IN_BRACKETS_KEY)){
- System.setProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, String.valueOf(true));
+
+ @Override
+ public void debug(String msg, Throwable t) {
+ if (verbose) {
+ mojo.getLog().debug(msg, t);
+ }
}
- }
- @Override
- public void log(Object... parts) {
- if (verbose) {
- logger.info(Joiner.on(" ").useForNull("null").join(parts));
+ @Override
+ public void info(String msg) {
+ if (verbose) {
+ mojo.getLog().info(msg);
+ }
}
- }
- @Override
- public void error(Object... parts) {
- if (verbose) {
- logger.error(Joiner.on(" ").useForNull("null").join(parts));
+ @Override
+ public void info(String format, Object arg) {
+ if (verbose) {
+ info(MessageFormatter.format(format, arg));
+ }
}
- }
- @Override
- public void warn(Object... parts) {
- if (verbose) {
- logger.warn(Joiner.on(" ").useForNull("null").join(parts));
+ @Override
+ public void info(String format, Object arg1, Object arg2) {
+ if (verbose) {
+ info(MessageFormatter.format(format, arg1, arg2));
+ }
}
- }
- @Override
- public void debug(Object... parts) {
- if (verbose) {
- logger.debug(Joiner.on(" ").useForNull("null").join(parts));
+ @Override
+ public void info(String format, Object... arguments) {
+ if (verbose) {
+ info(MessageFormatter.arrayFormat(format, arguments));
+ }
}
- }
- @Override
- public void setVerbose(boolean verbose) {
- this.verbose = verbose;
- }
+ @Override
+ public void info(String msg, Throwable t) {
+ if (verbose) {
+ mojo.getLog().info(msg, t);
+ }
+ }
- protected void setLogger(Logger logger){
- this.logger = logger;
- }
+ @Override
+ public void warn(String msg) {
+ if (verbose) {
+ mojo.getLog().warn(msg);
+ }
+ }
-}
+ @Override
+ public void warn(String format, Object arg) {
+ if (verbose) {
+ warn(MessageFormatter.format(format, arg));
+ }
+ }
+
+ @Override
+ public void warn(String format, Object arg1, Object arg2) {
+ if (verbose) {
+ warn(MessageFormatter.format(format, arg1, arg2));
+ }
+ }
+
+ @Override
+ public void warn(String format, Object... arguments) {
+ if (verbose) {
+ warn(MessageFormatter.arrayFormat(format, arguments));
+ }
+ }
+
+ @Override
+ public void warn(String msg, Throwable t) {
+ if (verbose) {
+ mojo.getLog().warn(msg, t);
+ }
+ }
+
+ @Override
+ public void error(String msg) {
+ if (verbose) {
+ mojo.getLog().error(msg);
+ }
+ }
+
+ @Override
+ public void error(String format, Object arg) {
+ if (verbose) {
+ error(MessageFormatter.format(format, arg));
+ }
+ }
+
+ @Override
+ public void error(String format, Object arg1, Object arg2) {
+ if (verbose) {
+ error(MessageFormatter.format(format, arg1, arg2));
+ }
+ }
+
+ @Override
+ public void error(String format, Object... arguments) {
+ if (verbose) {
+ error(MessageFormatter.arrayFormat(format, arguments));
+ }
+ }
+
+ @Override
+ public void error(String msg, Throwable t) {
+ if (verbose) {
+ mojo.getLog().error(msg, t);
+ }
+ }
+
+ private void debug(FormattingTuple tuple) {
+ if (null == tuple.getThrowable()) {
+ mojo.getLog().debug(tuple.getMessage());
+ } else {
+ mojo.getLog().debug(tuple.getMessage(), tuple.getThrowable());
+ }
+ }
+
+ private void info(FormattingTuple tuple) {
+ if (null == tuple.getThrowable()) {
+ mojo.getLog().info(tuple.getMessage());
+ } else {
+ mojo.getLog().info(tuple.getMessage(), tuple.getThrowable());
+ }
+ }
+
+ private void warn(FormattingTuple tuple) {
+ if (null == tuple.getThrowable()) {
+ mojo.getLog().warn(tuple.getMessage());
+ } else {
+ mojo.getLog().warn(tuple.getMessage(), tuple.getThrowable());
+ }
+ }
+
+ private void error(FormattingTuple tuple) {
+ if (null == tuple.getThrowable()) {
+ mojo.getLog().error(tuple.getMessage());
+ } else {
+ mojo.getLog().error(tuple.getMessage(), tuple.getThrowable());
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/pl/project13/maven/git/log/MessageFormatter.java b/src/main/java/pl/project13/maven/git/log/MessageFormatter.java
new file mode 100644
index 00000000..0631fb9a
--- /dev/null
+++ b/src/main/java/pl/project13/maven/git/log/MessageFormatter.java
@@ -0,0 +1,430 @@
+/*
+ * 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.log;
+
+/**
+ * Copyright (c) 2004-2011 QOS.ch
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+import java.text.MessageFormat;
+import java.util.HashMap;
+import java.util.Map;
+
+// contributors: lizongbo: proposed special treatment of array parameter values
+// Joern Huxhorn: pointed out double[] omission, suggested deep array copy
+/**
+ * Formats messages according to very simple substitution rules. Substitutions
+ * can be made 1, 2 or more arguments.
+ *
+ *
+ * The {} pair is called the formatting anchor. It serves to designate
+ * the location where arguments need to be substituted within the message
+ * pattern.
+ *
+ * In case your message contains the '{' or the '}' character, you do not have
+ * to do anything special unless the '}' character immediately follows '{'. For
+ * example,
+ *
+ *
+ * MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
+ *
+ *
+ * will return the string "Set {1,2,3} is not equal to 1,2.".
+ *
+ *
+ * If for whatever reason you need to place the string "{}" in the message
+ * without its formatting anchor meaning, then you need to escape the
+ * '{' character with '\', that is the backslash character. Only the '{'
+ * character should be escaped. There is no need to escape the '}' character.
+ * For example,
+ *
+ *
+ * MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
+ *
+ *
+ * will return the string "Set {} is not equal to 1,2.".
+ *
+ *
+ * The escaping behavior just described can be overridden by escaping the escape
+ * character '\'. Calling
+ *
+ *
+ * MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
+ *
+ *
+ * will return the string "File name is C:\file.zip".
+ *
+ *
+ * The formatting conventions are different than those of {@link MessageFormat}
+ * which ships with the Java platform. This is justified by the fact that
+ * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}.
+ * This local performance difference is both measurable and significant in the
+ * larger context of the complete logging processing chain.
+ *
+ *
+ * See also {@link #format(String, Object)},
+ * {@link #format(String, Object, Object)} and
+ * {@link #arrayFormat(String, Object[])} methods for more details.
+ *
+ * @author Ceki Gülcü
+ * @author Joern Huxhorn
+ */
+final public class MessageFormatter {
+ static final char DELIM_START = '{';
+ static final char DELIM_STOP = '}';
+ static final String DELIM_STR = "{}";
+ private static final char ESCAPE_CHAR = '\\';
+
+ /**
+ * Performs single argument substitution for the 'messagePattern' passed as
+ * parameter.
+ *
+ *
+ * @param messagePattern
+ * The message pattern which will be parsed and formatted
+ * @param arg
+ * The argument to be substituted in place of the formatting anchor
+ * @return The formatted message
+ */
+ final public static FormattingTuple format(String messagePattern, Object arg) {
+ return arrayFormat(messagePattern, new Object[] { arg });
+ }
+
+ /**
+ *
+ * Performs a two argument substitution for the 'messagePattern' passed as
+ * parameter.
+ *
+ * For example,
+ *
+ *
+ * MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
+ *
+ *
+ * will return the string "Hi Alice. My name is Bob.".
+ *
+ * @param messagePattern
+ * The message pattern which will be parsed and formatted
+ * @param arg1
+ * The argument to be substituted in place of the first formatting
+ * anchor
+ * @param arg2
+ * The argument to be substituted in place of the second formatting
+ * anchor
+ * @return The formatted message
+ */
+ final public static FormattingTuple format(final String messagePattern, Object arg1, Object arg2) {
+ return arrayFormat(messagePattern, new Object[] { arg1, arg2 });
+ }
+
+ static final Throwable getThrowableCandidate(Object[] argArray) {
+ if (argArray == null || argArray.length == 0) {
+ return null;
+ }
+
+ final Object lastEntry = argArray[argArray.length - 1];
+ if (lastEntry instanceof Throwable) {
+ return (Throwable) lastEntry;
+ }
+ return null;
+ }
+
+ /**
+ * Same principle as the {@link #format(String, Object)} and
+ * {@link #format(String, Object, Object)} methods except that any number of
+ * arguments can be passed in an array.
+ *
+ * @param messagePattern
+ * The message pattern which will be parsed and formatted
+ * @param argArray
+ * An array of arguments to be substituted in place of formatting
+ * anchors
+ * @return The formatted message
+ */
+ final public static FormattingTuple arrayFormat(final String messagePattern, final Object[] argArray) {
+
+ Throwable throwableCandidate = getThrowableCandidate(argArray);
+
+ if (messagePattern == null) {
+ return new FormattingTuple(null, argArray, throwableCandidate);
+ }
+
+ if (argArray == null) {
+ return new FormattingTuple(messagePattern);
+ }
+
+ int i = 0;
+ int j;
+ // use string builder for better multicore performance
+ StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
+
+ int L;
+ for (L = 0; L < argArray.length; L++) {
+
+ j = messagePattern.indexOf(DELIM_STR, i);
+
+ if (j == -1) {
+ // no more variables
+ if (i == 0) { // this is a simple string
+ return new FormattingTuple(messagePattern, argArray, throwableCandidate);
+ } else { // add the tail string which contains no variables and return
+ // the result.
+ sbuf.append(messagePattern, i, messagePattern.length());
+ return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate);
+ }
+ } else {
+ if (isEscapedDelimeter(messagePattern, j)) {
+ if (!isDoubleEscaped(messagePattern, j)) {
+ L--; // DELIM_START was escaped, thus should not be incremented
+ sbuf.append(messagePattern, i, j - 1);
+ sbuf.append(DELIM_START);
+ i = j + 1;
+ } else {
+ // The escape character preceding the delimiter start is
+ // itself escaped: "abc x:\\{}"
+ // we have to consume one backward slash
+ sbuf.append(messagePattern, i, j - 1);
+ deeplyAppendParameter(sbuf, argArray[L], new HashMap