Gradle Git Properties Plugin

June 19, 2026 · View on GitHub

Build Status Gradle Plugin Portal

A Gradle plugin that generates a git.properties file containing Git repository metadata at build time.

Table of Contents

Requirements

  • Java 17 or higher
  • Gradle 5.1 – 9.x
  • A Git repository (.git directory or git worktree)

Installation

Add the plugin to your build file:

Groovy DSL (build.gradle)

plugins {
    id "com.gorylenko.gradle-git-properties" version "4.0.1"
}

Kotlin DSL (build.gradle.kts)

plugins {
    id("com.gorylenko.gradle-git-properties") version "4.0.1"
}

The plugin generates git.properties at build/resources/main/git.properties. For Java projects, generation occurs automatically during the build. For non-Java projects, run the task explicitly:

./gradlew generateGitProperties

Configuration

All configuration is optional. The plugin uses sensible defaults.

Output Location

Customize the output file name and directory:

gitProperties {
    gitPropertiesName = "git-info.properties"
    gitPropertiesResourceDir = file("${project.rootDir}/src/main/resources")
}

Note: The older gitPropertiesDir property is deprecated. Replace it with gitPropertiesResourceDir.

Commit Timestamp Format

Configure the format and timezone for git.commit.time using SimpleDateFormat patterns and TimeZone IDs.

By default (no configuration), git.commit.time uses pattern yyyy-MM-dd'T'HH:mm:ssZ with the build machine's JVM default timezone.

Note: Z pattern (RFC 822 numeric offset) produces +0000 for UTC, not a literal Z. Use XXX (ISO 8601) to get Z for UTC and offsets like +05:30 for other timezones.

Warning: An unrecognized dateFormatTimeZone ID silently falls back to UTC — e.g. EST silently produces UTC output; use America/New_York instead. Verify IDs against Java's supported timezone IDs.

GoaldateFormatdateFormatTimeZoneExample output
Default (no config)(not set)(not set)2024-03-20T08:13:53+0300
Epoch seconds (empty string bypasses formatting)""(not set)1710904433
RFC 822, forced UTCyyyy-MM-dd'T'HH:mm:ssZUTC2024-03-20T05:13:53+0000
ISO 8601 with Z suffixyyyy-MM-dd'T'HH:mm:ssXXXUTC2024-03-20T05:13:53Z
ISO 8601 with specific timezoneyyyy-MM-dd'T'HH:mm:ssXXXAmerica/New_York2024-03-20T01:13:53-04:00
ISO 8601 with build machine timezoneyyyy-MM-dd'T'HH:mm:ssXXX(not set)2024-03-20T08:13:53+03:00

Commit ID Abbreviation Length

Configure the length of git.commit.id.abbrev (default: 7, range: 2-40):

gitProperties {
    commitIdAbbrevLength = 10
}

Available Properties

By default, the plugin generates all available properties:

PropertyDescription
git.branchCurrent branch name
git.commit.idFull 40-character commit SHA
git.commit.id.abbrevAbbreviated commit SHA (default 7 characters, configurable)
git.commit.id.describeHuman-readable name from git describe
git.commit.timeCommit timestamp
git.commit.message.shortCommit message (first line)
git.commit.message.fullCommit message (full text)
git.commit.user.nameCommit author name
git.commit.user.emailCommit author email
git.build.hostHostname of the build machine
git.build.user.nameName of the user running the build
git.build.user.emailEmail of the user running the build
git.build.versionProject version (project.version)
git.dirtytrue if working tree has uncommitted changes
git.tagsTags pointing to the current commit
git.closest.tag.nameName of the nearest ancestor tag
git.closest.tag.commit.countNumber of commits since the nearest tag
git.remote.origin.urlURL of the remote origin
git.total.commit.countTotal number of commits in the repository

To generate only specific properties, use the keys option:

gitProperties {
    keys = ['git.branch', 'git.commit.id', 'git.commit.time']
}

Custom Properties

Add custom properties using static values or closures. Closures receive a GitFacade instance for accessing Git data:

gitProperties {
    customProperty 'greeting', 'Hello'
    customProperty 'my_custom_git_id', { it.head().id }
    customProperty 'project_version', { project.version }
}

You can also override standard properties. This example includes lightweight tags in git.commit.id.describe:

gitProperties {
    customProperty 'git.commit.id.describe', { it.describe(tags: true) }
}

GitFacade API

The GitFacade class provides these methods for custom properties:

MethodReturnsDescription
head()GitCommitHEAD commit (id, abbreviatedId, author, dateTime, shortMessage, fullMessage)
status()GitStatusWorking tree status (clean property)
describe(options)StringGit describe output. Options: tags: true, longDescr: true
log(options)List<GitCommit>Commit history. Options: maxCommits: N
branch.current()GitBranchInfoCurrent branch info (use .name for branch name)
tag.list()List<GitTag>All tags (use .name for tag name)
getConfig(section, name)StringGit config value
isEmpty()booleanTrue if repository has no commits

Escape Hatch (Advanced)

For operations not covered by GitFacade, access the underlying JGit API:

gitProperties {
    // Access raw JGit Repository
    customProperty 'refs.count', { it.jgit.refDatabase.refs.size() }
    
    // Access JGit Git command interface (caller must close)
    customProperty 'stash.count', {
        def git = it.jgitCommands
        try {
            return git.stashList().call().size()
        } finally {
            git.close()
        }
    }
}

Branch Name

Override the detected branch name. This is useful in CI environments where builds run in detached HEAD state:

gitProperties {
    branch = System.getenv('BRANCH_NAME')
}

The plugin automatically detects branch names from these CI environments:

  • GitHub Actions
  • GitLab CI
  • Jenkins
  • CircleCI
  • Travis CI
  • Azure DevOps
  • Bitbucket Pipelines
  • Bamboo
  • AWS CodeBuild

Git Directory Location

Specify a custom .git directory location:

gitProperties {
    dotGitDirectory = layout.projectDirectory.dir("../.git")
}

To suppress errors when the .git directory is missing:

gitProperties {
    failOnNoGitDirectory = false
}

Disabling the Plugin

To disable git.properties generation:

tasks.withType(com.gorylenko.GenerateGitPropertiesTask).configureEach {
    enabled = false
}

Kotlin DSL Notes

Most configuration works identically in Kotlin DSL. For custom properties with closures, use KotlinClosure1:

import org.gradle.kotlin.dsl.KotlinClosure1
import com.gorylenko.jgit.GitFacade

gitProperties {
    dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    dateFormatTimeZone = "UTC"
    keys = listOf("git.branch", "git.commit.id", "git.commit.time")
    customProperty("greeting", "Hello")
    customProperty("my_custom_git_id", KotlinClosure1<GitFacade, String>({ head().id }))
}

Spring Boot Integration

The plugin integrates with Spring Boot Actuator. The /info endpoint automatically includes Git information when git.properties is present on the classpath.

By default, Spring Boot exposes only git.branch, git.commit.id, and git.commit.time. To expose all properties, add to application.properties:

management.info.git.mode=full
Example response from /actuator/info

Default mode:

{
  "git": {
    "commit": {
      "time": "2018-03-28T05:13:53Z",
      "id": "32ff212"
    },
    "branch": "Fix_issue_68"
  }
}

Full mode (management.info.git.mode=full):

{
  "git": {
    "build": {
      "host": "myserver-1",
      "version": "0.0.1-SNAPSHOT",
      "user": {
        "name": "First Last",
        "email": "username1@example.com"
      }
    },
    "branch": "Fix_issue_68",
    "commit": {
      "message": {
        "short": "Fix issue #68",
        "full": "Fix issue #68"
      },
      "id": {
        "describe": "v1.4.21-28-g32ff212-dirty",
        "abbrev": "32ff212",
        "full": "32ff212b9e2873fa4672f1b5dd41f67aca6e0731"
      },
      "time": "2018-03-28T05:13:53Z",
      "user": {
        "email": "username1@example.com",
        "name": "First Last"
      }
    },
    "closest": {
      "tag": {
        "name": "v1.4.21",
        "commit": {
          "count": "28"
        }
      }
    },
    "dirty": "true",
    "remote": {
      "origin": {
        "url": "git@github.com:n0mer/gradle-git-properties.git"
      }
    },
    "tags": "",
    "total": {
      "commit": {
        "count": "93"
      }
    }
  }
}

Advanced Usage

Accessing Properties at Build Time

Use extProperty to expose generated properties to other build tasks. This enables use cases such as printing Git info during the build or embedding the Git commit ID in JAR manifests.

Printing Git properties from a task:

gitProperties {
    extProperty = 'gitProps'
}

// Ensure properties are always regenerated
generateGitProperties.outputs.upToDateWhen { false }

task printGitProperties {
    dependsOn generateGitProperties
    // Capture project.ext before doLast for configuration cache compatibility
    def ext = project.ext
    doLast {
        println "git.branch=" + ext.gitProps['git.branch']
    }
}

Why def ext = project.ext before doLast? Gradle's configuration cache forbids referencing project inside doLast (execution phase). Capturing project.ext at configuration time—before doLast—keeps the task configuration-cache safe.

Embedding Git info in a JAR manifest (Spring Boot example):

gitProperties {
    extProperty = 'gitProps'
}

// Ensure properties are always regenerated
generateGitProperties.outputs.upToDateWhen { false }

bootJar {
    dependsOn generateGitProperties
    manifest {
        // Use lazy GString evaluation to defer property access
        attributes('Git-Commit': "${-> project.ext.gitProps['git.commit.id.abbrev']}")
    }
}

Compatibility

Plugin VersionGradleJavaNotes
4.0.x5.1 – 9.x17+Fixed overlapping outputs; processResources auto-wired
3.0.x5.1 – 9.x17+JGit backend, git worktree support
2.5.x5.1 – 9.x8+Grgit backend (deprecated)

The plugin supports Gradle configuration cache and git worktrees.

Migration Guide

Upgrading from 3.x

Version 4.0 changes the default output directory for generateGitProperties from build/resources/main/ to build/generated/resources/git/. The file still ends up at the root of your JAR — processResources copies it there.

  • Default config: No action needed.
  • gitPropertiesDir set explicitly: Behaviour unchanged, but deprecated — migrate to gitPropertiesResourceDir.
  • gitPropertiesResourceDir set explicitly: Behaviour unchanged.

See MIGRATION.md for the full migration table.

Upgrading from 2.x

Version 3.0 replaces the Grgit backend with JGit. Key changes:

  • Java 17+ required (was Java 8)
  • Custom properties: Closures now receive GitFacade instead of Grgit. See GitFacade API for available methods.
  • JGit escape hatch: For advanced use cases, access jgit (Repository) or jgitCommands (Git) directly.

Standard configuration options (keys, dateFormat, branch, etc.) are unchanged.

See MIGRATION.md for detailed upgrade instructions.

License

This project is licensed under the Apache License 2.0.


Originally inspired by @lievendoclo's article "Spring Boot's info endpoint, Git and Gradle" (2014).