2 Commits
Author SHA1 Message Date
Hartmut Bauer e9e28d2ce7 Rewrite: Plugin creates Version-class 2026-01-10 21:43:42 +01:00
Hartmut Bauer 0ec2193cc7 Versionsinfo in META-INF/MANIFEST.MF eintragen 2025-03-12 00:22:03 +01:00
10 changed files with 293 additions and 154 deletions

No files matched your search

+22 -12
View File
@@ -1,27 +1,37 @@
import java.time.Instant
/*
* This file was generated by the Gradle 'init' task.
*
* This is a general purpose Gradle build.
* To learn more about Gradle by exploring our Samples at https://docs.gradle.org/8.6/samples
*/
plugins {
`kotlin-dsl`
`maven-publish`
}
repositories {
mavenCentral()
maven("https://nexus.keinekekse.net/repository/maven-public/")
}
group = "net.keinekekse"
version = libs.versions.versionplugin.get()
version = masterLibs.versions.versionPluginVersion.get()
description = "Adds version information to the project."
project.ext.set("displayname", "Version-Plugin")
project.ext.set("copyright", "(c) 2024 Hartmut Bauer")
project.ext.set("buildTimestamp", Instant.now().toString())
extra["displayname"] = "Version-Plugin"
extra["copyright"] = "Copyright (c) 2024-2026 Hartmut Bauer"
extra["buildTimestamp"] = Instant.now().toString()
dependencies {
implementation(masterLibs.semver)
compileOnly(masterLibs.kotlinGradlePlugin)
}
publishing {
repositories {
maven {
credentials {
username = "admin"
password = "admin123"
}
url = uri("https://nexus.keinekekse.net/repository/maven-releases/")
}
}
}
gradlePlugin {
plugins {
create("version-plugin") {
@@ -33,6 +43,6 @@ gradlePlugin {
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
languageVersion.set(JavaLanguageVersion.of(masterLibs.versions.javaVersion.get()))
}
}
+1
View File
@@ -0,0 +1 @@
kotlin.code.style=official
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+7 -8
View File
@@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -84,7 +86,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -112,7 +114,6 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -170,7 +171,6 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@@ -203,15 +203,14 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
Vendored
+3 -2
View File
@@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@@ -68,11 +70,10 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
+6 -9
View File
@@ -1,16 +1,13 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.6/userguide/multi_project_builds.html in the Gradle documentation.
*/
rootProject.name = "version-plugin"
dependencyResolutionManagement {
repositories {
maven("https://nexus.keinekekse.net/repository/maven-public/")
}
versionCatalogs {
create("libs") {
from(files("../../gradle-deps/libs.versions.toml"))
create("masterLibs") {
from("net.keinekekse:version-catalog:104")
}
}
}
@@ -1,12 +1,134 @@
package net.keinekekse.version
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.TaskAction
import io.github.z4kn4fein.semver.Version
import io.github.z4kn4fein.semver.withoutSuffixes
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import java.util.*
abstract class AddVersionTask : Copy() {
abstract class AddVersionTask : DefaultTask() {
// 1. Define what triggers the task (Source Files)
@get:InputFiles
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val sourceFiles: ConfigurableFileCollection
// 2. Define the output (The properties file)
@get:OutputFile
abstract val buildNumberFile: RegularFileProperty
@get:OutputFile
abstract val versionClassFile: RegularFileProperty
@get:Input
abstract val projectVersion: Property<String>
@get:Input
abstract val projectName: Property<String>
@get:Input
abstract val projectDescription: Property<String>
@get:Input
abstract val displayNameExtra: Property<String>
@get:Input
abstract val copyrightExtra: Property<String>
@get:Input
abstract val versionPackageName: Property<String>
@TaskAction
fun updateVersion() {
// action is defined in plugin
fun execute() {
println("execute task: incrementBuildNumber")
val buildNumber = incrementAndGetBuildNumber()
writeClassFile(buildNumber)
}
private fun writeClassFile(buildNumber: String) {
val ver = getVersionInfo(buildNumber)
val file = versionClassFile.get().asFile
file.parentFile.mkdirs()
file.writeText(
"""
package ${versionPackageName.get()}
object VERSION {
const val version = "${ver.version}"
const val fullVersion = "${ver.fullVersion}"
const val major = ${ver.major}
const val minor = ${ver.minor}
const val patch = ${ver.patch}
const val preRelease = "${ver.preRelease}"
const val buildMetadata = "${ver.buildMetadata}"
const val buildDate = "${ver.buildDate}"
const val displayName = "${ver.displayName}"
const val copyright = "${ver.copyright}"
const val name = "${ver.name}"
const val description = "${ver.description}"
}
""".trimIndent()
)
}
private fun getVersionInfo(buildNumber: String): VersionInfo {
val version =
if (Version.parse(projectVersion.get(), strict = false).buildMetadata.isNullOrEmpty())
Version.parse(projectVersion.get() + "+build.$buildNumber", strict = false)
else Version.parse(projectVersion.get(), strict = false)
println("Source files changed. Setting version to $version")
return VersionInfo(
major = version.major,
minor = version.minor,
patch = version.patch,
preRelease = version.preRelease ?: "",
buildMetadata = version.buildMetadata ?: "",
fullVersion = version.toString(),
version = if (version.isPreRelease) version.toString() else
version.withoutSuffixes().toString(),
buildDate = java.time.Instant.now().toString(),
displayName = displayNameExtra.get(),
copyright = copyrightExtra.get(),
name = projectName.get(),
description = projectDescription.get() ?: ""
)
}
private fun incrementAndGetBuildNumber(): String {
val file = buildNumberFile.get().asFile
val props = Properties()
if (file.exists()) {
file.inputStream().use { props.load(it) }
}
val current = props.getProperty("build.number")?.toLongOrNull() ?: 0
val actual = (current + 1).toString()
props.setProperty("build.number", actual)
file.outputStream().use {
props.store(it, "auto generated")
}
return actual
}
data class VersionInfo(
val version: String,
val fullVersion: String,
val major: Int,
val minor: Int,
val patch: Int,
val preRelease: String,
val buildMetadata: String,
val buildDate: String,
val displayName: String,
val copyright: String,
val name: String,
val description: String,
)
}
@@ -1,129 +1,143 @@
package net.keinekekse.version
import org.gradle.api.InvalidUserDataException
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.RegularFile
import org.gradle.api.tasks.bundling.Jar
import org.gradle.api.tasks.bundling.War
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.getValue
import org.gradle.kotlin.dsl.named
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.util.*
import org.gradle.api.tasks.SourceSetContainer
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
/**
* Versions-Resource im Projekt anlegen und bei jedem Build eine Build-Nummer hochzählen
*
* Ohne weitere Konfiguration wird die Datei Version.kt mit der class VERSION im Verzeichnis
* src/main/kotlin/<project.group>/<project.name> erzeugt, für KMP in src/commonMain/kotlin.
* Die class wird mit Daten aus build.gradle.kts befüllt (s.u.).
*
* Für die Build-Nummer wird eine Datei buildnumber.properties im Projektverzeichnis erzeugt.
*
* Die class-Datei und der Package-Name können ggf. in build.gradle.kts konfiguriert werden:
*
* ```
* plugins {
* // Plugin einbinden
* id("net.keinekekse.version") version "3.0.0"
* }
*
* // Werte, die für die Version-Datei verwendet werden
* // in settings.gradle.kt: rootProject.name = "program-name"
* group = "org.example"
* version = "0.0.1-beta.1"
* description = "Program description"
* extra["displayname"] = "Program"
* extra["copyright"] = "Copyright (c) 2025 Hartmut Bauer"
*
*
* // Optional: Konfiguration der Version-Datei und des Packages
* versionConfig {
* versionClassFile.set(layout.projectDirectory.file("src/main/kotlin/Version.kt"))
* versionPackageName.set("net.keinekekse")
* }
* ```
*
* VERSION-class:
*
* ```
* object VERSION {
* const val version = "1.0.0-beta.1+build.13" // für Release-Ver: major.minor.patch
* const val fullVersion = "1.0.0-beta.1+build.13"
* const val major = 1
* const val minor = 0
* const val patch = 0
* const val preRelease = "beta.1"
* const val buildMetadata = "build.13"
* const val buildDate = "2026-01-10T18:54:42.227942Z"
* const val displayName = "Program"
* const val copyright = "Copyright (c) 2026 Hartmut Bauer"
* const val name = "program-name"
* const val description = "Program description"
* }
* ```
*
*
*/
class VersionPlugin : Plugin<Project> {
private lateinit var versionFileName: String
private val buildNumProp = "buildNumber"
private val addTaskName = "addVersion"
private var isWar = false
override fun apply(project: Project) {
// println("Version Plugin")
val extension = project.extensions.create("version", VersionPluginExtension::class.java)
versionFileName = extension.propertiesFilename.orNull ?: "${project.name}.properties"
val extension =
project.extensions.create("versionConfig", VersionPluginExtension::class.java)
val warSource =
project.layout.projectDirectory.file("src/main/webapp/WEB-INF/classes/${versionFileName}")
val jarSource =
project.layout.projectDirectory.file("src/main/properties/${versionFileName}")
val targetDir = project.layout.buildDirectory.dir("resources/main")
val countFile = project.layout.projectDirectory.file("buildnumber.properties")
if (warSource.asFile.parentFile.parentFile.exists()) {
isWar = true
}
if (isWar) {
if (!warSource.asFile.parentFile.exists())
warSource.asFile.parentFile.mkdir()
checkVersionFile(warSource)
} else {
checkVersionFile(jarSource)
}
val versionTask =
project.tasks.register("incrementBuildNumber", AddVersionTask::class.java) {
if (!extension.versionClassFile.isPresent) {
val packageName =
project.group.toString().replace("-", ".") +
"." + project.name.replace("-", ".")
val versionFileName = packageName.replace(".", "/") + "/Version.kt"
if (isWar) {
try {
project.tasks.named<War>("war") {
filesMatching("**/${versionFileName}") {
val num = buildNumber(countFile)
project.extra[buildNumProp] = num
expand(project.properties)
var targ = "src/main/kotlin/"
if (!project.layout.projectDirectory.file(targ).asFile.exists()) {
targ = "src/commonMain/kotlin/"
if (!project.layout.projectDirectory.file(targ).asFile.exists()) {
throw InvalidUserDataException(
"Version-Plugin: 'versionClassFile' and 'versionPackageName' must " +
"be set in a versionConfig-block in build.gradle.kts, " +
"as both 'src/main/kotlin' and 'src/commonMain/kotlin' do not exist!"
)
}
}
}
} catch (e: Exception) {
println("\n*** Falsche Reihenfolge ***\n\nWAR-Plugin muss vor dem Versions-Plugin eingetragen werden!\n")
throw e
}
} else {
project.tasks.named<Jar>("jar") {
dependsOn(project.tasks.named(addTaskName))
}
project.tasks.register(addTaskName, AddVersionTask::class.java) {
group = "net.keinekekse"
description = "Adds version information to the project."
outputs.upToDateWhen { false }
mustRunAfter(project.tasks.named("classes"))
onlyIf {
val cj by project.tasks.named("compileJava")
val pr by project.tasks.named("processResources")
// (cj.state.didWork || pr.didWork)
((cj.state.didWork && !cj.state.upToDate) || (pr.didWork && !pr.state.upToDate))
extension.versionClassFile.convention(project.layout.projectDirectory.file(targ + versionFileName))
extension.versionPackageName.convention(packageName)
}
from(jarSource)
into(targetDir)
filesMatching("*") {
val num = buildNumber(countFile)
project.extra[buildNumProp] = num
expand(project.properties)
}
// Point to the source sets
val files = project.files(
"src/main/kotlin", "src/main/java",
"src/commonMain/kotlin", "src/commonMain/java",
"src/jvmMain/kotlin", "src/jvmMain/java"
)
// Filter lazily using a provider
sourceFiles.from(extension.versionClassFile.map { classFile ->
files.asFileTree.filter { it.name != classFile.asFile.name }
})
// Point to the properties file
buildNumberFile.set(project.layout.projectDirectory.file("buildnumber.properties"))
// Link properties directly (this is lazy)
versionClassFile.set(extension.versionClassFile)
versionPackageName.set(extension.versionPackageName)
projectVersion.set(project.provider { project.version.toString() })
projectName.set(project.provider { project.name })
projectDescription.set(project.provider { project.description ?: "" })
displayNameExtra.set(project.provider {
project.extensions.extraProperties.let {
if (it.has("displayname")) it.get("displayname")?.toString() else ""
}
})
copyrightExtra.set(project.provider {
project.extensions.extraProperties.let {
if (it.has("copyright")) it.get("copyright")?.toString() else ""
}
})
}
// 1. Handle Kotlin/JVM (Standard Project)
project.plugins.withId("org.jetbrains.kotlin.jvm") {
project.extensions.getByType(SourceSetContainer::class.java).named("main") {
// This tells Gradle that this source set includes the directory containing the generated file
this.java.srcDir(versionTask.map { it.versionClassFile.get().asFile.parentFile })
}
}
}
/**
* Increment build number
*/
private fun buildNumber(propFile: RegularFile): String {
val propName = "build.number"
val props = Properties()
try {
FileInputStream(propFile.asFile).use { props.load(it) }
} catch (e: Exception) {
// noop
// 2. Handle Kotlin Multiplatform
project.plugins.withId("org.jetbrains.kotlin.multiplatform") {
val kotlinExt = project.extensions.getByType(KotlinMultiplatformExtension::class.java)
kotlinExt.sourceSets.named("commonMain") {
this.kotlin.srcDir(versionTask.map { it.versionClassFile.get().asFile.parentFile })
}
}
val numStr: String? = props.getProperty(propName)
var num = numStr?.toLongOrNull() ?: 0
num++
println("build number ${num}")
props.setProperty(propName, num.toString())
props.store(FileOutputStream(propFile.asFile, false), "auto generated")
return num.toString()
}
/**
* Create version properties file if it doesn't exist
*/
private fun checkVersionFile(file: RegularFile) {
if (!file.asFile.exists()) {
val content = """
|name=${'$'}{name}
|displayname=${'$'}{displayname}
|description=${'$'}{description}
|copyright=${'$'}{copyright}
|version=${'$'}{version}
|build.number=${'$'}{${buildNumProp}}
|build.timestamp=${'$'}{buildTimestamp}
""".trimMargin()
val outfile = OutputStreamWriter(FileOutputStream(file.asFile))
outfile.write(content)
outfile.close()
}
}
}
@@ -1,15 +1,10 @@
package net.keinekekse.version
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
interface VersionPluginExtension {
val versionPackageName: Property<String>
/**
* Name for the version properties file
* (JAR: src/main/properties, WAR: src/main/webapp/WEB-INF/classes)
* Will be copied to the classpath root.
*
* Default: <project.name>.properties
*/
val propertiesFilename: Property<String>
val versionClassFile: RegularFileProperty
}