From 617e466cba611b50d879b8c7308ab0817f334b5e Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Wed, 30 Dec 2015 23:45:29 +0100 Subject: [PATCH 01/22] first bite of logging refactoring: now logs are in line with standard Maven logging. log message string construction to address. --- pom.xml | 53 ++----- .../pl/project13/jgit/DescribeCommand.java | 51 ++---- .../java/pl/project13/jgit/JGitCommon.java | 33 ++-- .../project13/maven/git/GitCommitIdMojo.java | 83 ++++------ .../project13/maven/git/GitDataProvider.java | 26 ++- .../pl/project13/maven/git/JGitProvider.java | 27 ++-- .../maven/git/NativeGitProvider.java | 18 +-- .../maven/git/log/MavenLoggerBridge.java | 87 ---------- .../maven/git/log/StdOutLoggerBridge.java | 63 -------- .../{LoggerBridge.java => VerboseLog.java} | 28 +++- .../maven/git/log/VerboseLogger.java | 148 ++++++++++++++++++ .../DescribeCommandAbbrevIntegrationTest.java | 4 +- .../jgit/DescribeCommandIntegrationTest.java | 35 ++--- .../jgit/DescribeCommandOptionsTest.java | 3 +- .../DescribeCommandTagsIntegrationTest.java | 12 +- .../maven/git/FileSystemMavenSandbox.java | 5 +- .../git/GitCommitIdMojoIntegrationTest.java | 1 - .../maven/git/GitCommitIdMojoTest.java | 10 +- .../maven/git/GitIntegrationTest.java | 32 +++- .../maven/git/log/MavenLoggerBridgeTest.java | 47 ------ .../maven/git/log/StdOutLoggerBridgeTest.java | 46 ------ 21 files changed, 331 insertions(+), 481 deletions(-) delete mode 100644 src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java delete mode 100644 src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java rename src/main/java/pl/project13/maven/git/log/{LoggerBridge.java => VerboseLog.java} (65%) create mode 100644 src/main/java/pl/project13/maven/git/log/VerboseLogger.java delete mode 100644 src/test/java/pl/project13/maven/git/log/MavenLoggerBridgeTest.java delete mode 100644 src/test/java/pl/project13/maven/git/log/StdOutLoggerBridgeTest.java diff --git a/pom.xml b/pom.xml index bb335b1c..d7439af2 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ org.sonatype.oss oss-parent - 6 + 9 pl.project13.maven @@ -72,7 +72,6 @@ 3.1.1 4.0.0.201506090130-r - 1.7.12 4.12 2.0.5-beta @@ -129,18 +128,6 @@ ${jgit.version} - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - slf4j-simple - ${slf4j.version} - - junit @@ -184,6 +171,14 @@ 1.0.4 test + + + + org.slf4j + slf4j-simple + 1.7.13 + test + @@ -212,33 +207,6 @@ ${java.target} - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - package - - shade - - - false - - - pl.project13.maven.git.GitCommitIdMojo - - - - - org.slf4j:* - - - - - - @@ -339,5 +307,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..d667e2f7 100644 --- a/src/main/java/pl/project13/jgit/DescribeCommand.java +++ b/src/main/java/pl/project13/jgit/DescribeCommand.java @@ -21,6 +21,7 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; +import org.apache.maven.plugin.Mojo; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.GitCommand; import org.eclipse.jgit.api.Status; @@ -35,8 +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 Mojo mojo; private JGitCommon jGitCommon; // TODO not yet implemented options: @@ -98,29 +97,13 @@ 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) { 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; + public DescribeCommand withMojo(Mojo mojo) { + this.mojo = mojo; return this; } @@ -134,7 +117,7 @@ public DescribeCommand withLoggerBridge(LoggerBridge bridge) { @NotNull public DescribeCommand always(boolean always) { this.alwaysFlag = always; - log("--always =", always); + mojo.getLog().info("--always = " + always); return this; } @@ -153,7 +136,7 @@ public DescribeCommand always(boolean always) { public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) { if (forceLongFormat != null && forceLongFormat) { this.forceLongFormat = true; - log("--long =", true); + mojo.getLog().info("--long = " + true); } return this; } @@ -171,7 +154,7 @@ 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 >= 0, String.format("N (commit abbrev length) must be positive! (Was [%s])", n)); - log("--abbrev =", n); + mojo.getLog().info("--abbrev = " + n); abbrev = n; } return this; @@ -209,7 +192,7 @@ public DescribeCommand abbrev(@Nullable Integer n) { public DescribeCommand tags(@Nullable Boolean includeLightweightTagsInSearch) { if (includeLightweightTagsInSearch != null && includeLightweightTagsInSearch) { tagsFlag = includeLightweightTagsInSearch; - log("--tags =", includeLightweightTagsInSearch); + mojo.getLog().info("--tags = " + includeLightweightTagsInSearch); } return this; } @@ -251,7 +234,7 @@ public DescribeCommand apply(@Nullable GitDescribeConfig config) { @NotNull public DescribeCommand dirty(@Nullable String dirtyMarker) { Optional option = Optional.fromNullable(dirtyMarker); - log("--dirty =", option.or("")); + mojo.getLog().info("--dirty = " + option.or("")); this.dirtyOption = option; return this; } @@ -267,7 +250,7 @@ public DescribeCommand dirty(@Nullable String dirtyMarker) { public DescribeCommand match(@Nullable String pattern) { if (!"*".equals(pattern)) { matchOption = Optional.fromNullable(pattern); - log("--match =", matchOption.or("")); + mojo.getLog().info("--match =" + matchOption.or("")); } return this; } @@ -289,7 +272,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."); + mojo.getLog().info("The commit we're on is a Tag ([" + tagName + "]) and forceLongFormat == false, returning."); return new DescribeResult(tagName, dirty, dirtyOption); } @@ -362,7 +345,7 @@ boolean findDirtyState(Repository repo) throws GitAPIException { && status.getModified().isEmpty() && status.getConflicting().isEmpty()); - log("Repo is in dirty state [", isDirty, "]"); + mojo.getLog().info("Repo is in dirty state [" + isDirty + "]"); return isDirty; } @@ -379,7 +362,7 @@ RevCommit findHeadObjectId(@NotNull Repository repo) throws RuntimeException { RevCommit headCommit = walk.lookupCommit(headId); walk.dispose(); - log("HEAD is [",headCommit.getName(),"] "); + mojo.getLog().info("HEAD is [" + headCommit.getName() + "] "); return headCommit; } catch (IOException ex) { throw new RuntimeException("Unable to obtain HEAD commit!", ex); @@ -389,9 +372,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, mojo); Map> commitIdsToTagNames = jGitCommon.transformRevTagsMapToDateSortedTagNames(commitIdsToTags); - log("Created map: [",commitIdsToTagNames,"] "); + mojo.getLog().info("Created map: [" + commitIdsToTagNames + "] "); return commitIdsToTagNames; } @@ -407,9 +390,5 @@ private String createMatchPattern() { buf.append("\\E$"); return buf.toString(); } - - private void log(Object... parts) { - loggerBridge.log(parts); - } } diff --git a/src/main/java/pl/project13/jgit/JGitCommon.java b/src/main/java/pl/project13/jgit/JGitCommon.java index a991ca7e..713adb04 100644 --- a/src/main/java/pl/project13/jgit/JGitCommon.java +++ b/src/main/java/pl/project13/jgit/JGitCommon.java @@ -33,6 +33,7 @@ import java.util.Set; import java.util.regex.Pattern; +import org.apache.maven.plugin.Mojo; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; @@ -45,18 +46,14 @@ 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; public class JGitCommon { @@ -97,16 +94,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, @NotNull Mojo mojo){ + Map> map = getClosestTagAsMap(repo, mojo); 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, @NotNull Mojo mojo){ + HashMap> map = transformRevTagsMapToDateSortedTagNames(getClosestTagAsMap(repo, mojo)); ObjectId obj = (ObjectId) map.keySet().toArray()[0]; RevWalk walk = new RevWalk(repo); @@ -117,11 +114,11 @@ public String getClosestTagCommitCount(@NotNull LoggerBridge loggerBridge,@NotNu return String.valueOf(distance); } - private Map> getClosestTagAsMap(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo){ + private Map> getClosestTagAsMap(@NotNull Repository repo, @NotNull Mojo mojo){ Map> mapWithClosestTagOnly = newHashMap(); boolean includeLightweightTags = true; String matchPattern = ".*"; - Map> commitIdsToTags = getCommitIdsToTags(loggerBridge,repo,includeLightweightTags,matchPattern); + Map> commitIdsToTags = getCommitIdsToTags(repo, includeLightweightTags, matchPattern, mojo); LinkedHashMap> sortedCommitIdsToTags = sortByDatedRevTag(commitIdsToTags); for(Map.Entry> entry: sortedCommitIdsToTags.entrySet()){ @@ -154,7 +151,7 @@ public int compare(Map.Entry> m1, Map.Entry> getCommitIdsToTags(@NotNull LoggerBridge loggerBridge,@NotNull Repository repo, boolean includeLightweightTags, String matchPattern){ + protected Map> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern, @NotNull Mojo mojo){ Map> commitIdsToTags = newHashMap(); RevWalk walk = new RevWalk(repo); @@ -163,13 +160,13 @@ protected Map> getCommitIdsToTags(@NotNull LoggerBri List tagRefs = Git.wrap(repo).tagList().call(); Pattern regex = Pattern.compile(matchPattern); - loggerBridge.log("Tag refs [", tagRefs, "]"); + mojo.getLog().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, "]"); + mojo.getLog().info("Skipping tagRef with name [" + name + "] as it doesn't match [" + matchPattern + "]"); continue; } ObjectId resolvedCommitId = repo.resolve(name); @@ -178,7 +175,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,"] "); + mojo.getLog().info("Resolved tag [" + revTag.getTagName() + "] [" + revTag.getTaggerIdent() + "], points at [" + taggedCommitId + "] "); // sometimes a tag, may point to another tag, so we need to unpack it while (isTagId(taggedCommitId)) { @@ -195,7 +192,7 @@ protected Map> getCommitIdsToTags(@NotNull LoggerBri // it's an lightweight tag! (yeah, really) if (includeLightweightTags) { // --tags means "include lightweight tags" - loggerBridge.log("Including lightweight tag [", name, "]"); + mojo.getLog().info("Including lightweight tag [" + name + "]"); DatedRevTag datedRevTag = new DatedRevTag(resolvedCommitId, name); @@ -206,16 +203,16 @@ protected Map> getCommitIdsToTags(@NotNull LoggerBri } } } catch (Exception ignored) { - loggerBridge.error("Failed while parsing [",tagRef,"] -- ", Throwables.getStackTraceAsString(ignored)); + mojo.getLog().info("Failed while parsing [" + tagRef + "] -- ", ignored); } } for (Map.Entry> entry : commitIdsToTags.entrySet()) { - loggerBridge.log("key [",entry.getKey(),"], tags => [",entry.getValue(),"] "); + mojo.getLog().info("key [" + entry.getKey() + "], tags => [" + entry.getValue() + "] "); } return commitIdsToTags; } catch (Exception e) { - loggerBridge.log("Unable to locate tags\n[",Throwables.getStackTraceAsString(e),"]"); + mojo.getLog().info("Unable to locate tags", e); } finally { walk.close(); } diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 525ad929..218f32dc 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -35,8 +35,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import pl.project13.maven.git.log.LoggerBridge; -import pl.project13.maven.git.log.MavenLoggerBridge; +import pl.project13.maven.git.log.VerboseLog; +import pl.project13.maven.git.log.VerboseLogger; import pl.project13.maven.git.util.PropertyManager; import java.io.*; @@ -68,6 +68,8 @@ public class GitCommitIdMojo extends AbstractMojo { public static final String DIRTY = "dirty"; public static final String COMMIT_ID_FLAT = "commit.id"; public static final String COMMIT_ID_FULL = "commit.id.full"; + + // TODO this should be private instance field with getter and setter public static String COMMIT_ID = COMMIT_ID_FLAT; public static final String COMMIT_ID_ABBREV = "commit.id.abbrev"; @@ -88,6 +90,7 @@ 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 upgrade to Maven plugin annotations and fix private /** * The maven project. * @@ -363,50 +366,54 @@ public class GitCommitIdMojo extends AbstractMojo { */ private Properties properties; + // TODO remove this boolean runningTests = false; @NotNull - LoggerBridge loggerBridge = new MavenLoggerBridge(getLog(), true); + private final VerboseLog log = new VerboseLogger(this, true); + @Override public void execute() throws MojoExecutionException { // Set the verbose setting now it should be correctly loaded from maven. - loggerBridge.setVerbose(verbose); + log.setVerbose(verbose); if (skip) { - log("skip is enabled, skipping execution!"); + log.info("skip is enabled, skipping execution!"); return; } 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!"); + log.info("runOnlyOnce is enabled and this project is not the top level project, skipping execution!"); return; } } if (isPomProject(project) && skipPoms) { - log("isPomProject is true and skipPoms is true, return"); + log.info("isPomProject is true and skipPoms is true, return"); return; } dotGitDirectory = lookupGitDirectory(); - throwWhenRequiredDirectoryNotFound(dotGitDirectory, failOnNoGitDirectory, ".git directory could not be found! Please specify a valid [dotGitDirectory] in your pom.xml"); + if (failOnNoGitDirectory && !directoryExists(dotGitDirectory)) { + throw new MojoExecutionException(".git directory is not found! Please specify a valid [dotGitDirectory] in your pom.xml"); + } if (gitDescribe == null) { gitDescribe = new GitDescribeConfig(); } if (dotGitDirectory != null) { - log("dotGitDirectory", dotGitDirectory.getAbsolutePath()); + log.info("dotGitDirectory " + dotGitDirectory.getAbsolutePath()); } else { - log("dotGitDirectory is null, aborting execution!"); + log.info("dotGitDirectory is null, aborting execution!"); return; } try { switch(CommitIdGenerationModeEnum.getValue(commitIdGenerationMode)){ default: - loggerBridge.warn("Detected wrong setting for 'commitIdGenerationMode' will fallback to default 'flat'-Mode!"); + log.warn("Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat' mode!"); case FLAT: COMMIT_ID = COMMIT_ID_FLAT; break; @@ -436,10 +443,8 @@ public void execute() throws MojoExecutionException { appendPropertiesToReactorProjects(properties, prefixDot); } } catch (Exception e) { - e.printStackTrace(); handlePluginFailure(e); } - } private void filterNot(Properties properties, @Nullable List exclusions) { @@ -461,7 +466,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 +491,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); } } @@ -503,7 +508,7 @@ private void handlePluginFailure(Exception e) throws MojoExecutionException { if (failOnUnableToExtractRepoInfo) { throw new MojoExecutionException("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 +516,7 @@ private void appendPropertiesToReactorProjects(@NotNull Properties properties, @ for (MavenProject mavenProject : reactorProjects) { Properties mavenProperties = mavenProject.getProperties(); - log(mavenProject.getName(), "] project", mavenProject.getName()); + log.info(mavenProject.getName() + "] project " + mavenProject.getName()); for (Object key : properties.keySet()) { if (key.toString().startsWith(trimmedPrefixWithDot)) { @@ -521,12 +526,6 @@ 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. @@ -551,7 +550,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 +574,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 " + BUILD_HOST + ". Error message: " + e.getMessage()); } put(properties, BUILD_HOST, buildHost); } @@ -613,8 +612,7 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException final File basedir = project.getBasedir().getCanonicalFile(); GitDataProvider nativeGitProvider = NativeGitProvider - .on(basedir, loggerBridge) - .setVerbose(verbose) + .on(basedir, this) .setPrefixDot(prefixDot) .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) @@ -626,8 +624,7 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException void loadGitDataWithJGit(@NotNull Properties properties) throws IOException, MojoExecutionException { GitDataProvider jGitProvider = JGitProvider - .on(dotGitDirectory, loggerBridge) - .setVerbose(verbose) + .on(dotGitDirectory, this) .setPrefixDot(prefixDot) .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) @@ -648,12 +645,12 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, try { if (isJsonFormat) { - log("Reading exising json file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")..."); + log.info("Reading existing json file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); persistedProperties = readJsonProperties( gitPropsFile ); } else { - log("Reading exising properties file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")..."); + log.info("Reading existing properties file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); persistedProperties = readProperties( gitPropsFile ); } @@ -669,7 +666,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } catch ( CannotReadFileException ex ) { // Read has failed, regenerate file - log("Cannot read properties file [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")..."); + log.info("Cannot read properties file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); shouldGenerate = true; } } @@ -682,11 +679,11 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, try { outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), Charsets.UTF_8); if (isJsonFormat) { - log("Writing json file to [", gitPropsFile.getAbsolutePath(), "] (for module ", project.getName(), ")..."); + log.info("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(), ")..."); + log.info("Writing properties file to [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin"); } threw = false; @@ -697,7 +694,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } } else { - log("Properties file [", gitPropsFile.getAbsolutePath(), "] is up-to-date (for module ", project.getName(), ")..."); + log.info("Properties file [" + gitPropsFile.getAbsolutePath() + "] is up-to-date (for module " + project.getName() + ")..."); } } @@ -719,22 +716,14 @@ 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 { final HashMap propertiesMap; @@ -863,8 +852,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..63334f14 100644 --- a/src/main/java/pl/project13/maven/git/GitDataProvider.java +++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java @@ -17,9 +17,9 @@ package pl.project13.maven.git; +import org.apache.maven.plugin.Mojo; 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; import java.io.IOException; @@ -33,7 +33,7 @@ public abstract class GitDataProvider { @NotNull - protected LoggerBridge loggerBridge; + protected Mojo mojo; protected boolean verbose; @@ -47,8 +47,8 @@ public abstract class GitDataProvider { protected GitDescribeConfig gitDescribe = new GitDescribeConfig(); - public GitDataProvider(@NotNull LoggerBridge loggerBridge) { - this.loggerBridge = loggerBridge; + public GitDataProvider(@NotNull Mojo mojo) { + this.mojo = mojo; } public GitDataProvider setGitDescribe(GitDescribeConfig gitDescribe) { @@ -185,17 +185,17 @@ 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."); + String environmentBasedBranch = env.get("GIT_BRANCH"); + if(isNullOrEmpty(environmentBasedBranch)) { + mojo.getLog().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; + mojo.getLog().info("Using environment variable based branch name. " + "GIT_BRANCH = " + environmentBasedBranch); + return environmentBasedBranch; } } @@ -207,13 +207,9 @@ protected SimpleDateFormat getSimpleDateFormatWithTimeZone(){ 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); + mojo.getLog().info(keyWithPrefix + " " + value); PropertyManager.putWithoutPrefix(properties, keyWithPrefix, value); } } diff --git a/src/main/java/pl/project13/maven/git/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java index 9158b510..ed572479 100644 --- a/src/main/java/pl/project13/maven/git/JGitProvider.java +++ b/src/main/java/pl/project13/maven/git/JGitProvider.java @@ -21,6 +21,7 @@ import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; +import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; @@ -38,14 +39,12 @@ import pl.project13.jgit.DescribeCommand; import pl.project13.jgit.DescribeResult; import pl.project13.jgit.JGitCommon; -import pl.project13.maven.git.log.LoggerBridge; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; -import java.util.List; public class JGitProvider extends GitDataProvider { @@ -57,23 +56,16 @@ 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 Mojo mojo) { + return new JGitProvider(dotGitDirectory, mojo); } - JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - super(loggerBridge); + JGitProvider(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { + super(mojo); this.dotGitDirectory = dotGitDirectory; this.jGitCommon = new JGitCommon(); } - @NotNull - public JGitProvider setVerbose(boolean verbose) { - super.verbose = verbose; - super.loggerBridge.setVerbose(verbose); - return this; - } - @Override protected void init() throws MojoExecutionException { git = getGitRepository(); @@ -194,7 +186,7 @@ protected String getTags() throws MojoExecutionException { 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() + ")"); + mojo.getLog().error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); return ""; } } @@ -203,7 +195,7 @@ protected String getTags() throws MojoExecutionException { protected String getClosestTagName() throws MojoExecutionException { Repository repo = getGitRepository(); try { - return jGitCommon.getClosestTagName(loggerBridge,repo); + return jGitCommon.getClosestTagName(repo, mojo); } catch (Throwable t) { // could not find any tags to describe } @@ -214,7 +206,7 @@ protected String getClosestTagName() throws MojoExecutionException { protected String getClosestTagCommitCount() throws MojoExecutionException { Repository repo = getGitRepository(); try { - return jGitCommon.getClosestTagCommitCount(loggerBridge,repo,headCommit); + return jGitCommon.getClosestTagCommitCount(repo, headCommit, mojo); } catch (Throwable t) { // could not find any tags to describe } @@ -233,8 +225,7 @@ protected void finalCleanUp() { try { DescribeResult describeResult = DescribeCommand .on(repository) - .withLoggerBridge(super.loggerBridge) - .setVerbose(super.verbose) + .withMojo(mojo) .apply(super.gitDescribe) .call(); diff --git a/src/main/java/pl/project13/maven/git/NativeGitProvider.java b/src/main/java/pl/project13/maven/git/NativeGitProvider.java index c27b43a9..c601e3c7 100644 --- a/src/main/java/pl/project13/maven/git/NativeGitProvider.java +++ b/src/main/java/pl/project13/maven/git/NativeGitProvider.java @@ -22,11 +22,10 @@ import com.google.common.base.Throwables; import com.google.common.collect.Lists; +import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.jetbrains.annotations.NotNull; -import pl.project13.maven.git.log.LoggerBridge; - import java.io.*; import java.text.SimpleDateFormat; @@ -42,12 +41,12 @@ 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 Mojo mojo) { + return new NativeGitProvider(dotGitDirectory, mojo); } - NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - super(loggerBridge); + NativeGitProvider(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { + super(mojo); this.dotGitDirectory = dotGitDirectory; try { this.canonical = dotGitDirectory.getCanonicalFile(); @@ -57,13 +56,6 @@ public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull Logge } - @NotNull - public NativeGitProvider setVerbose(boolean verbose) { - super.verbose = verbose; - super.loggerBridge.setVerbose(verbose); - return this; - } - @Override protected void init() throws MojoExecutionException { // noop ... diff --git a/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java b/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java deleted file mode 100644 index b35109af..00000000 --- a/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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; - -import java.util.Properties; - -import com.google.common.base.Joiner; - -import org.apache.maven.plugin.logging.Log; -import org.slf4j.Logger; -import org.slf4j.impl.SimpleLogger; -import org.slf4j.impl.SimpleLoggerFactory; - -public class MavenLoggerBridge implements LoggerBridge { - - private Logger logger; - private boolean verbose; - - public MavenLoggerBridge(Log log, boolean verbose) { - setSimpleLoggerPorperties(); - this.logger = new SimpleLoggerFactory().getLogger(getClass().getName()); - this.verbose = verbose; - } - - 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)); - } - if(!sysProperties.containsKey(SimpleLogger.LEVEL_IN_BRACKETS_KEY)){ - System.setProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, String.valueOf(true)); - } - } - - @Override - public void log(Object... parts) { - if (verbose) { - logger.info(Joiner.on(" ").useForNull("null").join(parts)); - } - } - - @Override - public void error(Object... parts) { - if (verbose) { - logger.error(Joiner.on(" ").useForNull("null").join(parts)); - } - } - - @Override - public void warn(Object... parts) { - if (verbose) { - logger.warn(Joiner.on(" ").useForNull("null").join(parts)); - } - } - - @Override - public void debug(Object... parts) { - if (verbose) { - logger.debug(Joiner.on(" ").useForNull("null").join(parts)); - } - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - protected void setLogger(Logger logger){ - this.logger = logger; - } - -} diff --git a/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java b/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java deleted file mode 100644 index 3fdd2c83..00000000 --- a/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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; - -import com.google.common.base.Joiner; - -public class StdOutLoggerBridge implements LoggerBridge { - - private boolean verbose; - - public StdOutLoggerBridge(boolean verbose) { - this.verbose = verbose; - } - - @Override - public void log(Object... parts) { - if (verbose) { - System.out.println("LOG: " + Joiner.on(" ").join(parts)); - } - } - - @Override - public void error(Object... parts) { - if(verbose) { - System.out.println("ERR: " + Joiner.on(" ").join(parts)); - } - } - - @Override - public void warn(Object... parts) { - if(verbose) { - System.out.println("WRN: " + Joiner.on(" ").join(parts)); - } - } - - @Override - public void debug(Object... parts) { - if(verbose) { - System.out.println("DBG: " + Joiner.on(" ").join(parts)); - } - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - -} diff --git a/src/main/java/pl/project13/maven/git/log/LoggerBridge.java b/src/main/java/pl/project13/maven/git/log/VerboseLog.java similarity index 65% rename from src/main/java/pl/project13/maven/git/log/LoggerBridge.java rename to src/main/java/pl/project13/maven/git/log/VerboseLog.java index 53126ca1..d6fa0d9e 100644 --- a/src/main/java/pl/project13/maven/git/log/LoggerBridge.java +++ b/src/main/java/pl/project13/maven/git/log/VerboseLog.java @@ -17,10 +17,24 @@ package pl.project13.maven.git.log; -public interface LoggerBridge { - void log(Object... parts); - void error(Object... parts); - void warn(Object... parts); - void debug(Object... parts); - void setVerbose(boolean verbose); -} +import org.apache.maven.plugin.logging.Log; + +/** + * Allows user to specify verbosity level of logging. + */ +public interface VerboseLog extends Log { + + /** + * 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); +} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/git/log/VerboseLogger.java b/src/main/java/pl/project13/maven/git/log/VerboseLogger.java new file mode 100644 index 00000000..c0e528d3 --- /dev/null +++ b/src/main/java/pl/project13/maven/git/log/VerboseLogger.java @@ -0,0 +1,148 @@ +/* + * 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; + +import org.apache.maven.plugin.Mojo; + +/** + * Bridges logging to standard Maven log adhering to verbosity level. + */ +public class VerboseLogger implements VerboseLog { + + private boolean verbose; + private final Mojo mojo; + + public VerboseLogger(Mojo mojo, boolean verbose) { + this.mojo = mojo; + this.verbose = verbose; + } + + @Override + public void debug(CharSequence content) { + if (verbose) { + mojo.getLog().debug(content); + } + } + + @Override + public void debug(CharSequence content, Throwable error) { + if (verbose) { + mojo.getLog().debug(content, error); + } + } + + @Override + public void debug(Throwable error) { + if (verbose) { + mojo.getLog().debug(error); + } + } + + @Override + public void info(CharSequence content) { + if (verbose) { + mojo.getLog().info(content); + } + } + + @Override + public void info(CharSequence content, Throwable error) { + if (verbose) { + mojo.getLog().info(content, error); + } + } + + @Override + public void info(Throwable error) { + if (verbose) { + mojo.getLog().info(error); + } + } + + @Override + public void warn(CharSequence content) { + if (verbose) { + mojo.getLog().warn(content); + } + } + + @Override + public void warn(CharSequence content, Throwable error) { + if (verbose) { + mojo.getLog().warn(content, error); + } + } + + @Override + public void warn(Throwable error) { + if (verbose) { + mojo.getLog().warn(error); + } + } + + @Override + public void error(CharSequence content) { + if (verbose) { + mojo.getLog().error(content); + } + } + + @Override + public void error(CharSequence content, Throwable error) { + if (verbose) { + mojo.getLog().error(content, error); + } + } + + @Override + public void error(Throwable error) { + if (verbose) { + mojo.getLog().error(error); + } + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public boolean isDebugEnabled() { + return mojo.getLog().isDebugEnabled(); + } + + @Override + public boolean isInfoEnabled() { + return mojo.getLog().isInfoEnabled(); + } + + @Override + public boolean isWarnEnabled() { + return mojo.getLog().isWarnEnabled(); + } + + @Override + public boolean isErrorEnabled() { + return mojo.getLog().isErrorEnabled(); + } +} \ No newline at end of file diff --git a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java index 19644530..68d18b9c 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java @@ -70,8 +70,8 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .abbrev(2) // 2 is enough to be unique in this small repo - .setVerbose(true) .call(); // then @@ -95,8 +95,8 @@ public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .abbrev(2) // way too small to be unique in git-commit-id's repo! - .setVerbose(true) .call(); // then diff --git a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java index 4a41391b..0b12aa88 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java @@ -61,7 +61,7 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw // when DescribeResult res = DescribeCommand .on(repo) - .setVerbose(true) + .withMojo(mojo) .call(); // then @@ -83,10 +83,9 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFound() throws Exception { Repository repo = git().getRepository(); // when - DescribeCommand command = spy(DescribeCommand.on(repo)); + DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); doReturn(false).when(command).findDirtyState(any(Repository.class)); - command.setVerbose(true); DescribeResult res = command.call(); // then @@ -108,10 +107,9 @@ public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { Repository repo = git().getRepository(); // when - DescribeCommand command = spy(DescribeCommand.on(repo)); + DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); doReturn(false).when(command).findDirtyState(any(Repository.class)); - command.setVerbose(true); DescribeResult res = command.call(); // then @@ -134,11 +132,10 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfI Repository repo = git().getRepository(); // when - DescribeCommand command = spy(DescribeCommand.on(repo)); + DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); doReturn(false).when(command).findDirtyState(any(Repository.class)); command - .setVerbose(true) .abbrev(abbrevLength); DescribeResult res = command.call(); @@ -161,9 +158,8 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndDirtyMarker() thr Repository repo = git().getRepository(); // when - DescribeCommand command = DescribeCommand.on(repo); + DescribeCommand command = DescribeCommand.on(repo).withMojo(mojo); command.dirty(DIRTY_SUFFIX); - command.setVerbose(true); DescribeResult res = command.call(); // then @@ -188,8 +184,8 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker // when DescribeCommand command = DescribeCommand .on(repo) - .dirty(customDirtySuffix) - .setVerbose(true); + .withMojo(mojo) + .dirty(customDirtySuffix); DescribeResult res = command.call(); // then @@ -211,8 +207,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsId() throws Exception Git.wrap(repo).reset().setMode(ResetCommand.ResetType.HARD).call(); // when - DescribeCommand command = DescribeCommand.on(repo); - command.setVerbose(true); + DescribeCommand command = DescribeCommand.on(repo).withMojo(mojo); DescribeResult res = command.call(); // then @@ -236,8 +231,8 @@ public void shouldGiveTag() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -261,8 +256,8 @@ public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -288,9 +283,9 @@ public void shouldGiveTagWithCustomDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() .dirty(customDirtySuffix) - .setVerbose(true) .call(); // then @@ -313,8 +308,8 @@ public void shouldNotGiveDirtyTagByDefault() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -335,9 +330,9 @@ public void shouldGiveAnnotatedTagWithDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .dirty(DIRTY_SUFFIX) .abbrev(0) - .setVerbose(true) .call(); // then @@ -362,8 +357,8 @@ public void shouldGiveLightweightTagWithDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -420,8 +415,8 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .abbrev(zeroAbbrev) - .setVerbose(true) .call(); // then diff --git a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java index 9fe0e90d..36014082 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java @@ -20,6 +20,7 @@ import org.eclipse.jgit.lib.Repository; import org.junit.Test; import org.mockito.Matchers; +import pl.project13.maven.git.GitCommitIdMojo; import pl.project13.maven.git.GitDescribeConfig; import pl.project13.test.utils.AssertException; @@ -74,7 +75,7 @@ public void apply_shouldDelegateToAllOptions() throws Exception { GitDescribeConfig config = new GitDescribeConfig(true, DEVEL, MATCH, ABBREV, true, true); Repository repo = mock(Repository.class); - DescribeCommand command = DescribeCommand.on(repo); + DescribeCommand command = DescribeCommand.on(repo).withMojo(new GitCommitIdMojo()); DescribeCommand spiedCommand = spy(command); // when diff --git a/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java index 50fa3473..8c4671d2 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java @@ -64,7 +64,7 @@ public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) - .setVerbose(true) + .withMojo(mojo) .call(); // then @@ -87,8 +87,8 @@ public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -111,8 +111,8 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .match("annotated*") .call(); @@ -146,8 +146,8 @@ public void shouldFindNewerTagWhenACommitHasTwoOrMoreTags() throws Exception { // when DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -179,8 +179,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then @@ -209,8 +209,8 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t DescribeResult res = DescribeCommand .on(repo) + .withMojo(mojo) .tags() - .setVerbose(true) .call(); // then diff --git a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java index 6883dad4..638762ca 100644 --- a/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java +++ b/src/test/java/pl/project13/maven/git/FileSystemMavenSandbox.java @@ -148,7 +148,10 @@ private void cleanupIfRequired(CleanUp cleanupMode) throws IOException { public void cleanup() { try { - FileUtils.deleteDirectory(new File(rootSandboxPath)); + final File sandbox = new File(rootSandboxPath); + if (sandbox.exists()) { + FileUtils.deleteDirectory(sandbox); + } } catch (IOException e) { System.out.println("Unable to delete the directory: " + rootSandboxPath); } diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java index 9b8c219b..920cf91e 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java @@ -26,7 +26,6 @@ import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import org.eclipse.jgit.api.ResetCommand; -import org.eclipse.jgit.lib.Repository; import org.junit.Test; import org.junit.runner.RunWith; import pl.project13.maven.git.FileSystemMavenSandbox.CleanUp; diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java index 328b5f0b..c346cd4a 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java @@ -69,7 +69,7 @@ public void setUp() throws Exception { when(mojo.project.getPackaging()).thenReturn("jar"); when(mojo.project.getVersion()).thenReturn("3.3-SNAPSHOT"); - jGitProvider = JGitProvider.on(mojo.lookupGitDirectory(), mojo.getLoggerBridge()); + jGitProvider = JGitProvider.on(mojo.lookupGitDirectory(), mojo); } @Test @@ -280,8 +280,8 @@ private void assertShortDescribe(String commitDescribe, String expectedShortDesc public void testCraftPropertiesOutputFileWithRelativePath() throws IOException { GitCommitIdMojo commitIdMojo = new GitCommitIdMojo(); File baseDir = new File("."); - String targetDir = baseDir.getCanonicalPath() + "/"; - String generateGitPropertiesFilename = "target/classes/git.properties"; + String targetDir = baseDir.getCanonicalPath() + File.separator; + String generateGitPropertiesFilename = "target" + File.separator + "classes" + File.separator + "git.properties"; File result = commitIdMojo.craftPropertiesOutputFile(baseDir, generateGitPropertiesFilename); assertThat(result.getCanonicalPath()).isEqualTo(targetDir + generateGitPropertiesFilename); @@ -291,8 +291,8 @@ public void testCraftPropertiesOutputFileWithRelativePath() throws IOException { public void testCraftPropertiesOutputFileWithFullPath() throws IOException { GitCommitIdMojo commitIdMojo = new GitCommitIdMojo(); File baseDir = new File("."); - String targetDir = baseDir.getCanonicalPath() + "/"; - String generateGitPropertiesFilename = targetDir + "target/classes/git.properties"; + String targetDir = baseDir.getCanonicalPath() + File.separator; + String generateGitPropertiesFilename = targetDir + "target" + File.separator + "classes" + File.separator + "git.properties"; File result = commitIdMojo.craftPropertiesOutputFile(baseDir, generateGitPropertiesFilename); assertThat(result.getCanonicalPath()).isEqualTo(generateGitPropertiesFilename); diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index 40972385..7fc2e15a 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -18,32 +18,58 @@ package pl.project13.maven.git; import com.google.common.base.Optional; +import org.apache.commons.io.FileUtils; import org.apache.maven.project.MavenProject; import org.eclipse.jgit.api.Git; import org.jetbrains.annotations.NotNull; +import org.junit.After; import org.junit.Before; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import java.util.Random; import static org.mockito.internal.util.reflection.Whitebox.setInternalState; public abstract class GitIntegrationTest { + private final static Random r = new Random(); + final String SANDBOX_DIR = "target/sandbox"; + String currSandbox; protected GitCommitIdMojo mojo; protected FileSystemMavenSandbox mavenSandbox; @Before public void setUp() throws Exception { - mavenSandbox = new FileSystemMavenSandbox(SANDBOX_DIR); + // generate unique sandbox for this test + File sandbox; + do { + currSandbox = SANDBOX_DIR + File.separator + "sandbox" + Integer.toString(r.nextInt(Integer.MAX_VALUE)); + sandbox = new File(currSandbox); + } while (sandbox.exists()); + + mavenSandbox = new FileSystemMavenSandbox(currSandbox); mojo = new GitCommitIdMojo(); initializeMojoWithDefaults(mojo); } + @After + public void tearDown() throws Exception { + final File sandbox = new File(currSandbox); + try { + if (sandbox.exists()) { + FileUtils.deleteDirectory(sandbox); + } + } catch (IOException e) { + System.out.println("Unable to delete the directory. Scheduling deleteOnExit: " + currSandbox); + sandbox.deleteOnExit(); + } + } + protected Git git(String dir) throws IOException, InterruptedException { return Git.open(dotGitDir(Optional.of(dir))); } @@ -59,9 +85,9 @@ protected Optional projectDir() { @NotNull protected File dotGitDir(@NotNull Optional projectDir) { if (projectDir.isPresent()) { - return new File(SANDBOX_DIR + File.separator + projectDir.get() + File.separator + ".git"); + return new File(currSandbox + File.separator + projectDir.get() + File.separator + ".git"); } else { - return new File(SANDBOX_DIR + File.separator + ".git"); + return new File(currSandbox + File.separator + ".git"); } } diff --git a/src/test/java/pl/project13/maven/git/log/MavenLoggerBridgeTest.java b/src/test/java/pl/project13/maven/git/log/MavenLoggerBridgeTest.java deleted file mode 100644 index 0603f010..00000000 --- a/src/test/java/pl/project13/maven/git/log/MavenLoggerBridgeTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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; - -import org.junit.Test; -import org.slf4j.Logger; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - - -public class MavenLoggerBridgeTest { - Logger logger = mock(Logger.class); - MavenLoggerBridge bridge = new MavenLoggerBridge(null, true); - - @Test - public void shouldNotFailWhenMessageContainsPercentSigns() throws Exception { - // given - String start = "the output was: ["; - String content = "100% coverage!!!"; - String end = "]"; - String expectedExplicit = "the output was: [ 100% coverage!!! ]"; - - // when - bridge.setLogger(logger); - bridge.log(start, content, end); - - // then - verify(logger).info(expectedExplicit); - } - -} diff --git a/src/test/java/pl/project13/maven/git/log/StdOutLoggerBridgeTest.java b/src/test/java/pl/project13/maven/git/log/StdOutLoggerBridgeTest.java deleted file mode 100644 index 952094d8..00000000 --- a/src/test/java/pl/project13/maven/git/log/StdOutLoggerBridgeTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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; - -import org.junit.Test; - -public class StdOutLoggerBridgeTest { - - @Test - public void log_shouldNotFailWhenMessageContainsPercentSign() throws Exception { - // given - StdOutLoggerBridge bridge = new StdOutLoggerBridge(true); - - // when - bridge.log(); - - // then, should not have thrown - } - - @Test - public void error_shouldNotFailWhenMessageContainsPercentSign() throws Exception { - // given - StdOutLoggerBridge bridge = new StdOutLoggerBridge(true); - - // when - bridge.error(); - - // then, should not have thrown - } - -} From c56578802bac06caf08e2119bbd8c4e73b4e59d7 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Thu, 31 Dec 2015 09:42:39 +0100 Subject: [PATCH 02/22] improved description logical order --- pom.xml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index d7439af2..a5e36100 100644 --- a/pom.xml +++ b/pom.xml @@ -13,14 +13,15 @@ 2.2.1-SNAPSHOT Git Commit Id Plugin Maven Mojo - git-commit-id-plugin is a plugin quite similar to - https://fisheye.codehaus.org/browse/mojo/tags/buildnumber-maven-plugin-1.0-beta-4 for example but as buildnumber at - the time when I started this plugin only supported CVS and SVN, something had to be done. This plugin makes basic repository information available through maven resources. This can be used to display "what version is this?" or "who has deployed this and when, from which branch?" information at runtime - making it easy to find things like "oh, that isn't deployed yet, I'll test it tomorrow" and making both testers and developers life easier. + git-commit-id-plugin is quite similar to + https://fisheye.codehaus.org/browse/mojo/tags/buildnumber-maven-plugin-1.0-beta-4 for example but as buildnumber at + the time when I started this plugin only supported CVS and SVN, something had to be done. + The data currently exported is like this (that's the end effect from the GitRepositoryState Bean): { "branch" : "testing-maven-git-plugin", @@ -36,7 +37,7 @@ "buildUserEmail" : "konrad.malawski@java.pl" } - Note that the data is exported via maven resource filtering and is really easy to use with spring - + Note that the data is exported via maven resource filtering and is really easy to use with Spring - which I've explained in detail in this readme https://github.com/ktoso/maven-git-commit-id-plugin http://www.blog.project13.pl From e4827eb6014e1c7f1ad83f5c3fbf73f4ed11dd88 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Thu, 31 Dec 2015 18:05:36 +0100 Subject: [PATCH 03/22] dep updated, plugin management added --- pom.xml | 87 +++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index a5e36100..6c127d81 100644 --- a/pom.xml +++ b/pom.xml @@ -70,15 +70,17 @@ + UTF-8 + UTF-8 + + 1.7 + 3.1.1 - 4.0.0.201506090130-r + 4.1.1.201511131810-r 4.12 - 2.0.5-beta + 2.0.35-beta - 1.7 - UTF-8 - UTF-8 1.4 @@ -98,21 +100,21 @@ com.fasterxml.jackson.core jackson-databind - 2.5.1 + 2.6.4 joda-time joda-time - 2.7 + 2.9.1 com.google.guava guava - 18.0 + 19.0 @@ -147,7 +149,7 @@ org.codehaus.plexus plexus-utils - 3.0.21 + 3.0.22 test @@ -195,15 +197,78 @@ + + + + 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 + 3.4 + + + maven-surefire-plugin + 2.19 + + + maven-install-plugin + 2.5.2 + + + maven-deploy-plugin + 2.8.2 + + + maven-site-plugin + 3.4 + + + + org.apache.maven.plugins maven-compiler-plugin - 2.5.1 - UTF-8 ${java.target} ${java.target} From 4274dfc81335a5c208efa52ed4e03b5c355a59e0 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Thu, 31 Dec 2015 23:01:33 +0100 Subject: [PATCH 04/22] minor refactorings and typos --- README.md | 18 +++---- .../pl/project13/jgit/DescribeCommand.java | 8 ++- .../pl/project13/jgit/DescribeResult.java | 12 ++--- .../java/pl/project13/jgit/JGitCommon.java | 22 +++----- .../maven/git/CommitIdGenerationModeEnum.java | 2 +- .../project13/maven/git/GitCommitIdMojo.java | 10 ++-- .../project13/maven/git/GitDataProvider.java | 18 +++---- .../maven/git/GitDescribeConfig.java | 4 +- .../pl/project13/maven/git/GitDirLocator.java | 5 +- .../maven/git/GitRepositoryState.java | 3 -- .../pl/project13/maven/git/JGitProvider.java | 29 ++++------- .../maven/git/NativeGitProvider.java | 50 ++++--------------- .../pl/project13/maven/git/util/Pair.java | 2 +- 13 files changed, 63 insertions(+), 120 deletions(-) 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.core @@ -241,7 +250,7 @@ maven-plugin-plugin - 3.4 + ${maven-plugin-plugin.version} maven-surefire-plugin @@ -274,22 +283,28 @@ - - - - - - - - - - - - - - - - + + org.apache.maven.plugins + maven-plugin-plugin + + + default-descriptor + process-classes + + + + diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 15ee6951..71670f93 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -31,6 +31,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; @@ -54,13 +57,9 @@ /** * Goal which 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 @@ -90,279 +89,271 @@ 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 upgrade to Maven plugin annotations and fix private + // 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. + * 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.

* - * 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. + *

Injecting into all projects may slow down the build and you don't always need this feature. + * For details about why you might want to skip this: https://github.com/ktoso/maven-git-commit-id-plugin/pull/65. + *

* - * @parameter default-value="false" + *

Defaults to {@code false}.

*/ - @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" :-) + *

Set this to {@code true} to print more info while scanning for paths. + * It will make git-commit-id "eat it's own dog food" :-)

* - * @parameter default-value="false" + *

Defaults to {@code false}.

*/ - @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. + *

Set this to {@code false} to execute plugin in 'pom' packaged projects.

* - * @parameter parameter="git.skipPoms" default-value="true" + *

Defaults to {@code true}.

*/ - @SuppressWarnings("UnusedDeclaration") + @Parameter(defaultValue = "true", name = "git.skipPoms") 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 + *

Set this to {@code true} to generate {@code git.properties} file. + * By default plugin only adds properties to maven project properties.

* - * If set to "true" properties will be fully generated with no placeholders inside. - * - * @parameter default-value="false" + *

Defaults to {@code false}.

*/ - @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 location of {@code git.properties} file. Set {@code generateGitPropertiesFile} to {@code true} + * to generate this file.

* - * The path here is relative to your projects src directory. + *

The path here is relative to your projects src directory.

* - * @parameter default-value="${project.build.outputDirectory}/git.properties" + *

Defaults to {@code ${project.build.outputDirectory}/git.properties}.

*/ - @SuppressWarnings("UnusedDeclaration") + @Parameter(defaultValue = "${project.build.outputDirectory}/git.properties") private String generateGitPropertiesFilename; /** - * The root directory of the repository we want to check + *

The root directory of the repository we want to check.

* - * @parameter default-value="${project.basedir}/.git" + *

Defaults to {@code ${project.basedir}/.git}.

*/ - @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.

+ * + *

Defaults to {@code 7}.

* * 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. - *

+ *

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". + *

The format to save properties in: {@code properties} or {@code json}.

* - * @parameter default-value="properties" + *

Defaults to {@code properties}.

*/ - @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}' + *

The prefix to expose the properties on. + * For example {@code git} would allow you to access {@code ${git.branch}}.

* - * @parameter default-value="git" + *

Defaults to {@code git}.

*/ - @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. + *

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" + *

Defaults to {@code dd.MM.yyyy '@' HH:mm:ss z}.

*/ - @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 (e.g. 'America/Los_Angeles', 'GMT+10', 'PST').

+ * + *

Try to avoid three-letter time zone IDs because the same abbreviation is 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.

+ * + *

Defaults to {@code java.util.TimeZone.getDefault().getID()}.

*/ - @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. + * Set this to {@code false} to avoid failing the build on missing {@code .git} directory. * - * @parameter default-value="true" + *

Defaults to {@code true}.

*/ - @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 it's 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 behind this flag. + *

See https://github.com/ktoso/maven-git-commit-id-plugin/issues/63 + * for a rationale behind this flag.

* - * @parameter default-value="true" + *

Defaults to {@code true}.

*/ - @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. + * 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. * - * @parameter default-value="false" + *

Defaults to {@code false}.

* @since 2.1.9 */ - @SuppressWarnings("UnusedDeclaration") + @Parameter(defaultValue = "false") private boolean useNativeGit; /** - * Skip the plugin execution. + *

Set this to {@code true} to skip plugin execution.

* - * @parameter default-value="false" + *

Defaults to {@code false}.

* @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. + *

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.

* - * The git.* maven properties are available in all modules. + *

The git.* maven properties are available in all modules.

* - * @parameter default-value="false" + *

Defaults to {@code false}.

* @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 emitted into the resulting file. + *

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 etc. + * or the email of the committer etc.

* - * 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 *}). + *

Please note that the strings here are Java regular expressions ({@code .*} is a wildcard, not plain {@code *}).

* - * @parameter + *

Defaults to empty list.

* @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. + *

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}.

* - * 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. + *

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 *}). + *

Please note that the strings here are Java regular expressions ({@code .*} is a wildcard, not plain {@code *}).

* - * @parameter + *

Defaults to empty list.

* @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 convenient switch where you can choose if you would like the properties as they always had been, or if you rather need to support full json-object compatibility. - * In the case you need to fully support json-object we unfortunately need to change the '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. - * - * 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. + *

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

+ * + *

Due to naming issues in json export + * (see https://github.com/ktoso/maven-git-commit-id-plugin/issues/122) + * we need to make it possible to export all properties as a valid json-object. + * Due to the fact that this is one of the major properties the plugin is exporting we just don't want to change + * the exporting mechanism and somehow throw the backwards compatibility away. + * We rather provide a convenient switch where you can choose if you would like the properties as they always had been, + * or if you rather need to support full json-object compatibility. + * In the case you need to fully support json-object we unfortunately need to change the {@code git.commit.id} property + * from {@code git.commit.id} to {@code git.commit.id.full} in the exporting mechanism to allow the generation + * of a fully valid json object.

+ * + *

Currently the switch allows two different options:

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

* - * *Note*: 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. * - * @parameter default-value="flat" + *

Defaults to {@code flat}.

* @since 2.2.0 */ + @Parameter(defaultValue = "flat") private String commitIdGenerationMode; /** - * The Maven Session Object - * - * @parameter property="session" - * @required - * @readonly - */ - @SuppressWarnings("UnusedDeclaration") - protected MavenSession session; - - /** - * The properties we store our data in and then expose them + * The properties we store our data in and then expose them. */ private Properties properties; @@ -371,7 +362,7 @@ public class GitCommitIdMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { - // Set the verbose setting now it should be correctly loaded from maven. + // Set the verbose setting: now it should be correctly loaded from maven. log.setVerbose(verbose); if (skip) { From 7dd2e859de1f3276478ac0767b41592076df56c7 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Fri, 1 Jan 2016 17:50:16 +0100 Subject: [PATCH 11/22] refactored commitIdGenerationMode processing because changing static variable violates thread safety --- ...eEnum.java => CommitIdGenerationMode.java} | 16 ++--------- .../project13/maven/git/GitCommitIdMojo.java | 27 ++++++++----------- .../project13/maven/git/GitDataProvider.java | 14 ++++++++-- .../git/GitCommitIdMojoDirtyFilesTest.java | 2 ++ 4 files changed, 27 insertions(+), 32 deletions(-) rename src/main/java/pl/project13/maven/git/{CommitIdGenerationModeEnum.java => CommitIdGenerationMode.java} (71%) diff --git a/src/main/java/pl/project13/maven/git/CommitIdGenerationModeEnum.java b/src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java similarity index 71% rename from src/main/java/pl/project13/maven/git/CommitIdGenerationModeEnum.java rename to src/main/java/pl/project13/maven/git/CommitIdGenerationMode.java index cb1485fd..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().equalsIgnoreCase(o)){ - return v; - } - } - } - return CommitIdGenerationModeEnum.UNKNOWN; - } + FLAT; } diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 71670f93..2f832bbc 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -46,7 +46,6 @@ import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -65,12 +64,9 @@ 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"; - - // TODO this should be private instance field with getter and setter - 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"; @@ -134,7 +130,7 @@ public class GitCommitIdMojo extends AbstractMojo { * *

Defaults to {@code true}.

*/ - @Parameter(defaultValue = "true", name = "git.skipPoms") + @Parameter(defaultValue = "true") private boolean skipPoms; /** @@ -351,6 +347,7 @@ public class GitCommitIdMojo extends AbstractMojo { */ @Parameter(defaultValue = "flat") private String commitIdGenerationMode; + private CommitIdGenerationMode commitIdGenerationModeEnum; /** * The properties we store our data in and then expose them. @@ -399,15 +396,11 @@ public void execute() throws MojoExecutionException { } try { - switch(CommitIdGenerationModeEnum.getValue(commitIdGenerationMode)){ - default: + try { + commitIdGenerationModeEnum = CommitIdGenerationMode.valueOf(commitIdGenerationMode.toUpperCase()); + } catch (IllegalArgumentException e) { log.warn("Detected wrong setting for 'commitIdGenerationMode'. Falling back to default 'flat' mode!"); - case FLAT: - COMMIT_ID = COMMIT_ID_FLAT; - break; - case FULL: - COMMIT_ID = COMMIT_ID_FULL; - break; + commitIdGenerationModeEnum = CommitIdGenerationMode.FLAT; } properties = initProperties(); @@ -603,7 +596,8 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) .setDateFormatTimeZone(dateFormatTimeZone) - .setGitDescribe(gitDescribe); + .setGitDescribe(gitDescribe) + .setCommitIdGenerationMode(commitIdGenerationModeEnum); nativeGitProvider.loadGitData(properties); } @@ -615,7 +609,8 @@ void loadGitDataWithJGit(@NotNull Properties properties) throws IOException, Moj .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) .setDateFormatTimeZone(dateFormatTimeZone) - .setGitDescribe(gitDescribe); + .setGitDescribe(gitDescribe) + .setCommitIdGenerationMode(commitIdGenerationModeEnum); jGitProvider.loadGitData(properties); } diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java index 274f3266..3654bd5d 100644 --- a/src/main/java/pl/project13/maven/git/GitDataProvider.java +++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java @@ -45,6 +45,8 @@ public abstract class GitDataProvider { protected GitDescribeConfig gitDescribe = new GitDescribeConfig(); + protected CommitIdGenerationMode commitIdGenerationMode; + public GitDataProvider(@NotNull Mojo mojo) { this.mojo = mojo; } @@ -69,6 +71,11 @@ 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; @@ -110,8 +117,11 @@ 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()); + default: put(properties, GitCommitIdMojo.COMMIT_ID_FLAT, getCommitId()); + } + // git.commit.id.abbrev put(properties, GitCommitIdMojo.COMMIT_ID_ABBREV, getAbbrevCommitId()); // git.dirty put(properties, GitCommitIdMojo.DIRTY, Boolean.toString(isDirty())); diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java index 299dfbaa..f91cdd45 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java @@ -47,6 +47,7 @@ public void testDetectCleanWorkingDirectory() throws Exception { mojo.setVerbose(true); mojo.useNativeGit(false); mojo.setGitDescribe(gitDescribeConfig); + mojo.setCommitIdGenerationMode("flat"); mojo.project = mock(MavenProject.class, RETURNS_MOCKS); @@ -79,6 +80,7 @@ public void testDetectDirtyWorkingDirectory() throws Exception { mojo.setVerbose(true); mojo.useNativeGit(false); mojo.setGitDescribe(gitDescribeConfig); + mojo.setCommitIdGenerationMode("flat"); mojo.project = mock(MavenProject.class, RETURNS_MOCKS); From f63c67f215aafee7af54c9d65cbf8f513b7f3516 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Fri, 1 Jan 2016 19:12:25 +0100 Subject: [PATCH 12/22] improved formatting for command line help display --- pom.xml | 28 +--- .../project13/maven/git/GitCommitIdMojo.java | 148 ++++++------------ 2 files changed, 52 insertions(+), 124 deletions(-) diff --git a/pom.xml b/pom.xml index c06e3733..607d842c 100644 --- a/pom.xml +++ b/pom.xml @@ -11,34 +11,12 @@ git-commit-id-plugin maven-plugin 2.2.1-SNAPSHOT - Git Commit Id Plugin Maven Mojo + Git Commit Id Maven Plugin This plugin makes basic repository information available through maven resources. This can be used to display - "what version is this?" or "who has deployed this and when, from which branch?" information at runtime - making + "what version is this?" or "who has deployed this and when, from which branch?" information at runtime, making it easy to find things like "oh, that isn't deployed yet, I'll test it tomorrow" and making both testers and - developers life easier. - - git-commit-id-plugin is quite similar to - https://fisheye.codehaus.org/browse/mojo/tags/buildnumber-maven-plugin-1.0-beta-4 for example but as buildnumber at - the time when I started this plugin only supported CVS and SVN, something had to be done. - - The data currently exported is like this (that's the end effect from the GitRepositoryState Bean): - { - "branch" : "testing-maven-git-plugin", - "commitTime" : "06.01.1970 @ 16:16:26 CET", - "commitId" : "787e39f61f99110e74deed68ab9093088d64b969", - "commitUserName" : "Konrad Malawski", - "commitUserEmail" : "konrad.malawski@java.pl", - "commitMessageFull" : "releasing my fun plugin :-) + fixed some typos + cleaned up directory structure + added - license etc", - "commitMessageShort" : "releasing my fun plugin :-)", - "buildTime" : "06.01.1970 @ 16:17:53 CET", - "buildUserName" : "Konrad Malawski", - "buildUserEmail" : "konrad.malawski@java.pl" - } - - Note that the data is exported via maven resource filtering and is really easy to use with Spring - - which I've explained in detail in this readme https://github.com/ktoso/maven-git-commit-id-plugin + developers life easier. See https://github.com/ktoso/maven-git-commit-id-plugin http://www.blog.project13.pl diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 2f832bbc..740e5efa 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -54,7 +54,7 @@ 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. * * @since 1.0 */ @@ -105,80 +105,66 @@ public class GitCommitIdMojo extends AbstractMojo { private MavenSession session; /** - *

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

+ *

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

* *

Injecting into all projects may slow down the build and you don't always need this feature. - * For details about why you might want to skip this: https://github.com/ktoso/maven-git-commit-id-plugin/pull/65. + * See pull #65 for details about why you might want to skip this. *

- * - *

Defaults to {@code false}.

*/ @Parameter(defaultValue = "false") private boolean injectAllReactorProjects; /** - *

Set this to {@code true} to print more info while scanning for paths. - * It will make git-commit-id "eat it's own dog food" :-)

- * - *

Defaults to {@code 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" :-) */ @Parameter(defaultValue = "false") private boolean verbose; /** - *

Set this to {@code false} to execute plugin in 'pom' packaged projects.

- * - *

Defaults to {@code true}.

+ * Set this to {@code 'false'} to execute plugin in 'pom' packaged projects. */ @Parameter(defaultValue = "true") private boolean skipPoms; /** - *

Set this to {@code true} to generate {@code git.properties} file. - * By default plugin only adds properties to maven project properties.

- * - *

Defaults to {@code false}.

+ * Set this to {@code 'true'} to generate {@code 'git.properties'} file. + * By default plugin only adds properties to maven project properties. */ @Parameter(defaultValue = "false") private boolean generateGitPropertiesFile; /** - *

The location of {@code git.properties} file. Set {@code generateGitPropertiesFile} to {@code true} + *

The location of {@code 'git.properties'} file. Set {@code 'generateGitPropertiesFile'} to {@code 'true'} * to generate this file.

* - *

The path here is relative to your projects src directory.

- * - *

Defaults to {@code ${project.build.outputDirectory}/git.properties}.

+ *

The path here is relative to your project src directory.

*/ @Parameter(defaultValue = "${project.build.outputDirectory}/git.properties") private String generateGitPropertiesFilename; /** - *

The root directory of the repository we want to check.

- * - *

Defaults to {@code ${project.basedir}/.git}.

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

Minimum length of {@code git.commit.id.abbrev} property. + *

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 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.

- * - *

Defaults to {@code 7}.

+ * 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 + *

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.

* @@ -187,18 +173,13 @@ public class GitCommitIdMojo extends AbstractMojo { private int abbrevLength; /** - *

The format to save properties in: {@code properties} or {@code json}.

- * - *

Defaults to {@code properties}.

+ * The format to save properties in: {@code 'properties'} or {@code 'json'}. */ @Parameter(defaultValue = "properties") private String format; /** - *

The prefix to expose the properties on. - * For example {@code git} would allow you to access {@code ${git.branch}}.

- * - *

Defaults to {@code git}.

+ * The prefix to expose the properties on. For example {@code 'git'} would allow you to access {@code ${git.branch}}. */ @Parameter(defaultValue = "git") private String prefix; @@ -206,77 +187,62 @@ public class GitCommitIdMojo extends AbstractMojo { private String prefixDot = ""; /** - *

The date format to be used for any dates exported by this plugin. - * It should be a valid SimpleDateFormat string.

- * - *

Defaults to {@code 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. */ @Parameter(defaultValue = "dd.MM.yyyy '@' HH:mm:ss z") private String dateFormat; /** *

The timezone used in the date format of dates exported by this plugin. - * It should be a valid Timezone string (e.g. 'America/Los_Angeles', 'GMT+10', 'PST').

+ * It should be a valid Timezone string such as {@code 'America/Los_Angeles'}, {@code 'GMT+10'} or {@code 'PST'}.

* *

Try to avoid three-letter time zone IDs because the same abbreviation is 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.

- * - *

Defaults to {@code java.util.TimeZone.getDefault().getID()}.

*/ @Parameter private String dateFormatTimeZone; /** - * Set this to {@code false} to avoid failing the build on missing {@code .git} directory. - * - *

Defaults to {@code true}.

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

Set this to {@code false} to continue the build even if unable to get enough data for a complete run. + *

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

* - *

Setting this value to {@code false} causes the plugin to gracefully tell you "I did my best" - * and abort 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 + *

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

- * - *

Defaults to {@code true}.

*/ @Parameter(defaultValue = "true") private boolean failOnUnableToExtractRepoInfo; /** - * Set this to {@code true} to use native GIT executable to fetch information about the repository. + * 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. - * - *

Defaults to {@code false}.

* @since 2.1.9 */ @Parameter(defaultValue = "false") private boolean useNativeGit; /** - *

Set this to {@code true} to skip plugin execution.

- * - *

Defaults to {@code false}.

+ * Set this to {@code 'true'} to skip plugin execution. * @since 2.1.8 */ @Parameter(defaultValue = "false") private boolean skip; /** - *

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}, + *

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.

* *

The git.* maven properties are available in all modules.

- * - *

Defaults to {@code false}.

* @since 2.1.12 */ @Parameter(defaultValue = "false") @@ -284,15 +250,13 @@ public class GitCommitIdMojo extends AbstractMojo { /** *

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 etc.

- * - *

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.

+ * 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.

* - *

Please note that the strings here are Java regular expressions ({@code .*} is a wildcard, not plain {@code *}).

+ *

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.

* - *

Defaults to empty list.

+ *

Note: The strings here are Java regular expressions: {@code '.*'} is a wildcard, not plain {@code '*'}.

* @since 2.1.9 */ @Parameter @@ -300,49 +264,35 @@ public class GitCommitIdMojo extends AbstractMojo { /** *

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}.

+ * This list will be overruled by the {@code 'excludeProperties'}.

* - *

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.

+ *

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.

* - *

Please note that the strings here are Java regular expressions ({@code .*} is a wildcard, not plain {@code *}).

- * - *

Defaults to empty list.

+ *

Note: The strings here are Java regular expressions: {@code '.*'} is a wildcard, not plain {@code '*'}.

* @since 2.1.14 */ @Parameter private List includeOnlyProperties; /** - *

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

+ *

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

* - *

Due to naming issues in json export - * (see https://github.com/ktoso/maven-git-commit-id-plugin/issues/122) - * we need to make it possible to export all properties as a valid json-object. - * Due to the fact that this is one of the major properties the plugin is exporting we just don't want to change - * the exporting mechanism and somehow throw the backwards compatibility away. - * We rather provide a convenient switch where you can choose if you would like the properties as they always had been, - * or if you rather need to support full json-object compatibility. - * In the case you need to fully support json-object we unfortunately need to change the {@code git.commit.id} property - * from {@code git.commit.id} to {@code git.commit.id.full} in the exporting mechanism to allow the generation - * of a fully valid json object.

+ *

{@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: * - *

Currently the switch allows two different options:

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

    * - * Note: Depending on your plugin configuration you obviously can choose the 'prefix' of your properties + *

    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. - * - *

    Defaults to {@code flat}.

    + * 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") From c6ba6ae9c02338eea8206f08c61d952d895acdb7 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Fri, 1 Jan 2016 23:25:20 +0100 Subject: [PATCH 13/22] avoid copying test repositories with other test resources --- pom.xml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/pom.xml b/pom.xml index 607d842c..52fbee55 100644 --- a/pom.xml +++ b/pom.xml @@ -183,6 +183,15 @@ + + + src/test/resources + + _git_*/** + README.md + + + From a00cf642a7ac1580f01967ed2ceb52872c18d9e8 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 10:23:55 +0100 Subject: [PATCH 14/22] removed extra property="session" --- src/main/java/pl/project13/maven/git/GitCommitIdMojo.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index 740e5efa..dc43f222 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -101,7 +101,7 @@ public class GitCommitIdMojo extends AbstractMojo { /** * The Maven Session Object. */ - @Parameter(property = "session", required = true, readonly = true) + @Parameter(required = true, readonly = true) private MavenSession session; /** From eaf19ad34634953e5ebd314c2b1811cfb178b1dc Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 10:28:45 +0100 Subject: [PATCH 15/22] enumerated all cases to make adding new mode easier (just in case) --- .../pl/project13/maven/git/GitDataProvider.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java index 3654bd5d..e44c7c4e 100644 --- a/src/main/java/pl/project13/maven/git/GitDataProvider.java +++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java @@ -118,8 +118,17 @@ public void loadGitData(@NotNull Properties properties) throws IOException, Mojo maybePutGitDescribe(properties); // git.commit.id switch (commitIdGenerationMode) { - case FULL: put(properties, GitCommitIdMojo.COMMIT_ID_FULL, getCommitId()); - default: put(properties, GitCommitIdMojo.COMMIT_ID_FLAT, getCommitId()); + case FULL: { + put(properties, GitCommitIdMojo.COMMIT_ID_FULL, getCommitId()); + break; + } + case FLAT: { + put(properties, GitCommitIdMojo.COMMIT_ID_FLAT, getCommitId()); + break; + } + default: { + throw new MojoExecutionException("Unsupported commitIdGenerationMode: " + commitIdGenerationMode); + } } // git.commit.id.abbrev put(properties, GitCommitIdMojo.COMMIT_ID_ABBREV, getAbbrevCommitId()); From d62371dda164ff1acb7565a75aea63d08f132f39 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 10:53:49 +0100 Subject: [PATCH 16/22] keep verbose (and others for uniformity) as fields --- .../git/GitCommitIdMojoDirtyFilesTest.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java index f91cdd45..489044c3 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoDirtyFilesTest.java @@ -38,16 +38,19 @@ public void testDetectCleanWorkingDirectory() throws Exception { String prefix = "git"; int abbrevLength = 7; String dateFormat = "dd.MM.yyyy '@' HH:mm:ss z"; + boolean verbose = true; + boolean useNativeGit = false; + String commitIdGenerationMode = "flat"; GitCommitIdMojo mojo = new GitCommitIdMojo(); mojo.setDotGitDirectory(dotGitDirectory); mojo.setPrefix(prefix); mojo.setAbbrevLength(abbrevLength); mojo.setDateFormat(dateFormat); - mojo.setVerbose(true); - mojo.useNativeGit(false); + mojo.setVerbose(verbose); + mojo.useNativeGit(useNativeGit); mojo.setGitDescribe(gitDescribeConfig); - mojo.setCommitIdGenerationMode("flat"); + mojo.setCommitIdGenerationMode(commitIdGenerationMode); mojo.project = mock(MavenProject.class, RETURNS_MOCKS); @@ -71,16 +74,19 @@ public void testDetectDirtyWorkingDirectory() throws Exception { String prefix = "git"; int abbrevLength = 7; String dateFormat = "dd.MM.yyyy '@' HH:mm:ss z"; + boolean verbose = true; + boolean useNativeGit = false; + String commitIdGenerationMode = "flat"; GitCommitIdMojo mojo = new GitCommitIdMojo(); mojo.setDotGitDirectory(dotGitDirectory); mojo.setPrefix(prefix); mojo.setAbbrevLength(abbrevLength); mojo.setDateFormat(dateFormat); - mojo.setVerbose(true); - mojo.useNativeGit(false); + mojo.setVerbose(verbose); + mojo.useNativeGit(useNativeGit); mojo.setGitDescribe(gitDescribeConfig); - mojo.setCommitIdGenerationMode("flat"); + mojo.setCommitIdGenerationMode(commitIdGenerationMode); mojo.project = mock(MavenProject.class, RETURNS_MOCKS); From b1e1727cc04faa6d7129e0e1e4fb171fd5877e7b Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 11:02:23 +0100 Subject: [PATCH 17/22] switched to ThreadLocalRandom.current() instead of static variable --- .../java/pl/project13/maven/git/GitIntegrationTest.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java index 401741ab..3ed1c915 100644 --- a/src/test/java/pl/project13/maven/git/GitIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitIntegrationTest.java @@ -29,17 +29,12 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; import static org.mockito.internal.util.reflection.Whitebox.setInternalState; public abstract class GitIntegrationTest { - /** - * Random number generator for generating random sandbox folder names. - */ - private final static Random r = new Random(); - private final static String SANDBOX_DIR = "target" + File.separator + "sandbox" + File.separator; /** @@ -55,7 +50,7 @@ public void setUp() throws Exception { // generate unique sandbox for this test File sandbox; do { - currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(r.nextInt(Integer.MAX_VALUE)); + currSandbox = SANDBOX_DIR + "sandbox" + Integer.toString(ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE)); sandbox = new File(currSandbox); } while (sandbox.exists()); From a8ca586f459aaf21d08802e7d0a547caf4c0c22f Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 11:09:19 +0100 Subject: [PATCH 18/22] switched from AssertException to @Test(expected = IllegalArgumentException.class) --- .../jgit/DescribeCommandOptionsTest.java | 29 +--- .../git/GitCommitIdMojoIntegrationTest.java | 14 +- .../project13/test/utils/AssertException.java | 147 ------------------ 3 files changed, 7 insertions(+), 183 deletions(-) delete mode 100644 src/test/java/pl/project13/test/utils/AssertException.java diff --git a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java index 36014082..eae8816b 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java @@ -22,47 +22,28 @@ import org.mockito.Matchers; import pl.project13.maven.git.GitCommitIdMojo; import pl.project13.maven.git.GitDescribeConfig; -import pl.project13.test.utils.AssertException; import static org.mockito.Mockito.*; public class DescribeCommandOptionsTest { - @Test + @Test(expected = IllegalArgumentException.class) public void abbrev_shouldVerifyLengthContract_failOn41() throws Exception { // given final Repository repo = mock(Repository.class); final int length = 41; - // when - AssertException.CodeBlock block = new AssertException.CodeBlock() { - @Override - public void run() throws Exception { - DescribeCommand.on(repo).abbrev(length); - } - }; - - // then - AssertException.thrown(IllegalArgumentException.class, block); + DescribeCommand.on(repo).abbrev(length); } - @Test + @Test(expected = IllegalArgumentException.class) public void abbrev_shouldVerifyLengthContract_failOnMinus12() throws Exception { // given final Repository repo = mock(Repository.class); final int length = -12; - // when - AssertException.CodeBlock block = new AssertException.CodeBlock() { - @Override - public void run() { - DescribeCommand.on(repo).abbrev(length); - } - }; - - // then - AssertException.thrown(IllegalArgumentException.class, block); + DescribeCommand.on(repo).abbrev(length); } @Test @@ -88,4 +69,4 @@ public void apply_shouldDelegateToAllOptions() throws Exception { verify(spiedCommand).tags(Matchers.eq(true)); verify(spiedCommand).forceLongFormat(Matchers.eq(true)); } -} +} \ No newline at end of file diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java index 931e6583..bea34d77 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoIntegrationTest.java @@ -29,7 +29,6 @@ import org.eclipse.jgit.api.ResetCommand; import org.junit.Test; import org.junit.runner.RunWith; -import pl.project13.test.utils.AssertException; import java.io.File; import java.nio.charset.Charset; @@ -154,7 +153,7 @@ public void shouldUseChildProjectRepoIfInvokedFromChild(boolean useNativeGit) th assertGitPropertiesPresentInProject(targetProject.getProperties()); } - @Test + @Test(expected = MojoExecutionException.class) @Parameters(method = "useNativeGit") public void shouldFailWithExceptionWhenNoGitRepoFound(boolean useNativeGit) throws Exception { // given @@ -168,16 +167,7 @@ public void shouldFailWithExceptionWhenNoGitRepoFound(boolean useNativeGit) thro alterMojoSettings("skipPoms", false); alterMojoSettings("useNativeGit", useNativeGit); - // when - AssertException.CodeBlock block = new AssertException.CodeBlock() { - @Override - public void run() throws Exception { - mojo.execute(); - } - }; - - // then - AssertException.thrown(MojoExecutionException.class, block); + mojo.execute(); } @Test diff --git a/src/test/java/pl/project13/test/utils/AssertException.java b/src/test/java/pl/project13/test/utils/AssertException.java deleted file mode 100644 index 3fe87392..00000000 --- a/src/test/java/pl/project13/test/utils/AssertException.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * 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.test.utils; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.junit.Assert; - -import static pl.project13.test.utils.AssertException.ExceptionMatch.EXCEPTION_CLASS_MUST_EQUAL; - -/** - * Allows expecting and intercepting exceptions in a nice way. - * Use it to intercept exceptions in your tests, in a way that allows - * sticking to the given/when/then flow, and validate exception throws on - * - * SoftwareBirr 02.2012 - * - * @see AssertException in softwaremill-common/softwaremill-test-util - */ -public class AssertException { - - public interface CodeBlock { - void run() throws Exception; - } - - public static abstract class ExceptionMatch { - - public static final ExceptionMatch.Strategy EXCEPTION_CLASS_MUST_EQUAL = new Strategy() { - @Override - public boolean matchesExpected(Class expectedClass, @NotNull Throwable got, String expectedMessage) { - return got.getClass().equals(expectedClass); - } - - public void failWithExpectedButGot(@NotNull Class expectedClass, @NotNull Throwable got, String expectedMessage) { - Assert.fail(String.format("Expected [%s] to be thrown but got [%s]", expectedClass.getSimpleName(), got.getClass().getSimpleName())); - } - }; - - /** - * Please use EXCEPTION_CLASS_MUST_EQUAL instead - */ - @Deprecated - public static final ExceptionMatch.Strategy EXCEPTION_MUST_EQUAL = EXCEPTION_CLASS_MUST_EQUAL; - - public static final ExceptionMatch.Strategy EXCEPTION_MAY_BE_SUBCLASS_OF = new Strategy() { - @Override - public boolean matchesExpected(@NotNull Class expectedClass, @NotNull Throwable got, String expectedMessage) { - return expectedClass.isAssignableFrom(got.getClass()); - } - - public void failWithExpectedButGot(@NotNull Class expectedClass, @NotNull Throwable got, String expectedMessage) { - Assert.fail(String.format("Expected subclass of [%s] to be thrown but got [%s]", expectedClass.getSimpleName(), got.getClass().getSimpleName())); - } - }; - - public static final ExceptionMatch.Strategy EXCEPTION_CLASS_AND_MESSAGE_MUST_EQUAL = new Strategy() { - @Override - public boolean matchesExpected(Class expectedClass, @NotNull Throwable got, @NotNull String expectedMessage) { - return got.getClass().equals(expectedClass) && expectedMessage.equals(got.getMessage()); - } - - public void failWithExpectedButGot(@NotNull Class expectedClass, @NotNull Throwable got, String expectedMessage) { - Assert.fail(String.format("Expected [%s] to be thrown with message [%s] but got [%s] with message [%s]", expectedClass.getSimpleName(), - expectedMessage, got.getClass().getSimpleName(), got.getMessage())); - } - }; - - interface Strategy { - boolean matchesExpected(Class expectedClass, Throwable got, String expectedMessage); - - void failWithExpectedButGot(Class expectedClass, Throwable got, String expectedMessage); - } - } - - @SuppressWarnings("ThrowableResultOfMethodCallIgnored") - public static void thrown(@NotNull ExceptionMatch.Strategy matchStrategy, - @NotNull Class expectedThrowableClass, - @NotNull CodeBlock block) { - intercept(matchStrategy, expectedThrowableClass, block); - } - - @SuppressWarnings("ThrowableResultOfMethodCallIgnored") - public static void thrownWithMessage(@NotNull ExceptionMatch.Strategy matchStrategy, - @NotNull Class expectedThrowableClass, String expectedMessage, - @NotNull CodeBlock block) { - intercept(matchStrategy, expectedThrowableClass, expectedMessage, block); - } - - public static void thrown(@NotNull Class expectedThrowableClass, - @NotNull CodeBlock block) { - thrown(EXCEPTION_CLASS_MUST_EQUAL, expectedThrowableClass, block); - } - - @Nullable - public static T intercept(@NotNull Class expectedThrowableClass, - @NotNull CodeBlock block) { - return intercept(EXCEPTION_CLASS_MUST_EQUAL, expectedThrowableClass, block); - } - - @Nullable - public static T intercept(@NotNull ExceptionMatch.Strategy matchStrategy, - @NotNull Class expectedThrowableClass, - @NotNull CodeBlock block) { - return intercept(matchStrategy, expectedThrowableClass, null, block); - } - - @Nullable - public static T intercept(@NotNull ExceptionMatch.Strategy matchStrategy, - @NotNull Class expectedThrowableClass, @Nullable String expectedMessage, - @NotNull CodeBlock block) { - try { - block.run(); - - failWithExpectedButGotNothing(expectedThrowableClass); // will throw - return null; // make compiler happy - - } catch (Throwable thr) { - boolean gotExpectedException = matchStrategy.matchesExpected(expectedThrowableClass, thr, expectedMessage); - if (gotExpectedException) { - return expectedThrowableClass.cast(thr); - } else { - matchStrategy.failWithExpectedButGot(expectedThrowableClass, thr, expectedMessage); - return null; // make compiler happy - } - } - } - - private static void failWithExpectedButGotNothing(@NotNull Class expected) { - Assert.fail(String.format("Expected [%s] to be thrown but no exception was thrown.", expected.getSimpleName())); - } - -} From 5f76cde4869923f3dd3323e62dc6c2f6fca3c60d Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 16:44:39 +0100 Subject: [PATCH 19/22] bridging logging to address Konrad and Michael comments regarding modularization (#92) --- .../pl/project13/jgit/DescribeCommand.java | 49 +- .../java/pl/project13/jgit/JGitCommon.java | 38 +- .../project13/maven/git/GitCommitIdMojo.java | 43 +- .../project13/maven/git/GitDataProvider.java | 16 +- .../pl/project13/maven/git/JGitProvider.java | 21 +- .../maven/git/NativeGitProvider.java | 12 +- .../maven/git/log/FormattingTuple.java | 93 ++++ .../project13/maven/git/log/LoggerBridge.java | 328 +++++++++++++ .../maven/git/log/MavenLoggerBridge.java | 236 ++++++++++ .../maven/git/log/MessageFormatter.java | 430 ++++++++++++++++++ .../maven/git/log/StdOutLoggerBridge.java | 205 +++++++++ .../project13/maven/git/log/VerboseLog.java | 40 -- .../maven/git/log/VerboseLogger.java | 148 ------ .../DescribeCommandAbbrevIntegrationTest.java | 7 +- .../jgit/DescribeCommandIntegrationTest.java | 40 +- .../jgit/DescribeCommandOptionsTest.java | 8 +- .../DescribeCommandTagsIntegrationTest.java | 19 +- .../jgit/JGitCommonIntegrationTest.java | 4 +- .../maven/git/GitCommitIdMojoTest.java | 3 +- 19 files changed, 1417 insertions(+), 323 deletions(-) create mode 100644 src/main/java/pl/project13/maven/git/log/FormattingTuple.java create mode 100644 src/main/java/pl/project13/maven/git/log/LoggerBridge.java create mode 100644 src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java create mode 100644 src/main/java/pl/project13/maven/git/log/MessageFormatter.java create mode 100644 src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java delete mode 100644 src/main/java/pl/project13/maven/git/log/VerboseLog.java delete mode 100644 src/main/java/pl/project13/maven/git/log/VerboseLogger.java diff --git a/src/main/java/pl/project13/jgit/DescribeCommand.java b/src/main/java/pl/project13/jgit/DescribeCommand.java index aa156a47..82554225 100644 --- a/src/main/java/pl/project13/jgit/DescribeCommand.java +++ b/src/main/java/pl/project13/jgit/DescribeCommand.java @@ -21,7 +21,6 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import org.apache.maven.plugin.Mojo; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.GitCommand; import org.eclipse.jgit.api.Status; @@ -36,6 +35,7 @@ import pl.project13.jgit.dummy.DatedRevTag; import pl.project13.maven.git.GitDescribeConfig; +import pl.project13.maven.git.log.LoggerBridge; import pl.project13.maven.git.util.Pair; import java.io.IOException; @@ -46,7 +46,7 @@ */ public class DescribeCommand extends GitCommand { - private Mojo mojo; + private LoggerBridge log; private JGitCommon jGitCommon; // TODO not yet implemented options: @@ -84,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); } /** @@ -96,15 +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) { + private DescribeCommand(Repository repo, @NotNull LoggerBridge log) { super(repo); - this.jGitCommon = new JGitCommon(); - } - - @NotNull - public DescribeCommand withMojo(Mojo mojo) { - this.mojo = mojo; - return this; + this.jGitCommon = new JGitCommon(log); + this.log = log; } /** @@ -117,7 +113,7 @@ public DescribeCommand withMojo(Mojo mojo) { @NotNull public DescribeCommand always(boolean always) { this.alwaysFlag = always; - mojo.getLog().info("--always = " + always); + log.info("--always = {}", always); return this; } @@ -136,7 +132,7 @@ public DescribeCommand always(boolean always) { public DescribeCommand forceLongFormat(@Nullable Boolean forceLongFormat) { if (forceLongFormat != null && forceLongFormat) { this.forceLongFormat = true; - mojo.getLog().info("--long = " + true); + log.info("--long = {}", true); } return this; } @@ -152,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)); - mojo.getLog().info("--abbrev = " + n); + log.info("--abbrev = {}", n); abbrev = n; } return this; @@ -192,7 +188,7 @@ public DescribeCommand abbrev(@Nullable Integer n) { public DescribeCommand tags(@Nullable Boolean includeLightweightTagsInSearch) { if (includeLightweightTagsInSearch != null && includeLightweightTagsInSearch) { tagsFlag = includeLightweightTagsInSearch; - mojo.getLog().info("--tags = " + includeLightweightTagsInSearch); + log.info("--tags = {}", includeLightweightTagsInSearch); } return this; } @@ -234,7 +230,7 @@ public DescribeCommand apply(@Nullable GitDescribeConfig config) { @NotNull public DescribeCommand dirty(@Nullable String dirtyMarker) { Optional option = Optional.fromNullable(dirtyMarker); - mojo.getLog().info("--dirty = " + option.or("")); + log.info("--dirty = {}", option.or("")); this.dirtyOption = option; return this; } @@ -250,7 +246,7 @@ public DescribeCommand dirty(@Nullable String dirtyMarker) { public DescribeCommand match(@Nullable String pattern) { if (!"*".equals(pattern)) { matchOption = Optional.fromNullable(pattern); - mojo.getLog().info("--match =" + matchOption.or("")); + log.info("--match = {}", matchOption.or("")); } return this; } @@ -272,7 +268,7 @@ public DescribeResult call() throws GitAPIException { if (hasTags(headCommit, tagObjectIdToName) && !forceLongFormat) { String tagName = tagObjectIdToName.get(headCommit).iterator().next(); - mojo.getLog().info("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); } @@ -345,7 +341,7 @@ boolean findDirtyState(Repository repo) throws GitAPIException { && status.getModified().isEmpty() && status.getConflicting().isEmpty()); - mojo.getLog().info("Repo is in dirty state [" + isDirty + "]"); + log.info("Repo is in dirty state [{}]", isDirty); return isDirty; } @@ -362,7 +358,7 @@ RevCommit findHeadObjectId(@NotNull Repository repo) throws RuntimeException { RevCommit headCommit = walk.lookupCommit(headId); walk.dispose(); - mojo.getLog().info("HEAD is [" + headCommit.getName() + "] "); + log.info("HEAD is [{}]", headCommit.getName()); return headCommit; } catch (IOException ex) { throw new RuntimeException("Unable to obtain HEAD commit!", ex); @@ -372,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(repo, tagsFlag, matchPattern, mojo); + Map> commitIdsToTags = jGitCommon.getCommitIdsToTags(repo, tagsFlag, matchPattern); Map> commitIdsToTagNames = jGitCommon.transformRevTagsMapToDateSortedTagNames(commitIdsToTags); - mojo.getLog().info("Created map: [" + commitIdsToTagNames + "] "); + log.info("Created map: [{}]", commitIdsToTagNames); return commitIdsToTagNames; } @@ -388,5 +384,4 @@ private String createMatchPattern() { matchOption.get().replace("*", "\\E.*\\Q").replace("?", "\\E.\\Q") + "\\E$"; } -} - +} \ No newline at end of file diff --git a/src/main/java/pl/project13/jgit/JGitCommon.java b/src/main/java/pl/project13/jgit/JGitCommon.java index 8c4ab7ea..7285345a 100644 --- a/src/main/java/pl/project13/jgit/JGitCommon.java +++ b/src/main/java/pl/project13/jgit/JGitCommon.java @@ -24,7 +24,6 @@ import java.util.*; import java.util.regex.Pattern; -import org.apache.maven.plugin.Mojo; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; @@ -43,8 +42,16 @@ import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; +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 { @@ -80,16 +87,16 @@ public Collection getTags(Repository repo, final ObjectId headId) throws } } - public String getClosestTagName(@NotNull Repository repo, @NotNull Mojo mojo){ - Map> map = getClosestTagAsMap(repo, mojo); + 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 Repository repo, RevCommit headCommit, @NotNull Mojo mojo){ - HashMap> map = transformRevTagsMapToDateSortedTagNames(getClosestTagAsMap(repo, mojo)); + 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); @@ -100,11 +107,10 @@ public String getClosestTagCommitCount(@NotNull Repository repo, RevCommit headC return String.valueOf(distance); } - private Map> getClosestTagAsMap(@NotNull Repository repo, @NotNull Mojo mojo){ + private Map> getClosestTagAsMap(@NotNull Repository repo){ Map> mapWithClosestTagOnly = newHashMap(); - boolean includeLightweightTags = true; String matchPattern = ".*"; - Map> commitIdsToTags = getCommitIdsToTags(repo, includeLightweightTags, matchPattern, mojo); + Map> commitIdsToTags = getCommitIdsToTags(repo, true, matchPattern); LinkedHashMap> sortedCommitIdsToTags = sortByDatedRevTag(commitIdsToTags); for (Map.Entry> entry: sortedCommitIdsToTags.entrySet()){ @@ -137,7 +143,7 @@ public int compare(Map.Entry> m1, Map.Entry> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern, @NotNull Mojo mojo){ + protected Map> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern){ Map> commitIdsToTags = newHashMap(); try (RevWalk walk = new RevWalk(repo)) { @@ -145,13 +151,13 @@ protected Map> getCommitIdsToTags(@NotNull Repositor List tagRefs = Git.wrap(repo).tagList().call(); Pattern regex = Pattern.compile(matchPattern); - mojo.getLog().info("Tag refs [" + tagRefs + "]"); + log.info("Tag refs [{}]", tagRefs); for (Ref tagRef : tagRefs) { walk.reset(); String name = tagRef.getName(); if (!regex.matcher(name).matches()) { - mojo.getLog().info("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); @@ -160,7 +166,7 @@ protected Map> getCommitIdsToTags(@NotNull Repositor try { final RevTag revTag = walk.parseTag(resolvedCommitId); ObjectId taggedCommitId = revTag.getObject().getId(); - mojo.getLog().info("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)) { @@ -177,7 +183,7 @@ protected Map> getCommitIdsToTags(@NotNull Repositor // it's an lightweight tag! (yeah, really) if (includeLightweightTags) { // --tags means "include lightweight tags" - mojo.getLog().info("Including lightweight tag [" + name + "]"); + log.info("Including lightweight tag [{}]", name); DatedRevTag datedRevTag = new DatedRevTag(resolvedCommitId, name); @@ -188,16 +194,16 @@ protected Map> getCommitIdsToTags(@NotNull Repositor } } } catch (Exception ignored) { - mojo.getLog().info("Failed while parsing [" + tagRef + "] -- ", ignored); + log.info("Failed while parsing [{}] -- ", tagRef, ignored); } } for (Map.Entry> entry : commitIdsToTags.entrySet()) { - mojo.getLog().info("key [" + entry.getKey() + "], tags => [" + entry.getValue() + "] "); + log.info("key [{}], tags => [{}] ", entry.getKey(), entry.getValue()); } return commitIdsToTags; } catch (Exception e) { - mojo.getLog().info("Unable to locate tags", e); + log.info("Unable to locate tags", e); } return Collections.emptyMap(); } diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index dc43f222..b9b7f1d3 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; @@ -38,13 +37,14 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import pl.project13.maven.git.log.VerboseLog; -import pl.project13.maven.git.log.VerboseLogger; +import pl.project13.maven.git.log.LoggerBridge; +import pl.project13.maven.git.log.MavenLoggerBridge; import pl.project13.maven.git.util.PropertyManager; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; +import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; @@ -305,7 +305,7 @@ public class GitCommitIdMojo extends AbstractMojo { private Properties properties; @NotNull - private final VerboseLog log = new VerboseLogger(this, true); + private final LoggerBridge log = new MavenLoggerBridge(this, false); @Override public void execute() throws MojoExecutionException { @@ -339,7 +339,7 @@ public void execute() throws MojoExecutionException { } if (dotGitDirectory != null) { - log.info("dotGitDirectory " + dotGitDirectory.getAbsolutePath()); + log.info("dotGitDirectory {}", dotGitDirectory.getAbsolutePath()); } else { log.info("dotGitDirectory is null, aborting execution!"); return; @@ -397,7 +397,7 @@ public Predicate apply(String exclude) { for (String key : properties.stringPropertyNames()) { if (shouldExclude.apply(key)) { - log.debug("shouldExclude.apply(" + key + ") = " + shouldExclude.apply(key)); + log.debug("shouldExclude.apply({}) = {}", key, shouldExclude.apply(key)); properties.remove(key); } } @@ -422,7 +422,7 @@ public Predicate apply(String exclude) { for (String key : properties.stringPropertyNames()) { if (!shouldInclude.apply(key)) { - log.debug("!shouldInclude.apply(" + key + ") = " + shouldInclude.apply(key)); + log.debug("!shouldInclude.apply({}) = {}", key, shouldInclude.apply(key)); properties.remove(key); } } @@ -447,7 +447,8 @@ private void appendPropertiesToReactorProjects(@NotNull Properties properties, @ for (MavenProject mavenProject : reactorProjects) { Properties mavenProperties = mavenProject.getProperties(); - log.info(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)) { @@ -479,7 +480,7 @@ private void logProperties(@NotNull Properties properties) { for (Object key : properties.keySet()) { String keyString = key.toString(); if (isOurProperty(keyString)) { - log.info("found property " + keyString); + log.info("found property {}", keyString); } } } @@ -503,7 +504,7 @@ void loadBuildHostData(@NotNull Properties properties) { try { buildHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { - log.info("Unable to get build host, skipping property " + BUILD_HOST + ". Error message: " + e.getMessage()); + log.info("Unable to get build host, skipping property {}. Error message: {}", BUILD_HOST, e.getMessage()); } put(properties, BUILD_HOST, buildHost); } @@ -541,7 +542,7 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException final File basedir = project.getBasedir().getCanonicalFile(); GitDataProvider nativeGitProvider = NativeGitProvider - .on(basedir, this) + .on(basedir, log) .setPrefixDot(prefixDot) .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) @@ -554,7 +555,7 @@ void loadGitDataWithNativeGit(@NotNull Properties properties) throws IOException void loadGitDataWithJGit(@NotNull Properties properties) throws IOException, MojoExecutionException { GitDataProvider jGitProvider = JGitProvider - .on(dotGitDirectory, this) + .on(dotGitDirectory, log) .setPrefixDot(prefixDot) .setAbbrevLength(abbrevLength) .setDateFormat(dateFormat) @@ -576,12 +577,12 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, try { if (isJsonFormat) { - log.info("Reading existing json file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); + log.info("Reading existing json file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); persistedProperties = readJsonProperties( gitPropsFile ); } else { - log.info("Reading existing properties file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); + log.info("Reading existing properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); persistedProperties = readProperties( gitPropsFile ); } @@ -597,7 +598,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } catch ( CannotReadFileException ex ) { // Read has failed, regenerate file - log.info("Cannot read properties file [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); + log.info("Cannot read properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); shouldGenerate = true; } } @@ -608,13 +609,13 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, boolean threw = true; try { - outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), Charsets.UTF_8); + outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), StandardCharsets.UTF_8); if (isJsonFormat) { - log.info("Writing json file to [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); + 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 [" + gitPropsFile.getAbsolutePath() + "] (for module " + project.getName() + ")..."); + log.info("Writing properties file to [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); localProperties.store(outputWriter, "Generated by Git-Commit-Id-Plugin"); } threw = false; @@ -625,7 +626,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, } } else { - log.info("Properties file [" + gitPropsFile.getAbsolutePath() + "] is up-to-date (for module " + project.getName() + ")..."); + log.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); } } @@ -668,7 +669,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, StandardCharsets.UTF_8); closeable = reader; final ObjectMapper mapper = new ObjectMapper(); @@ -705,7 +706,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, StandardCharsets.UTF_8); closeable = reader; final Properties retVal = new Properties(); diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java index e44c7c4e..2de5e485 100644 --- a/src/main/java/pl/project13/maven/git/GitDataProvider.java +++ b/src/main/java/pl/project13/maven/git/GitDataProvider.java @@ -17,9 +17,9 @@ package pl.project13.maven.git; -import org.apache.maven.plugin.Mojo; 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; import java.io.IOException; @@ -33,7 +33,7 @@ public abstract class GitDataProvider { @NotNull - protected final Mojo mojo; + protected final LoggerBridge log; protected String prefixDot; @@ -47,8 +47,8 @@ public abstract class GitDataProvider { protected CommitIdGenerationMode commitIdGenerationMode; - public GitDataProvider(@NotNull Mojo mojo) { - this.mojo = mojo; + public GitDataProvider(@NotNull LoggerBridge log) { + this.log = log; } public GitDataProvider setGitDescribe(GitDescribeConfig gitDescribe) { @@ -208,10 +208,10 @@ private boolean runningOnBuildServer(Map env) { protected String determineBranchNameOnBuildServer(Map env) throws IOException { String environmentBasedBranch = env.get("GIT_BRANCH"); if (isNullOrEmpty(environmentBasedBranch)) { - mojo.getLog().info("Detected that running on CI environment, but using repository branch, no GIT_BRANCH detected."); + log.info("Detected that running on CI environment, but using repository branch, no GIT_BRANCH detected."); return getBranchName(); } else { - mojo.getLog().info("Using environment variable based branch name. " + "GIT_BRANCH = " + environmentBasedBranch); + log.info("Using environment variable based branch name. GIT_BRANCH = {}", environmentBasedBranch); return environmentBasedBranch; } } @@ -226,7 +226,7 @@ protected SimpleDateFormat getSimpleDateFormatWithTimeZone(){ protected void put(@NotNull Properties properties, String key, String value) { String keyWithPrefix = prefixDot + key; - mojo.getLog().info(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/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java index 8ab04a3b..a0fec598 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.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; @@ -39,6 +38,7 @@ import pl.project13.jgit.DescribeCommand; import pl.project13.jgit.DescribeResult; import pl.project13.jgit.JGitCommon; +import pl.project13.maven.git.log.LoggerBridge; import java.io.File; import java.io.IOException; @@ -56,14 +56,14 @@ public class JGitProvider extends GitDataProvider { private JGitCommon jGitCommon; @NotNull - public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { - return new JGitProvider(dotGitDirectory, mojo); + public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + return new JGitProvider(dotGitDirectory, log); } - JGitProvider(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { - super(mojo); + JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + super(log); this.dotGitDirectory = dotGitDirectory; - this.jGitCommon = new JGitCommon(); + this.jGitCommon = new JGitCommon(log); } @Override @@ -177,7 +177,7 @@ protected String getTags() throws MojoExecutionException { Collection tags = jGitCommon.getTags(repo,headId); return Joiner.on(",").join(tags); } catch (GitAPIException e) { - mojo.getLog().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 ""; } } @@ -186,7 +186,7 @@ protected String getTags() throws MojoExecutionException { protected String getClosestTagName() throws MojoExecutionException { Repository repo = getGitRepository(); try { - return jGitCommon.getClosestTagName(repo, mojo); + return jGitCommon.getClosestTagName(repo); } catch (Throwable t) { // could not find any tags to describe } @@ -197,7 +197,7 @@ protected String getClosestTagName() throws MojoExecutionException { protected String getClosestTagCommitCount() throws MojoExecutionException { Repository repo = getGitRepository(); try { - return jGitCommon.getClosestTagCommitCount(repo, headCommit, mojo); + return jGitCommon.getClosestTagCommitCount(repo, headCommit); } catch (Throwable t) { // could not find any tags to describe } @@ -215,8 +215,7 @@ protected void finalCleanUp() { @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws MojoExecutionException { try { DescribeResult describeResult = DescribeCommand - .on(repository) - .withMojo(mojo) + .on(repository, log) .apply(super.gitDescribe) .call(); diff --git a/src/main/java/pl/project13/maven/git/NativeGitProvider.java b/src/main/java/pl/project13/maven/git/NativeGitProvider.java index 88ab770c..2d52ebcd 100644 --- a/src/main/java/pl/project13/maven/git/NativeGitProvider.java +++ b/src/main/java/pl/project13/maven/git/NativeGitProvider.java @@ -22,9 +22,9 @@ import com.google.common.base.Throwables; import com.google.common.collect.Lists; -import org.apache.maven.plugin.Mojo; import org.apache.maven.plugin.MojoExecutionException; import org.jetbrains.annotations.NotNull; +import pl.project13.maven.git.log.LoggerBridge; import java.io.*; import java.text.SimpleDateFormat; @@ -41,12 +41,12 @@ public class NativeGitProvider extends GitDataProvider { private static final int REMOTE_COLS = 3; @NotNull - public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { - return new NativeGitProvider(dotGitDirectory, mojo); + public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + return new NativeGitProvider(dotGitDirectory, log); } - NativeGitProvider(@NotNull File dotGitDirectory, @NotNull Mojo mojo) { - super(mojo); + NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge log) { + super(log); this.dotGitDirectory = dotGitDirectory; try { this.canonical = dotGitDirectory.getCanonicalFile(); @@ -420,4 +420,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 new file mode 100644 index 00000000..23fb9b61 --- /dev/null +++ b/src/main/java/pl/project13/maven/git/log/LoggerBridge.java @@ -0,0 +1,328 @@ +/* + * 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; + +/** + * 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 { + + /** + * 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 new file mode 100644 index 00000000..49f100d5 --- /dev/null +++ b/src/main/java/pl/project13/maven/git/log/MavenLoggerBridge.java @@ -0,0 +1,236 @@ +/* + * 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; + +import org.apache.maven.plugin.Mojo; + +/** + * Bridges logging to standard Maven log adhering to verbosity level. + */ +public class MavenLoggerBridge implements LoggerBridge { + + private boolean verbose; + private final Mojo mojo; + + public MavenLoggerBridge(Mojo mojo, boolean verbose) { + this.mojo = mojo; + this.verbose = verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public boolean isDebugEnabled() { + return mojo.getLog().isDebugEnabled(); + } + + @Override + public boolean isInfoEnabled() { + return mojo.getLog().isInfoEnabled(); + } + + @Override + public boolean isWarnEnabled() { + return mojo.getLog().isWarnEnabled(); + } + + @Override + public boolean isErrorEnabled() { + return mojo.getLog().isErrorEnabled(); + } + + @Override + public void debug(String msg) { + if (verbose) { + mojo.getLog().debug(msg); + } + } + + @Override + public void debug(String format, Object arg) { + if (verbose) { + debug(MessageFormatter.format(format, arg)); + } + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + if (verbose) { + debug(MessageFormatter.format(format, arg1, arg2)); + } + } + + @Override + public void debug(String format, Object... arguments) { + if (verbose) { + debug(MessageFormatter.arrayFormat(format, arguments)); + } + } + + @Override + public void debug(String msg, Throwable t) { + if (verbose) { + mojo.getLog().debug(msg, t); + } + } + + @Override + public void info(String msg) { + if (verbose) { + mojo.getLog().info(msg); + } + } + + @Override + public void info(String format, Object arg) { + if (verbose) { + info(MessageFormatter.format(format, arg)); + } + } + + @Override + public void info(String format, Object arg1, Object arg2) { + if (verbose) { + info(MessageFormatter.format(format, arg1, arg2)); + } + } + + @Override + public void info(String format, Object... arguments) { + if (verbose) { + info(MessageFormatter.arrayFormat(format, arguments)); + } + } + + @Override + public void info(String msg, Throwable t) { + if (verbose) { + mojo.getLog().info(msg, t); + } + } + + @Override + public void warn(String msg) { + if (verbose) { + mojo.getLog().warn(msg); + } + } + + @Override + public void warn(String format, Object arg) { + if (verbose) { + warn(MessageFormatter.format(format, arg)); + } + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + if (verbose) { + warn(MessageFormatter.format(format, arg1, arg2)); + } + } + + @Override + public void warn(String format, Object... arguments) { + if (verbose) { + warn(MessageFormatter.arrayFormat(format, arguments)); + } + } + + @Override + public void warn(String msg, Throwable t) { + if (verbose) { + mojo.getLog().warn(msg, t); + } + } + + @Override + public void error(String msg) { + if (verbose) { + mojo.getLog().error(msg); + } + } + + @Override + public void error(String format, Object arg) { + if (verbose) { + error(MessageFormatter.format(format, arg)); + } + } + + @Override + public void error(String format, Object arg1, Object arg2) { + if (verbose) { + error(MessageFormatter.format(format, arg1, arg2)); + } + } + + @Override + public void error(String format, Object... arguments) { + if (verbose) { + error(MessageFormatter.arrayFormat(format, arguments)); + } + } + + @Override + public void error(String msg, Throwable t) { + if (verbose) { + mojo.getLog().error(msg, t); + } + } + + private void debug(FormattingTuple tuple) { + if (null == tuple.getThrowable()) { + mojo.getLog().debug(tuple.getMessage()); + } else { + mojo.getLog().debug(tuple.getMessage(), tuple.getThrowable()); + } + } + + private void info(FormattingTuple tuple) { + if (null == tuple.getThrowable()) { + mojo.getLog().info(tuple.getMessage()); + } else { + mojo.getLog().info(tuple.getMessage(), tuple.getThrowable()); + } + } + + private void warn(FormattingTuple tuple) { + if (null == tuple.getThrowable()) { + mojo.getLog().warn(tuple.getMessage()); + } else { + mojo.getLog().warn(tuple.getMessage(), tuple.getThrowable()); + } + } + + private void error(FormattingTuple tuple) { + if (null == tuple.getThrowable()) { + mojo.getLog().error(tuple.getMessage()); + } else { + mojo.getLog().error(tuple.getMessage(), tuple.getThrowable()); + } + } +} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/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. + * + *

    + * For example, + * + *

    + * MessageFormatter.format("Hi {}.", "there")
    + * 
    + * + * will return the string "Hi there.". + *

    + * 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. + *

    + * For example, + * + *

    +     * MessageFormatter.format("Hi {}.", "there");
    +     * 
    + * + * will return the string "Hi there.". + *

    + * + * @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()); + i = j + 2; + } + } else { + // normal case + sbuf.append(messagePattern, i, j); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } + } + // append the characters following the last {} pair. + sbuf.append(messagePattern, i, messagePattern.length()); + if (L < argArray.length - 1) { + return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); + } else { + return new FormattingTuple(sbuf.toString(), argArray, null); + } + } + + final static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) { + + if (delimeterStartIndex == 0) { + return false; + } + char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); + if (potentialEscape == ESCAPE_CHAR) { + return true; + } else { + return false; + } + } + + final static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) { + if (delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { + return true; + } else { + return false; + } + } + + // special treatment of array values was suggested by 'lizongbo' + private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map seenMap) { + if (o == null) { + sbuf.append("null"); + return; + } + if (!o.getClass().isArray()) { + safeObjectAppend(sbuf, o); + } else { + // check for primitive array types because they + // unfortunately cannot be cast to Object[] + if (o instanceof boolean[]) { + booleanArrayAppend(sbuf, (boolean[]) o); + } else if (o instanceof byte[]) { + byteArrayAppend(sbuf, (byte[]) o); + } else if (o instanceof char[]) { + charArrayAppend(sbuf, (char[]) o); + } else if (o instanceof short[]) { + shortArrayAppend(sbuf, (short[]) o); + } else if (o instanceof int[]) { + intArrayAppend(sbuf, (int[]) o); + } else if (o instanceof long[]) { + longArrayAppend(sbuf, (long[]) o); + } else if (o instanceof float[]) { + floatArrayAppend(sbuf, (float[]) o); + } else if (o instanceof double[]) { + doubleArrayAppend(sbuf, (double[]) o); + } else { + objectArrayAppend(sbuf, (Object[]) o, seenMap); + } + } + } + + private static void safeObjectAppend(StringBuilder sbuf, Object o) { + try { + String oAsString = o.toString(); + sbuf.append(oAsString); + } catch (Throwable t) { + System.err.println("SLF4J: Failed toString() invocation on an object of type [" + o.getClass().getName() + "]"); + t.printStackTrace(); + sbuf.append("[FAILED toString()]"); + } + + } + + private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map seenMap) { + sbuf.append('['); + if (!seenMap.containsKey(a)) { + seenMap.put(a, null); + final int len = a.length; + for (int i = 0; i < len; i++) { + deeplyAppendParameter(sbuf, a[i], seenMap); + if (i != len - 1) + sbuf.append(", "); + } + // allow repeats in siblings + seenMap.remove(a); + } else { + sbuf.append("..."); + } + sbuf.append(']'); + } + + private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void byteArrayAppend(StringBuilder sbuf, byte[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void charArrayAppend(StringBuilder sbuf, char[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void shortArrayAppend(StringBuilder sbuf, short[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void intArrayAppend(StringBuilder sbuf, int[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void longArrayAppend(StringBuilder sbuf, long[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void floatArrayAppend(StringBuilder sbuf, float[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } + + private static void doubleArrayAppend(StringBuilder sbuf, double[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) + sbuf.append(", "); + } + sbuf.append(']'); + } +} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java b/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java new file mode 100644 index 00000000..e2dae46d --- /dev/null +++ b/src/main/java/pl/project13/maven/git/log/StdOutLoggerBridge.java @@ -0,0 +1,205 @@ +/* + * 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; + +/** + * Logs everything to System.out. + */ +public class StdOutLoggerBridge implements LoggerBridge { + + private boolean verbose; + + public StdOutLoggerBridge(boolean verbose) { + this.verbose = verbose; + } + + @Override + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + @Override + public boolean isVerbose() { + return verbose; + } + + @Override + public boolean isDebugEnabled() { + return true; + } + + @Override + public void debug(String msg) { + if (verbose) { + System.out.println("[DEBUG] " + msg); + } + } + + @Override + public void debug(String format, Object arg) { + if (verbose) { + System.out.println("[DEBUG] " + MessageFormatter.format(format, arg).getMessage()); + } + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + if (verbose) { + System.out.println("[DEBUG] " + MessageFormatter.format(format, arg1, arg2).getMessage()); + } + } + + @Override + public void debug(String format, Object... arguments) { + if (verbose) { + System.out.println("[DEBUG] " + MessageFormatter.arrayFormat(format, arguments).getMessage()); + } + } + + @Override + public void debug(String msg, Throwable t) { + if (verbose) { + System.out.println("[DEBUG] " + msg); + t.printStackTrace(System.out); + } + } + + @Override + public boolean isInfoEnabled() { + return true; + } + + @Override + public void info(String msg) { + if (verbose) { + System.out.println("[INFO] " + msg); + } + } + + @Override + public void info(String format, Object arg) { + if (verbose) { + System.out.println("[INFO] " + MessageFormatter.format(format, arg).getMessage()); + } + } + + @Override + public void info(String format, Object arg1, Object arg2) { + if (verbose) { + System.out.println("[INFO] " + MessageFormatter.format(format, arg1, arg2).getMessage()); + } + } + + @Override + public void info(String format, Object... arguments) { + if (verbose) { + System.out.println("[INFO] " + MessageFormatter.arrayFormat(format, arguments).getMessage()); + } + } + + @Override + public void info(String msg, Throwable t) { + if (verbose) { + System.out.println("[INFO] " + msg); + t.printStackTrace(System.out); + } + } + + @Override + public boolean isWarnEnabled() { + return true; + } + + @Override + public void warn(String msg) { + if (verbose) { + System.out.println("[WARN] " + msg); + } + } + + @Override + public void warn(String format, Object arg) { + if (verbose) { + System.out.println("[WARN] " + MessageFormatter.format(format, arg).getMessage()); + } + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + if (verbose) { + System.out.println("[WARN] " + MessageFormatter.format(format, arg1, arg2).getMessage()); + } + } + + @Override + public void warn(String format, Object... arguments) { + if (verbose) { + System.out.println("[WARN] " + MessageFormatter.arrayFormat(format, arguments).getMessage()); + } + } + + @Override + public void warn(String msg, Throwable t) { + if (verbose) { + System.out.println("[WARN] " + msg); + t.printStackTrace(System.out); + } + } + + @Override + public boolean isErrorEnabled() { + return true; + } + + @Override + public void error(String msg) { + if (verbose) { + System.out.println("[ERROR] " + msg); + } + } + + @Override + public void error(String format, Object arg) { + if (verbose) { + System.out.println("[ERROR] " + MessageFormatter.format(format, arg).getMessage()); + } + } + + @Override + public void error(String format, Object arg1, Object arg2) { + if (verbose) { + System.out.println("[ERROR] " + MessageFormatter.format(format, arg1, arg2).getMessage()); + } + + } + + @Override + public void error(String format, Object... arguments) { + if (verbose) { + System.out.println("[ERROR] " + MessageFormatter.arrayFormat(format, arguments).getMessage()); + } + } + + @Override + public void error(String msg, Throwable t) { + if (verbose) { + System.out.println("[ERROR] " + msg); + t.printStackTrace(System.out); + } + } +} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/git/log/VerboseLog.java b/src/main/java/pl/project13/maven/git/log/VerboseLog.java deleted file mode 100644 index d6fa0d9e..00000000 --- a/src/main/java/pl/project13/maven/git/log/VerboseLog.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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; - -import org.apache.maven.plugin.logging.Log; - -/** - * Allows user to specify verbosity level of logging. - */ -public interface VerboseLog extends Log { - - /** - * 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); -} \ No newline at end of file diff --git a/src/main/java/pl/project13/maven/git/log/VerboseLogger.java b/src/main/java/pl/project13/maven/git/log/VerboseLogger.java deleted file mode 100644 index c0e528d3..00000000 --- a/src/main/java/pl/project13/maven/git/log/VerboseLogger.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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; - -import org.apache.maven.plugin.Mojo; - -/** - * Bridges logging to standard Maven log adhering to verbosity level. - */ -public class VerboseLogger implements VerboseLog { - - private boolean verbose; - private final Mojo mojo; - - public VerboseLogger(Mojo mojo, boolean verbose) { - this.mojo = mojo; - this.verbose = verbose; - } - - @Override - public void debug(CharSequence content) { - if (verbose) { - mojo.getLog().debug(content); - } - } - - @Override - public void debug(CharSequence content, Throwable error) { - if (verbose) { - mojo.getLog().debug(content, error); - } - } - - @Override - public void debug(Throwable error) { - if (verbose) { - mojo.getLog().debug(error); - } - } - - @Override - public void info(CharSequence content) { - if (verbose) { - mojo.getLog().info(content); - } - } - - @Override - public void info(CharSequence content, Throwable error) { - if (verbose) { - mojo.getLog().info(content, error); - } - } - - @Override - public void info(Throwable error) { - if (verbose) { - mojo.getLog().info(error); - } - } - - @Override - public void warn(CharSequence content) { - if (verbose) { - mojo.getLog().warn(content); - } - } - - @Override - public void warn(CharSequence content, Throwable error) { - if (verbose) { - mojo.getLog().warn(content, error); - } - } - - @Override - public void warn(Throwable error) { - if (verbose) { - mojo.getLog().warn(error); - } - } - - @Override - public void error(CharSequence content) { - if (verbose) { - mojo.getLog().error(content); - } - } - - @Override - public void error(CharSequence content, Throwable error) { - if (verbose) { - mojo.getLog().error(content, error); - } - } - - @Override - public void error(Throwable error) { - if (verbose) { - mojo.getLog().error(error); - } - } - - @Override - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } - - @Override - public boolean isVerbose() { - return verbose; - } - - @Override - public boolean isDebugEnabled() { - return mojo.getLog().isDebugEnabled(); - } - - @Override - public boolean isInfoEnabled() { - return mojo.getLog().isInfoEnabled(); - } - - @Override - public boolean isWarnEnabled() { - return mojo.getLog().isWarnEnabled(); - } - - @Override - public boolean isErrorEnabled() { - return mojo.getLog().isErrorEnabled(); - } -} \ No newline at end of file diff --git a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java index f7fa4dd4..68e17153 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandAbbrevIntegrationTest.java @@ -24,6 +24,7 @@ import org.junit.Test; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; +import pl.project13.maven.git.log.StdOutLoggerBridge; import static org.fest.assertions.Assertions.assertThat; @@ -68,8 +69,7 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .abbrev(2) // 2 is enough to be unique in this small repo .call(); @@ -93,8 +93,7 @@ public void onGitCommitIdsRepo_shouldNoticeThat2CharsIsTooLittleToBeUniqueAndUse try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .abbrev(2) // way too small to be unique in git-commit-id's repo! .call(); diff --git a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java index 593ce589..2feed85e 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandIntegrationTest.java @@ -28,6 +28,7 @@ import org.junit.Test; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; +import pl.project13.maven.git.log.StdOutLoggerBridge; import static java.util.Collections.singletonList; import static org.fest.assertions.Assertions.assertThat; @@ -58,8 +59,7 @@ public void shouldGiveTheCommitIdAndDirtyMarkerWhenNothingElseCanBeFound() throw try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .call(); // then @@ -81,7 +81,7 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFound() throws Exception { try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); + DescribeCommand command = spy(DescribeCommand.on(repo, new StdOutLoggerBridge(true))); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -105,7 +105,7 @@ public void shouldGiveTheCommitIdWhenTagIsOnOtherBranch() throws Exception { try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); + DescribeCommand command = spy(DescribeCommand.on(repo, new StdOutLoggerBridge(true))); doReturn(false).when(command).findDirtyState(any(Repository.class)); DescribeResult res = command.call(); @@ -130,7 +130,7 @@ public void shouldGiveTheCommitIdWhenNothingElseCanBeFoundAndUseAbbrevVersionOfI int abbrevLength = 10; try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = spy(DescribeCommand.on(repo).withMojo(mojo)); + DescribeCommand command = spy(DescribeCommand.on(repo, new StdOutLoggerBridge(true))); doReturn(false).when(command).findDirtyState(any(Repository.class)); command @@ -156,7 +156,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndDirtyMarker() thr try (final Git git = git(); final Repository repo = git.getRepository()) { // when - DescribeCommand command = DescribeCommand.on(repo).withMojo(mojo); + DescribeCommand command = DescribeCommand.on(repo, new StdOutLoggerBridge(true)); command.dirty(DIRTY_SUFFIX); DescribeResult res = command.call(); @@ -181,8 +181,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsIdAndCustomDirtyMarker try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeCommand command = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .dirty(customDirtySuffix); DescribeResult res = command.call(); @@ -208,7 +207,7 @@ public void shouldGiveTagWithDistanceToCurrentCommitAndItsId() throws Exception } // when - DescribeCommand command = DescribeCommand.on(repo).withMojo(mojo); + DescribeCommand command = DescribeCommand.on(repo, new StdOutLoggerBridge(true)); DescribeResult res = command.call(); // then @@ -232,8 +231,7 @@ public void shouldGiveTag() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -258,8 +256,7 @@ public void shouldNotGiveDirtyMarkerWhenOnATagAndDirtyButNoDirtyOptionConfigured // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -286,8 +283,7 @@ public void shouldGiveTagWithCustomDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .dirty(customDirtySuffix) .call(); @@ -311,8 +307,7 @@ public void shouldNotGiveDirtyTagByDefault() throws Exception { try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -333,8 +328,7 @@ public void shouldGiveAnnotatedTagWithDirtyMarker() throws Exception { try (final Git git = git(); final Repository repo = git.getRepository()) { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .dirty(DIRTY_SUFFIX) .abbrev(0) .call(); @@ -362,8 +356,7 @@ public void shouldGiveLightweightTagWithDirtyMarker() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -423,8 +416,7 @@ public void shouldReturnJustTheNearestTagWhenAbbrevIsZero() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .abbrev(zeroAbbrev) .call(); @@ -444,4 +436,4 @@ String abbrev(@NotNull String id) { String abbrev(@NotNull String id, int n) { return id.substring(0, n); } -} +} \ No newline at end of file diff --git a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java index eae8816b..46a2de26 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandOptionsTest.java @@ -20,8 +20,8 @@ import org.eclipse.jgit.lib.Repository; import org.junit.Test; import org.mockito.Matchers; -import pl.project13.maven.git.GitCommitIdMojo; import pl.project13.maven.git.GitDescribeConfig; +import pl.project13.maven.git.log.StdOutLoggerBridge; import static org.mockito.Mockito.*; @@ -34,7 +34,7 @@ public void abbrev_shouldVerifyLengthContract_failOn41() throws Exception { final Repository repo = mock(Repository.class); final int length = 41; - DescribeCommand.on(repo).abbrev(length); + DescribeCommand.on(repo, new StdOutLoggerBridge(true)).abbrev(length); } @Test(expected = IllegalArgumentException.class) @@ -43,7 +43,7 @@ public void abbrev_shouldVerifyLengthContract_failOnMinus12() throws Exception { final Repository repo = mock(Repository.class); final int length = -12; - DescribeCommand.on(repo).abbrev(length); + DescribeCommand.on(repo, new StdOutLoggerBridge(true)).abbrev(length); } @Test @@ -56,7 +56,7 @@ public void apply_shouldDelegateToAllOptions() throws Exception { GitDescribeConfig config = new GitDescribeConfig(true, DEVEL, MATCH, ABBREV, true, true); Repository repo = mock(Repository.class); - DescribeCommand command = DescribeCommand.on(repo).withMojo(new GitCommitIdMojo()); + DescribeCommand command = DescribeCommand.on(repo, new StdOutLoggerBridge(true)); DescribeCommand spiedCommand = spy(command); // when diff --git a/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java index b0c000cc..eb60b2b6 100644 --- a/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/DescribeCommandTagsIntegrationTest.java @@ -25,6 +25,7 @@ import org.junit.Test; import pl.project13.maven.git.AvailableGitTestRepo; import pl.project13.maven.git.GitIntegrationTest; +import pl.project13.maven.git.log.StdOutLoggerBridge; import static org.fest.assertions.Assertions.assertThat; @@ -62,8 +63,7 @@ public void shouldFindAnnotatedTagWithTagsOptionNotGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .call(); // then @@ -86,8 +86,7 @@ public void shouldFindLightweightTagWithTagsOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -111,8 +110,7 @@ public void shouldFindAnnotatedTagWithMatchOptionGiven() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .match("annotated*") .call(); @@ -147,8 +145,7 @@ public void shouldFindNewerTagWhenACommitHasTwoOrMoreTags() throws Exception { // when DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -181,8 +178,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Except wrap.tag().setName(latestTag).call(); DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); @@ -214,8 +210,7 @@ public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() t } DescribeResult res = DescribeCommand - .on(repo) - .withMojo(mojo) + .on(repo, new StdOutLoggerBridge(true)) .tags() .call(); diff --git a/src/test/java/pl/project13/jgit/JGitCommonIntegrationTest.java b/src/test/java/pl/project13/jgit/JGitCommonIntegrationTest.java index cb88b636..96b1a697 100644 --- a/src/test/java/pl/project13/jgit/JGitCommonIntegrationTest.java +++ b/src/test/java/pl/project13/jgit/JGitCommonIntegrationTest.java @@ -19,6 +19,8 @@ import org.junit.Test; import pl.project13.maven.git.GitIntegrationTest; +import pl.project13.maven.git.log.StdOutLoggerBridge; + import static org.fest.assertions.Assertions.assertThat; public class JGitCommonIntegrationTest extends GitIntegrationTest { @@ -29,7 +31,7 @@ public void trimFullTagName_shouldTrimFullTagNamePrefix() throws Exception { String fullName = "refs/tags/v1.0.0"; // when - String simpleName = new JGitCommon().trimFullTagName(fullName); + String simpleName = new JGitCommon(new StdOutLoggerBridge(true)).trimFullTagName(fullName); // then assertThat(simpleName).isEqualTo("v1.0.0"); diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java index 53e0c0f8..8dacad0d 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java @@ -23,6 +23,7 @@ import org.eclipse.jgit.lib.Repository; import org.junit.Before; import org.junit.Test; +import pl.project13.maven.git.log.StdOutLoggerBridge; import java.io.File; import java.io.IOException; @@ -69,7 +70,7 @@ public void setUp() throws Exception { when(mojo.project.getPackaging()).thenReturn("jar"); when(mojo.project.getVersion()).thenReturn("3.3-SNAPSHOT"); - jGitProvider = JGitProvider.on(mojo.lookupGitDirectory(), mojo); + jGitProvider = JGitProvider.on(mojo.lookupGitDirectory(), new StdOutLoggerBridge(true)); } @Test From fed04ca9d4fe250fb64d24e53d6b45012d88db08 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 16:54:46 +0100 Subject: [PATCH 20/22] replaced static collection constructors from Google with standard Java ones --- .../java/pl/project13/jgit/DescribeResult.java | 9 +++++---- src/main/java/pl/project13/jgit/JGitCommon.java | 17 +++++++---------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/main/java/pl/project13/jgit/DescribeResult.java b/src/main/java/pl/project13/jgit/DescribeResult.java index a9b399cd..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. "-") diff --git a/src/main/java/pl/project13/jgit/JGitCommon.java b/src/main/java/pl/project13/jgit/JGitCommon.java index 7285345a..725549ae 100644 --- a/src/main/java/pl/project13/jgit/JGitCommon.java +++ b/src/main/java/pl/project13/jgit/JGitCommon.java @@ -17,9 +17,6 @@ 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.*; import java.util.regex.Pattern; @@ -108,7 +105,7 @@ public String getClosestTagCommitCount(@NotNull Repository repo, RevCommit headC } private Map> getClosestTagAsMap(@NotNull Repository repo){ - Map> mapWithClosestTagOnly = newHashMap(); + Map> mapWithClosestTagOnly = new HashMap<>(); String matchPattern = ".*"; Map> commitIdsToTags = getCommitIdsToTags(repo, true, matchPattern); LinkedHashMap> sortedCommitIdsToTags = sortByDatedRevTag(commitIdsToTags); @@ -144,7 +141,7 @@ public int compare(Map.Entry> m1, Map.Entry> getCommitIdsToTags(@NotNull Repository repo, boolean includeLightweightTags, String matchPattern){ - Map> commitIdsToTags = newHashMap(); + Map> commitIdsToTags = new HashMap<>(); try (RevWalk walk = new RevWalk(repo)) { walk.markStart(walk.parseCommit(repo.resolve("HEAD"))); @@ -176,7 +173,7 @@ protected Map> getCommitIdsToTags(@NotNull Repositor 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) { @@ -190,7 +187,7 @@ protected Map> getCommitIdsToTags(@NotNull Repositor 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) { @@ -214,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); @@ -226,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() { @@ -341,4 +338,4 @@ private void seeAllParents(@NotNull RevWalk revWalk, RevCommit child, @NotNull S } } -} +} \ No newline at end of file From 01ee123a335c559cb47865c680a886f632d103ef Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 17:24:19 +0100 Subject: [PATCH 21/22] replaced MojoExecutionException with GitCommitIdExecutionException - plugin-specific exception to address Michael comment about modularization (#92) --- .../git/GitCommitIdExecutionException.java | 45 ++++ .../project13/maven/git/GitCommitIdMojo.java | 247 +++++++++--------- .../project13/maven/git/GitDataProvider.java | 55 ++-- .../pl/project13/maven/git/JGitProvider.java | 71 +++-- .../maven/git/NativeGitProvider.java | 49 ++-- .../maven/git/GitCommitIdMojoTest.java | 2 +- 6 files changed, 260 insertions(+), 209 deletions(-) create mode 100644 src/main/java/pl/project13/maven/git/GitCommitIdExecutionException.java 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 b9b7f1d3..d515f5cb 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -309,72 +309,76 @@ public class GitCommitIdMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException { - // Set the verbose setting: now it should be correctly loaded from maven. - log.setVerbose(verbose); - - if (skip) { - log.info("skip is enabled, skipping execution!"); - return; - } + try { + // Set the verbose setting: now it should be correctly loaded from maven. + log.setVerbose(verbose); - 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!"); + if (skip) { + log.info("skip is enabled, skipping execution!"); return; } - } - if (isPomProject(project) && skipPoms) { - log.info("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(); - if (failOnNoGitDirectory && !directoryExists(dotGitDirectory)) { - throw new MojoExecutionException(".git directory is not 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.info("dotGitDirectory {}", dotGitDirectory.getAbsolutePath()); - } else { - log.info("dotGitDirectory is null, aborting execution!"); - return; - } + if (gitDescribe == null) { + gitDescribe = new GitDescribeConfig(); + } - 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; + 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) { - handlePluginFailure(e); + } catch (GitCommitIdExecutionException e) { + throw new MojoExecutionException(e.getMessage(), e); } } @@ -430,14 +434,14 @@ 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 { log.error(e.getMessage(), e); } @@ -464,11 +468,11 @@ private void appendPropertiesToReactorProjects(@NotNull Properties properties, @ * * @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 { @@ -530,7 +534,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 { @@ -538,22 +542,26 @@ 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, log) - .setPrefixDot(prefixDot) - .setAbbrevLength(abbrevLength) - .setDateFormat(dateFormat) - .setDateFormatTimeZone(dateFormatTimeZone) - .setGitDescribe(gitDescribe) - .setCommitIdGenerationMode(commitIdGenerationModeEnum); - - 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, log) .setPrefixDot(prefixDot) @@ -566,67 +574,68 @@ void loadGitDataWithJGit(@NotNull Properties properties) throws IOException, Moj 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.info("Reading existing json file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); + try { + if (isJsonFormat) { + log.info("Reading existing json file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); - persistedProperties = readJsonProperties( gitPropsFile ); - } - else { - log.info("Reading existing properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), 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.info("Cannot read properties file [{}] (for module {})...", gitPropsFile.getAbsolutePath(), 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), StandardCharsets.UTF_8); - 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"); + try { + outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), StandardCharsets.UTF_8); + 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.info("Properties file [{}] is up-to-date (for module {})...", gitPropsFile.getAbsolutePath(), project.getName()); + } catch (IOException e) { + throw new GitCommitIdExecutionException(e); } } diff --git a/src/main/java/pl/project13/maven/git/GitDataProvider.java b/src/main/java/pl/project13/maven/git/GitDataProvider.java index 2de5e485..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; @@ -81,27 +80,27 @@ public GitDataProvider setDateFormatTimeZone(String dateFormatTimeZone){ return this; } - protected abstract void init() throws MojoExecutionException; - protected abstract String getBuildAuthorName(); - protected abstract String getBuildAuthorEmail(); - protected abstract void prepareGitToExtractMoreDetailedRepoInformation() 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()); @@ -127,7 +126,7 @@ public void loadGitData(@NotNull Properties properties) throws IOException, Mojo break; } default: { - throw new MojoExecutionException("Unsupported commitIdGenerationMode: " + commitIdGenerationMode); + throw new GitCommitIdExecutionException("Unsupported commitIdGenerationMode: " + commitIdGenerationMode); } } // git.commit.id.abbrev @@ -157,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()); @@ -166,9 +165,9 @@ 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(String.format("Abbreviated commit id length must be between 2 and 40, inclusive! Was [%s]. ", 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)."); } } @@ -180,7 +179,7 @@ void validateAbbrevLength(int abbrevLength) throws MojoExecutionException { * @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 { @@ -205,7 +204,7 @@ private boolean runningOnBuildServer(Map env) { * 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 { + 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."); diff --git a/src/main/java/pl/project13/maven/git/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java index a0fec598..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; @@ -67,97 +66,99 @@ public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBrid } @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 prepareGitToExtractMoreDetailedRepoInformation() 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 { - return git.getBranch(); + protected String getBranchName() throws GitCommitIdExecutionException { + try { + return git.getBranch(); + } catch (IOException e) { + throw new GitCommitIdExecutionException(e); + } } @Override - protected String getGitDescribe() throws MojoExecutionException { + protected String getGitDescribe() throws GitCommitIdExecutionException { return getGitDescribe(git); } @Override - protected String getCommitId() { + protected String getCommitId() throws GitCommitIdExecutionException { return headCommit.getName(); } @Override - protected String getAbbrevCommitId() throws MojoExecutionException { + 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() { + protected String getCommitAuthorName() throws GitCommitIdExecutionException { return headCommit.getAuthorIdent().getName(); } @Override - protected String getCommitAuthorEmail() { + protected String getCommitAuthorEmail() throws GitCommitIdExecutionException { return headCommit.getAuthorIdent().getEmailAddress(); } @Override - protected String getCommitMessageFull() { + protected String getCommitMessageFull() throws GitCommitIdExecutionException { return headCommit.getFullMessage().trim(); } @Override - protected String getCommitMessageShort() { + 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(); @@ -165,12 +166,12 @@ protected String getCommitTime() { } @Override - protected String getRemoteOriginUrl() throws MojoExecutionException { + 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(); @@ -183,7 +184,7 @@ protected String getTags() throws MojoExecutionException { } @Override - protected String getClosestTagName() throws MojoExecutionException { + protected String getClosestTagName() throws GitCommitIdExecutionException { Repository repo = getGitRepository(); try { return jGitCommon.getClosestTagName(repo); @@ -194,7 +195,7 @@ protected String getClosestTagName() throws MojoExecutionException { } @Override - protected String getClosestTagCommitCount() throws MojoExecutionException { + protected String getClosestTagCommitCount() throws GitCommitIdExecutionException { Repository repo = getGitRepository(); try { return jGitCommon.getClosestTagCommitCount(repo, headCommit); @@ -211,8 +212,7 @@ 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, log) @@ -222,23 +222,22 @@ protected void finalCleanUp() { 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(); @@ -249,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; @@ -265,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 2d52ebcd..660cb629 100644 --- a/src/main/java/pl/project13/maven/git/NativeGitProvider.java +++ b/src/main/java/pl/project13/maven/git/NativeGitProvider.java @@ -22,7 +22,6 @@ 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; @@ -51,17 +50,17 @@ public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull Logge 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)); } } @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) { @@ -73,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) { @@ -85,22 +84,22 @@ protected String getBuildAuthorEmail() { } @Override - protected void prepareGitToExtractMoreDetailedRepoInformation() 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) { + 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) { + } 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")) { @@ -113,7 +112,7 @@ private String getBranch(File canonical) { } @Override - protected String getGitDescribe() { + protected String getGitDescribe() throws GitCommitIdExecutionException { final String argumentsForGitDescribe = getArgumentsForGitDescribe(gitDescribe); return runQuietGitCommand(canonical, "describe" + argumentsForGitDescribe); } @@ -150,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(); @@ -169,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) { @@ -222,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"); @@ -231,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"); @@ -245,7 +244,7 @@ private String getOriginRemote(File directory) throws MojoExecutionException { if (trimmed.startsWith("origin")) { String[] split = trimmed.split("\\s+"); if (split.length != REMOTE_COLS - 1) { // because (fetch/push) was trimmed - throw new MojoExecutionException("Unsupported GIT output (verbose remote address): " + line); + throw new GitCommitIdExecutionException("Unsupported GIT output (verbose remote address): " + line); } remoteUrl = split[1]; } diff --git a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java index 8dacad0d..f9a33400 100644 --- a/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java +++ b/src/test/java/pl/project13/maven/git/GitCommitIdMojoTest.java @@ -218,7 +218,7 @@ public void shouldSkipDescribeWhenConfiguredToDoSo() throws Exception { } @Test - public void shouldUseJenkinsBranchInfoWhenAvailable() throws IOException { + public void shouldUseJenkinsBranchInfoWhenAvailable() throws GitCommitIdExecutionException, IOException { // given Repository git = mock(Repository.class); Map env = Maps.newHashMap(); From 2e9482bd74fde9144c67c85680581c0b3844a130 Mon Sep 17 00:00:00 2001 From: Aliaksandr Autayeu Date: Sun, 3 Jan 2016 17:45:22 +0100 Subject: [PATCH 22/22] adhere to project encoding while reading-writing property files --- .../project13/maven/git/GitCommitIdMojo.java | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java index d515f5cb..a14c33e5 100644 --- a/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java +++ b/src/main/java/pl/project13/maven/git/GitCommitIdMojo.java @@ -44,6 +44,7 @@ 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.Date; @@ -101,7 +102,7 @@ public class GitCommitIdMojo extends AbstractMojo { /** * The Maven Session Object. */ - @Parameter(required = true, readonly = true) + @Parameter(property = "session", required = true, readonly = true) private MavenSession session; /** @@ -304,6 +305,11 @@ public class GitCommitIdMojo extends AbstractMojo { */ private Properties properties; + /** + * Charset to read-write project sources. + */ + private Charset sourceCharset = StandardCharsets.UTF_8; + @NotNull private final LoggerBridge log = new MavenLoggerBridge(this, false); @@ -313,6 +319,14 @@ public void execute() throws MojoExecutionException { // Set the verbose setting: now it should be correctly loaded from maven. log.setVerbose(verbose); + // 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 (skip) { log.info("skip is enabled, skipping execution!"); return; @@ -616,7 +630,7 @@ void maybeGeneratePropertiesFile(@NotNull Properties localProperties, File base, boolean threw = true; try { - outputWriter = new OutputStreamWriter(new FileOutputStream(gitPropsFile), StandardCharsets.UTF_8); + 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(); @@ -666,7 +680,7 @@ private boolean directoryExists(@Nullable File fileLocation) { } @SuppressWarnings( "resource" ) - static Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFileException { + private Properties readJsonProperties(@NotNull File jsonFile) throws CannotReadFileException { final HashMap propertiesMap; { @@ -678,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, StandardCharsets.UTF_8); + final InputStreamReader reader = new InputStreamReader(fis, sourceCharset); closeable = reader; final ObjectMapper mapper = new ObjectMapper(); @@ -706,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 { @@ -715,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, StandardCharsets.UTF_8); + final InputStreamReader reader = new InputStreamReader(fis, sourceCharset); closeable = reader; final Properties retVal = new Properties();