Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for configuration cache #164

Merged
merged 8 commits into from Mar 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 31 additions & 17 deletions README.md
Expand Up @@ -7,22 +7,31 @@ Idea - @lievendoclo, originally published in article [Spring Boot's info endpoin

[![Build Status](https://travis-ci.org/n0mer/gradle-git-properties.svg?branch=master)](https://travis-ci.org/n0mer/gradle-git-properties)

## compatibility matrix

This Gradle plugin is compatible with the following versions of Gradle:

| Plugin version | Min. Gradle version |
| -------------- | ------------------- |
| 2.3.0 | 5.1 |
| 2.2.4 | 4.x |

## notes
* Plugin requires Java 8+
* If git.properties is missing on gradle 5.1.x and 5.2.x [Issue 128](https://github.com/n0mer/gradle-git-properties/issues/128), use gitPropertiesResourceDir to config a diffrent output directory
* Since gradle-git-properties v2.x, we requires jgit 5.x, this might cause some issues if you have other gradle plugin which uses jgit 1.4.x. In that case, you can use gradle-git-properties v1.5.x (instead of 2.x) which uses jgit 1.4.x. See [Issue 133](https://github.com/n0mer/gradle-git-properties/issues/133) for more info about this plugin's dependencies
* If `git.properties` is missing on Gradle 5.1.x and 5.2.x [Issue 128](https://github.com/n0mer/gradle-git-properties/issues/128), use `gitPropertiesResourceDir` to config a different output directory
* Since gradle-git-properties v2.x, we require JGit 5.x, this might cause some issues if you have other gradle plugin which uses JGit 1.4.x. In that case, you can use gradle-git-properties v1.5.x (instead of 2.x) which uses JGit 1.4.x. See [Issue 133](https://github.com/n0mer/gradle-git-properties/issues/133) for more info about this plugin's dependencies

## usage

Declare this in your `build.gradle`

```groovy
plugins {
id "com.gorylenko.gradle-git-properties" version "2.2.4"
id "com.gorylenko.gradle-git-properties" version "2.3.0"
}
```

A git.properties file will be generated when building Java-based projects (the plugin will configure any existing `classes` task to depend on `generateGitProperties` task - which is responsible for generated git.properties file). For non-Java projects, `generateGitProperties` task must be executed explicitly to generate git.properties file. The git repository for the project will be used.
A `git.properties` file will be generated when building Java-based projects (the plugin will configure any existing `classes` task to depend on `generateGitProperties` task - which is responsible for generated `git.properties` file). For non-Java projects, `generateGitProperties` task must be executed explicitly to generate `git.properties` file. The git repository for the project will be used.

Spring Boot specific info: This is enough to see git details via `info` endpoint of [spring-boot-actuator](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready).

Expand Down Expand Up @@ -92,7 +101,7 @@ git.remote.origin.url
git.tags
git.total.commit.count
```
You can have more fine grained control of the content of 'git.properties' using `keys`:
You can have more fine-grained control of the content of `git.properties` using `keys`:

```groovy
gitProperties {
Expand All @@ -110,7 +119,7 @@ gitProperties {
}
```

You can also replace standard properties using `customProperty`. In the below example, the logic `it.describe(tags: true)` will replace plugin's logic which using `describe(tags: false)`
You can also replace standard properties using `customProperty`. In the below example, the logic `it.describe(tags: true)` will replace the plugin's logic which using `describe(tags: false)`

```groovy
gitProperties {
Expand All @@ -122,10 +131,11 @@ gitProperties {
```


> Spring Boot specific info: By default, the `info` endpoint exposes only `git.branch`, `git.commit.id`, and `git.commit.time` properties (even then there are more in your git.properties).
> Spring Boot specific info: By default, the `info` endpoint exposes only `git.branch`, `git.commit.id`, and `git.commit.time` properties (even then there are more in your `git.properties`).
> In order to expose all available properties, set the "management.info.git.mode" property to "full" per [the Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#production-ready-application-info-git), e.g. in application.properties:

> `management.info.git.mode=full`
> ```
> management.info.git.mode=full
> ```


The `.git` directory for the project should be detected automatically, otherwise it can be specified manually using `dotGitDirectory`:
Expand All @@ -144,15 +154,15 @@ gitProperties {
}
```

To skip plugin execution completely, configure task's `enabled` property:
To skip plugin execution completely, configure the `enabled` property:

```groovy
tasks.withType(com.gorylenko.GenerateGitPropertiesTask).all { enabled = false }
```

## result from `info` endpoint (if used with Spring Boot apps)

When using with Spring Boot: This is raw `JSON` from `info` endpoint (with management.info.git.mode=simple or not configured):
When using with Spring Boot: This is raw `JSON` from `info` endpoint (with `management.info.git.mode=simple` or not configured):

```json
{
Expand All @@ -166,7 +176,7 @@ When using with Spring Boot: This is raw `JSON` from `info` endpoint (with manag
}
```

This is raw `JSON` from `info` endpoint (with management.info.git.mode=full):
This is raw `JSON` from `info` endpoint (with `management.info.git.mode=full`):

```json
{
Expand Down Expand Up @@ -222,7 +232,10 @@ This is raw `JSON` from `info` endpoint (with management.info.git.mode=full):

### other usages

This plugin can also be used for other purposes (by configuring `extProperty` to keep generated properties and accessing the properties from `project.ext`). Note that the git.properties file is always generated and currently there is no option to disable it. Also please make sure that the `generateGitProperties` task is executed before accessing the generated properties.
This plugin can also be used for other purposes (by configuring `extProperty` to keep generated properties and accessing the properties from `project.ext`).

Note that the `git.properties` file is always generated and currently there is no option to disable it.
Please also make sure that the `generateGitProperties` task is executed before accessing the generated properties.

In the below example, `printGitProperties` will print `git.commit.id.abbrev` property when it is executed:

Expand All @@ -239,7 +252,7 @@ task printGitProperties(dependsOn: 'generateGitProperties') { // make sure gener
}
```

Below is another example about using generated properties for MANIFEST.MF of a Spring Boot webapp (similar can be done for non Spring apps). Note the usage of GString lazy evaluation to delay evaluating `project.ext.gitProps['git.commit.id.abbrev']` until MANIFEST.MF is created. Because `generateGitProperties` task will always execute automatically before any `classes` task (in Java projects), no `dependsOn` is needed for `bootJar` task.
Below is another example about using generated properties for `MANIFEST.MF` of a Spring Boot webapp (similar can be done for non Spring apps). Note the usage of `GString` lazy evaluation to delay evaluating `project.ext.gitProps['git.commit.id.abbrev']` until `MANIFEST.MF` is created. Because `generateGitProperties` task will always execute automatically before any `classes` task (in Java projects), no `dependsOn` is needed for `bootJar` task.

```groovy
gitProperties {
Expand All @@ -255,13 +268,14 @@ bootJar {
}
}
```
Note: Kotlin DSL syntax (similar to above GString example)

Note: Kotlin DSL syntax (similar to above `GString` example)
```kotlin
...
// [...]
put("Implementation-Version", object {
override fun toString():String = (project.extra["gitProps"] as Map<String, String>)["git.commit.id"]!!
})
...
// [...]
```
## license

Expand Down
4 changes: 3 additions & 1 deletion build.gradle
@@ -1,6 +1,7 @@
plugins {
id 'groovy'
id 'maven-publish'
id 'java-gradle-plugin'
id "com.gradle.plugin-publish" version "0.13.0"
id "com.gorylenko.gradle-git-properties" version "2.2.4"
}
Expand Down Expand Up @@ -30,9 +31,10 @@ dependencies {


testImplementation 'junit:junit:4.12'
testImplementation gradleTestKit()
}

version = "2.2.4"
version = "2.3.0"
group = "com.gorylenko.gradle-git-properties"

gitProperties {
Expand Down
108 changes: 63 additions & 45 deletions src/main/groovy/com/gorylenko/GenerateGitPropertiesTask.groovy
@@ -1,52 +1,67 @@
package com.gorylenko

import org.gradle.api.GradleException
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity

import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.GradleException
import org.gradle.api.Transformer
import org.gradle.api.file.Directory
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileTree
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction

import javax.inject.Inject

@CacheableTask
class GenerateGitPropertiesTask extends DefaultTask {
public class GenerateGitPropertiesTask extends DefaultTask {
public static final String TASK_NAME = "generateGitProperties"

private static final String DEFAULT_OUTPUT_DIR = "resources/main"

private final GitPropertiesPluginExtension gitProperties

GenerateGitPropertiesTask() {
// Description for the task
description = 'Generate a git.properties file.'

outputs.upToDateWhen {
this.gitProperties = project.extensions.getByType(GitPropertiesPluginExtension)

outputs.upToDateWhen { GenerateGitPropertiesTask task ->
// when extProperty is configured or failOnNoGitDirectory=false always execute the task
return !gitProperties.extProperty && gitProperties.failOnNoGitDirectory
return !task.getGitProperties().extProperty && task.getGitProperties().failOnNoGitDirectory
}
}

private Map<String, String> generatedProperties

@Internal
public GitPropertiesPluginExtension getGitProperties() {
return project.gitProperties
@Inject
ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException()
}

@Inject
ProjectLayout getLayout() {
throw new UnsupportedOperationException()
}

@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public FileTree getSource() {
File dotGitDirectory = getDotGitDirectory(project)
return (dotGitDirectory == null) ? project.files().asFileTree : project.files(dotGitDirectory).asFileTree
File dotGitDirectory = getDotGitDirectory()
return (dotGitDirectory == null) ? layout.files().asFileTree : layout.files(dotGitDirectory).asFileTree
}

@OutputFile
public File getOutput() {
return getGitPropertiesFile(project)
public RegularFileProperty getOutput() {
return getGitPropertiesFile()
}

/**
Expand All @@ -66,7 +81,7 @@ class GenerateGitPropertiesTask extends DefaultTask {
return [:]
}

File dotGitDirectory = getDotGitDirectory(project)
File dotGitDirectory = getDotGitDirectory()

if (dotGitDirectory == null) {
throw new GradleException("No Git repository found.")
Expand All @@ -90,6 +105,10 @@ class GenerateGitPropertiesTask extends DefaultTask {
return this.generatedProperties
}

@Internal
GitPropertiesPluginExtension getGitProperties() {
return gitProperties
}

@TaskAction
void generate() {
Expand All @@ -110,14 +129,20 @@ class GenerateGitPropertiesTask extends DefaultTask {

// Write to git.properties file

logger.debug("gitProperties.gitPropertiesResourceDir=" + gitProperties.gitPropertiesResourceDir)
logger.debug("gitProperties.gitPropertiesDir=" + gitProperties.gitPropertiesDir)
logger.debug("gitProperties.gitPropertiesName=" + gitProperties.gitPropertiesName)
logger.debug("gitProperties.gitPropertiesResourceDir=${gitProperties.gitPropertiesResourceDir}")
logger.debug("gitProperties.gitPropertiesDir=${gitProperties.gitPropertiesDir}")
logger.debug("gitProperties.gitPropertiesName=${gitProperties.gitPropertiesName}")

File file = getGitPropertiesFile(project)
logger.info "git.properties location = [${file?.absolutePath}]"
RegularFileProperty file = getGitPropertiesFile()
def absolutePath = file.asFile.map(new Transformer<String, File>() {
@Override
String transform(File f) {
f.absolutePath
}
}).getOrElse("unknown")
logger.info "git.properties location = [${absolutePath}]"

boolean written = new PropertiesFileWriter().write(newMap, file, gitProperties.force)
boolean written = new PropertiesFileWriter().write(newMap, file.asFile.get(), gitProperties.force)
if (written) {
logger.info("Written properties to [${file}]...")
} else {
Expand All @@ -126,10 +151,9 @@ class GenerateGitPropertiesTask extends DefaultTask {

}

private static File getDotGitDirectory(Project project) {
GitPropertiesPluginExtension gitProperties = project.gitProperties
File dotGitDirectory = gitProperties.dotGitDirectory ? project.file(gitProperties.dotGitDirectory) : null
return new GitDirLocator(project.projectDir).lookupGitDirectory(dotGitDirectory)
private File getDotGitDirectory() {
DirectoryProperty dotGitDirectory = gitProperties.dotGitDirectory
return new GitDirLocator(layout.projectDirectory.asFile).lookupGitDirectory(dotGitDirectory.asFile.get())
}


Expand All @@ -138,32 +162,26 @@ class GenerateGitPropertiesTask extends DefaultTask {
// at the end of evaluation phase (to make sure extension values are set)
logger.debug "GenerateGitPropertiesTask: found Java plugin"
if (gitProperties.gitPropertiesResourceDir) {
logger.debug ("gitProperties.gitPropertiesResourceDir=" + gitProperties.gitPropertiesResourceDir)
String gitPropertiesDir = getGitPropertiesDir(project).absolutePath
logger.debug("gitProperties.gitPropertiesResourceDir=${gitProperties.gitPropertiesResourceDir}")
String gitPropertiesDir = getGitPropertiesDir().asFile.absolutePath
project.sourceSets.main.resources.srcDir gitPropertiesDir
logger.info "GenerateGitPropertiesTask: added classpath entry(gitPropertiesResourceDir): ${gitPropertiesDir}"
}
}

private File getGitPropertiesDir(Project project) {
GitPropertiesPluginExtension gitProperties = project.gitProperties

File gitPropertiesDir
if (gitProperties.gitPropertiesResourceDir) {
gitPropertiesDir = project.file(gitProperties.gitPropertiesResourceDir)
} else if (gitProperties.gitPropertiesDir) {
gitPropertiesDir = project.file(gitProperties.gitPropertiesDir)
private Directory getGitPropertiesDir() {
if (gitProperties.gitPropertiesResourceDir.present) {
return gitProperties.gitPropertiesResourceDir.get()
} else if (gitProperties.gitPropertiesDir.present) {
return gitProperties.gitPropertiesDir.get()
} else {
gitPropertiesDir = new File(project.buildDir, DEFAULT_OUTPUT_DIR)
return layout.buildDirectory.dir(DEFAULT_OUTPUT_DIR).get()
}

return gitPropertiesDir
}

private File getGitPropertiesFile(Project project) {
GitPropertiesPluginExtension gitProperties = project.gitProperties
File gitPropertiesDir = getGitPropertiesDir(project)
File gitPropertiesFile = new File(gitPropertiesDir, gitProperties.gitPropertiesName)
return gitPropertiesFile
private RegularFileProperty getGitPropertiesFile() {
def fileProperty = objectFactory.fileProperty()
fileProperty.set(getGitPropertiesDir().file(gitProperties.gitPropertiesName))
return fileProperty
}
}