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

Refactors task's inputs to support configuration cache for modern Gradle versions #235

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,22 +139,19 @@ gitProperties {
> ```


The `.git` directory for the project should be detected automatically, otherwise it can be specified manually using `dotGitDirectory`:
If the `.git` directory is not located in the same directory as the Gradle project, you will need to specify it using `dotGitDirectory`:

```groovy
gitProperties {
// if .git directory is on the same level as the root project
dotGitDirectory = project.rootProject.layout.projectDirectory.dir(".git")

// if .git directory is in a different location
dotGitDirectory = "${project.rootDir}/../somefolder/.git"
}
```

Note: Kotlin DSL syntax
```kotlin
configure<com.gorylenko.GitPropertiesPluginExtension> {
(dotGitDirectory as DirectoryProperty).set("${project.rootDir}/../somefolder/.git")
}
```

If for some reason, the `.git` directory for the project doesn't exist and you don't want the task to fail in that case, use `failOnNoGitDirectory=false`:
If for some reason, the `.git` directory for the project doesn't exist, and you don't want the task to fail in that case, use `failOnNoGitDirectory=false`:

```groovy
gitProperties {
Expand Down
70 changes: 32 additions & 38 deletions src/main/groovy/com/gorylenko/GenerateGitPropertiesTask.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import org.gradle.api.DefaultTask
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.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
Expand All @@ -28,20 +28,30 @@ public class GenerateGitPropertiesTask extends DefaultTask {

private final GitPropertiesPluginExtension gitProperties

private final FileTree source
private final Property<Object> projectVersion

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

this.gitProperties = project.extensions.getByType(GitPropertiesPluginExtension)

// we will not be able to access the project in the @TaskAction method,
// if the configuration cache is enabled
this.source = project.fileTree(gitProperties.dotGitDirectory) {
include('config')
include('HEAD')
include('refs/**')
}
this.projectVersion = project.objects.property(Object).convention(project.version)

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

private Map<String, String> generatedProperties

@Inject
ObjectFactory getObjectFactory() {
throw new UnsupportedOperationException()
Expand All @@ -55,54 +65,39 @@ public class GenerateGitPropertiesTask extends DefaultTask {
@InputFiles
@PathSensitive(PathSensitivity.RELATIVE)
public FileTree getSource() {
File dotGitDirectory = getDotGitDirectory()
return (dotGitDirectory == null) ? layout.files().asFileTree : layout.files(dotGitDirectory).asFileTree
return source
}

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

/**
* To support cacheable task and UP-TO-DATE check
*/
@Input
public Map<String, String> getGeneratedProperties() {

if (this.generatedProperties != null) return this.generatedProperties
public Property<Object> getProjectVersion() {
return projectVersion
}

private Map<String, String> generateProperties() {
if (logger.debugEnabled) {
logger.debug("gitProperties = ${gitProperties}")
}

if (!gitProperties.failOnNoGitDirectory && getSource().empty) {
logger.info("Exiting because no Git repository found and failOnNoGitDirectory = false.")
return [:]
}

File dotGitDirectory = getDotGitDirectory()

if (dotGitDirectory == null) {
throw new GradleException("No Git repository found.")
}

File dotGitDirectory = gitProperties.dotGitDirectory.get().asFile
logger.info("dotGitDirectory = [${dotGitDirectory?.absolutePath}]")


// Generate properties

GitProperties builder = new GitProperties()
Map<String, String> newMap = builder.generate(dotGitDirectory,
gitProperties.keys, gitProperties.dateFormat, gitProperties.dateFormatTimeZone, gitProperties.branch,
project.version, gitProperties.customProperties)
projectVersion.get(), gitProperties.customProperties)

if (logger.debugEnabled) {
logger.debug("Generated Git properties = ${newMap}")
}
generatedProperties = newMap

return this.generatedProperties
return newMap
}

@Internal
Expand All @@ -113,22 +108,26 @@ public class GenerateGitPropertiesTask extends DefaultTask {
@TaskAction
void generate() {

if (!gitProperties.failOnNoGitDirectory && getSource().empty) {
logger.info("Exiting because no Git repository found and failOnNoGitDirectory = false.")
return
if (getSource().empty) {
if (gitProperties.failOnNoGitDirectory) {
throw new GradleException(
"No Git repository found. " +
"Ensure the gitProperties.dotGitDirectory property points to the correct .git directory.")
} else {
logger.info("No Git repository found and failOnNoGitDirectory = false.")
return
}
}

Map<String, String> newMap = getGeneratedProperties()
Map<String, String> newMap = generateProperties()

// Expose generated properties to project.ext[gitProperties.extProperty] if configured

if (gitProperties.extProperty) {
logger.debug("Exposing git properties model to project.ext[${gitProperties.extProperty}]")
project.ext[gitProperties.extProperty] = new HashMap(newMap)
}

// Write to git.properties file

logger.debug("gitProperties.gitPropertiesResourceDir=${gitProperties.gitPropertiesResourceDir}")
logger.debug("gitProperties.gitPropertiesDir=${gitProperties.gitPropertiesDir}")
logger.debug("gitProperties.gitPropertiesName=${gitProperties.gitPropertiesName}")
Expand All @@ -150,11 +149,6 @@ public class GenerateGitPropertiesTask extends DefaultTask {
}
}

private File getDotGitDirectory() {
DirectoryProperty dotGitDirectory = gitProperties.dotGitDirectory
return new GitDirLocator(layout.projectDirectory.asFile).lookupGitDirectory(dotGitDirectory.asFile.get())
}

private Directory getGitPropertiesDir() {
if (gitProperties.gitPropertiesResourceDir.present) {
return gitProperties.gitPropertiesResourceDir.get()
Expand Down
53 changes: 0 additions & 53 deletions src/main/groovy/com/gorylenko/GitDirLocator.groovy

This file was deleted.

3 changes: 0 additions & 3 deletions src/main/groovy/com/gorylenko/GitPropertiesPlugin.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,9 @@ class GitPropertiesPlugin implements Plugin<Project> {

@ToString(includeNames=true)
class GitPropertiesPluginExtension {
@InputDirectory
final DirectoryProperty gitPropertiesDir
@InputDirectory
final DirectoryProperty gitPropertiesResourceDir
String gitPropertiesName = "git.properties"
@InputDirectory
final DirectoryProperty dotGitDirectory
List keys = GitProperties.standardProperties
Map<String, Object> customProperties = [:]
Expand Down
5 changes: 3 additions & 2 deletions src/test/groovy/com/gorylenko/BasicFunctionalTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder

import static org.hamcrest.CoreMatchers.containsString
import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertTrue
import static org.junit.Assert.assertThat

public class BasicFunctionalTest {
@Rule
Expand All @@ -32,7 +33,7 @@ public class BasicFunctionalTest {
def result = runner.buildAndFail()

assertEquals(TaskOutcome.FAILED, result.task(":generateGitProperties").outcome)
assertTrue(result.output.contains("No Git repository found."))
assertThat(result.output, containsString("No Git repository found."))
}

@Test
Expand Down
68 changes: 0 additions & 68 deletions src/test/groovy/com/gorylenko/GitDirLocatorTest.groovy

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import org.junit.After
import org.junit.Before
import org.junit.Test

import static org.hamcrest.CoreMatchers.startsWith
import static org.junit.Assert.assertEquals
import static org.junit.Assert.assertFalse
import static org.junit.Assert.assertNotNull
import static org.junit.Assert.assertThat
import static org.junit.Assert.assertTrue
import static org.junit.Assert.fail

Expand Down Expand Up @@ -93,7 +95,7 @@ class GitPropertiesPluginTests {
fail('should have gotten a GradleException')
} catch (Exception e) {
assertEquals(GradleException, e.class)
assertEquals("No Git repository found.", e.message)
assertThat(e.message, startsWith("No Git repository found."))
}
}
}