Cannot find '.git' directory breaks the build even if the plugin is not used
What happened?
When I run tests with Github Actions it may copy source code without .git directory, therefore the build fails with:
* What went wrong:
An exception occurred applying plugin request [id: 'com.palantir.git-version', version: '0.12.2']
> Failed to apply plugin [id 'com.palantir.git-version']
> Cannot find '.git' directory
What did you want to happen?
Show error but keep build usable, especially if plugin is not used (but declared)
The problem that it fails right inside GitVersionPlugin.apply(), so the line id 'com.palantir.git-version' version '0.12.2' causes the build to fail even before any task has started. It happens even if I don't use the plugin functionality for this particular task (ex. for the unit testing, like in my case).
Same here. We optionally build your project in Docker, and .dockerignore contains .git, so inside Docker we build without Git information. That's basically fine as we can override the Gradle version property for that case, but as already just applying the plugin fails with a missing .git directory, the code to do so becomes a bit ugly.
I made a workaround in our projects build.gradle.kts, I hope it helps;
import java.io.File
import java.io.FileInputStream
import java.util.Properties
plugins {
java
id("com.palantir.git-version") version "0.12.3" apply false
}
fun getProps(f: File): Properties {
val props = Properties()
props.load(FileInputStream(f))
return props
}
val folder = project.file("src/main/resources");
if (!folder.exists()) {
folder.mkdirs()
}
val props = project.file("src/main/resources/version.properties")
var iscleanTag = false
try {
// apply this plugin in a try-catch block so that we can handle cases without .git directory
apply(plugin = "com.palantir.git-version")
val versionDetails: groovy.lang.Closure<com.palantir.gradle.gitversion.VersionDetails> by extra
val details = versionDetails()
isCleanTag = detials.isCreanTag
if (isCleanTag) {
// project tagging v1.2.3 style for releases
version = details.lastTag.substring(1)
} else {
// 1.2.3-1-abcdefg-SNAPSHOT
version = details.lastTag.substring(1) + "-" + details.commitDistance + "-" + details.gitHash + "-SNAPSHOT"
}
tasks.register("writeVersionFile") {
props.delete()
props.appendText("version=" + project.version + "\n")
props.appendText("commit=" + details.gitHashFull + "\n")
props.appendText("branch=" + details.branchName)
}
tasks.getByName("jar") {
dependsOn("writeVersionFile")
}
} catch (e:Exception) {
// source distribution have version.properties produced in above block
if (props.exists()) {
val versionProperties = getProps(props)
version = versionProperties.getProperty("version")
} else {
// last fall back
version = "1.0.0-SNAPSHOT"
}
}
signing { onlyIf { isCleanTag } }
Here is an idea to produce version.properties file. It can be used in application to show help message/about dialog with its version as a primary purpose.