├── .mvn ├── maven.config ├── jvm.config ├── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties └── extensions.xml.template ├── git-versioner-maven-plugin ├── src │ ├── test │ │ ├── resources │ │ │ ├── mockito-extensions │ │ │ │ └── org.mockito.plugins.MockMaker │ │ │ ├── project-to-test │ │ │ │ └── pom.xml │ │ │ └── project-to-tag │ │ │ │ └── pom.xml │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── manikmagar │ │ │ └── maven │ │ │ └── versioner │ │ │ └── plugin │ │ │ ├── mojo │ │ │ ├── params │ │ │ │ ├── VersionConfigParamTest.java │ │ │ │ ├── InitialVersionParamTest.java │ │ │ │ └── VersionKeywordsParamTest.java │ │ │ ├── ProjectMojoRule.java │ │ │ ├── AbstractVersionerMojoTest.java │ │ │ └── HelpMojo.java │ │ │ ├── SetTest.java │ │ │ ├── AbstractMojoTest.java │ │ │ ├── TagTest.java │ │ │ ├── PrintTest.java │ │ │ └── VersionCommitTest.java │ └── main │ │ ├── resources │ │ └── git-versioner-maven-core.properties │ │ └── java │ │ └── com │ │ └── github │ │ └── manikmagar │ │ └── maven │ │ └── versioner │ │ └── plugin │ │ └── mojo │ │ ├── Print.java │ │ ├── Set.java │ │ ├── AbstractVersionerMojo.java │ │ ├── params │ │ ├── VersionConfigParam.java │ │ ├── InitialVersionParam.java │ │ └── VersionKeywordsParam.java │ │ ├── Tag.java │ │ └── VersionCommit.java └── pom.xml ├── .sdkmanrc ├── git-versioner-maven-core ├── src │ ├── main │ │ ├── resources │ │ │ └── git-versioner-maven-core.properties │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── manikmagar │ │ │ └── maven │ │ │ └── versioner │ │ │ └── core │ │ │ ├── version │ │ │ ├── VersionComponentType.java │ │ │ ├── Versioner.java │ │ │ ├── VersionStrategy.java │ │ │ ├── AbstractVersionStrategy.java │ │ │ ├── Version.java │ │ │ ├── SemVerStrategy.java │ │ │ └── VersionPatternStrategy.java │ │ │ ├── Util.java │ │ │ ├── GitVersionerException.java │ │ │ ├── git │ │ │ ├── GitTag.java │ │ │ ├── JGit.java │ │ │ └── JGitVersioner.java │ │ │ └── params │ │ │ ├── VersionPattern.java │ │ │ ├── VersionConfig.java │ │ │ ├── InitialVersion.java │ │ │ └── VersionKeywords.java │ └── test │ │ └── java │ │ └── com │ │ └── github │ │ └── manikmagar │ │ └── maven │ │ └── versioner │ │ ├── core │ │ └── git │ │ │ └── JGitVersionerTest.java │ │ └── plugin │ │ └── mojo │ │ └── params │ │ ├── VersionKeywordsTest.java │ │ ├── VersionConfigTest.java │ │ └── InitialVersionTest.java └── pom.xml ├── git-versioner-maven-extension ├── src │ ├── test │ │ ├── resources │ │ │ ├── project-with-extension │ │ │ │ ├── .mvn │ │ │ │ │ ├── 1.git-versioner.extensions.properties │ │ │ │ │ ├── 3.git-versioner.extensions.properties │ │ │ │ │ ├── 2.git-versioner.extensions.properties │ │ │ │ │ └── extensions.xml │ │ │ │ └── pom.xml │ │ │ ├── multi-module-project │ │ │ │ ├── cli │ │ │ │ │ ├── src │ │ │ │ │ │ └── main │ │ │ │ │ │ │ └── java │ │ │ │ │ │ │ └── com │ │ │ │ │ │ │ └── github │ │ │ │ │ │ │ └── manikmagar │ │ │ │ │ │ │ └── Main.java │ │ │ │ │ └── pom.xml │ │ │ │ ├── lib │ │ │ │ │ ├── src │ │ │ │ │ │ └── main │ │ │ │ │ │ │ └── java │ │ │ │ │ │ │ └── com │ │ │ │ │ │ │ └── github │ │ │ │ │ │ │ └── manikmagar │ │ │ │ │ │ │ └── Main.java │ │ │ │ │ └── pom.xml │ │ │ │ ├── .mvn │ │ │ │ │ └── extensions.xml │ │ │ │ └── pom.xml │ │ │ ├── parent-child-project │ │ │ │ ├── cli │ │ │ │ │ ├── src │ │ │ │ │ │ └── main │ │ │ │ │ │ │ └── java │ │ │ │ │ │ │ └── com │ │ │ │ │ │ │ └── github │ │ │ │ │ │ │ └── manikmagar │ │ │ │ │ │ │ └── Main.java │ │ │ │ │ └── pom.xml │ │ │ │ ├── lib │ │ │ │ │ ├── src │ │ │ │ │ │ └── main │ │ │ │ │ │ │ └── java │ │ │ │ │ │ │ └── com │ │ │ │ │ │ │ └── github │ │ │ │ │ │ │ └── manikmagar │ │ │ │ │ │ │ └── Main.java │ │ │ │ │ └── pom.xml │ │ │ │ ├── pom.xml │ │ │ │ └── .mvn │ │ │ │ │ └── extensions.xml │ │ │ └── project-with-extension-plugin │ │ │ │ ├── .mvn │ │ │ │ └── extensions.xml │ │ │ │ └── pom.xml │ │ └── java │ │ │ └── com │ │ │ └── github │ │ │ └── manikmagar │ │ │ └── maven │ │ │ └── versioner │ │ │ └── extension │ │ │ └── ExtensionTestIT.java │ └── main │ │ ├── resources │ │ └── git-versioner-maven-extension.properties │ │ └── java │ │ └── com │ │ └── github │ │ └── manikmagar │ │ └── maven │ │ └── versioner │ │ └── extension │ │ ├── GAV.java │ │ ├── Util.java │ │ └── GitVersionerModelProcessor.java └── pom.xml ├── .gitignore ├── .github ├── dependabot.yml └── workflows │ ├── build.yml │ └── release.yml ├── LICENSE ├── jreleaser.yml ├── CONTRIBUTING.adoc ├── mvnw.cmd ├── README.adoc ├── mvnw └── pom.xml /.mvn/maven.config: -------------------------------------------------------------------------------- 1 | -B -------------------------------------------------------------------------------- /.mvn/jvm.config: -------------------------------------------------------------------------------- 1 | -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker: -------------------------------------------------------------------------------- 1 | mock-maker-inline -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manikmagar/git-versioner-maven-extension/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.sdkmanrc: -------------------------------------------------------------------------------- 1 | # Enable auto-env through the sdkman_auto_env config 2 | # Add key=value pairs of SDKs to use below 3 | java=11.0.17-tem 4 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/resources/git-versioner-maven-core.properties: -------------------------------------------------------------------------------- 1 | projectGroupId=${project.groupId} 2 | projectArtifactId=${project.artifactId} 3 | projectVersion=${project.version} -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/resources/git-versioner-maven-core.properties: -------------------------------------------------------------------------------- 1 | projectGroupId=${project.groupId} 2 | projectArtifactId=${project.artifactId} 3 | projectVersion=${project.version} -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension/.mvn/1.git-versioner.extensions.properties: -------------------------------------------------------------------------------- 1 | gv.initialVersion.major=1 2 | gv.initialVersion.minor=3 3 | gv.initialVersion.patch=4 -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/main/resources/git-versioner-maven-extension.properties: -------------------------------------------------------------------------------- 1 | projectGroupId=${project.groupId} 2 | projectArtifactId=${project.artifactId} 3 | projectVersion=${project.version} -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension/.mvn/3.git-versioner.extensions.properties: -------------------------------------------------------------------------------- 1 | gv.initialVersion.major=1 2 | gv.initialVersion.minor=3 3 | gv.initialVersion.patch=4 4 | 5 | gv.pattern.pattern=%M.%m.%p+%h -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/VersionComponentType.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.version; 2 | 3 | public enum VersionComponentType { 4 | MAJOR, MINOR, PATCH, COMMIT; 5 | } 6 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/Versioner.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.core.version; 3 | 4 | public interface Versioner { 5 | public VersionStrategy version(); 6 | } 7 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/cli/src/main/java/com/github/manikmagar/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/lib/src/main/java/com/github/manikmagar/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/cli/src/main/java/com/github/manikmagar/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/lib/src/main/java/com/github/manikmagar/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension/.mvn/2.git-versioner.extensions.properties: -------------------------------------------------------------------------------- 1 | gv.initialVersion.major=0 2 | gv.initialVersion.minor=0 3 | gv.initialVersion.patch=0 4 | gv.keywords.majorKey=[BIG] 5 | gv.keywords.minorKey=[MEDIUM] 6 | gv.keywords.patchKey=[SMALL] 7 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/Util.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core; 2 | 3 | public final class Util { 4 | 5 | private Util() { 6 | } 7 | 8 | public static void mustBePositive(int number, String label) { 9 | if (number < 0) 10 | throw new IllegalArgumentException(label + " must be a positive number"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/GitVersionerException.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core; 2 | 3 | public class GitVersionerException extends RuntimeException { 4 | public GitVersionerException(String message, Exception cause) { 5 | super(message, cause); 6 | } 7 | 8 | public GitVersionerException(String message) { 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | pom.xml.tag 3 | pom.xml.releaseBackup 4 | pom.xml.versionsBackup 5 | pom.xml.next 6 | release.properties 7 | dependency-reduced-pom.xml 8 | buildNumber.properties 9 | .mvn/timing.properties 10 | # https://github.com/takari/maven-wrapper#usage-without-binary-jar 11 | .mvn/wrapper/maven-wrapper.jar 12 | .idea 13 | .DS_Store 14 | 15 | #git-versioner intermediate pom 16 | **/.git-versioner.pom.xml 17 | /.mvn/extensions.xml 18 | **/*.iml 19 | /jreleaser-1.4.0-SNAPSHOT/ 20 | out 21 | .flattened-pom.xml -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.github.manikmagar 5 | git-versioner-maven-extension 6 | V-LATEST-SNAPSHOT 7 | 8 | 9 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension/.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.github.manikmagar 5 | git-versioner-maven-extension 6 | V-LATEST-SNAPSHOT 7 | 8 | 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "maven" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension-plugin/.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.github.manikmagar 5 | git-versioner-maven-extension 6 | V-LATEST-SNAPSHOT 7 | 8 | 9 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | versioner-maven-extension-test 9 | 0.0.0 10 | jar 11 | 12 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionConfigParamTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class VersionConfigParamTest { 9 | 10 | @Test 11 | public void toVersionConfig() { 12 | assertThat(new VersionConfigParam()).extracting(VersionConfigParam::toVersionConfig) 13 | .isEqualTo(new VersionConfig()); 14 | } 15 | } -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.manikmagar 5 | parent-test-pom 6 | pom 7 | 0 8 | parent-test-pom 9 | 10 | 11 | lib 12 | cli 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/VersionStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.version; 2 | 3 | /** 4 | * Common interface for versioning strategies. 5 | */ 6 | public interface VersionStrategy { 7 | String strategyName(); 8 | String toVersionString(); 9 | 10 | /** 11 | * Increments the version component 12 | * 13 | * @param type 14 | * {@link VersionComponentType} to increment 15 | * @param hashRef 16 | * {@link String} hash representing the change log 17 | */ 18 | void increment(VersionComponentType type, String hashRef); 19 | String getHash(); 20 | String getHashShort(); 21 | String getBranchName(); 22 | Version getVersion(); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | lib 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 11 13 | 11 14 | UTF-8 15 | 16 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/.mvn/extensions.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | com.github.manikmagar 5 | git-versioner-maven-extension 6 | V-LATEST-SNAPSHOT 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.mvn/extensions.xml.template: -------------------------------------------------------------------------------- 1 | 3 | 4 | 9 | 10 | com.github.manikmagar 11 | git-versioner-maven-extension 12 | V-LATEST-SNAPSHOT 13 | 14 | 15 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/Print.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin.mojo; 3 | 4 | import org.apache.maven.plugin.MojoExecutionException; 5 | import org.apache.maven.plugin.MojoFailureException; 6 | import org.apache.maven.plugins.annotations.LifecyclePhase; 7 | import org.apache.maven.plugins.annotations.Mojo; 8 | 9 | /** 10 | * Generate a version from git commit history and prints it to maven build logs. 11 | */ 12 | @Mojo(name = "print", defaultPhase = LifecyclePhase.VALIDATE) 13 | public class Print extends AbstractVersionerMojo { 14 | 15 | @Override 16 | public void execute() throws MojoExecutionException, MojoFailureException { 17 | getLog().info(getVersioner().version().toString()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/InitialVersionParamTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.InitialVersion; 4 | import org.assertj.core.api.Assertions; 5 | import org.junit.Test; 6 | 7 | public class InitialVersionParamTest { 8 | 9 | @Test 10 | public void toInitialVersion() { 11 | Assertions.assertThat(new InitialVersionParam(1, 2, 3)).extracting(InitialVersionParam::toInitialVersion) 12 | .isEqualTo(new InitialVersion(1, 2, 3)); 13 | } 14 | 15 | @Test 16 | public void createNewVersionParam() { 17 | Assertions.assertThat(new InitialVersionParam(1, 2, 3)).extracting("major", "minor", "patch").containsExactly(1, 18 | 2, 3); 19 | } 20 | } -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/git/GitTag.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.git; 2 | 3 | import org.eclipse.jgit.lib.Ref; 4 | 5 | import java.io.File; 6 | 7 | public class GitTag { 8 | 9 | private GitTag() { 10 | 11 | } 12 | 13 | public static String create(File basePath, final String tagName, final String tagMessage) { 14 | return JGit.executeOperation(basePath, git -> { 15 | Ref tag = git.tag().setName(tagName).setMessage(tagMessage).call(); 16 | return String.format("%s@%s", tag.getName(), tag.getObjectId().getName()); 17 | }); 18 | } 19 | 20 | public static boolean exists(File basePath, final String tagName) { 21 | return JGit.executeOperation(basePath, git -> null != git.getRepository().findRef("refs/tags/" + tagName)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/lib/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | lib 8 | 9 | com.github.manikmagar 10 | parent-test-pom 11 | 0 12 | 13 | 14 | 15 | 11 16 | 11 17 | UTF-8 18 | 19 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/params/VersionPattern.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.params; 2 | 3 | import java.util.Objects; 4 | 5 | public class VersionPattern { 6 | 7 | public static final String GV_PATTERN_PATTERN = "gv.pattern.pattern"; 8 | private String pattern = ""; 9 | public String getPattern() { 10 | return pattern; 11 | } 12 | 13 | public void setPattern(String pattern) { 14 | this.pattern = pattern; 15 | } 16 | 17 | @Override 18 | public boolean equals(Object o) { 19 | if (this == o) 20 | return true; 21 | if (!(o instanceof VersionPattern)) 22 | return false; 23 | VersionPattern that = (VersionPattern) o; 24 | return Objects.equals(getPattern(), that.getPattern()); 25 | } 26 | 27 | @Override 28 | public int hashCode() { 29 | return Objects.hash(getPattern()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.manikmagar 5 | multi-module-parent 6 | pom 7 | 1.0-SNAPSHOT 8 | multi-module-parent 9 | http://maven.apache.org 10 | 11 | 12 | lib 13 | cli 14 | 15 | 16 | 17 | 18 | junit 19 | junit 20 | 3.8.1 21 | test 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/multi-module-project/cli/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | cli 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 11 13 | 11 14 | UTF-8 15 | 16 | 17 | 18 | com.github.manikmagar 19 | lib 20 | ${project.version} 21 | 22 | 23 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/Set.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin.mojo; 3 | 4 | import org.apache.maven.plugin.MojoExecutionException; 5 | import org.apache.maven.plugins.annotations.LifecyclePhase; 6 | import org.apache.maven.plugins.annotations.Mojo; 7 | 8 | import java.io.File; 9 | 10 | /** Generate a version from git commit history and set it in the project pom. */ 11 | @Mojo(name = "set", defaultPhase = LifecyclePhase.INITIALIZE) 12 | public class Set extends AbstractVersionerMojo { 13 | 14 | @Override 15 | public void execute() throws MojoExecutionException { 16 | File gitVersionerPom = mavenProject.getBasedir().toPath().resolve(".git-versioner.pom.xml").toFile(); 17 | if (gitVersionerPom.exists()) { 18 | // Extension is in-force, user the generated pom 19 | mavenProject.setPomFile(gitVersionerPom); 20 | } else { 21 | throw new MojoExecutionException("Cannot find .git-versioner.pom.xml"); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /git-versioner-maven-core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | git-versioner-maven-parent 9 | V-LATEST-SNAPSHOT 10 | 11 | 12 | git-versioner-maven-core 13 | Git Versioner Maven Core 14 | 15 | 16 | 17 | org.eclipse.jgit 18 | org.eclipse.jgit 19 | 20 | 21 | com.github.manikmagar 22 | semver4j 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/project-with-extension-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | versioner-maven-extension-test 9 | 0.0.0 10 | jar 11 | 12 | 13 | 14 | 15 | com.github.manikmagar 16 | git-versioner-maven-plugin 17 | V-LATEST-SNAPSHOT 18 | 19 | 20 | set-version 21 | 22 | set 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 19 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/AbstractVersionStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.version; 2 | 3 | public abstract class AbstractVersionStrategy implements VersionStrategy { 4 | 5 | private final String branchName; 6 | private String hash; 7 | 8 | protected AbstractVersionStrategy(String branchName, String hash) { 9 | this.branchName = branchName; 10 | this.hash = hash; 11 | } 12 | 13 | public String getBranchName() { 14 | return branchName; 15 | } 16 | 17 | public String getHash() { 18 | return hash; 19 | } 20 | 21 | @Override 22 | public String getHashShort() { 23 | return hash != null ? hash.substring(0, 7) : null; 24 | } 25 | 26 | public void setHash(String hash) { 27 | this.hash = hash; 28 | } 29 | 30 | @Override 31 | public String strategyName() { 32 | return ""; 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return String.format("%s [branch: %s, version: %s, hash: %s]", getClass().getSimpleName(), getBranchName(), 38 | toVersionString(), hash); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/resources/parent-child-project/cli/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | cli 7 | 8 | com.github.manikmagar 9 | parent-test-pom 10 | 0 11 | 12 | 13 | 11 14 | 11 15 | UTF-8 16 | 17 | 18 | 19 | com.github.manikmagar 20 | lib 21 | ${project.version} 22 | 23 | 24 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/SetTest.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin; 3 | 4 | import java.io.File; 5 | 6 | import org.apache.maven.plugin.MojoExecutionException; 7 | import org.junit.Test; 8 | 9 | import com.github.manikmagar.maven.versioner.plugin.mojo.Set; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.assertj.core.api.Assertions.catchThrowableOfType; 13 | 14 | public class SetTest extends AbstractMojoTest { 15 | 16 | /** 17 | * @throws Exception 18 | * if any 19 | */ 20 | @Test 21 | public void testSetVersion() throws Exception { 22 | File pom = new File("target/test-classes/project-to-test/"); 23 | assertThat(pom).as("POM file").isNotNull().exists(); 24 | 25 | Set set = (Set) rule.lookupConfiguredMojo(pom, "set"); 26 | assertThat(set).isNotNull(); 27 | MojoExecutionException exception = catchThrowableOfType(() -> set.execute(), MojoExecutionException.class); 28 | assertThat(exception).isNotNull().hasMessage("Cannot find .git-versioner.pom.xml"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Manik Magar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/AbstractMojoTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin; 2 | 3 | import org.apache.maven.execution.MavenSession; 4 | import org.apache.maven.plugin.Mojo; 5 | import org.apache.maven.plugin.MojoExecution; 6 | import org.apache.maven.plugin.testing.MojoRule; 7 | import org.codehaus.plexus.component.configurator.ComponentConfigurationException; 8 | import org.junit.Rule; 9 | 10 | import com.github.manikmagar.maven.versioner.plugin.mojo.ProjectMojoRule; 11 | 12 | public abstract class AbstractMojoTest { 13 | 14 | protected MavenSession mavenSession; 15 | 16 | @Rule 17 | public MojoRule rule = new ProjectMojoRule() { 18 | @Override 19 | protected void before() throws Throwable { 20 | } 21 | 22 | @Override 23 | protected void after() { 24 | } 25 | 26 | @Override 27 | public Mojo lookupConfiguredMojo(MavenSession session, MojoExecution execution) 28 | throws Exception, ComponentConfigurationException { 29 | mavenSession = session; 30 | return super.lookupConfiguredMojo(session, execution); 31 | } 32 | }; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/resources/project-to-test/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | versioner-maven-plugin-test 9 | 0.0.0 10 | jar 11 | Test MyMojo 12 | 13 | 14 | 15 | 16 | com.github.manikmagar 17 | git-versioner-maven-plugin 18 | V-LATEST-SNAPSHOT 19 | 20 | 21 | 22 | 1 23 | 3 24 | 4 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionKeywordsParamTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.VersionKeywords; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class VersionKeywordsParamTest { 9 | 10 | @Test 11 | public void newVersionKeywords() { 12 | assertThat(new VersionKeywords("[big]", "[medium]", "[small]", false)) 13 | .extracting("majorKey", "minorKey", "patchKey").containsExactly("[big]", "[medium]", "[small]"); 14 | } 15 | 16 | @Test 17 | public void toDefaultVersionKeywords() { 18 | assertThat(new VersionKeywordsParam()).extracting(VersionKeywordsParam::toVersionKeywords) 19 | .isEqualTo(new VersionKeywords()); 20 | } 21 | @Test 22 | public void toCustomVersionKeywords() { 23 | assertThat(new VersionKeywordsParam("[big]", "[medium]", "[small]", false)) 24 | .extracting(VersionKeywordsParam::toVersionKeywords) 25 | .isEqualTo(new VersionKeywords("[big]", "[medium]", "[small]", false)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/ProjectMojoRule.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo; 2 | 3 | import java.io.File; 4 | import java.io.FileReader; 5 | 6 | import org.apache.maven.model.Model; 7 | import org.apache.maven.model.io.xpp3.MavenXpp3Reader; 8 | import org.apache.maven.plugin.testing.MojoRule; 9 | import org.apache.maven.project.MavenProject; 10 | 11 | public class ProjectMojoRule extends MojoRule { 12 | 13 | @Override 14 | public MavenProject readMavenProject(File basedir) throws Exception { 15 | // Manual project instantiation is to avoid 16 | // Invalid repository system session: Local Repository Manager is not set. 17 | // when using default implementation. 18 | File pom = new File(basedir, "pom.xml"); 19 | MavenXpp3Reader mavenReader = new MavenXpp3Reader(); 20 | try (FileReader reader = new FileReader(pom)) { 21 | Model model = mavenReader.read(reader); 22 | model.setPomFile(pom); 23 | MavenProject mavenProject = new MavenProject(model); 24 | mavenProject.setFile(pom); 25 | return mavenProject; 26 | } catch (Exception e) { 27 | throw new RuntimeException("Couldn't read pom: " + pom); 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/git/JGit.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.git; 2 | 3 | import com.github.manikmagar.maven.versioner.core.GitVersionerException; 4 | import org.eclipse.jgit.api.Git; 5 | import org.eclipse.jgit.lib.Repository; 6 | import org.eclipse.jgit.storage.file.FileRepositoryBuilder; 7 | 8 | import java.io.File; 9 | 10 | public class JGit { 11 | 12 | private JGit() { 13 | } 14 | 15 | public static R executeOperation(File basePath, Operation work) throws GitVersionerException { 16 | try (Repository repository = new FileRepositoryBuilder().readEnvironment().findGitDir(basePath).build()) { 17 | try (Git git = new Git(repository)) { 18 | return work.apply(git); 19 | } 20 | } catch (Exception e) { 21 | throw new GitVersionerException(e.getMessage(), e); 22 | } 23 | } 24 | 25 | /** 26 | * Find local git dir by scanning upwards to find .git dir 27 | */ 28 | public static String findGitDir(String basePath) { 29 | try (Repository repository = new FileRepositoryBuilder().readEnvironment().findGitDir(new File(basePath)) 30 | .build()) { 31 | return repository.getDirectory().getAbsolutePath(); 32 | } catch (Exception e) { 33 | throw new GitVersionerException(e.getMessage(), e); 34 | } 35 | } 36 | 37 | @FunctionalInterface 38 | public interface Operation { 39 | R apply(T t) throws Exception; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | push: 4 | branches: 5 | - '**' 6 | pull_request: 7 | branches: 8 | - 'main' 9 | 10 | env: 11 | JAVA_VERSION: '11' 12 | JAVA_DISTRO: 'zulu' 13 | 14 | jobs: 15 | build: 16 | name: Build 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v3 20 | with: 21 | fetch-depth: '0' 22 | - name: Setup Java 23 | uses: actions/setup-java@v3 24 | with: 25 | java-version: ${{ env.JAVA_VERSION }} 26 | distribution: ${{ env.JAVA_DISTRO }} 27 | cache: maven 28 | - name: Verify 29 | run: ./mvnw verify -Prun-its 30 | - name: Upload Test Results 31 | if: always() 32 | uses: actions/upload-artifact@v3 33 | with: 34 | name: artifacts 35 | path: ./*/*/surefire-reports/*.xml 36 | publish-test-results: 37 | name: "Publish Tests Results" 38 | needs: build 39 | runs-on: ubuntu-latest 40 | permissions: 41 | checks: write 42 | pull-requests: write 43 | contents: read 44 | issues: read 45 | if: always() 46 | steps: 47 | - name: Download Artifacts 48 | uses: actions/download-artifact@v3 49 | with: 50 | path: artifacts 51 | - name: Publish Test Results 52 | uses: EnricoMi/publish-unit-test-result-action@v2 53 | with: 54 | junit_files: "artifacts/**/*.xml" 55 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/TagTest.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin; 3 | 4 | import java.io.File; 5 | 6 | import org.junit.Test; 7 | 8 | import com.github.manikmagar.maven.versioner.plugin.mojo.Tag; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | public class TagTest extends AbstractMojoTest { 13 | 14 | /** 15 | * @throws Exception 16 | * if any 17 | */ 18 | @Test 19 | public void readDefaultParameters() throws Exception { 20 | File pom = new File("target/test-classes/project-to-test/"); 21 | assertThat(pom).as("POM file").isNotNull().exists(); 22 | Tag tag = (Tag) rule.lookupConfiguredMojo(pom, "tag"); 23 | assertThat(tag).isNotNull(); 24 | assertThat(tag.getTagNamePattern()).isEqualTo("v%v"); 25 | assertThat(tag.getTagMessagePattern()).isEqualTo("Release version %v"); 26 | assertThat(tag.isFailWhenTagExist()).isTrue(); 27 | } 28 | 29 | @Test 30 | public void readPropertiesParameters() throws Exception { 31 | File pom = new File("target/test-classes/project-to-tag/"); 32 | assertThat(pom).as("POM file").isNotNull().exists(); 33 | Tag tag = (Tag) rule.lookupConfiguredMojo(pom, "tag"); 34 | assertThat(tag).isNotNull(); 35 | assertThat(tag.getTagNamePattern()).isEqualTo("version-%v"); 36 | assertThat(tag.getTagMessagePattern()).isEqualTo("Release message %v"); 37 | assertThat(tag.isFailWhenTagExist()).isFalse(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/resources/project-to-tag/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | versioner-maven-plugin-test 9 | 0.0.0 10 | jar 11 | Test MyMojo 12 | 13 | 14 | version-%v 15 | Release message %v 16 | false 17 | 18 | 19 | 20 | 21 | 22 | com.github.manikmagar 23 | git-versioner-maven-plugin 24 | V-LATEST-SNAPSHOT 25 | 26 | 27 | tag 28 | 29 | tag 30 | 31 | 32 | true 33 | v%v 34 | Release version %v 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/test/java/com/github/manikmagar/maven/versioner/core/git/JGitVersionerTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.git; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 4 | import junitparams.JUnitParamsRunner; 5 | import junitparams.Parameters; 6 | import org.assertj.core.util.Files; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | @RunWith(JUnitParamsRunner.class) 13 | public class JGitVersionerTest { 14 | private VersionConfig versionConfig = new VersionConfig(); 15 | private JGitVersioner jGitVersioner = new JGitVersioner(Files.currentFolder(), versionConfig); 16 | 17 | @Test 18 | @Parameters(value = {"Fix: [minor] corrected typo, .*\\[minor\\].*, true", 19 | "[minor] Fix: corrected typo, ^\\[minor\\].*, true", "Fix: [minor] corrected typo, ^\\[minor\\].*, false", 20 | "Update: improved performance, [minor], false"}) 21 | public void testHasValueWithRegex(String commitMessage, String keyword, boolean expected) { 22 | versionConfig.getKeywords().setUseRegex(true); 23 | 24 | assertThat(jGitVersioner.hasValue(commitMessage, keyword)).isEqualTo(expected); 25 | } 26 | 27 | @Test 28 | public void testHasValueWithoutRegex() { 29 | versionConfig.getKeywords().setUseRegex(false); 30 | 31 | String commitMessage = "Fix: [minor] corrected typo"; 32 | assertThat(jGitVersioner.hasValue(commitMessage, "[minor]")).isTrue(); 33 | 34 | commitMessage = "Update: improved performance"; 35 | assertThat(jGitVersioner.hasValue(commitMessage, "[minor]")).isFalse(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/Version.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.core.version; 3 | 4 | import java.util.Objects; 5 | 6 | public class Version { 7 | private final int major; 8 | private final int minor; 9 | private final int patch; 10 | private int commit; 11 | private final String branch; 12 | private final String hash; 13 | 14 | public Version(String branch, String hash) { 15 | this(branch, hash, 0, 0, 0, 0); 16 | } 17 | 18 | public Version(String branch, String hash, int major, int minor, int patch, int commit) { 19 | this.major = major; 20 | this.minor = minor; 21 | this.patch = patch; 22 | this.branch = branch; 23 | this.hash = hash; 24 | this.commit = commit; 25 | } 26 | 27 | public int getMajor() { 28 | return major; 29 | } 30 | 31 | public int getMinor() { 32 | return minor; 33 | } 34 | 35 | public int getPatch() { 36 | return patch; 37 | } 38 | 39 | public int getCommit() { 40 | return commit; 41 | } 42 | 43 | public String getBranch() { 44 | return branch; 45 | } 46 | 47 | public String getHash() { 48 | return hash; 49 | } 50 | public String getHashShort() { 51 | return hash != null ? hash.substring(0, 7) : null; 52 | } 53 | @Override 54 | public boolean equals(Object o) { 55 | if (this == o) 56 | return true; 57 | if (!(o instanceof Version)) 58 | return false; 59 | Version version = (Version) o; 60 | return getMajor() == version.getMajor() && getMinor() == version.getMinor() && getPatch() == version.getPatch(); 61 | } 62 | 63 | @Override 64 | public int hashCode() { 65 | return Objects.hash(getMajor(), getMinor(), getPatch()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | git-versioner-maven-parent 9 | V-LATEST-SNAPSHOT 10 | 11 | 12 | git-versioner-maven-extension 13 | Git Versioner Maven Extension 14 | 15 | 16 | 17 | com.github.manikmagar 18 | git-versioner-maven-core 19 | ${project.version} 20 | 21 | 22 | com.github.manikmagar 23 | git-versioner-maven-plugin 24 | ${project.version} 25 | test 26 | 27 | 28 | org.apache.maven 29 | maven-core 30 | 31 | 32 | org.apache.maven.shared 33 | maven-verifier 34 | 35 | 36 | org.apache.maven.plugin-tools 37 | maven-plugin-annotations 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/params/VersionConfig.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.params; 2 | 3 | import java.util.Objects; 4 | 5 | public final class VersionConfig { 6 | 7 | /** 8 | * Define initial version components 9 | */ 10 | private InitialVersion initial = new InitialVersion(); 11 | 12 | /** 13 | * Define the version keywords to use when parsing git commit messages 14 | */ 15 | private VersionKeywords keywords = new VersionKeywords(); 16 | 17 | private VersionPattern versionPattern = new VersionPattern(); 18 | 19 | public InitialVersion getInitial() { 20 | return initial; 21 | } 22 | 23 | public void setInitial(InitialVersion initialVersion) { 24 | this.initial = initialVersion; 25 | } 26 | 27 | public VersionKeywords getKeywords() { 28 | return keywords; 29 | } 30 | 31 | public void setKeywords(VersionKeywords keywords) { 32 | this.keywords = keywords; 33 | } 34 | 35 | public VersionPattern getVersionPattern() { 36 | return versionPattern; 37 | } 38 | 39 | public void setVersionPattern(VersionPattern versionPattern) { 40 | this.versionPattern = versionPattern; 41 | } 42 | 43 | @Override 44 | public boolean equals(Object o) { 45 | if (this == o) 46 | return true; 47 | if (!(o instanceof VersionConfig)) 48 | return false; 49 | VersionConfig that = (VersionConfig) o; 50 | return Objects.equals(getInitial(), that.getInitial()) && Objects.equals(getKeywords(), that.getKeywords()) 51 | && Objects.equals(getVersionPattern(), that.getVersionPattern()); 52 | } 53 | 54 | @Override 55 | public int hashCode() { 56 | return Objects.hash(getInitial(), getKeywords(), getVersionPattern()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/PrintTest.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin; 3 | 4 | import java.io.File; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | import org.apache.maven.plugin.testing.SilentLog; 9 | import org.junit.Test; 10 | 11 | import com.github.manikmagar.maven.versioner.plugin.mojo.Print; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | public class PrintTest extends AbstractMojoTest { 16 | 17 | public static class TestLog extends SilentLog { 18 | List messages = new ArrayList<>(); 19 | 20 | @Override 21 | public void warn(String message) { 22 | super.warn(message); 23 | messages.add(message); 24 | } 25 | 26 | @Override 27 | public boolean isInfoEnabled() { 28 | return true; 29 | } 30 | 31 | @Override 32 | public void info(CharSequence content) { 33 | super.info(content); 34 | messages.add(content.toString()); 35 | } 36 | 37 | public List getMessages() { 38 | return messages; 39 | } 40 | } 41 | 42 | /** 43 | * @throws Exception 44 | * if any 45 | */ 46 | @Test 47 | public void testPrint() throws Exception { 48 | File pom = new File("target/test-classes/project-to-test/"); 49 | assertThat(pom).as("POM file").isNotNull().exists(); 50 | 51 | Print printVersionMojo = (Print) rule.lookupConfiguredMojo(pom, "print"); 52 | TestLog testLog = new TestLog(); 53 | printVersionMojo.setLog(testLog); 54 | assertThat(printVersionMojo).isNotNull(); 55 | printVersionMojo.execute(); 56 | assertThat(testLog.getMessages()).isNotEmpty().allMatch(s -> s.startsWith("VersionPatternStrategy [branch:")); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/main/java/com/github/manikmagar/maven/versioner/extension/GAV.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.extension; 2 | 3 | import org.apache.maven.model.Model; 4 | 5 | import java.util.Objects; 6 | 7 | public class GAV { 8 | private String groupId; 9 | private String artifactId; 10 | private String version; 11 | 12 | private GAV() { 13 | 14 | } 15 | public static GAV with(String groupId, String artifactId, String version) { 16 | Objects.requireNonNull(groupId, "groupId must not be null"); 17 | Objects.requireNonNull(artifactId, "artifactId must not be null"); 18 | Objects.requireNonNull(version, "version must not be null"); 19 | GAV gav = new GAV(); 20 | gav.groupId = groupId; 21 | gav.artifactId = artifactId; 22 | gav.version = version; 23 | return gav; 24 | } 25 | 26 | public static GAV of(Model model) { 27 | return GAV.with(model.getGroupId(), model.getArtifactId(), model.getVersion()); 28 | } 29 | 30 | public String getGroupId() { 31 | return groupId; 32 | } 33 | 34 | public String getArtifactId() { 35 | return artifactId; 36 | } 37 | 38 | public String getVersion() { 39 | return version; 40 | } 41 | 42 | @Override 43 | public boolean equals(Object o) { 44 | if (this == o) 45 | return true; 46 | if (!(o instanceof GAV)) 47 | return false; 48 | GAV gav = (GAV) o; 49 | return getGroupId().equals(gav.getGroupId()) && getArtifactId().equals(gav.getArtifactId()) 50 | && getVersion().equals(gav.getVersion()); 51 | } 52 | 53 | @Override 54 | public int hashCode() { 55 | return Objects.hash(getGroupId(), getArtifactId(), getVersion()); 56 | } 57 | 58 | @Override 59 | public String toString() { 60 | return String.format("%s:%s:%s", getGroupId(), getArtifactId(), getVersion()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/AbstractVersionerMojo.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin.mojo; 3 | 4 | import com.github.manikmagar.maven.versioner.core.git.JGitVersioner; 5 | import com.github.manikmagar.maven.versioner.core.version.VersionStrategy; 6 | import com.github.manikmagar.maven.versioner.core.version.Versioner; 7 | import com.github.manikmagar.maven.versioner.plugin.mojo.params.VersionConfigParam; 8 | import org.apache.maven.plugin.AbstractMojo; 9 | import org.apache.maven.plugins.annotations.Parameter; 10 | import org.apache.maven.project.MavenProject; 11 | 12 | public abstract class AbstractVersionerMojo extends AbstractMojo { 13 | 14 | /** 15 | * Set Version Configuration 16 | */ 17 | @Parameter(name = "versionConfig") 18 | private VersionConfigParam _versionConfig; 19 | 20 | public VersionConfigParam getVersionConfig() { 21 | defaultConfig(); 22 | return _versionConfig; 23 | } 24 | public void setVersionConfig(VersionConfigParam versionConfig) { 25 | this._versionConfig = versionConfig; 26 | defaultConfig(); 27 | } 28 | 29 | private void defaultConfig() { 30 | if (this._versionConfig == null) { 31 | this._versionConfig = new VersionConfigParam(); 32 | } 33 | } 34 | 35 | @Parameter(defaultValue = "${project}", readonly = true) 36 | protected MavenProject mavenProject; 37 | 38 | public void setMavenProject(MavenProject mavenProject) { 39 | this.mavenProject = mavenProject; 40 | } 41 | 42 | protected Versioner getVersioner() { 43 | return new JGitVersioner(mavenProject.getBasedir().getAbsoluteFile(), getVersionConfig().toVersionConfig()); 44 | } 45 | 46 | protected String replaceTokens(String pattern, VersionStrategy versionStrategy) { 47 | return pattern.replace("%v", versionStrategy.toVersionString()); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionConfigParam.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 4 | import org.apache.maven.plugins.annotations.Parameter; 5 | 6 | import java.util.Objects; 7 | 8 | public final class VersionConfigParam { 9 | 10 | /** 11 | * Define initial version components 12 | */ 13 | @Parameter(name = "initial") 14 | private InitialVersionParam initial = new InitialVersionParam(); 15 | 16 | /** 17 | * Define the version keywords to use when parsing git commit messages 18 | */ 19 | @Parameter(name = "keywords") 20 | private VersionKeywordsParam keywords = new VersionKeywordsParam(); 21 | 22 | public InitialVersionParam getInitial() { 23 | return initial; 24 | } 25 | 26 | public void setInitial(InitialVersionParam initialVersion) { 27 | this.initial = initialVersion; 28 | } 29 | 30 | public VersionKeywordsParam getKeywords() { 31 | return keywords; 32 | } 33 | public void setKeywords(VersionKeywordsParam keywords) { 34 | this.keywords = keywords; 35 | } 36 | 37 | public VersionConfig toVersionConfig() { 38 | VersionConfig versionConfig = new VersionConfig(); 39 | versionConfig.setInitial(getInitial().toInitialVersion()); 40 | versionConfig.setKeywords(getKeywords().toVersionKeywords()); 41 | return versionConfig; 42 | } 43 | 44 | @Override 45 | public boolean equals(Object o) { 46 | if (this == o) 47 | return true; 48 | if (!(o instanceof VersionConfigParam)) 49 | return false; 50 | VersionConfigParam that = (VersionConfigParam) o; 51 | return getInitial().equals(that.getInitial()) && getKeywords().equals(that.getKeywords()); 52 | } 53 | 54 | @Override 55 | public int hashCode() { 56 | return Objects.hash(getInitial(), getKeywords()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.manikmagar 8 | git-versioner-maven-parent 9 | V-LATEST-SNAPSHOT 10 | 11 | 12 | git-versioner-maven-plugin 13 | maven-plugin 14 | Git Versioner Maven Plugin 15 | 16 | 17 | ${maven.version} 18 | 19 | 20 | 21 | com.github.manikmagar 22 | git-versioner-maven-core 23 | ${project.version} 24 | 25 | 26 | org.apache.maven 27 | maven-plugin-api 28 | 29 | 30 | org.apache.maven 31 | maven-core 32 | 33 | 34 | org.apache.maven 35 | maven-compat 36 | 37 | 38 | org.apache.maven.plugin-tools 39 | maven-plugin-annotations 40 | 41 | 42 | org.apache.maven.plugin-testing 43 | maven-plugin-testing-harness 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/InitialVersionParam.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.InitialVersion; 4 | import org.apache.maven.plugins.annotations.Parameter; 5 | 6 | import java.util.Objects; 7 | 8 | import static com.github.manikmagar.maven.versioner.core.params.InitialVersion.*; 9 | 10 | public class InitialVersionParam { 11 | 12 | /** 13 | * Initial Major version. 14 | */ 15 | @Parameter(name = "major", defaultValue = "0", property = GV_INITIAL_VERSION_MAJOR) 16 | private int major = 0; 17 | /** 18 | * Initial Minor version. 19 | */ 20 | @Parameter(name = "minor", defaultValue = "0", property = GV_INITIAL_VERSION_MINOR) 21 | private int minor = 0; 22 | /** 23 | * Initial Patch version. 24 | */ 25 | @Parameter(name = "patch", defaultValue = "0", property = GV_INITIAL_VERSION_PATCH) 26 | private int patch = 0; 27 | 28 | public InitialVersionParam(int major, int minor, int patch) { 29 | this.major = major; 30 | this.minor = minor; 31 | this.patch = patch; 32 | } 33 | 34 | public InitialVersionParam() { 35 | } 36 | 37 | public int getMajor() { 38 | return major; 39 | } 40 | 41 | public int getMinor() { 42 | return minor; 43 | } 44 | 45 | public int getPatch() { 46 | return patch; 47 | } 48 | 49 | public InitialVersion toInitialVersion() { 50 | return new InitialVersion(getMajor(), getMinor(), getPatch()); 51 | } 52 | 53 | @Override 54 | public boolean equals(Object o) { 55 | if (this == o) 56 | return true; 57 | if (!(o instanceof InitialVersionParam)) 58 | return false; 59 | InitialVersionParam that = (InitialVersionParam) o; 60 | return getMajor() == that.getMajor() && getMinor() == that.getMinor() && getPatch() == that.getPatch(); 61 | } 62 | 63 | @Override 64 | public int hashCode() { 65 | return Objects.hash(getMajor(), getMinor(), getPatch()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/params/InitialVersion.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.params; 2 | 3 | import java.util.Objects; 4 | 5 | import com.github.manikmagar.maven.versioner.core.Util; 6 | 7 | /** 8 | * Defines the initial values for version components in SemVer - 9 | * {major}.{minor}.{patch} 10 | */ 11 | public final class InitialVersion { 12 | 13 | public static final String GV_INITIAL_VERSION_MAJOR = "gv.initialVersion.major"; 14 | public static final String GV_INITIAL_VERSION_MINOR = "gv.initialVersion.minor"; 15 | public static final String GV_INITIAL_VERSION_PATCH = "gv.initialVersion.patch"; 16 | 17 | public InitialVersion(int major, int minor, int patch) { 18 | setMajor(major); 19 | setMinor(minor); 20 | setPatch(patch); 21 | } 22 | 23 | public InitialVersion() { 24 | this(0, 0, 0); 25 | } 26 | 27 | /** 28 | * Initial Major version. 29 | */ 30 | private int major = 0; 31 | /** 32 | * Initial Minor version. 33 | */ 34 | private int minor = 0; 35 | /** 36 | * Initial Patch version. 37 | */ 38 | private int patch = 0; 39 | 40 | public int getMajor() { 41 | return major; 42 | } 43 | 44 | public void setMajor(int major) { 45 | Util.mustBePositive(major, "InitialVersion.major"); 46 | this.major = major; 47 | } 48 | 49 | public int getMinor() { 50 | return minor; 51 | } 52 | 53 | public void setMinor(int minor) { 54 | Util.mustBePositive(minor, "InitialVersion.minor"); 55 | this.minor = minor; 56 | } 57 | 58 | public int getPatch() { 59 | return patch; 60 | } 61 | 62 | public void setPatch(int patch) { 63 | Util.mustBePositive(patch, "InitialVersion.patch"); 64 | this.patch = patch; 65 | } 66 | 67 | @Override 68 | public boolean equals(Object o) { 69 | if (this == o) 70 | return true; 71 | if (!(o instanceof InitialVersion)) 72 | return false; 73 | InitialVersion that = (InitialVersion) o; 74 | return major == that.major && minor == that.minor && patch == that.patch; 75 | } 76 | 77 | @Override 78 | public int hashCode() { 79 | return Objects.hash(major, minor, patch); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionKeywordsTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.VersionKeywords; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | 7 | import junitparams.JUnitParamsRunner; 8 | import junitparams.Parameters; 9 | 10 | import static com.github.manikmagar.maven.versioner.core.params.VersionKeywords.*; 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | @RunWith(JUnitParamsRunner.class) 14 | public class VersionKeywordsTest { 15 | 16 | @Test 17 | public void defaultKeywords() { 18 | assertThat(new VersionKeywords()).extracting("majorKey", "minorKey", "patchKey", "useRegex") 19 | .containsExactly(KEY_MAJOR, KEY_MINOR, KEY_PATCH, false); 20 | } 21 | 22 | @Test 23 | @Parameters(value = {"[A-MAJOR], [A-MAJOR], Custom", ",[major], Default"}) 24 | public void setMajorKey(String key, String expected, String keyType) { 25 | var versionKeywords = new VersionKeywords(); 26 | versionKeywords.setMajorKey(key); 27 | assertThat(versionKeywords.getMajorKey()).as(keyType).isEqualTo(expected); 28 | } 29 | 30 | @Test 31 | @Parameters(value = {"[A-MINOR], [A-MINOR], Custom", ",[minor], Default"}) 32 | public void setMinorKey(String key, String expected, String keyType) { 33 | var versionKeywords = new VersionKeywords(); 34 | versionKeywords.setMinorKey(key); 35 | assertThat(versionKeywords.getMinorKey()).as(keyType).isEqualTo(expected); 36 | } 37 | 38 | @Test 39 | @Parameters(value = {"[A-PATCH], [A-PATCH], Custom", ",[patch], Default"}) 40 | public void setPatchKey(String key, String expected, String keyType) { 41 | var versionKeywords = new VersionKeywords(); 42 | versionKeywords.setPatchKey(key); 43 | assertThat(versionKeywords.getPatchKey()).as(keyType).isEqualTo(expected); 44 | } 45 | 46 | @Test 47 | @Parameters(value = {"true", "false"}) 48 | public void setUseRegex(boolean useRegex) { 49 | var versionKeywords = new VersionKeywords(); 50 | versionKeywords.setUseRegex(useRegex); 51 | assertThat(versionKeywords.isUseRegex()).isEqualTo(useRegex); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.InitialVersion; 4 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 5 | import com.github.manikmagar.maven.versioner.core.params.VersionKeywords; 6 | import org.junit.Test; 7 | 8 | import static com.github.manikmagar.maven.versioner.core.params.VersionKeywords.*; 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | public class VersionConfigTest { 12 | 13 | @Test 14 | public void getDefaultInitial() { 15 | assertThat(new VersionConfig().getInitial()).isEqualTo(new InitialVersion(0, 0, 0)); 16 | } 17 | 18 | @Test 19 | public void setInitial() { 20 | VersionConfig versionConfig = new VersionConfig(); 21 | InitialVersion initialVersion = new InitialVersion(); 22 | initialVersion.setMajor(1); 23 | versionConfig.setInitial(initialVersion); 24 | assertThat(versionConfig.getInitial()).isEqualTo(new InitialVersion(1, 0, 0)); 25 | } 26 | 27 | @Test 28 | public void getDefaultKeywords() { 29 | assertThat(new VersionConfig().getKeywords()).extracting("majorKey", "minorKey", "patchKey") 30 | .containsExactly(KEY_MAJOR, KEY_MINOR, KEY_PATCH); 31 | } 32 | 33 | @Test 34 | public void setKeywords() { 35 | VersionConfig versionConfig = new VersionConfig(); 36 | VersionKeywords versionKeywords = new VersionKeywords(); 37 | versionKeywords.setMajorKey("[TEST]"); 38 | versionConfig.setKeywords(versionKeywords); 39 | assertThat(versionConfig.getKeywords()).extracting("majorKey", "minorKey", "patchKey", "useRegex") 40 | .containsExactly("[TEST]", KEY_MINOR, KEY_PATCH, false); 41 | } 42 | 43 | @Test 44 | public void setUseRegEx() { 45 | VersionConfig versionConfig = new VersionConfig(); 46 | VersionKeywords versionKeywords = new VersionKeywords(); 47 | versionKeywords.setUseRegex(true); 48 | versionConfig.setKeywords(versionKeywords); 49 | assertThat(versionConfig.getKeywords()).extracting("majorKey", "minorKey", "patchKey", "useRegex") 50 | .containsExactly(KEY_MAJOR, KEY_MINOR, KEY_PATCH, true); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/InitialVersionTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 2 | 3 | import com.github.manikmagar.maven.versioner.core.params.InitialVersion; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | import static org.assertj.core.api.Assertions.catchThrowableOfType; 8 | 9 | public class InitialVersionTest { 10 | 11 | @Test 12 | public void testDefaultVersion() { 13 | assertThat(new InitialVersion()).isEqualTo(new InitialVersion(0, 0, 0)); 14 | } 15 | 16 | @Test 17 | public void testMajorVersion() { 18 | var initialVersion = new InitialVersion(); 19 | initialVersion.setMajor(1); 20 | assertThat(initialVersion).isEqualTo(new InitialVersion(1, 0, 0)); 21 | } 22 | 23 | @Test 24 | public void testNegativeMajorVersion() { 25 | var initialVersion = new InitialVersion(); 26 | var ex = catchThrowableOfType(() -> initialVersion.setMajor(-1), IllegalArgumentException.class); 27 | assertThat(ex).isNotNull().hasMessage("InitialVersion.major must be a positive number"); 28 | } 29 | @Test 30 | public void testMinorVersion() { 31 | var initialVersion = new InitialVersion(); 32 | initialVersion.setMinor(1); 33 | assertThat(initialVersion).isEqualTo(new InitialVersion(0, 1, 0)); 34 | } 35 | 36 | @Test 37 | public void testNegativeMinorVersion() { 38 | var initialVersion = new InitialVersion(); 39 | var ex = catchThrowableOfType(() -> initialVersion.setMinor(-1), IllegalArgumentException.class); 40 | assertThat(ex).isNotNull().hasMessage("InitialVersion.minor must be a positive number"); 41 | } 42 | @Test 43 | public void testPatchVersion() { 44 | var initialVersion = new InitialVersion(); 45 | initialVersion.setPatch(1); 46 | assertThat(initialVersion).isEqualTo(new InitialVersion(0, 0, 1)); 47 | } 48 | 49 | @Test 50 | public void testNegativePatchVersion() { 51 | var initialVersion = new InitialVersion(); 52 | IllegalArgumentException ex = catchThrowableOfType(() -> initialVersion.setPatch(-1), 53 | IllegalArgumentException.class); 54 | assertThat(ex).isNotNull().hasMessage("InitialVersion.patch must be a positive number"); 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/SemVerStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.version; 2 | 3 | import java.util.Objects; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | import com.github.manikmagar.semver4j.SemVer; 7 | 8 | /** 9 | * Create Semantic version string 10 | */ 11 | public class SemVerStrategy extends AbstractVersionStrategy { 12 | 13 | private final SemVer semVer; 14 | 15 | private final AtomicInteger commitCount = new AtomicInteger(0); 16 | 17 | public SemVerStrategy(int major, int minor, int patch, String branchName, String hashRef) { 18 | super(branchName, hashRef); 19 | semVer = SemVer.of(major, minor, patch); 20 | } 21 | public SemVerStrategy(String branchName, String hashRef) { 22 | super(branchName, hashRef); 23 | semVer = SemVer.zero(); 24 | } 25 | 26 | @Override 27 | public String strategyName() { 28 | return "SemVer"; 29 | } 30 | 31 | @Override 32 | public String toVersionString() { 33 | if (commitCount.get() > 0) { 34 | semVer.withNew(SemVer.build(getHashShort())); 35 | } 36 | return semVer.toString(); 37 | } 38 | 39 | @Override 40 | public Version getVersion() { 41 | return new Version(getBranchName(), getHash(), semVer.getMajor(), semVer.getMinor(), semVer.getPatch(), 42 | commitCount.get()); 43 | } 44 | 45 | @Override 46 | public void increment(VersionComponentType type, String hashRef) { 47 | Objects.requireNonNull(type, "Version component type must not be null"); 48 | Objects.requireNonNull(hashRef, "Hash Reference must not be null"); 49 | setHash(hashRef); 50 | switch (type) { 51 | case MAJOR : 52 | onMajorIncrement(); 53 | break; 54 | case MINOR : 55 | onMinorIncrement(); 56 | break; 57 | case PATCH : 58 | onPatchIncrement(); 59 | break; 60 | case COMMIT : 61 | onCommitIncrement(); 62 | break; 63 | } 64 | } 65 | private void onMajorIncrement() { 66 | semVer.incrementMajor(); 67 | commitCount.set(0); 68 | } 69 | 70 | private void onMinorIncrement() { 71 | semVer.incrementMinor(); 72 | commitCount.set(0); 73 | } 74 | 75 | private void onPatchIncrement() { 76 | semVer.incrementPatch(); 77 | commitCount.set(0); 78 | } 79 | 80 | private void onCommitIncrement() { 81 | commitCount.incrementAndGet(); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/main/java/com/github/manikmagar/maven/versioner/extension/Util.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.extension; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.Writer; 6 | import java.nio.charset.Charset; 7 | import java.nio.file.Files; 8 | import java.nio.file.Path; 9 | import java.util.Properties; 10 | 11 | import com.github.manikmagar.maven.versioner.core.GitVersionerException; 12 | import org.apache.maven.model.Model; 13 | import org.apache.maven.model.io.xpp3.MavenXpp3Reader; 14 | import org.apache.maven.model.io.xpp3.MavenXpp3Writer; 15 | import org.codehaus.plexus.util.xml.pull.XmlPullParserException; 16 | 17 | public class Util { 18 | 19 | private Util() { 20 | } 21 | 22 | public static final String GIT_VERSIONER_POM_XML = ".git-versioner.pom.xml"; 23 | 24 | public static final String GIT_VERSIONER_MAVEN_CORE_PROPERTIES = "git-versioner-maven-core.properties"; 25 | public static final String GIT_VERSIONER_MAVEN_EXTENSION_PROPERTIES = "git-versioner-maven-extension.properties"; 26 | public static final String GIT_VERSIONER_MAVEN_PLUGIN_PROPERTIES = "git-versioner-maven-plugin.properties"; 27 | 28 | public static Path writePom(Model projectModel, Path originalPomPath) { 29 | Path newPomPath = originalPomPath.resolveSibling(GIT_VERSIONER_POM_XML); 30 | try (Writer fileWriter = Files.newBufferedWriter(newPomPath, Charset.defaultCharset())) { 31 | MavenXpp3Writer writer = new MavenXpp3Writer(); 32 | writer.write(fileWriter, projectModel); 33 | } catch (IOException e) { 34 | throw new GitVersionerException(e.getMessage(), e); 35 | } 36 | return newPomPath; 37 | } 38 | public static Model readPom(Path pomPath) { 39 | try (InputStream inputStream = Files.newInputStream(pomPath)) { 40 | MavenXpp3Reader reader = new MavenXpp3Reader(); 41 | return reader.read(inputStream); 42 | } catch (IOException | XmlPullParserException e) { 43 | throw new GitVersionerException(e.getMessage(), e); 44 | } 45 | } 46 | public static GAV extensionArtifact() { 47 | Properties props = new Properties(); 48 | try (InputStream inputStream = Util.class.getClassLoader().getResource(GIT_VERSIONER_MAVEN_EXTENSION_PROPERTIES) 49 | .openStream()) { 50 | props.load(inputStream); 51 | return GAV.with(props.getProperty("projectGroupId"), props.getProperty("projectArtifactId"), 52 | props.getProperty("projectVersion")); 53 | } catch (Exception e) { 54 | throw new GitVersionerException(e.getMessage(), e); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/git/JGitVersioner.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.core.git; 3 | 4 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 5 | import com.github.manikmagar.maven.versioner.core.version.*; 6 | import org.eclipse.jgit.lib.Ref; 7 | import org.eclipse.jgit.revwalk.RevCommit; 8 | 9 | import java.io.File; 10 | import java.util.Collections; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | import java.util.stream.StreamSupport; 14 | 15 | public class JGitVersioner implements Versioner { 16 | 17 | File basePath; 18 | VersionConfig versionConfig; 19 | 20 | public JGitVersioner(File basePath, VersionConfig versionConfig) { 21 | this.versionConfig = versionConfig; 22 | this.basePath = basePath; 23 | } 24 | 25 | public VersionStrategy version() { 26 | return JGit.executeOperation(basePath, git -> { 27 | var branch = git.getRepository().getBranch(); 28 | Ref head = git.getRepository().findRef("HEAD"); 29 | var hash = ""; 30 | if (head != null && head.getObjectId() != null) { 31 | hash = head.getObjectId().getName(); 32 | } 33 | var versionStrategy = new VersionPatternStrategy(versionConfig.getInitial().getMajor(), 34 | versionConfig.getInitial().getMinor(), versionConfig.getInitial().getPatch(), branch, hash, 35 | versionConfig.getVersionPattern().getPattern()); 36 | var commits = git.log().call(); 37 | List revCommits = StreamSupport.stream(commits.spliterator(), false) 38 | .collect(Collectors.toList()); 39 | Collections.reverse(revCommits); 40 | for (RevCommit commit : revCommits) { 41 | if (hasValue(commit.getFullMessage(), versionConfig.getKeywords().getMajorKey())) { 42 | versionStrategy.increment(VersionComponentType.MAJOR, hash); 43 | } else if (hasValue(commit.getFullMessage(), versionConfig.getKeywords().getMinorKey())) { 44 | versionStrategy.increment(VersionComponentType.MINOR, hash); 45 | } else if (hasValue(commit.getFullMessage(), versionConfig.getKeywords().getPatchKey())) { 46 | versionStrategy.increment(VersionComponentType.PATCH, hash); 47 | } else { 48 | versionStrategy.increment(VersionComponentType.COMMIT, hash); 49 | } 50 | } 51 | return versionStrategy; 52 | }); 53 | } 54 | 55 | boolean hasValue(String commitMessage, String keyword) { 56 | if (versionConfig.getKeywords().isUseRegex()) { 57 | return commitMessage.matches(keyword); 58 | } else { 59 | return commitMessage.contains(keyword); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/params/VersionKeywordsParam.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.plugin.mojo.params; 3 | 4 | import com.github.manikmagar.maven.versioner.core.params.VersionKeywords; 5 | import org.apache.maven.plugins.annotations.Parameter; 6 | 7 | import java.util.Objects; 8 | 9 | import static com.github.manikmagar.maven.versioner.core.params.VersionKeywords.*; 10 | 11 | /** 12 | * Define the version keywords to use when parsing git commit messages. 13 | */ 14 | public final class VersionKeywordsParam { 15 | 16 | /** 17 | * The keyword for calculating major version of the SemVer. 18 | */ 19 | @Parameter(name = "majorKey", defaultValue = KEY_MAJOR, property = GV_KEYWORDS_MAJOR_KEY) 20 | private String majorKey = KEY_MAJOR; 21 | /** 22 | * The keyword for calculating minor version of the SemVer. 23 | */ 24 | @Parameter(name = "minorKey", defaultValue = KEY_MINOR, property = GV_KEYWORDS_MINOR_KEY) 25 | private String minorKey = KEY_MINOR; 26 | /** 27 | * The keyword for calculating patch version of the SemVer. 28 | */ 29 | @Parameter(name = "patchKey", defaultValue = KEY_PATCH, property = GV_KEYWORDS_PATCH_KEY) 30 | private String patchKey = KEY_PATCH; 31 | 32 | @Parameter(name = "useRegex", defaultValue = "false", property = GV_KEYWORDS_KEY_USEREGEX) 33 | private boolean useRegex = false; 34 | 35 | public VersionKeywordsParam(String majorKey, String minorKey, String patchKey, boolean useRegex) { 36 | this.majorKey = majorKey; 37 | this.minorKey = minorKey; 38 | this.patchKey = patchKey; 39 | this.useRegex = useRegex; 40 | } 41 | 42 | public VersionKeywordsParam() { 43 | 44 | } 45 | 46 | public String getMajorKey() { 47 | return majorKey; 48 | } 49 | 50 | public String getMinorKey() { 51 | return minorKey; 52 | } 53 | 54 | public String getPatchKey() { 55 | return patchKey; 56 | } 57 | 58 | public boolean isUseRegex() { 59 | return useRegex; 60 | } 61 | 62 | public VersionKeywords toVersionKeywords() { 63 | return new VersionKeywords(getMajorKey(), getMinorKey(), getPatchKey(), isUseRegex()); 64 | } 65 | @Override 66 | public boolean equals(Object o) { 67 | if (this == o) 68 | return true; 69 | if (!(o instanceof VersionKeywordsParam)) 70 | return false; 71 | VersionKeywordsParam that = (VersionKeywordsParam) o; 72 | return getMajorKey().equals(that.getMajorKey()) && getMinorKey().equals(that.getMinorKey()) 73 | && getPatchKey().equals(that.getPatchKey()) && isUseRegex() == that.isUseRegex(); 74 | } 75 | 76 | @Override 77 | public int hashCode() { 78 | return Objects.hash(getMajorKey(), getMinorKey(), getPatchKey()); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /jreleaser.yml: -------------------------------------------------------------------------------- 1 | project: 2 | name: git-versioner-maven-plugin 3 | description: Generate maven project version from git commit logs 4 | longDescription: | 5 | Generate maven project version from git commit logs. 6 | 7 | links: 8 | homepage: https://github.com/manikmagar/ 9 | documentation: https://github.com/manikmagar/git-versioner-maven-plugin 10 | license: https://github.com/manikmagar/git-versioner-maven-plugin/blob/main/LICENSE 11 | contribute: https://github.com/manikmagar/mulefd/blob/main/README.adoc 12 | authors: 13 | - Manik Magar 14 | license: MIT 15 | inceptionYear: 2022 16 | tags: 17 | - maven 18 | - git-versioning 19 | - project-versioning 20 | - versioning 21 | - maven-extension 22 | - maven-plugin 23 | java: 24 | groupId: com.github.manikmagar 25 | version: 11 26 | 27 | release: 28 | github: 29 | overwrite: true 30 | draft: false 31 | sign: true 32 | releaseName: '{{tagName}}' 33 | skipTag: true 34 | milestone: 35 | close: false 36 | changelog: 37 | formatted: always 38 | preset: conventional-commits 39 | format: '- {{commitShortHash}} {{commitTitle}}' 40 | skipMergeCommits: true 41 | contributors: 42 | format: '- {{contributorName}}{{#contributorUsernameAsLink}} ({{.}}){{/contributorUsernameAsLink}}' 43 | labelers: 44 | - label: 'dependencies' 45 | title: 'chore(deps):' 46 | order: 130 47 | categories: 48 | - title: '⚙️ Dependencies' 49 | key: 'dependencies' 50 | order: 80 51 | labels: 52 | - 'dependencies' 53 | hide: 54 | categories: 55 | - 'merge' 56 | contributors: 57 | - 'GitHub' 58 | 59 | checksum: 60 | individual: true 61 | 62 | signing: 63 | active: always 64 | armored: true 65 | 66 | deploy: 67 | maven: 68 | nexus2: 69 | maven-central: 70 | active: ALWAYS 71 | url: https://oss.sonatype.org/service/local 72 | applyMavenCentralRules: true 73 | closeRepository: true 74 | releaseRepository: true 75 | stagingRepositories: 76 | - target/staging-deploy 77 | - git-versioner-maven-core/target/staging-deploy 78 | - git-versioner-maven-plugin/target/staging-deploy 79 | - git-versioner-maven-extension/target/staging-deploy 80 | 81 | announce: 82 | twitter: 83 | active: release 84 | status: '🚀 {{projectName}} {{projectVersion}} has been released! {{releaseNotesUrl}}' 85 | mastodon: 86 | active: release 87 | host: https://fosstodon.org 88 | status: '🚀 {{projectNameCapitalized}} {{projectVersion}} has been released! {{releaseNotesUrl}}' 89 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/Tag.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo; 2 | 3 | import com.github.manikmagar.maven.versioner.core.GitVersionerException; 4 | import com.github.manikmagar.maven.versioner.core.git.GitTag; 5 | import org.apache.maven.plugin.MojoExecutionException; 6 | import org.apache.maven.plugin.MojoFailureException; 7 | import org.apache.maven.plugins.annotations.Mojo; 8 | import org.apache.maven.plugins.annotations.Parameter; 9 | 10 | /** 11 | * Create a local git tag with current version. 12 | */ 13 | @Mojo(name = "tag", requiresProject = true) 14 | public class Tag extends AbstractVersionerMojo { 15 | 16 | /** 17 | * Fail the build if tag already exist? 18 | */ 19 | @Parameter(name = "failWhenTagExist", defaultValue = "true", property = "tag.failWhenTagExist") 20 | private boolean failWhenTagExist = true; 21 | 22 | /** 23 | * Pattern to create tag message. You may use following tokens - 24 | * 25 | *
26 | 	 *    - %v : replace with the generated version
27 | 	 * 
28 | */ 29 | @Parameter(name = "tagMessagePattern", defaultValue = "Release version %v", property = "tag.messagePattern") 30 | private String tagMessagePattern = "Release version %v"; 31 | 32 | /** 33 | * Pattern to create tag name. You may use following tokens - 34 | * 35 | *
36 | 	 *    - %v : replace with the generated version
37 | 	 * 
38 | */ 39 | @Parameter(name = "tagNamePattern", defaultValue = "v%v", property = "tag.namePattern") 40 | private String tagNamePattern = "v%v"; 41 | 42 | public boolean isFailWhenTagExist() { 43 | return failWhenTagExist; 44 | } 45 | 46 | public String getTagMessagePattern() { 47 | return tagMessagePattern; 48 | } 49 | 50 | public String getTagNamePattern() { 51 | return tagNamePattern; 52 | } 53 | 54 | @Override 55 | public void execute() throws MojoExecutionException, MojoFailureException { 56 | var versionStrategy = getVersioner().version(); 57 | var tagName = replaceTokens(getTagNamePattern(), versionStrategy); 58 | var tagMessage = replaceTokens(getTagMessagePattern(), versionStrategy); 59 | getLog().info("Current Version: " + versionStrategy.toVersionString()); 60 | getLog().info(String.format("Tag Version '%s' with message '%s'", tagName, tagMessage)); 61 | if (GitTag.exists(mavenProject.getBasedir().getAbsoluteFile(), tagName)) { 62 | getLog().error(String.format("Tag already exist: %s", tagName)); 63 | if (isFailWhenTagExist()) 64 | throw new GitVersionerException("Tag already exist: " + tagName); 65 | } else { 66 | String tagId = GitTag.create(mavenProject.getBasedir().getAbsoluteFile(), tagName, tagMessage); 67 | getLog().info(String.format("Created tag: '%s'", tagId)); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: tag-and-release 2 | on: 3 | push: 4 | tags: 5 | - 'v*' 6 | 7 | env: 8 | JAVA_VERSION: '11' 9 | JAVA_DISTRO: 'zulu' 10 | 11 | jobs: 12 | release: 13 | runs-on: ubuntu-latest 14 | name: Release 15 | env: 16 | JRELEASER_TWITTER_CONSUMER_KEY: ${{ secrets.JRELEASER_TWITTER_CONSUMER_KEY }} 17 | JRELEASER_TWITTER_CONSUMER_SECRET: ${{ secrets.JRELEASER_TWITTER_CONSUMER_SECRET }} 18 | JRELEASER_TWITTER_ACCESS_TOKEN: ${{ secrets.JRELEASER_TWITTER_ACCESS_TOKEN }} 19 | JRELEASER_TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.JRELEASER_TWITTER_ACCESS_TOKEN_SECRET }} 20 | JRELEASER_MASTODON_ACCESS_TOKEN: ${{ secrets.JRELEASER_MASTODON_ACCESS_TOKEN }} 21 | JRELEASER_GITHUB_TOKEN: ${{ secrets.JRELEASER_GITHUB_TOKEN }} 22 | JRELEASER_GPG_PASSPHRASE: ${{ secrets.JRELEASER_GPG_PASSPHRASE }} 23 | JRELEASER_GPG_PUBLIC_KEY: ${{ secrets.JRELEASER_GPG_PUBLIC_KEY }} 24 | JRELEASER_GPG_SECRET_KEY: ${{ secrets.JRELEASER_GPG_SECRET_KEY }} 25 | JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD: ${{ secrets.JRELEASER_NEXUS2_MAVEN_CENTRAL_PASSWORD }} 26 | JRELEASER_NEXUS2_USERNAME: ${{ secrets.JRELEASER_NEXUS2_USERNAME }} 27 | JRELEASER_VERSION: early-access 28 | steps: 29 | - uses: actions/checkout@v3 30 | with: 31 | fetch-depth: '0' 32 | - name: Setup Java 33 | uses: actions/setup-java@v3 34 | with: 35 | java-version: ${{ env.JAVA_VERSION }} 36 | distribution: ${{ env.JAVA_DISTRO }} 37 | cache: maven 38 | - name: Install LATEST extension 39 | run: ./mvnw install -DskipTests 40 | - name: Configure git-versioner Extension 41 | run: | 42 | mv ./.mvn/extensions.xml.template ./.mvn/extensions.xml 43 | - name: Stage Deploy 44 | run: ./mvnw deploy -Pdeploy -DskipTests 45 | - name: Set Version 46 | id: set-version 47 | run: | 48 | echo "RELEASE_VERSION=$(./mvnw -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec)" >> $GITHUB_OUTPUT 49 | - name: Print Version 50 | run: | 51 | echo "Releasing version: ${{steps.set-version.outputs.RELEASE_VERSION}}" 52 | - name: Run JReleaser 53 | uses: jreleaser/release-action@v2 54 | env: 55 | JRELEASER_PROJECT_VERSION: ${{steps.set-version.outputs.RELEASE_VERSION}} 56 | with: 57 | version: ${{ env.JRELEASER_VERSION }} 58 | arguments: full-release 59 | - name: JReleaser release output 60 | if: always() 61 | uses: actions/upload-artifact@v2 62 | with: 63 | name: jreleaser-release 64 | path: | 65 | out/jreleaser/trace.log 66 | out/jreleaser/output.properties 67 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/AbstractVersionerMojoTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo; 2 | 3 | import com.github.manikmagar.maven.versioner.core.git.JGitVersioner; 4 | import com.github.manikmagar.maven.versioner.core.version.SemVerStrategy; 5 | import com.github.manikmagar.maven.versioner.core.version.Versioner; 6 | import com.github.manikmagar.maven.versioner.plugin.mojo.params.InitialVersionParam; 7 | import com.github.manikmagar.maven.versioner.plugin.mojo.params.VersionConfigParam; 8 | import org.apache.maven.plugin.MojoExecutionException; 9 | import org.apache.maven.plugin.MojoFailureException; 10 | import org.apache.maven.project.MavenProject; 11 | import org.junit.Test; 12 | 13 | import java.io.File; 14 | 15 | import static com.github.manikmagar.maven.versioner.core.params.VersionKeywords.*; 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | public class AbstractVersionerMojoTest { 19 | 20 | private AbstractVersionerMojo testMojo = new AbstractVersionerMojo() { 21 | 22 | { 23 | mavenProject = new MavenProject(); 24 | mavenProject.setFile(new File("my/pom.xml")); 25 | } 26 | @Override 27 | public void execute() throws MojoExecutionException, MojoFailureException { 28 | 29 | } 30 | }; 31 | 32 | @Test 33 | public void getVersionConfig() { 34 | assertThat(testMojo.getVersionConfig()).isNotNull(); 35 | assertThat(testMojo.getVersionConfig().getInitial()).isNotNull().isEqualTo(new InitialVersionParam(0, 0, 0)); 36 | assertThat(testMojo.getVersionConfig().getKeywords()).isNotNull().extracting("majorKey", "minorKey", "patchKey") 37 | .containsExactly(KEY_MAJOR, KEY_MINOR, KEY_PATCH); 38 | } 39 | 40 | @Test 41 | public void setVersionConfig() { 42 | AbstractVersionerMojo mojo = new AbstractVersionerMojo() { 43 | @Override 44 | public void execute() throws MojoExecutionException, MojoFailureException { 45 | 46 | } 47 | }; 48 | InitialVersionParam one = new InitialVersionParam(1, 0, 0); 49 | VersionConfigParam versionConfig = new VersionConfigParam(); 50 | versionConfig.setInitial(one); 51 | mojo.setVersionConfig(versionConfig); 52 | assertThat(mojo.getVersionConfig().getInitial()).isNotNull().isEqualTo(one); 53 | assertThat(testMojo.getVersionConfig().getKeywords()).isNotNull().extracting("majorKey", "minorKey", "patchKey") 54 | .containsExactly(KEY_MAJOR, KEY_MINOR, KEY_PATCH); 55 | } 56 | 57 | @Test 58 | public void getVersioner() { 59 | Versioner versioner = testMojo.getVersioner(); 60 | assertThat(versioner).isNotNull().isInstanceOf(JGitVersioner.class); 61 | } 62 | 63 | @Test 64 | public void replaceVersionToken() { 65 | assertThat(testMojo.replaceTokens("v%v", new SemVerStrategy(1, 2, 3, "test", "testHash"))).isEqualTo("v1.2.3"); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/params/VersionKeywords.java: -------------------------------------------------------------------------------- 1 | /* (C)2022 */ 2 | package com.github.manikmagar.maven.versioner.core.params; 3 | 4 | import java.util.Objects; 5 | 6 | /** 7 | * Define the version keywords to use when parsing git commit messages. 8 | */ 9 | public final class VersionKeywords { 10 | public static final String KEY_MAJOR = "[major]"; 11 | public static final String KEY_MINOR = "[minor]"; 12 | public static final String KEY_PATCH = "[patch]"; 13 | public static final String GV_KEYWORDS_MAJOR_KEY = "gv.keywords.majorKey"; 14 | public static final String GV_KEYWORDS_MINOR_KEY = "gv.keywords.minorKey"; 15 | public static final String GV_KEYWORDS_PATCH_KEY = "gv.keywords.patchKey"; 16 | public static final String GV_KEYWORDS_KEY_USEREGEX = "gv.keywords.useRegex"; 17 | 18 | /** 19 | * The keyword for calculating major version of the SemVer. 20 | */ 21 | private String majorKey = KEY_MAJOR; 22 | /** 23 | * The keyword for calculating minor version of the SemVer. 24 | */ 25 | private String minorKey = KEY_MINOR; 26 | /** 27 | * The keyword for calculating patch version of the SemVer. 28 | */ 29 | private String patchKey = KEY_PATCH; 30 | /** 31 | * Whether to use regex for matching keywords. 32 | */ 33 | private boolean useRegex = false; 34 | 35 | public VersionKeywords(String majorKey, String minorKey, String patchKey, boolean useRegex) { 36 | setMajorKey(majorKey); 37 | setMinorKey(minorKey); 38 | setPatchKey(patchKey); 39 | setUseRegex(useRegex); 40 | } 41 | public VersionKeywords() { 42 | 43 | } 44 | 45 | public String getMajorKey() { 46 | return majorKey; 47 | } 48 | 49 | public void setMajorKey(String majorKey) { 50 | if (majorKey == null || majorKey.trim().isEmpty()) { 51 | this.majorKey = KEY_MAJOR; 52 | } else { 53 | this.majorKey = majorKey; 54 | } 55 | } 56 | 57 | public String getMinorKey() { 58 | return minorKey; 59 | } 60 | 61 | public void setMinorKey(String minorKey) { 62 | if (minorKey == null || minorKey.trim().isEmpty()) { 63 | this.minorKey = KEY_MINOR; 64 | } else { 65 | this.minorKey = minorKey; 66 | } 67 | } 68 | 69 | public String getPatchKey() { 70 | return patchKey; 71 | } 72 | 73 | public void setPatchKey(String patchKey) { 74 | if (patchKey == null || patchKey.trim().isEmpty()) { 75 | this.patchKey = KEY_PATCH; 76 | } else { 77 | this.patchKey = patchKey; 78 | } 79 | } 80 | 81 | public void setUseRegex(boolean useRegex) { 82 | this.useRegex = useRegex; 83 | } 84 | 85 | public boolean isUseRegex() { 86 | return useRegex; 87 | } 88 | 89 | @Override 90 | public boolean equals(Object o) { 91 | if (this == o) 92 | return true; 93 | if (!(o instanceof VersionKeywords)) 94 | return false; 95 | VersionKeywords that = (VersionKeywords) o; 96 | return majorKey.equals(that.majorKey) && minorKey.equals(that.minorKey) && patchKey.equals(that.patchKey); 97 | } 98 | 99 | @Override 100 | public int hashCode() { 101 | return Objects.hash(majorKey, minorKey, patchKey); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/main/java/com/github/manikmagar/maven/versioner/plugin/mojo/VersionCommit.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin.mojo; 2 | 3 | import com.github.manikmagar.maven.versioner.core.git.JGit; 4 | import org.apache.maven.plugin.MojoExecutionException; 5 | import org.apache.maven.plugin.MojoFailureException; 6 | import org.apache.maven.plugins.annotations.Mojo; 7 | import org.apache.maven.plugins.annotations.Parameter; 8 | 9 | import java.io.IOException; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | /** 13 | * Add a new commit to change version 14 | */ 15 | public abstract class VersionCommit extends AbstractVersionerMojo { 16 | 17 | public static final String KEYWORD_TOKEN = "[%k]"; 18 | 19 | public enum IncrementType { 20 | MAJOR("major"), MINOR("minor"), PATCH("patch"); 21 | private final String name; 22 | IncrementType(String name) { 23 | this.name = name; 24 | } 25 | public String getName() { 26 | return name; 27 | } 28 | } 29 | 30 | @Parameter(name = "message", property = "gv.commit.message", defaultValue = "chore(release): " + KEYWORD_TOKEN) 31 | private String message; 32 | 33 | public void setMessage(String message) { 34 | this.message = message; 35 | } 36 | 37 | abstract IncrementType getIncrementType(); 38 | 39 | @Override 40 | public void execute() throws MojoExecutionException, MojoFailureException { 41 | String typeName = getIncrementType().getName(); 42 | switch (getIncrementType()) { 43 | case MAJOR : 44 | typeName = getVersionConfig().getKeywords().getMajorKey(); 45 | break; 46 | case MINOR : 47 | typeName = getVersionConfig().getKeywords().getMinorKey(); 48 | break; 49 | case PATCH : 50 | typeName = getVersionConfig().getKeywords().getPatchKey(); 51 | break; 52 | } 53 | if (!message.contains(KEYWORD_TOKEN)) 54 | message = message.concat(" " + KEYWORD_TOKEN); 55 | String resolvedMessage = message.replace(KEYWORD_TOKEN, typeName); 56 | try { 57 | // Use local git configuration for any write operations to retain local user 58 | // settings such as sign 59 | String gitDir = JGit.findGitDir(mavenProject.getBasedir().getAbsoluteFile().toPath().toString()); 60 | boolean completed = new ProcessBuilder() 61 | .command("git", "--git-dir", gitDir, "commit", "--allow-empty", "-m", resolvedMessage).inheritIO() 62 | .start().waitFor(5, TimeUnit.SECONDS); 63 | if (!completed) { 64 | throw new MojoFailureException("Timed out for creating commit"); 65 | } 66 | } catch (IOException | InterruptedException e) { 67 | throw new MojoFailureException(e.getMessage(), e); 68 | } 69 | } 70 | 71 | /** 72 | * Add a new git commit to increment patch version. 73 | */ 74 | @Mojo(name = "commit-patch") 75 | public static class VersionCommitPatch extends VersionCommit { 76 | 77 | public IncrementType getIncrementType() { 78 | return IncrementType.PATCH; 79 | } 80 | } 81 | /** 82 | * Add a new git commit to increment minor version. 83 | */ 84 | @Mojo(name = "commit-minor") 85 | public static class VersionCommitMinor extends VersionCommit { 86 | 87 | public IncrementType getIncrementType() { 88 | return IncrementType.MINOR; 89 | } 90 | } 91 | 92 | /** 93 | * Add a new git commit to increment major version. 94 | */ 95 | @Mojo(name = "commit-major") 96 | public static class VersionCommitMajor extends VersionCommit { 97 | 98 | public IncrementType getIncrementType() { 99 | return IncrementType.MAJOR; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /CONTRIBUTING.adoc: -------------------------------------------------------------------------------- 1 | = Contributing 2 | ifndef::env-github[:icons: font] 3 | ifdef::env-github[] 4 | :caution-caption: :fire: 5 | :important-caption: :exclamation: 6 | :note-caption: :paperclip: 7 | :tip-caption: :bulb: 8 | :warning-caption: :warning: 9 | endif::[] 10 | 11 | == Build 12 | 13 | === Java Support 14 | 15 | Source code uses *Java 11* for development, however the API compatibility is restricted to *Java 8*. 16 | This allows us to use the syntactical sugar advancements such as var, switch etc but still _support Java 8 projects_. 17 | This is achieved with the use of https://github.com/bsideup/jabel[Jabel - javac compiler plugin]. 18 | 19 | - Development dependency: Java 11 20 | - Runtime dependency: Java 8+ 21 | 22 | WARNING: Using Java 9+ APIs will result in compilation failure. See https://github.com/bsideup/jabel#how-jabel-works[how and why Jabel works] for more details. 23 | 24 | === Installation 25 | Install artifacts to local repository - 26 | 27 | [source,shell] 28 | ---- 29 | ./mvnw install 30 | ---- 31 | 32 | == Releasing 33 | GitHub Actions workflow is configured to use this same extension to version the project 34 | and then use https://jreleaser.org/[JReleaser] to release this to https://search.maven.org/search?q=a:git-versioner-maven-extension[Maven Central]. 35 | 36 | _To trigger the release:_ 37 | 38 | *Install* the latest extension to local repository - 39 | 40 | [source,shell] 41 | ---- 42 | ./mvnw install 43 | ---- 44 | 45 | *Commit* using one of the link:README.adoc#_how_do_i_increment_version[Version Commit goals] - 46 | 47 | .Example goal to increment patch 48 | [source,shell] 49 | ---- 50 | ./mvnw com.github.manikmagar:git-versioner-maven-plugin:V-LATEST-SNAPSHOT:commit-patch --non-recursive 51 | ---- 52 | 53 | .Example goal to increment minor 54 | [source,shell] 55 | ---- 56 | ./mvnw com.github.manikmagar:git-versioner-maven-plugin:V-LATEST-SNAPSHOT:commit-minor --non-recursive 57 | ---- 58 | 59 | *Verify* the new version by running plugin's `print` goal - 60 | 61 | [source,shell] 62 | ---- 63 | ./mvnw com.github.manikmagar:git-versioner-maven-plugin:V-LATEST-SNAPSHOT:print --non-recursive 64 | ---- 65 | 66 | In the output, you can look for version - 67 | 68 | .Example version 0.6.0 print 69 | [source,log] 70 | ---- 71 | ... 72 | [INFO] --- git-versioner-maven-plugin:V-LATEST-SNAPSHOT:print (default-cli) @ git-versioner-maven-parent --- 73 | [INFO] VersionPatternStrategy [branch: main, version: 0.6.0, hash: 238bedfdff4e84f7c3964a494b91a76c4998287f] 74 | .... 75 | ---- 76 | 77 | *Tag* the new version by running plugin's `tag` goal - 78 | 79 | [source,shell] 80 | ---- 81 | ./mvnw com.github.manikmagar:git-versioner-maven-plugin:V-LATEST-SNAPSHOT:tag --non-recursive 82 | ---- 83 | 84 | This should create a tag with current verison. 85 | 86 | .Example tag goal creating v0.6.0 tag 87 | [source,log] 88 | ---- 89 | [INFO] 90 | [INFO] --- git-versioner-maven-plugin:V-LATEST-SNAPSHOT:tag (default-cli) @ git-versioner-maven-parent --- 91 | [INFO] Current Version: 0.6.0 92 | [INFO] Tag Version 'v0.6.0' with message 'Release version 0.6.0' 93 | [INFO] Created tag: 'refs/tags/v0.6.0@c95da362ef54a682f45b0a723aea609b3e980247' 94 | [INFO] ------------------------------------------------------------------------ 95 | ---- 96 | 97 | **Push** the release commit and tag 98 | 99 | [source,shell] 100 | ---- 101 | # push branch commit 102 | git push 103 | 104 | tagName=$(./mvnw help:evaluate -Dexpression=project.version -q -DforceStdout) 105 | # push the new tag 106 | # example - git push origin v0.6.0 107 | git push origin v$tagName 108 | ---- 109 | 110 | *Monitor* GitHub Actions Workflows for https://github.com/manikmagar/git-versioner-maven-plugin/actions/workflows/release.yml[release]. 111 | 112 | Once the pipeline succeeds, the new release should soon be available on -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/VersionCommitTest.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.plugin; 2 | 3 | import com.github.manikmagar.maven.versioner.plugin.mojo.VersionCommit; 4 | import junitparams.JUnitParamsRunner; 5 | import junitparams.Parameters; 6 | import org.eclipse.jgit.api.Git; 7 | import org.eclipse.jgit.api.errors.GitAPIException; 8 | import org.eclipse.jgit.lib.StoredConfig; 9 | import org.eclipse.jgit.revwalk.RevCommit; 10 | import org.junit.Rule; 11 | import org.junit.Test; 12 | import org.junit.rules.TemporaryFolder; 13 | import org.junit.runner.RunWith; 14 | 15 | import java.io.File; 16 | import java.io.IOException; 17 | import java.nio.file.Files; 18 | import java.nio.file.Path; 19 | import java.nio.file.Paths; 20 | import java.nio.file.StandardCopyOption; 21 | import java.util.stream.Collectors; 22 | import java.util.stream.StreamSupport; 23 | 24 | import static org.assertj.core.api.Assertions.assertThat; 25 | 26 | @RunWith(JUnitParamsRunner.class) 27 | public class VersionCommitTest extends AbstractMojoTest { 28 | 29 | @Rule 30 | public TemporaryFolder temporaryFolder = new TemporaryFolder(); 31 | 32 | @Test 33 | @Parameters(value = {"commit-patch, patch", "commit-minor, minor", "commit-major, major"}) 34 | public void executeVersionCommit(String goal, String keyword) throws Exception { 35 | File tempProject = setupTestProject(); 36 | try (Git git = getMain(tempProject)) { 37 | addEmptyCommit(git); 38 | var commit = (VersionCommit) rule.lookupConfiguredMojo(tempProject, goal); 39 | assertThat(commit).isNotNull(); 40 | commit.execute(); 41 | var commits = git.log().call(); 42 | var revCommits = StreamSupport.stream(commits.spliterator(), false).collect(Collectors.toList()); 43 | assertThat(revCommits.get(0).getShortMessage()).isEqualTo(String.format("chore(release): [%s]", keyword)); 44 | } 45 | } 46 | 47 | @Test 48 | @Parameters(value = {"commit-patch, patch", "commit-minor, minor", "commit-major, major"}) 49 | public void executeVersionCommitCustomMessage(String goal, String keyword) throws Exception { 50 | File tempProject = setupTestProject(); 51 | try (Git git = getMain(tempProject)) { 52 | addEmptyCommit(git); 53 | var commit = (VersionCommit) rule.lookupConfiguredMojo(tempProject, goal); 54 | commit.setMessage("chore: releasing [%k]"); 55 | assertThat(commit).isNotNull(); 56 | commit.execute(); 57 | var commits = git.log().call(); 58 | var revCommits = StreamSupport.stream(commits.spliterator(), false).collect(Collectors.toList()); 59 | assertThat(revCommits.get(0).getShortMessage()).isEqualTo(String.format("chore: releasing [%s]", keyword)); 60 | } 61 | } 62 | 63 | private File setupTestProject() throws IOException { 64 | File tempProject = temporaryFolder.newFolder(); 65 | Path testProject = Paths.get("src/test/resources/project-to-test/"); 66 | Files.copy(testProject.resolve("pom.xml"), tempProject.toPath().resolve("pom.xml"), 67 | StandardCopyOption.REPLACE_EXISTING); 68 | assertThat(tempProject.list()).contains("pom.xml"); 69 | return tempProject; 70 | } 71 | private static Git getMain(File tempProject) throws GitAPIException, IOException { 72 | Git main = Git.init().setInitialBranch("main").setDirectory(tempProject).call(); 73 | StoredConfig config = main.getRepository().getConfig(); 74 | config.setString("user", null, "name", "GitHub Actions Test"); 75 | config.setString("user", null, "email", ""); 76 | config.save(); 77 | return main; 78 | } 79 | private static void addEmptyCommit(Git git) throws GitAPIException { 80 | git.commit().setSign(false).setMessage("Empty commit").setAllowEmpty(true).call(); 81 | } 82 | private static String addCommit(Git git, String message) throws GitAPIException { 83 | RevCommit commit = git.commit().setSign(false).setMessage(message).setAllowEmpty(true).call(); 84 | return commit.toObjectId().getName(); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /git-versioner-maven-core/src/main/java/com/github/manikmagar/maven/versioner/core/version/VersionPatternStrategy.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.core.version; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | import static java.lang.String.valueOf; 6 | 7 | public class VersionPatternStrategy extends SemVerStrategy { 8 | 9 | public static final String DEFAULT_VERSION_PATTERN = "%M.%m.%p(-%c)"; 10 | private final String versionPattern; 11 | 12 | public VersionPatternStrategy(int major, int minor, int patch, String branchName, String hashRef, 13 | String versionPattern) { 14 | super(major, minor, patch, branchName, hashRef); 15 | if (versionPattern == null || versionPattern.trim().isEmpty()) { 16 | this.versionPattern = DEFAULT_VERSION_PATTERN; 17 | } else { 18 | this.versionPattern = versionPattern; 19 | } 20 | } 21 | 22 | public VersionPatternStrategy(String branchName, String hashRef, String versionPattern) { 23 | super(branchName, hashRef); 24 | this.versionPattern = versionPattern; 25 | } 26 | 27 | public VersionPatternStrategy(int major, int minor, int patch, String branchName, String hashRef) { 28 | this(major, minor, patch, branchName, hashRef, DEFAULT_VERSION_PATTERN); 29 | } 30 | 31 | public VersionPatternStrategy(String branchName, String hashRef) { 32 | this(branchName, hashRef, DEFAULT_VERSION_PATTERN); 33 | } 34 | 35 | public String getVersionPattern() { 36 | return versionPattern; 37 | } 38 | 39 | @Override 40 | public String toVersionString() { 41 | return new TokenReplacer(getVersionPattern()).replace(PatternToken.MAJOR, getVersion().getMajor()) 42 | .replace(PatternToken.MINOR, getVersion().getMinor()) 43 | .replace(PatternToken.PATCH, getVersion().getPatch()) 44 | .replace(PatternToken.COMMIT, getVersion().getCommit()) 45 | .replace(PatternToken.BRANCH, getVersion().getBranch()) 46 | .replace(PatternToken.HASH_SHORT, getVersion().getHashShort()) 47 | .replace(PatternToken.HASH, getVersion().getHash()).toString(); 48 | } 49 | 50 | public static class TokenReplacer { 51 | private String text; 52 | 53 | public TokenReplacer(String text) { 54 | this.text = text; 55 | } 56 | 57 | public TokenReplacer replace(PatternToken token, int value) { 58 | return replace(token, valueOf(value)); 59 | } 60 | 61 | public TokenReplacer replace(PatternToken token, String value) { 62 | if (!text.contains(token.getToken())) 63 | return this; 64 | if (!PatternToken.COMMIT.equals(token)) { 65 | if (text.contains(token.getToken())) { 66 | text = text.replace(token.getToken(), value); 67 | } 68 | } else { 69 | // Full regex to match the version string containing group regex 70 | var fullRegex = ".*" + token.getTokenGroupRegex() + ".*"; 71 | if (Pattern.matches(fullRegex, text)) { 72 | if (value != null && !value.trim().isEmpty() && !value.equals("0")) { 73 | text = text.replace(token.getToken(), value); 74 | } else { 75 | text = text.replaceAll(token.getTokenGroupRegex(), ""); 76 | } 77 | } else if (text.contains(token.getToken())) { 78 | text = text.replace(token.getToken(), value); 79 | } 80 | } 81 | return this; 82 | } 83 | 84 | private String deTokenized() { 85 | return text.replace("(", "").replace(")", ""); 86 | } 87 | 88 | @Override 89 | public String toString() { 90 | return deTokenized(); 91 | } 92 | } 93 | 94 | public enum PatternToken { 95 | MAJOR("%M"), MINOR("%m"), PATCH("%p"), COMMIT("%c"), BRANCH("%b"), HASH_SHORT("%h"), HASH("%H"); 96 | 97 | private final String token; 98 | private final String tokenGroupRegex; 99 | 100 | PatternToken(String token) { 101 | this.token = token; 102 | this.tokenGroupRegex = String.format("(\\([^(]*%s[^)]*\\))", token); 103 | } 104 | 105 | public String getToken() { 106 | return token; 107 | } 108 | 109 | public String getTokenGroupRegex() { 110 | return tokenGroupRegex; 111 | } 112 | 113 | @Override 114 | public String toString() { 115 | return getToken(); 116 | } 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | = Git Versioner Maven Plugin 2 | ifndef::env-github[:icons: font] 3 | ifdef::env-github[] 4 | :caution-caption: :fire: 5 | :important-caption: :exclamation: 6 | :note-caption: :paperclip: 7 | :tip-caption: :bulb: 8 | :warning-caption: :warning: 9 | endif::[] 10 | :toc: macro 11 | 12 | image:https://img.shields.io/github/release/manikmagar/git-versioner-maven-plugin.svg[Release,link=https://github.com/manikmagar/git-versioner-maven-plugin/releases] 13 | image:https://github.com/manikmagar/git-versioner-maven-plugin/workflows/build/badge.svg[Build Status,link=https://github.com/manikmagar/git-versioner-maven-plugin/actions] 14 | image:https://img.shields.io/github/license/manikmagar/git-versioner-maven-plugin[GitHub] 15 | 16 | Generate the semver version using the git commit history and automatically set it to maven pom. 17 | 18 | No more manually modifying the pom.xml to decide on the versions. 19 | You continue developing and adding commits to your project. 20 | When it is time to release, add a commit with a message containing 21 | a specific version keyword and watch the magic happen. 22 | 23 | toc::[] 24 | 25 | == How does it work? 26 | This extension iterates over all the commit history and looks for a predefined keywords representing version changes. 27 | It then computes the version number upto current commit. 28 | 29 | The extension supports generating Semantic Versions `x.y.z` format. The format pattern is configurable to use 30 | values such as Git hash, branch name etc. 31 | 32 | See https://github.com/manikmagar/git-versioner-maven-extension-examples[manikmagar/git-versioner-maven-extension-examples] 33 | for examples of using this extension. 34 | 35 | [#versionKeywords] 36 | == What are version keywords? 37 | *Version keywords* are the reserved words that describes which milestone of the release is this. 38 | 39 | By default, extension supports following keywords - 40 | 41 | - `[major]` - A Major version milestone Eg. 1.0.0 -> 2.0.0 42 | - `[minor]` - A Minor version milestone Eg. 1.1.0 -> 1.2. 43 | - `[patch]` - A Patch version milestone Eg. 1.1.1 -> 1.1.2 44 | 45 | To change the keywords, see how to link:#versionKeywords_custom[Customize Version Keywords]. 46 | 47 | == How to configure? 48 | This is a maven build core extension that can - 49 | 50 | - Participate in maven build lifecycle 51 | - Automatically set the building project's version 52 | - No explicit mojo executions needed to set the version 53 | - Project's POM remain unchanged 54 | 55 | To use as a maven build extension, 56 | 57 | Create (or modify) `extensions.xml` file in `${project.baseDir}/.mvn/` 58 | to have the following entry - 59 | 60 | NOTE: The artifact id is *git-versioner-maven-_extension_*. 61 | 62 | ..mvn/extensions.xml 63 | [source,xml] 64 | ---- 65 | 67 | 68 | com.github.manikmagar 69 | git-versioner-maven-extension 70 | ${latest-version-here} 71 | 72 | 73 | 74 | ---- 75 | 76 | See an example test project at link:git-versioner-maven-extension/src/test/resources/project-with-extension/[]. 77 | 78 | With just that configuration, next time your project runs any maven goals, you should see version from this module 79 | is used by Maven reactor. Try running `mvn package` on your project. 80 | 81 | == How to start with a different version? 82 | It is possible that your project is already released with a certain version. 83 | In that case, you can configure the initial version to start counting versions from. 84 | 85 | You can add following properties to `.mvn/git-versioner.extensions.properties` file - 86 | 87 | .Example configuration for initial version for extension mode 88 | [source,properties] 89 | ---- 90 | gv.initialVersion.major=1 91 | gv.initialVersion.minor=3 92 | gv.initialVersion.patch=4 93 | ---- 94 | 95 | With above initial version configuration, the first version calculated by this extension will be - 96 | 97 | - Major: *2.0.0* 98 | - Minor: 1.*4.0* 99 | - Patch: 1.3.*5* 100 | 101 | == How do I increment version? 102 | Now that you have extension configured, you can continue with your regular development. 103 | 104 | When it is time to increment version, you may use one of the following three goals 105 | to add an *_empty commit_* with appropriate link:#versionKeywords[Version Keyword] - 106 | 107 | - `git-versioner:commit-major`: Adds a git commit with a commit message containing *Major* version keyword 108 | - `git-versioner:commit-minor`: Adds a git commit with a commit message containing *Minor* version keyword 109 | - `git-versioner:commit-patch`: Adds a git commit with a commit message containing *Patch* version keyword 110 | 111 | CAUTION: Use `--non-recursive` flag when running commit goal in a multi-module maven project to avoid adding one commit per included module. 112 | 113 | The default message pattern is `chore(release): [%k]` where `[%k]` is the keyword token. 114 | To change the default message pattern, you could pass `-Dgv.commit.message=` argument when running the goal. 115 | 116 | NOTE: When this extension is configured, it automatically makes `git-versioner` plugin goals available 117 | with *NO* any additional configuration. 118 | 119 | .Example commit patch with a custom message 120 | [source, shell] 121 | ---- 122 | mvn git-versioner:commit-patch "-Dgv.commit.message=chore: [%k] release" --non-recursive 123 | ---- 124 | 125 | Off course, you can also add commits manually with appropriate version keywords. 126 | 127 | .Manually adding a version commit 128 | [source, shell] 129 | ---- 130 | git commit --allow-empty -m "chore: [] release" // <1> 131 | ---- 132 | 133 | <1> where `` can be one of these - major, minor, or patch. 134 | 135 | == How to change the version pattern? 136 | 137 | The default version pattern used is `major.minor.patch(-commit)` where `(-commit)` is skipped if commit count is 0. 138 | 139 | This pattern can be canged by setting a property in `.mvn/git-versioner.extensions.properties`. 140 | 141 | The following example will generate versions as `major.minor.patch+shorthash`, eg. `1.2.3+a5a29f8`. 142 | 143 | .Example configuration for version pattern in extension mode 144 | [source,properties] 145 | ---- 146 | gv.pattern.pattern=%M.%m.%p+%h 147 | ---- 148 | 149 | .Available Tokens for Version Pattern 150 | |=== 151 | |Token |Description |Example 152 | 153 | |%M 154 | |Major Version 155 | |**1**.y.z 156 | 157 | |%m 158 | |Minor Version 159 | |x.**1**.z 160 | 161 | |%p 162 | |Patch Version 163 | |x.y.**1** 164 | 165 | |%c 166 | |Commit count 167 | |x.y.z-**4** 168 | 169 | |([anything]%c) 170 | |Non-Zero Commit count 171 | |Given _%M.%m.%p(-%c)_ 172 | with _%M=1_, _%m=2_, _%p=3_ 173 | 174 | when c == 0 -> _1.2.3_ 175 | 176 | when c > 0, = 5 -> _1.2.3-**5**_ 177 | 178 | |%b 179 | |Branch name 180 | |_%M.%m.%p+%b_ -> _1.2.3+**main**_ 181 | 182 | |%H 183 | |Long Hash Ref 184 | |_%M.%m.%p+%H_ -> _1.2.3+**b5f600c40f362d9977132e8bf7398d2cdc745c28**_ 185 | 186 | |%h 187 | |Short Hash Ref 188 | |_%M.%m.%p+%H_ -> _1.2.3+**a5a29f8**_ 189 | |=== 190 | 191 | [#versionKeywords_custom] 192 | == How to customize version keywords? 193 | The default link:#versionKeywords[version keywords] `[major]`, `[minor]`, and `[patch]` can be customized by overriding the configuration. 194 | 195 | To use different keywords, you can add following properties to `.mvn/git-versioner.extensions.properties` file - 196 | 197 | .Example configuration for initial version for extension mode 198 | [source,properties] 199 | ---- 200 | gv.keywords.majorKey=[BIG] 201 | gv.keywords.minorKey=[SMALL] 202 | gv.keywords.patchKey=[FIX] 203 | ---- 204 | 205 | === Use regex for version keywords 206 | You can also use regex to match version keywords. 207 | This is useful when you want to be sure that the version keyword will only be matched when it is the first word in the commit message. 208 | So if for example you have a merge commit message which contains the messages of the merged commits, you can use a regex to match only the first commit message. 209 | 210 | To use regex for version keywords, you can add following properties to `.mvn/git-versioner.extensions.properties` file - 211 | 212 | .Example configuration for regex version keywords 213 | ---- 214 | gv.keywords.useRegex=true 215 | gv.keywords.majorKey=^\\[major\\].* 216 | gv.keywords.minorKey=^\\[minor\\].* 217 | gv.keywords.patchKey=^\\[patch\\].* 218 | ---- 219 | 220 | == How to access generated version properties? 221 | This extension adds all version properties to *Maven properties* during build cycle - 222 | 223 | .Example of Injected maven properties (demo values) 224 | [source, properties] 225 | ---- 226 | git-versioner.commitNumber=0 227 | git-versioner.major=0 228 | git-versioner.minor=0 229 | git-versioner.patch=1 230 | git-versioner.version=0.0.1 231 | git.branch=main 232 | git.hash=67550ad6a64fe4e09bf9e36891c09b2f7bdc52f9 233 | git.hash.short=67550ad 234 | ---- 235 | 236 | You may use these properties in maven pom file, for example as `${git.branch}` to access git branch name. 237 | 238 | == How to create Git tags? 239 | 240 | You can use `git-versioner:tag` goal to create a git tag for current version in local git repository. 241 | 242 | NOTE: This does not push tag to remote repository. 243 | 244 | .Tag goal with default parameter values 245 | [source,shell] 246 | ---- 247 | mvn git-versioner:tag \ 248 | "-Dtag.failWhenTagExist=true" \ 249 | "-Dtag.messagePattern=Release version %v" \ 250 | "-Dtag.namePattern=v%v" 251 | ---- 252 | 253 | For Tag goal, it is possible to configure pom.xml to contain the git-versioner plugin with required execution configuration. 254 | 255 | .Git Tag Goal with default configuration parameters 256 | [source, xml] 257 | ---- 258 | 259 | com.github.manikmagar 260 | git-versioner-maven-plugin 261 | 262 | 263 | tag 264 | 265 | tag 266 | 267 | 268 | true // <1> 269 | v%v // <2> 270 | Release version %v // <3> 271 | 272 | 273 | 274 | 275 | ---- 276 | 277 | <1> If set to not fail, it will just log warning and skip tag creation. 278 | <2> Tag name pattern to use. Default `v%v` will result in tags like `v1.2.3`. 279 | <3> Tag message pattern to use. Default `Release version %v` will add tag message like `Release version 1.2.3`. 280 | 281 | == Contributing 282 | 283 | All contributions are welcome. Please see link:CONTRIBUTING.adoc[Contributing] guides. 284 | 285 | == Acknowledgement 286 | This is inspired from Gradle plugin https://github.com/toolebox-io/gradle-git-versioner[toolebox-io/gradle-git-versioner] that I have been using for my Gradle projects. This maven plugin is my attempt to get those auto-version capabilities into my Maven builds. 287 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/main/java/com/github/manikmagar/maven/versioner/extension/GitVersionerModelProcessor.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.extension; 2 | 3 | import com.github.manikmagar.maven.versioner.core.GitVersionerException; 4 | import com.github.manikmagar.maven.versioner.core.git.JGitVersioner; 5 | import com.github.manikmagar.maven.versioner.core.params.InitialVersion; 6 | import com.github.manikmagar.maven.versioner.core.params.VersionConfig; 7 | import com.github.manikmagar.maven.versioner.core.params.VersionKeywords; 8 | import com.github.manikmagar.maven.versioner.core.params.VersionPattern; 9 | import com.github.manikmagar.maven.versioner.core.version.VersionStrategy; 10 | import org.apache.maven.building.Source; 11 | import org.apache.maven.model.*; 12 | import org.apache.maven.model.building.DefaultModelProcessor; 13 | import org.apache.maven.model.building.ModelProcessor; 14 | import org.apache.maven.shared.utils.logging.MessageBuilder; 15 | import org.apache.maven.shared.utils.logging.MessageUtils; 16 | import org.codehaus.plexus.util.xml.Xpp3Dom; 17 | import org.codehaus.plexus.util.xml.Xpp3DomBuilder; 18 | import org.codehaus.plexus.util.xml.pull.XmlPullParserException; 19 | import org.eclipse.sisu.Typed; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | import javax.inject.Named; 24 | import javax.inject.Singleton; 25 | import java.io.*; 26 | import java.nio.file.Files; 27 | import java.nio.file.Path; 28 | import java.nio.file.Paths; 29 | import java.util.*; 30 | import java.util.stream.Collectors; 31 | 32 | /** 33 | * Maven @{@link ModelProcessor} implementation to set the project version 34 | * before build is initialized. 35 | */ 36 | @Named("core-default") 37 | @Singleton 38 | @Typed(ModelProcessor.class) 39 | public class GitVersionerModelProcessor extends DefaultModelProcessor { 40 | 41 | private static final Logger LOGGER = LoggerFactory.getLogger(GitVersionerModelProcessor.class); 42 | 43 | public static final String GIT_VERSIONER_EXTENSIONS_PROPERTIES = "git-versioner.extensions.properties"; 44 | public static final String DOT_MVN = ".mvn"; 45 | private boolean initialized = false; 46 | 47 | private final List relatedPoms = new ArrayList<>(); 48 | private VersionStrategy versionStrategy; 49 | private Path dotmvnDirectory; 50 | private VersionConfig versionConfig; 51 | 52 | @Override 53 | public Model read(File input, Map options) throws IOException { 54 | return processModel(super.read(input, options), options); 55 | } 56 | 57 | @Override 58 | public Model read(Reader input, Map options) throws IOException { 59 | return processModel(super.read(input, options), options); 60 | } 61 | 62 | @Override 63 | public Model read(InputStream input, Map options) throws IOException { 64 | return processModel(super.read(input, options), options); 65 | } 66 | 67 | private Model processModel(Model projectModel, Map options) { 68 | final Source pomSource = (Source) options.get(ModelProcessor.SOURCE); 69 | 70 | if (pomSource != null) { 71 | projectModel.setPomFile(new File(pomSource.getLocation())); 72 | } 73 | 74 | // Only source poms are with .xml 75 | // dependency poms are with .pom 76 | if (pomSource == null || !pomSource.getLocation().endsWith(".xml")) { 77 | return projectModel; 78 | } 79 | 80 | // This model processor is invoked for every POM on the classpath, including the 81 | // plugins. 82 | // The first execution is with the project's pom though. 83 | // Use first initialized flag to avoid processing other classpath poms. 84 | if (!initialized) { 85 | dotmvnDirectory = getDOTMVNDirectory(projectModel.getPomFile().toPath()); 86 | GAV extensionGAV = Util.extensionArtifact(); 87 | LOGGER.info(MessageUtils.buffer().a("--- ").mojo(extensionGAV).a(" ").strong("[core-extension]").a(" ---") 88 | .toString()); 89 | versionConfig = loadConfig(); 90 | versionStrategy = new JGitVersioner(projectModel.getPomFile().getAbsoluteFile(), versionConfig).version(); 91 | findRelatedProjects(projectModel); 92 | initialized = true; 93 | } 94 | processRelatedProjects(projectModel); 95 | return projectModel; 96 | } 97 | 98 | private void processRelatedProjects(Model projectModel) { 99 | if (!relatedPoms.contains(projectModel.getPomFile().toPath())) 100 | return; 101 | LOGGER.info("Project {}:{}, Computed version: {}", getGroupId(projectModel), projectModel.getArtifactId(), 102 | MessageUtils.buffer().strong(versionStrategy.toVersionString())); 103 | projectModel.setVersion(versionStrategy.toVersionString()); 104 | 105 | Parent parent = projectModel.getParent(); 106 | if (parent != null) { 107 | var path = Paths.get(parent.getRelativePath()); 108 | // Parent is part of this build 109 | try { 110 | Path parentPomPath = Paths.get( 111 | projectModel.getPomFile().getParentFile().toPath().resolve(path).toFile().getCanonicalPath()); 112 | LOGGER.debug("Looking for parent pom {}", parentPomPath); 113 | if (Files.exists(parentPomPath) && this.relatedPoms.contains(parentPomPath)) { 114 | LOGGER.info("Setting parent {} version to {}", parent, versionStrategy.toVersionString()); 115 | parent.setVersion(versionStrategy.toVersionString()); 116 | } else { 117 | LOGGER.debug("Parent {} is not part of this build. Skipping version change for parent.", parent); 118 | } 119 | } catch (IOException e) { 120 | throw new GitVersionerException(e.getMessage(), e); 121 | } 122 | } 123 | addVersionerProperties(projectModel); 124 | Path versionerPom = Util.writePom(projectModel, projectModel.getPomFile().toPath()); 125 | LOGGER.debug("Generated versioner pom at {}", versionerPom); 126 | // NOTE: Build plugin must be running a mojo to set .git-versioner.pom.xml as 127 | // project pom 128 | // Otherwise, the published pom will still be original pom.xml with default 129 | // version 130 | addVersionerBuildPlugin(projectModel); 131 | } 132 | 133 | private static String getGroupId(Model projectModel) { 134 | return (projectModel.getGroupId() == null && projectModel.getParent() != null) 135 | ? projectModel.getParent().getGroupId() 136 | : projectModel.getGroupId(); 137 | } 138 | 139 | private void addVersionerBuildPlugin(Model projectModel) { 140 | GAV extensionGAV = Util.extensionArtifact(); 141 | LOGGER.debug("Adding build plugin version {}", extensionGAV); 142 | if (projectModel.getBuild() == null) { 143 | projectModel.setBuild(new Build()); 144 | } 145 | if (projectModel.getBuild().getPlugins() == null) { 146 | projectModel.getBuild().setPlugins(new ArrayList<>()); 147 | } 148 | Plugin plugin = new Plugin(); 149 | plugin.setGroupId(extensionGAV.getGroupId()); 150 | plugin.setArtifactId(extensionGAV.getArtifactId().replace("-extension", "-plugin")); 151 | plugin.setVersion(extensionGAV.getVersion()); 152 | Plugin existing = projectModel.getBuild().getPluginsAsMap().get(plugin.getKey()); 153 | boolean addExecution = true; 154 | if (existing != null) { 155 | plugin = existing; 156 | LOGGER.warn("Found existing plugin configuration for {}", plugin.getKey()); 157 | if (!existing.getVersion().equals(extensionGAV.getVersion())) { 158 | LOGGER.warn(MessageUtils.buffer().mojo(plugin).warning(" version is different than ").mojo(extensionGAV) 159 | .newline().a("This can introduce unexpected behaviors.").toString()); 160 | } 161 | Optional setGoal = existing.getExecutions().stream() 162 | .filter(e -> e.getGoals().contains("set")).findFirst(); 163 | if (setGoal.isPresent()) { 164 | LOGGER.info("Using existing plugin execution with id {}", setGoal.get().getId()); 165 | addExecution = false; 166 | } 167 | } 168 | addPluginConfiguration(plugin); 169 | if (addExecution) { 170 | LOGGER.debug("Adding build plugin execution for {}", plugin.getKey()); 171 | PluginExecution execution = new PluginExecution(); 172 | execution.setId("git-versioner-set"); 173 | execution.setGoals(Collections.singletonList("set")); 174 | plugin.addExecution(execution); 175 | } 176 | if (existing == null) 177 | projectModel.getBuild().getPlugins().add(0, plugin); 178 | } 179 | 180 | /** 181 | * Add plugin configuration from version properties 182 | * 183 | * @param plugin 184 | */ 185 | private void addPluginConfiguration(Plugin plugin) { 186 | // Version keywords are used by version commit goals. 187 | String config = String.format( 188 | " %s" 189 | + " %s %s" 190 | + " %s" + " ", 191 | versionConfig.getKeywords().getMajorKey(), versionConfig.getKeywords().getMinorKey(), 192 | versionConfig.getKeywords().getPatchKey(), versionConfig.getKeywords().isUseRegex()); 193 | try { 194 | Xpp3Dom configDom = Xpp3DomBuilder.build(new StringReader(config)); 195 | plugin.setConfiguration(configDom); 196 | } catch (XmlPullParserException | IOException e) { 197 | throw new GitVersionerException(e.getMessage(), e); 198 | } 199 | } 200 | 201 | private VersionConfig loadConfig() { 202 | VersionConfig coreVersionConfig = new VersionConfig(); 203 | Properties properties = loadExtensionProperties(); 204 | InitialVersion version = new InitialVersion(); 205 | version.setMajor(Integer.parseInt(properties.getProperty(InitialVersion.GV_INITIAL_VERSION_MAJOR, "0"))); 206 | version.setMinor(Integer.parseInt(properties.getProperty(InitialVersion.GV_INITIAL_VERSION_MINOR, "0"))); 207 | version.setPatch(Integer.parseInt(properties.getProperty(InitialVersion.GV_INITIAL_VERSION_PATCH, "0"))); 208 | coreVersionConfig.setInitial(version); 209 | 210 | VersionKeywords keywords = new VersionKeywords(); 211 | keywords.setMajorKey(properties.getProperty(VersionKeywords.GV_KEYWORDS_MAJOR_KEY)); 212 | keywords.setMinorKey(properties.getProperty(VersionKeywords.GV_KEYWORDS_MINOR_KEY)); 213 | keywords.setPatchKey(properties.getProperty(VersionKeywords.GV_KEYWORDS_PATCH_KEY)); 214 | keywords.setUseRegex(properties.getProperty(VersionKeywords.GV_KEYWORDS_KEY_USEREGEX, "false").equals("true")); 215 | coreVersionConfig.setKeywords(keywords); 216 | 217 | VersionPattern versionPattern = new VersionPattern(); 218 | versionPattern.setPattern(properties.getProperty(VersionPattern.GV_PATTERN_PATTERN)); 219 | coreVersionConfig.setVersionPattern(versionPattern); 220 | 221 | return coreVersionConfig; 222 | } 223 | private Properties loadExtensionProperties() { 224 | Properties props = new Properties(); 225 | Path propertiesPath = dotmvnDirectory.resolve(GIT_VERSIONER_EXTENSIONS_PROPERTIES); 226 | if (propertiesPath.toFile().exists()) { 227 | LOGGER.debug("Reading versioner properties from {}", propertiesPath); 228 | try (Reader reader = Files.newBufferedReader(propertiesPath)) { 229 | props.load(reader); 230 | } catch (IOException e) { 231 | throw new GitVersionerException("Failed to load extensions properties file", e); 232 | } 233 | } 234 | return props; 235 | } 236 | 237 | private void findRelatedProjects(Model projectModel) { 238 | LOGGER.debug("Finding related projects for {}", projectModel.getArtifactId()); 239 | 240 | // Add main project 241 | relatedPoms.add(projectModel.getPomFile().toPath()); 242 | 243 | // Find modules 244 | List modulePoms = projectModel.getModules().stream().map(module -> projectModel.getProjectDirectory() 245 | .toPath().resolve(module).resolve("pom.xml").toAbsolutePath()).collect(Collectors.toList()); 246 | LOGGER.debug("Modules found: {}", modulePoms); 247 | relatedPoms.addAll(modulePoms); 248 | } 249 | 250 | private void addVersionerProperties(Model projectModel) { 251 | Map properties = new TreeMap<>(); 252 | properties.put("git-versioner.version", versionStrategy.toVersionString()); 253 | properties.put("git-versioner.major", String.valueOf(versionStrategy.getVersion().getMajor())); 254 | properties.put("git-versioner.minor", String.valueOf(versionStrategy.getVersion().getMinor())); 255 | properties.put("git-versioner.patch", String.valueOf(versionStrategy.getVersion().getPatch())); 256 | properties.put("git-versioner.commitNumber", String.valueOf(versionStrategy.getVersion().getCommit())); 257 | properties.put("git.branch", versionStrategy.getVersion().getBranch()); 258 | properties.put("git.hash", versionStrategy.getVersion().getHash()); 259 | properties.put("git.hash.short", versionStrategy.getVersion().getHashShort()); 260 | MessageBuilder builder = MessageUtils.buffer().a("properties:"); 261 | for (Map.Entry entry : properties.entrySet()) { 262 | builder = builder.newline(); 263 | String key = entry.getKey(); 264 | String value = entry.getValue(); 265 | builder = builder.format(" %s=%s", key, value); 266 | } 267 | LOGGER.info("Adding generated properties to project model: {}", builder); 268 | projectModel.getProperties().putAll(properties); 269 | } 270 | 271 | /** 272 | * Find the first .mvn directory in currentDir and parents. 273 | * 274 | * @param currentDir 275 | * Path 276 | * @return Path of .mvn directory 277 | */ 278 | private static Path getDOTMVNDirectory(final Path currentDir) { 279 | LOGGER.info("Finding .mvn in {}", currentDir); 280 | Path refDir = currentDir; 281 | Path dotMvn = refDir.resolve(DOT_MVN); 282 | while (!Files.exists(dotMvn)) { 283 | refDir = refDir.getParent(); 284 | dotMvn = refDir.resolve(DOT_MVN); 285 | } 286 | return dotMvn; 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /git-versioner-maven-plugin/src/test/java/com/github/manikmagar/maven/versioner/plugin/mojo/HelpMojo.java: -------------------------------------------------------------------------------- 1 | 2 | package com.github.manikmagar.maven.versioner.plugin.mojo; 3 | 4 | import org.apache.maven.plugin.AbstractMojo; 5 | import org.apache.maven.plugin.MojoExecutionException; 6 | import org.apache.maven.plugins.annotations.Mojo; 7 | import org.apache.maven.plugins.annotations.Parameter; 8 | 9 | import org.w3c.dom.Document; 10 | import org.w3c.dom.Element; 11 | import org.w3c.dom.Node; 12 | import org.w3c.dom.NodeList; 13 | import org.xml.sax.SAXException; 14 | 15 | import javax.xml.parsers.DocumentBuilder; 16 | import javax.xml.parsers.DocumentBuilderFactory; 17 | import javax.xml.parsers.ParserConfigurationException; 18 | import java.io.IOException; 19 | import java.io.InputStream; 20 | import java.util.ArrayList; 21 | import java.util.List; 22 | 23 | /** 24 | * Display help information on git-versioner-maven-plugin.
25 | * Call 26 | * mvn git-versioner:help -Ddetail=true -Dgoal=<goal-name> to 27 | * display parameter details. 28 | * 29 | * @author maven-plugin-tools 30 | */ 31 | @Mojo(name = "help", requiresProject = false, threadSafe = true) 32 | public class HelpMojo extends AbstractMojo { 33 | /** 34 | * If true, display all settable properties for each goal. 35 | * 36 | */ 37 | @Parameter(property = "detail", defaultValue = "false") 38 | private boolean detail; 39 | 40 | /** 41 | * The name of the goal for which to show help. If unspecified, all goals will 42 | * be displayed. 43 | * 44 | */ 45 | @Parameter(property = "goal") 46 | private java.lang.String goal; 47 | 48 | /** 49 | * The maximum length of a display line, should be positive. 50 | * 51 | */ 52 | @Parameter(property = "lineLength", defaultValue = "80") 53 | private int lineLength; 54 | 55 | /** 56 | * The number of spaces per indentation level, should be positive. 57 | * 58 | */ 59 | @Parameter(property = "indentSize", defaultValue = "2") 60 | private int indentSize; 61 | 62 | // groupId/artifactId/plugin-help.xml 63 | private static final String PLUGIN_HELP_PATH = "/META-INF/maven/com.github.manikmagar/git-versioner-maven-plugin/plugin-help.xml"; 64 | 65 | private static final int DEFAULT_LINE_LENGTH = 80; 66 | 67 | private Document build() throws MojoExecutionException { 68 | getLog().debug("load plugin-help.xml: " + PLUGIN_HELP_PATH); 69 | InputStream is = null; 70 | try { 71 | is = getClass().getResourceAsStream(PLUGIN_HELP_PATH); 72 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 73 | DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 74 | return dBuilder.parse(is); 75 | } catch (IOException e) { 76 | throw new MojoExecutionException(e.getMessage(), e); 77 | } catch (ParserConfigurationException e) { 78 | throw new MojoExecutionException(e.getMessage(), e); 79 | } catch (SAXException e) { 80 | throw new MojoExecutionException(e.getMessage(), e); 81 | } finally { 82 | if (is != null) { 83 | try { 84 | is.close(); 85 | } catch (IOException e) { 86 | throw new MojoExecutionException(e.getMessage(), e); 87 | } 88 | } 89 | } 90 | } 91 | 92 | /** 93 | * {@inheritDoc} 94 | */ 95 | public void execute() throws MojoExecutionException { 96 | if (lineLength <= 0) { 97 | getLog().warn("The parameter 'lineLength' should be positive, using '80' as default."); 98 | lineLength = DEFAULT_LINE_LENGTH; 99 | } 100 | if (indentSize <= 0) { 101 | getLog().warn("The parameter 'indentSize' should be positive, using '2' as default."); 102 | indentSize = 2; 103 | } 104 | 105 | Document doc = build(); 106 | 107 | StringBuilder sb = new StringBuilder(); 108 | Node plugin = getSingleChild(doc, "plugin"); 109 | 110 | String name = getValue(plugin, "name"); 111 | String version = getValue(plugin, "version"); 112 | String id = getValue(plugin, "groupId") + ":" + getValue(plugin, "artifactId") + ":" + version; 113 | if (isNotEmpty(name) && !name.contains(id)) { 114 | append(sb, name + " " + version, 0); 115 | } else { 116 | if (isNotEmpty(name)) { 117 | append(sb, name, 0); 118 | } else { 119 | append(sb, id, 0); 120 | } 121 | } 122 | append(sb, getValue(plugin, "description"), 1); 123 | append(sb, "", 0); 124 | 125 | // plugin 126 | String goalPrefix = getValue(plugin, "goalPrefix"); 127 | 128 | Node mojos1 = getSingleChild(plugin, "mojos"); 129 | 130 | List mojos = findNamedChild(mojos1, "mojo"); 131 | 132 | if (goal == null || goal.length() <= 0) { 133 | append(sb, "This plugin has " + mojos.size() + (mojos.size() > 1 ? " goals:" : " goal:"), 0); 134 | append(sb, "", 0); 135 | } 136 | 137 | for (Node mojo : mojos) { 138 | writeGoal(sb, goalPrefix, (Element) mojo); 139 | } 140 | 141 | if (getLog().isInfoEnabled()) { 142 | getLog().info(sb.toString()); 143 | } 144 | } 145 | 146 | private static boolean isNotEmpty(String string) { 147 | return string != null && string.length() > 0; 148 | } 149 | 150 | private String getValue(Node node, String elementName) throws MojoExecutionException { 151 | return getSingleChild(node, elementName).getTextContent(); 152 | } 153 | 154 | private Node getSingleChild(Node node, String elementName) throws MojoExecutionException { 155 | List namedChild = findNamedChild(node, elementName); 156 | if (namedChild.isEmpty()) { 157 | throw new MojoExecutionException("Could not find " + elementName + " in plugin-help.xml"); 158 | } 159 | if (namedChild.size() > 1) { 160 | throw new MojoExecutionException("Multiple " + elementName + " in plugin-help.xml"); 161 | } 162 | return namedChild.get(0); 163 | } 164 | 165 | private List findNamedChild(Node node, String elementName) { 166 | List result = new ArrayList(); 167 | NodeList childNodes = node.getChildNodes(); 168 | for (int i = 0; i < childNodes.getLength(); i++) { 169 | Node item = childNodes.item(i); 170 | if (elementName.equals(item.getNodeName())) { 171 | result.add(item); 172 | } 173 | } 174 | return result; 175 | } 176 | 177 | private Node findSingleChild(Node node, String elementName) throws MojoExecutionException { 178 | List elementsByTagName = findNamedChild(node, elementName); 179 | if (elementsByTagName.isEmpty()) { 180 | return null; 181 | } 182 | if (elementsByTagName.size() > 1) { 183 | throw new MojoExecutionException("Multiple " + elementName + "in plugin-help.xml"); 184 | } 185 | return elementsByTagName.get(0); 186 | } 187 | 188 | private void writeGoal(StringBuilder sb, String goalPrefix, Element mojo) throws MojoExecutionException { 189 | String mojoGoal = getValue(mojo, "goal"); 190 | Node configurationElement = findSingleChild(mojo, "configuration"); 191 | Node description = findSingleChild(mojo, "description"); 192 | if (goal == null || goal.length() <= 0 || mojoGoal.equals(goal)) { 193 | append(sb, goalPrefix + ":" + mojoGoal, 0); 194 | Node deprecated = findSingleChild(mojo, "deprecated"); 195 | if ((deprecated != null) && isNotEmpty(deprecated.getTextContent())) { 196 | append(sb, "Deprecated. " + deprecated.getTextContent(), 1); 197 | if (detail && description != null) { 198 | append(sb, "", 0); 199 | append(sb, description.getTextContent(), 1); 200 | } 201 | } else if (description != null) { 202 | append(sb, description.getTextContent(), 1); 203 | } 204 | append(sb, "", 0); 205 | 206 | if (detail) { 207 | Node parametersNode = getSingleChild(mojo, "parameters"); 208 | List parameters = findNamedChild(parametersNode, "parameter"); 209 | append(sb, "Available parameters:", 1); 210 | append(sb, "", 0); 211 | 212 | for (Node parameter : parameters) { 213 | writeParameter(sb, parameter, configurationElement); 214 | } 215 | } 216 | } 217 | } 218 | 219 | private void writeParameter(StringBuilder sb, Node parameter, Node configurationElement) 220 | throws MojoExecutionException { 221 | String parameterName = getValue(parameter, "name"); 222 | String parameterDescription = getValue(parameter, "description"); 223 | 224 | Element fieldConfigurationElement = null; 225 | if (configurationElement != null) { 226 | fieldConfigurationElement = (Element) findSingleChild(configurationElement, parameterName); 227 | } 228 | 229 | String parameterDefaultValue = ""; 230 | if (fieldConfigurationElement != null && fieldConfigurationElement.hasAttribute("default-value")) { 231 | parameterDefaultValue = " (Default: " + fieldConfigurationElement.getAttribute("default-value") + ")"; 232 | } 233 | append(sb, parameterName + parameterDefaultValue, 2); 234 | Node deprecated = findSingleChild(parameter, "deprecated"); 235 | if ((deprecated != null) && isNotEmpty(deprecated.getTextContent())) { 236 | append(sb, "Deprecated. " + deprecated.getTextContent(), 3); 237 | append(sb, "", 0); 238 | } 239 | append(sb, parameterDescription, 3); 240 | if ("true".equals(getValue(parameter, "required"))) { 241 | append(sb, "Required: Yes", 3); 242 | } 243 | if ((fieldConfigurationElement != null) && isNotEmpty(fieldConfigurationElement.getTextContent())) { 244 | String property = getPropertyFromExpression(fieldConfigurationElement.getTextContent()); 245 | append(sb, "User property: " + property, 3); 246 | } 247 | 248 | append(sb, "", 0); 249 | } 250 | 251 | /** 252 | *

253 | * Repeat a String n times to form a new string. 254 | *

255 | * 256 | * @param str 257 | * String to repeat 258 | * @param repeat 259 | * number of times to repeat str 260 | * @return String with repeated String 261 | * @throws NegativeArraySizeException 262 | * if repeat < 0 263 | * @throws NullPointerException 264 | * if str is null 265 | */ 266 | private static String repeat(String str, int repeat) { 267 | StringBuilder buffer = new StringBuilder(repeat * str.length()); 268 | 269 | for (int i = 0; i < repeat; i++) { 270 | buffer.append(str); 271 | } 272 | 273 | return buffer.toString(); 274 | } 275 | 276 | /** 277 | * Append a description to the buffer by respecting the indentSize and 278 | * lineLength parameters. Note: The last character is always a new line. 279 | * 280 | * @param sb 281 | * The buffer to append the description, not null. 282 | * @param description 283 | * The description, not null. 284 | * @param indent 285 | * The base indentation level of each line, must not be negative. 286 | */ 287 | private void append(StringBuilder sb, String description, int indent) { 288 | for (String line : toLines(description, indent, indentSize, lineLength)) { 289 | sb.append(line).append('\n'); 290 | } 291 | } 292 | 293 | /** 294 | * Splits the specified text into lines of convenient display length. 295 | * 296 | * @param text 297 | * The text to split into lines, must not be null. 298 | * @param indent 299 | * The base indentation level of each line, must not be negative. 300 | * @param indentSize 301 | * The size of each indentation, must not be negative. 302 | * @param lineLength 303 | * The length of the line, must not be negative. 304 | * @return The sequence of display lines, never null. 305 | * @throws NegativeArraySizeException 306 | * if indent < 0 307 | */ 308 | private static List toLines(String text, int indent, int indentSize, int lineLength) { 309 | List lines = new ArrayList(); 310 | 311 | String ind = repeat("\t", indent); 312 | 313 | String[] plainLines = text.split("(\r\n)|(\r)|(\n)"); 314 | 315 | for (String plainLine : plainLines) { 316 | toLines(lines, ind + plainLine, indentSize, lineLength); 317 | } 318 | 319 | return lines; 320 | } 321 | 322 | /** 323 | * Adds the specified line to the output sequence, performing line wrapping if 324 | * necessary. 325 | * 326 | * @param lines 327 | * The sequence of display lines, must not be null. 328 | * @param line 329 | * The line to add, must not be null. 330 | * @param indentSize 331 | * The size of each indentation, must not be negative. 332 | * @param lineLength 333 | * The length of the line, must not be negative. 334 | */ 335 | private static void toLines(List lines, String line, int indentSize, int lineLength) { 336 | int lineIndent = getIndentLevel(line); 337 | StringBuilder buf = new StringBuilder(256); 338 | 339 | String[] tokens = line.split(" +"); 340 | 341 | for (String token : tokens) { 342 | if (buf.length() > 0) { 343 | if (buf.length() + token.length() >= lineLength) { 344 | lines.add(buf.toString()); 345 | buf.setLength(0); 346 | buf.append(repeat(" ", lineIndent * indentSize)); 347 | } else { 348 | buf.append(' '); 349 | } 350 | } 351 | 352 | for (int j = 0; j < token.length(); j++) { 353 | char c = token.charAt(j); 354 | if (c == '\t') { 355 | buf.append(repeat(" ", indentSize - buf.length() % indentSize)); 356 | } else if (c == '\u00A0') { 357 | buf.append(' '); 358 | } else { 359 | buf.append(c); 360 | } 361 | } 362 | } 363 | lines.add(buf.toString()); 364 | } 365 | 366 | /** 367 | * Gets the indentation level of the specified line. 368 | * 369 | * @param line 370 | * The line whose indentation level should be retrieved, must not be 371 | * null. 372 | * @return The indentation level of the line. 373 | */ 374 | private static int getIndentLevel(String line) { 375 | int level = 0; 376 | for (int i = 0; i < line.length() && line.charAt(i) == '\t'; i++) { 377 | level++; 378 | } 379 | for (int i = level + 1; i <= level + 4 && i < line.length(); i++) { 380 | if (line.charAt(i) == '\t') { 381 | level++; 382 | break; 383 | } 384 | } 385 | return level; 386 | } 387 | 388 | private String getPropertyFromExpression(String expression) { 389 | if (expression != null && expression.startsWith("${") && expression.endsWith("}") 390 | && !expression.substring(2).contains("${")) { 391 | // expression="${xxx}" -> property="xxx" 392 | return expression.substring(2, expression.length() - 1); 393 | } 394 | // no property can be extracted 395 | return null; 396 | } 397 | } 398 | -------------------------------------------------------------------------------- /git-versioner-maven-extension/src/test/java/com/github/manikmagar/maven/versioner/extension/ExtensionTestIT.java: -------------------------------------------------------------------------------- 1 | package com.github.manikmagar.maven.versioner.extension; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.Path; 7 | import java.nio.file.Paths; 8 | import java.nio.file.StandardCopyOption; 9 | 10 | import org.apache.commons.io.FileUtils; 11 | import org.apache.maven.it.Verifier; 12 | import org.eclipse.jgit.api.Git; 13 | import org.eclipse.jgit.api.errors.GitAPIException; 14 | import org.eclipse.jgit.lib.StoredConfig; 15 | import org.eclipse.jgit.revwalk.RevCommit; 16 | import org.junit.*; 17 | import org.junit.rules.TemporaryFolder; 18 | import org.junit.runner.RunWith; 19 | 20 | import junitparams.JUnitParamsRunner; 21 | import junitparams.Parameters; 22 | 23 | import static com.github.manikmagar.maven.versioner.extension.GitVersionerModelProcessor.DOT_MVN; 24 | import static com.github.manikmagar.maven.versioner.extension.GitVersionerModelProcessor.GIT_VERSIONER_EXTENSIONS_PROPERTIES; 25 | import static org.assertj.core.api.Assertions.assertThat; 26 | 27 | @RunWith(JUnitParamsRunner.class) 28 | public class ExtensionTestIT { 29 | 30 | @Rule 31 | public TemporaryFolder temporaryFolder = new TemporaryFolder(); 32 | 33 | @Before 34 | public void housekeeping() { 35 | // IT tests do not print to standard maven logs 36 | // It may look like process is stuck until all tests are executed in background. 37 | System.out.print("."); 38 | } 39 | @AfterClass 40 | public static void cleanHousekeeping() { 41 | System.out.println("."); 42 | System.out.println("IT Log files are available in target/it-logs/"); 43 | } 44 | 45 | @Test 46 | public void extensionBuildInitialVersion() throws Exception { 47 | File tempProject = setupTestProject(); 48 | try (Git git = getMain(tempProject)) { 49 | addEmptyCommit(git); 50 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 51 | verifier.displayStreamBuffers(); 52 | verifier.executeGoal("verify"); 53 | copyExecutionLog(tempProject, verifier, "extensionBuildInitialVersion.log.txt"); 54 | verifier.verifyErrorFreeLog(); 55 | String expectedVersion = "0.0.0-1"; 56 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 57 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 58 | assertThat(tempProject.toPath().resolve(Util.GIT_VERSIONER_POM_XML).toFile()).as("Git versioner pom file") 59 | .exists(); 60 | } 61 | } 62 | 63 | @Test 64 | public void extensionBuildVersionWithCommits() throws Exception { 65 | File tempProject = setupTestProject(); 66 | try (Git git = getMain(tempProject)) { 67 | addEmptyCommit(git); 68 | addEmptyCommit(git); 69 | addEmptyCommit(git); 70 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 71 | verifier.displayStreamBuffers(); 72 | verifier.executeGoal("verify"); 73 | copyExecutionLog(tempProject, verifier, "extensionBuildVersionWithCommits.log.txt"); 74 | verifier.verifyErrorFreeLog(); 75 | String expectedVersion = "0.0.0-3"; 76 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 77 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 78 | assertThat(tempProject.toPath().resolve(Util.GIT_VERSIONER_POM_XML).toFile()).as("Git versioner pom file") 79 | .exists(); 80 | } 81 | } 82 | 83 | @Test 84 | public void extensionBuildWithExistingPlugin() throws Exception { 85 | File tempProject = temporaryFolder.newFolder("test").toPath().toFile(); 86 | FileUtils.copyDirectory(Paths.get("src/test/resources/project-with-extension-plugin").toFile(), tempProject); 87 | try (Git git = getMain(tempProject)) { 88 | addEmptyCommit(git); 89 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 90 | verifier.displayStreamBuffers(); 91 | verifier.executeGoal("verify"); 92 | copyExecutionLog(tempProject, verifier, "extensionBuildWithExistingPlugin.log.txt"); 93 | verifier.verifyErrorFreeLog(); 94 | String expectedVersion = "0.0.0-1"; 95 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 96 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 97 | verifier.verifyTextInLog("Using existing plugin execution with id set-version"); 98 | assertThat(tempProject.toPath().resolve(Util.GIT_VERSIONER_POM_XML).toFile()).as("Git versioner pom file") 99 | .exists(); 100 | } 101 | } 102 | 103 | @Test 104 | public void extensionValidateVersionProperties() throws Exception { 105 | File tempProject = setupTestProject(); 106 | try (Git git = getMain(tempProject)) { 107 | addEmptyCommit(git); 108 | addCommit(git, "[patch]"); 109 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 110 | verifier.displayStreamBuffers(); 111 | verifier.executeGoal("verify"); 112 | copyExecutionLog(tempProject, verifier, "extensionValidateVersionProperties.log.txt"); 113 | verifier.verifyErrorFreeLog(); 114 | String expectedVersion = "0.0.1"; 115 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 116 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 117 | verifier.verifyTextInLog("git-versioner.commitNumber=0"); 118 | verifier.verifyTextInLog("git-versioner.major=0"); 119 | verifier.verifyTextInLog("git-versioner.minor=0"); 120 | verifier.verifyTextInLog("git-versioner.patch=1"); 121 | verifier.verifyTextInLog("git-versioner.version=0.0.1"); 122 | verifier.verifyTextInLog("git.branch="); 123 | verifier.verifyTextInLog("git.hash="); 124 | verifier.verifyTextInLog("git.hash.short="); 125 | } 126 | } 127 | @Test 128 | public void extensionBuildPatchVersion() throws Exception { 129 | File tempProject = setupTestProject(); 130 | try (Git git = getMain(tempProject)) { 131 | addEmptyCommit(git); 132 | addCommit(git, "[patch]"); 133 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 134 | verifier.displayStreamBuffers(); 135 | verifier.executeGoal("verify"); 136 | copyExecutionLog(tempProject, verifier, "extensionBuildPatchVersion.log.txt"); 137 | verifier.verifyErrorFreeLog(); 138 | String expectedVersion = "0.0.1"; 139 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 140 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 141 | } 142 | } 143 | @Test 144 | public void extensionBuildMinorVersion() throws Exception { 145 | File tempProject = setupTestProject(); 146 | try (Git git = getMain(tempProject)) { 147 | addEmptyCommit(git); 148 | addCommit(git, "[minor]"); 149 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 150 | verifier.displayStreamBuffers(); 151 | verifier.executeGoal("verify"); 152 | copyExecutionLog(tempProject, verifier, "extensionBuildMinorVersion.log.txt"); 153 | verifier.verifyErrorFreeLog(); 154 | String expectedVersion = "0.1.0"; 155 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 156 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 157 | } 158 | } 159 | @Test 160 | public void extensionBuildMajorVersion() throws Exception { 161 | File tempProject = setupTestProject(); 162 | try (Git git = getMain(tempProject)) { 163 | addEmptyCommit(git); 164 | addCommit(git, "[major]"); 165 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 166 | verifier.displayStreamBuffers(); 167 | verifier.executeGoal("verify"); 168 | copyExecutionLog(tempProject, verifier, "extensionBuildMajorVersion.log.txt"); 169 | verifier.verifyErrorFreeLog(); 170 | String expectedVersion = "1.0.0"; 171 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 172 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 173 | } 174 | } 175 | @Test 176 | public void extensionBuildHashVersion() throws Exception { 177 | File tempProject = setupTestProject(true, "3."); 178 | try (Git git = getMain(tempProject)) { 179 | addEmptyCommit(git); 180 | addCommit(git, "[patch]"); 181 | String hash = addCommit(git, "new commit"); 182 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 183 | verifier.displayStreamBuffers(); 184 | verifier.executeGoal("verify"); 185 | copyExecutionLog(tempProject, verifier, "extensionBuildHashVersion.log.txt"); 186 | verifier.verifyErrorFreeLog(); 187 | String expectedVersion = "1.3.5+" + hash.substring(0, 7); 188 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 189 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 190 | } 191 | } 192 | 193 | @Test 194 | public void extensionWithInitialVersionProperties() throws Exception { 195 | File tempProject = setupTestProject(true, "1."); 196 | try (Git git = getMain(tempProject)) { 197 | addEmptyCommit(git); 198 | addCommit(git, "[patch]"); 199 | String hash = addCommit(git, "new commit"); 200 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 201 | verifier.displayStreamBuffers(); 202 | verifier.executeGoal("verify"); 203 | copyExecutionLog(tempProject, verifier, "extensionWithInitialVersionProperties.log.txt"); 204 | verifier.verifyErrorFreeLog(); 205 | String expectedVersion = "1.3.5-1"; 206 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 207 | verifier.verifyTextInLog("versioner-maven-extension-test-" + expectedVersion + ".jar"); 208 | } 209 | } 210 | @Test 211 | public void extensionWithModule() throws Exception { 212 | File tempProject = temporaryFolder.newFolder("test").toPath().toFile(); 213 | FileUtils.copyDirectory(Paths.get("src/test/resources/multi-module-project").toFile(), tempProject); 214 | try (Git git = getMain(tempProject)) { 215 | addEmptyCommit(git); 216 | addCommit(git, "[patch]"); 217 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 218 | verifier.displayStreamBuffers(); 219 | verifier.executeGoal("verify"); 220 | copyExecutionLog(tempProject, verifier, "extensionWithModule.log.txt"); 221 | verifier.verifyErrorFreeLog(); 222 | String expectedVersion = "0.0.1"; 223 | verifier.verifyTextInLog("Building multi-module-parent " + expectedVersion); 224 | verifier.verifyTextInLog("Building cli " + expectedVersion); 225 | verifier.verifyTextInLog("Building lib " + expectedVersion); 226 | } 227 | } 228 | @Test 229 | public void extensionWithParentChild() throws Exception { 230 | File tempProject = temporaryFolder.newFolder("test").toPath().toFile(); 231 | FileUtils.copyDirectory(Paths.get("src/test/resources/parent-child-project").toFile(), tempProject); 232 | try (Git git = getMain(tempProject)) { 233 | addEmptyCommit(git); 234 | addCommit(git, "[patch]"); 235 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 236 | verifier.displayStreamBuffers(); 237 | verifier.executeGoal("verify"); 238 | copyExecutionLog(tempProject, verifier, "extensionWithParentChild.log.txt"); 239 | verifier.verifyErrorFreeLog(); 240 | String expectedVersion = "0.0.1"; 241 | verifier.verifyTextInLog("Building parent-test-pom " + expectedVersion); 242 | verifier.verifyTextInLog("Building cli " + expectedVersion); 243 | verifier.verifyTextInLog( 244 | "Setting parent com.github.manikmagar:parent-test-pom:pom:0 version to " + expectedVersion); 245 | verifier.verifyTextInLog("Building lib " + expectedVersion); 246 | } 247 | } 248 | 249 | @Test 250 | @Parameters(value = {"[BIG], 1.0.0", "[MEDIUM], 0.1.0", "[SMALL], 0.0.1"}) 251 | public void extensionWithVersionKeywordProperties(String key, String expectedVersion) throws Exception { 252 | File tempProject = setupTestProject(true, "2."); 253 | try (Git git = getMain(tempProject)) { 254 | addEmptyCommit(git); 255 | addCommit(git, key); 256 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 257 | verifier.displayStreamBuffers(); 258 | verifier.executeGoal("verify"); 259 | copyExecutionLog(tempProject, verifier, "extensionWithVersionKeywordProperties" + key + ".log.txt"); 260 | verifier.verifyErrorFreeLog(); 261 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 262 | } 263 | } 264 | 265 | @Test 266 | @Parameters(value = {"[BIG], 1.0.0, commit-major", "[MEDIUM], 0.1.0, commit-minor", "[SMALL], 0.0.1, commit-patch"}) 267 | public void extensionWithVersionKeyword_AddCommits(String key, String expectedVersion, String goal) 268 | throws Exception { 269 | File tempProject = setupTestProject(true, "2."); 270 | try (Git git = getMain(tempProject)) { 271 | addEmptyCommit(git); 272 | Verifier verifier = new Verifier(tempProject.getAbsolutePath(), true); 273 | verifier.displayStreamBuffers(); 274 | verifier.executeGoal("git-versioner:" + goal); 275 | verifier.executeGoal("verify"); 276 | copyExecutionLog(tempProject, verifier, "extensionWithVersionKeyword_AddCommits" + key + ".log.txt"); 277 | verifier.verifyErrorFreeLog(); 278 | verifier.verifyTextInLog("Building versioner-maven-extension-test " + expectedVersion); 279 | } 280 | } 281 | 282 | private static void copyExecutionLog(File tempProject, Verifier verifier, String logName) throws IOException { 283 | Path target = Files.createDirectories(Paths.get("./target/it-logs/")).resolve(logName); 284 | if (target.toFile().exists()) 285 | target.toFile().delete(); 286 | Files.copy(tempProject.toPath().resolve(verifier.getLogFileName()), target); 287 | } 288 | 289 | private static void addEmptyCommit(Git git) throws GitAPIException { 290 | git.commit().setSign(false).setMessage("Empty commit").setAllowEmpty(true).call(); 291 | } 292 | private static String addCommit(Git git, String message) throws GitAPIException { 293 | RevCommit commit = git.commit().setSign(false).setMessage(message).setAllowEmpty(true).call(); 294 | return commit.toObjectId().getName(); 295 | } 296 | 297 | private static Git getMain(File tempProject) throws GitAPIException, IOException { 298 | Git main = Git.init().setInitialBranch("main").setDirectory(tempProject).call(); 299 | StoredConfig config = main.getRepository().getConfig(); 300 | config.setString("user", null, "name", "GitHub Actions Test"); 301 | config.setString("user", null, "email", ""); 302 | config.save(); 303 | return main; 304 | } 305 | private File setupTestProject() throws IOException { 306 | return setupTestProject(false, ""); 307 | } 308 | private File setupTestProject(boolean copyProperties, String propPrefix) throws IOException { 309 | File tempProject = temporaryFolder.newFolder(); 310 | Path testProject = Paths.get("src/test/resources/project-with-extension/"); 311 | Files.copy(testProject.resolve("pom.xml"), tempProject.toPath().resolve("pom.xml"), 312 | StandardCopyOption.REPLACE_EXISTING); 313 | Path mvnDir = tempProject.toPath().resolve(DOT_MVN); 314 | Files.createDirectory(mvnDir); 315 | Files.copy(testProject.resolve(DOT_MVN).resolve("extensions.xml"), mvnDir.resolve("extensions.xml"), 316 | StandardCopyOption.REPLACE_EXISTING); 317 | if (copyProperties) { 318 | Files.copy(testProject.resolve(DOT_MVN).resolve(propPrefix.concat(GIT_VERSIONER_EXTENSIONS_PROPERTIES)), 319 | mvnDir.resolve(GIT_VERSIONER_EXTENSIONS_PROPERTIES), StandardCopyOption.REPLACE_EXISTING); 320 | assertThat(mvnDir.toFile().list()).contains(GIT_VERSIONER_EXTENSIONS_PROPERTIES); 321 | } 322 | assertThat(tempProject.list()).contains("pom.xml"); 323 | assertThat(mvnDir.toFile().list()).contains("extensions.xml"); 324 | return tempProject; 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.github.manikmagar 7 | git-versioner-maven-parent 8 | V-LATEST-SNAPSHOT 9 | pom 10 | 11 | Git Versioner Maven Parent 12 | Generate maven project version from git commit logs 13 | 2022 14 | 15 | git-versioner-maven-extension 16 | git-versioner-maven-core 17 | git-versioner-maven-plugin 18 | 19 | https://github.com/manikmagar/git-versioner-maven-plugin 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 3.8.1 26 | manikmagar/git-versioner-maven-plugin 27 | https://oss.sonatype.org 28 | git@github.com:${project.github.repository}.git 29 | 30 | 31 | 32 | scm:git:${repository.url} 33 | scm:ssh:${repository.url} 34 | HEAD 35 | ${repository.url} 36 | 37 | 38 | 39 | 40 | MIT 41 | https://spdx.org/licenses/MIT.html 42 | repo 43 | 44 | 45 | 46 | 47 | Manik Magar 48 | https://github.com/manikmagar 49 | 50 | 51 | 52 | 53 | manikmagar 54 | Manik Magar 55 | https://manik.magar.me 56 | 57 | 58 | 59 | 60 | github.com 61 | https://github.com/${project.github.repository}/issues 62 | 63 | 64 | 65 | 66 | 67 | src/main/resources 68 | true 69 | 70 | git-versioner-maven-*.properties 71 | 72 | 73 | 74 | 75 | 76 | 77 | org.apache.maven.plugins 78 | maven-site-plugin 79 | 3.7.1 80 | 81 | 82 | org.apache.maven.plugins 83 | maven-clean-plugin 84 | 3.1.0 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-javadoc-plugin 90 | 3.2.0 91 | 92 | 93 | org.apache.maven.plugins 94 | maven-source-plugin 95 | 3.3.1 96 | 97 | 98 | org.apache.maven.plugins 99 | maven-compiler-plugin 100 | 3.10.1 101 | 102 | 103 | org.apache.maven.plugins 104 | maven-plugin-plugin 105 | 3.6.1 106 | 107 | 108 | org.apache.maven.plugins 109 | maven-surefire-plugin 110 | 3.0.0-M5 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-jar-plugin 115 | 3.4.1 116 | 117 | 118 | org.apache.maven.plugins 119 | maven-install-plugin 120 | 3.1.2 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-deploy-plugin 125 | 3.1.1 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-invoker-plugin 130 | 3.1.0 131 | 132 | 133 | org.codehaus.mojo 134 | flatten-maven-plugin 135 | 1.3.0 136 | 137 | 138 | net.revelc.code 139 | impsort-maven-plugin 140 | 1.12.0 141 | 142 | java.,javax.,org.,com. 143 | true 144 | true 145 | 146 | 147 | 148 | sort-imports 149 | 150 | sort 151 | 152 | process-sources 153 | 154 | 155 | 156 | 157 | org.apache.maven.plugins 158 | maven-failsafe-plugin 159 | 3.3.1 160 | 161 | 162 | com.diffplug.spotless 163 | spotless-maven-plugin 164 | 2.43.0 165 | 166 | 167 | 168 | 169 | *.md 170 | .gitignore 171 | 172 | 173 | 174 | 175 | 176 | true 177 | 4 178 | 179 | 180 | 181 | 182 | 183 | 184 | 4.13.0 185 | 186 | 187 | 188 | 189 | 190 | checkSpotlessx 191 | 192 | check 193 | 194 | compile 195 | 196 | 197 | applySpotless 198 | 199 | apply 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | org.apache.maven.plugins 209 | maven-compiler-plugin 210 | 211 | 8 212 | ${java.version} 213 | ${java.version} 214 | 215 | -Xplugin:jabel 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | org.eclipse.jgit 226 | org.eclipse.jgit 227 | 228 | 5.13.1.202206130422-r 229 | 230 | 231 | org.twdata.maven 232 | mojo-executor 233 | 2.4.0 234 | 235 | 236 | com.github.manikmagar 237 | semver4j 238 | 0.2.0 239 | 240 | 241 | org.apache.maven 242 | maven-plugin-api 243 | ${maven.version} 244 | provided 245 | 246 | 247 | org.apache.maven 248 | maven-core 249 | ${maven.version} 250 | provided 251 | 252 | 253 | org.apache.maven 254 | maven-compat 255 | ${maven.version} 256 | test 257 | 258 | 259 | org.apache.maven.plugin-tools 260 | maven-plugin-annotations 261 | 3.6.4 262 | provided 263 | 264 | 265 | junit 266 | junit 267 | 4.13.2 268 | test 269 | 270 | 271 | pl.pragmatists 272 | JUnitParams 273 | 1.1.0 274 | test 275 | 276 | 277 | org.assertj 278 | assertj-core 279 | 3.24.2 280 | test 281 | 282 | 283 | org.mockito 284 | mockito-inline 285 | 4.8.0 286 | test 287 | 288 | 289 | org.apache.maven.plugin-testing 290 | maven-plugin-testing-harness 291 | 3.3.0 292 | test 293 | 294 | 295 | org.apache.maven.shared 296 | maven-verifier 297 | 1.8.0 298 | test 299 | 300 | 301 | com.github.bsideup.jabel 302 | jabel-javac-plugin 303 | 1.0.0 304 | provided 305 | 306 | 307 | 308 | 309 | 310 | junit 311 | junit 312 | 313 | 314 | pl.pragmatists 315 | JUnitParams 316 | 317 | 318 | org.assertj 319 | assertj-core 320 | 321 | 322 | org.mockito 323 | mockito-inline 324 | 325 | 326 | com.github.bsideup.jabel 327 | jabel-javac-plugin 328 | 329 | 330 | 331 | 332 | 333 | intellij-idea-only 334 | 335 | 336 | idea.maven.embedder.version 337 | 338 | 339 | 340 | 341 | 342 | org.apache.maven.plugins 343 | maven-compiler-plugin 344 | 345 | 11 346 | 347 | 348 | 349 | 350 | 351 | 352 | run-its 353 | 354 | 355 | 356 | 357 | org.apache.maven.plugins 358 | maven-javadoc-plugin 359 | 360 | 361 | attach-javadocs 362 | 363 | jar 364 | 365 | 366 | true 367 | 368 | 369 | 370 | 371 | 372 | org.apache.maven.plugins 373 | maven-invoker-plugin 374 | 3.1.0 375 | 376 | false 377 | 378 | */pom.xml 379 | 380 | ${project.build.directory}/local-repo 381 | 382 | 383 | 384 | integration-test 385 | 386 | install 387 | integration-test 388 | verify 389 | 390 | 391 | 392 | 393 | 394 | org.apache.maven.plugins 395 | maven-failsafe-plugin 396 | 397 | 398 | ${project.build.directory}/local-repo 399 | 400 | 401 | 402 | 403 | 404 | integration-test 405 | verify 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | deploy 415 | 416 | true 417 | true 418 | 419 | 420 | 421 | 422 | org.codehaus.mojo 423 | flatten-maven-plugin 424 | 1.3.0 425 | 426 | 427 | flatten 428 | process-resources 429 | 430 | flatten 431 | 432 | 433 | ossrh 434 | 435 | 436 | 437 | flatten.clean 438 | clean 439 | 440 | clean 441 | 442 | 443 | 444 | 445 | 446 | org.apache.maven.plugins 447 | maven-source-plugin 448 | 449 | 450 | attach-sources 451 | 452 | jar 453 | 454 | 455 | true 456 | 457 | 458 | 459 | 460 | 461 | org.apache.maven.plugins 462 | maven-javadoc-plugin 463 | 464 | 465 | attach-javadocs 466 | 467 | jar 468 | 469 | 470 | true 471 | 472 | 473 | 474 | 475 | 476 | org.jreleaser 477 | jreleaser-maven-plugin 478 | 1.9.0 479 | 480 | jreleaser.yml 481 | 482 | 483 | 484 | 485 | 486 | 487 | build-stage 488 | default 489 | file://${project.build.directory}/staging-deploy 490 | 491 | 492 | 493 | 494 | 495 | --------------------------------------------------------------------------------