Gradle automatically generates version number from git and uses it in Java

Thing you want to do

Referenced site

Automatically assign version number with Gradle ~ Collaboration with git-describe grgit-gradle BuildConfig Gradle-plugin for Java and Groovy projects

Implementation

build.gradle


plugins {
    id 'idea'
    id 'application'
    id 'org.ajoberstar.grgit' version '3.1.1'
    id 'de.fuerstenau.buildconfig' version '1.1.8'
}

group 'com.example'
version = {
    def tags = grgit.tag.list().collect { it.getName() }
    def versionStr
    if (tags.any { it ==~ /v\d.*/ }) {
        versionStr = grgit.describe(longDescr: false, tags: true, match: ["v[0-9]*"])
    } else {
        versionStr = grgit.head().abbreviatedId
    }
    return versionStr + (grgit.status().isClean() ? "" : "+dirty")
}()

repositories {
    mavenCentral()
}

task showVersion {
    doLast {
        println version
    }
}

mainClassName = 'Main'

Main.java


import com.example.BuildConfig;

public class Main {

    public static void main(String... args) {
        System.out.println(BuildConfig.VERSION);
    }
}

Execution example

If there is no tag indicating the version

2f9b747  //Commit hash

If HEAD has a tag indicating the version

v0.1

When committing additionally from the tag indicating the version

v0.0-10-g3636be7

If there are uncommitted changes

v0.0-10-g3636be7+dirty

Recommended Posts

Gradle automatically generates version number from git and uses it in Java
Implement Java Interface in JRuby class and call it from Java
Hello world in Java and Gradle
Using JavaScript from Java in Rhino 2021 version
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Capture and save from selenium installation in Java
Generate OffsetDateTime from Clock and LocalDateTime in Java
[Android development] Get an image from the server in Java and set it in ImageView! !!
Get the value from the array and find out what number it is included in
Write a class in Kotlin and call it in Java
Reverse Enum constants from strings and values in Java
JSON in Java and Jackson Part 1 Return JSON from the server
[Kotlin] Get Java Constructor / Method from KFunction and call it
Correct the character code in Java and read from the URL
Get attributes and values from an XML file in Java
Java version 8 and later features
Using Docker from Java Gradle
In Java 10, when you do gradle eclipse and JavaSE-1.10 comes out, ...
Install the memcached plugin on MySQL and access it from Java