Skip to content

Commit bb13910

Browse files
authored
Add version command line option
PR: #52
1 parent 2065208 commit bb13910

File tree

8 files changed

+141
-79
lines changed

8 files changed

+141
-79
lines changed

.github/workflows/develop.yml

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,15 @@ jobs:
2424
uses: gradle/actions/setup-gradle@v4.2.2
2525

2626
- name: Build
27-
run: ./gradlew build
27+
run: |
28+
./gradlew build
29+
mv scripting-host/build/distributions/scripting-host-release*.tar.gz scripting-host-release.tar.gz
2830
2931
- name: Upload build
3032
uses: actions/upload-artifact@v4.5.0
3133
with:
3234
name: release-artifact
33-
path: scripting-host/build/distributions/scripting-host-release.tar.gz
35+
path: scripting-host-release.tar.gz
3436
compression-level: '0'
3537
retention-days: 7
3638

@@ -53,7 +55,19 @@ jobs:
5355
name: release-artifact
5456

5557
- name: Untar release artifact
56-
run: tar --extract --gunzip --file scripting-host-release.tar.gz
58+
run: |
59+
mkdir scripting-host-release
60+
tar --extract --gunzip --directory scripting-host-release --strip-components 1 --file scripting-host-release.tar.gz
61+
62+
- name: Test version output
63+
timeout-minutes: 1
64+
run: |
65+
version="$(cat gradle.properties | sed -n 's/version=//p')"
66+
hostVersion=$(./scripting-host-release/bin/kss --version)
67+
if [ "$hostVersion" != "Version: $version" ]; then
68+
echo "host version ($hostVersion) doesn't match gradle properties version ($version)"
69+
exit 1
70+
fi
5771
5872
- name: Start nginx
5973
uses: nyurik/action-setup-nginx@v1.1

.github/workflows/release.yml

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ jobs:
2626
- name: Create info variables
2727
id: variables
2828
run: |
29-
echo "version=${GITHUB_REF#refs/*/}" >> $GITHUB_OUTPUT
29+
gradleVersion="$(cat gradle.properties | sed -n 's/version=//p')"
30+
gitVersion="${GITHUB_REF#refs/*/}"
31+
if [ "$gradleVersion" != "$gitVersion" ]; then
32+
echo "gradle properties version ($gradleVersion) doesn't match git tag version ($gitVersion)"
33+
exit 1
34+
fi
35+
echo "version=$gitVersion" >> $GITHUB_OUTPUT
3036
3137
- name: Get Changelog
3238
id: changelog
@@ -41,7 +47,7 @@ jobs:
4147
body: "${{ steps.changelog.outputs.changes }}"
4248
fail_on_unmatched_files: true
4349
files: |
44-
scripting-host/build/distributions/scripting-host-release.tar.gz
45-
scripting-host/build/distributions/scripting-host-release.zip
50+
scripting-host/build/distributions/scripting-host-release*.tar.gz
51+
scripting-host/build/distributions/scripting-host-release*.zip
4652
draft: false
4753
prerelease: false

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
- test for install script
1010
- option to install via release archive file
1111
- option to set local maven repository settings
12+
- version and help command line option
1213

1314
### Changed
1415

gradle.properties

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@
1717
kotlin.code.style=official
1818
org.gradle.caching=true
1919
org.gradle.parallel=true
20+
21+
version=0.5.0-SNAPSHOT

gradle/libs.versions.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
[versions]
2+
clikt = "5.0.2"
23
kotlin = "2.1.0"
34
kotlinx-coroutines = "1.10.1"
45
logback = "1.5.15"
56
oshai-logging = "7.0.3"
67
okio = "3.9.1"
78

89
[libraries]
10+
clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" }
911
kotlin-scripting-common = { module = "org.jetbrains.kotlin:kotlin-scripting-common", version.ref = "kotlin" }
1012
kotlin-scripting-dependencies = { module = "org.jetbrains.kotlin:kotlin-scripting-dependencies", version.ref = "kotlin" }
1113
kotlin-scripting-dependencies-maven = { module = "org.jetbrains.kotlin:kotlin-scripting-dependencies-maven", version.ref = "kotlin" }

install.sh

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -255,16 +255,16 @@ fi
255255
github_args=(--location ${authorization_args[@]+"${authorization_args[@]}"} --header 'X-GitHub-Api-Version: 2022-11-28')
256256

257257
# shellcheck disable=SC2016
258-
query='query ($user: String!, $repo: String!, $asset: String!) { repository(owner: $user, name: $repo) { latestRelease { releaseAssets(name: $asset, first: 1) { nodes { url } } } } }'
258+
query='query ($user: String!, $repo: String!) { repository(owner: $user, name: $repo) { latestRelease { releaseAssets(first: 10) { nodes { contentType url } } } } }'
259259

260260
function extractUrlFromGraphqlQuery() {
261-
local response=$1
262-
if [[ -n $(command -v jq || echo '') ]]; then
263-
jq --raw-output '.data.repository.latestRelease.releaseAssets.nodes[0].url' <<< "$response"
264-
else
265-
local response_tmp="${response%\"*}"
266-
echo "${response_tmp##*\"}"
267-
fi
261+
local response=$1
262+
if [[ -n $(command -v jq || echo '') ]]; then
263+
jq --raw-output '.data.repository.latestRelease.releaseAssets.nodes | map(select(.contentType == "application/gzip"))[0].url' <<< "$response"
264+
else
265+
local response_tmp="${response#*\"contentType\":\"application\/gzip\",\"url\":\"}"
266+
echo "${response_tmp%%\"*}"
267+
fi
268268
}
269269

270270
function downloadBinary() {
@@ -281,7 +281,7 @@ archive)
281281
;;
282282
gh)
283283
echo 'download latest release data via gh commandline tool' >&2
284-
response="$(gh api graphql -F 'user=EdwarDDay' -F 'repo=kotlin-server-scripts' -F 'asset=scripting-host-release.tar.gz' -f "query=$query")"
284+
response="$(gh api graphql -F 'user=EdwarDDay' -F 'repo=kotlin-server-scripts' -f "query=$query")"
285285
url="$(extractUrlFromGraphqlQuery "$response")"
286286
downloadBinary
287287
;;
@@ -291,8 +291,7 @@ curl-authenticated)
291291
\"query\":\"$query\",
292292
\"variables\":{
293293
\"user\":\"EdwarDDay\",
294-
\"repo\":\"kotlin-server-scripts\",
295-
\"asset\":\"scripting-host-release.tar.gz\"
294+
\"repo\":\"kotlin-server-scripts\"
296295
}
297296
}"
298297
response="$(curl --request POST "${github_args[@]}" --fail --silent --url 'https://api.github.com/graphql' --data "$data")"
@@ -308,13 +307,14 @@ esac
308307

309308
echo 'extract binary' >&2
310309

311-
tar --extract --gunzip --file "${archive_name}" --strip-components 2 --directory "${execution_directory}" 'scripting-host-release/bin/'
310+
archiveInternalName="$(tar --list --file "${archive_name}" --exclude="*/?*")"
311+
tar --extract --gunzip --file "${archive_name}" --strip-components 2 --directory "${execution_directory}" "${archiveInternalName}bin/"
312312

313313
if [[ -n "${service_directory}" ]]; then
314314
echo 'configure service' >&2
315315
# escape sed escape char
316316
service_user="${service_user/|/\\\|}"
317-
tar --extract --gunzip --file "${archive_name}" --to-stdout "scripting-host-release/service/$service_file" |\
317+
tar --extract --gunzip --file "${archive_name}" --to-stdout "${archiveInternalName}service/$service_file" |\
318318
sed "s|{{DIRECTORY}}|${execution_directory}|g" | \
319319
sed "s|{{WORKING_DIRECTORY}}|${configuration_directory}|g" | \
320320
sed "s|{{LOG_DIRECTORY}}|${log_directory}|g" | \
@@ -342,7 +342,7 @@ if [[ -n "${service_directory}" ]]; then
342342
;;
343343
esac
344344

345-
tar --extract --gunzip --file "${archive_name}" --strip-components 2 --directory "${configuration_directory}" 'scripting-host-release/config/'
345+
tar --extract --gunzip --file "${archive_name}" --strip-components 2 --directory "${configuration_directory}" "${archiveInternalName}config/"
346346
echo "A sample configuration is in '${configuration_directory}'. Remove the '.sample' extension and edit it as you see fit."
347347
echo "A sample logging file is in '${configuration_directory}'. Remove the '.sample' extension, reference it in the configuration and edit it as you see fit."
348348
fi

scripting-host/build.gradle.kts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@ plugins {
2222
}
2323

2424
group = "net.edwardday.serverscript"
25+
version = findProperty("version") as String
2526

2627
dependencies {
2728
implementation(libs.kotlin.scripting.common)
2829
implementation(libs.kotlin.scripting.jvm)
2930
implementation(libs.kotlin.scripting.jvm.host)
3031
implementation(project(":scripting-definition")) // the script definition module
3132

33+
implementation(libs.clikt)
3234
implementation(libs.okio)
3335
implementation(libs.kotlinx.coroutines)
3436
implementation(libs.kotlinx.coroutines.slf4j)
@@ -114,3 +116,19 @@ application {
114116
applicationName = "kss"
115117
executableDir = ""
116118
}
119+
120+
val processResourceVersionFile by tasks.registering {
121+
inputs.property("version", project.version)
122+
val outputFile = layout.buildDirectory.file("resources/main/version.properties")
123+
outputs.file(outputFile)
124+
doLast {
125+
val version = requireNotNull(inputs.properties["version"])
126+
outputFile.get().asFile.printWriter().use {
127+
it.print("version=$version")
128+
}
129+
}
130+
}
131+
132+
tasks.processResources {
133+
dependsOn(processResourceVersionFile)
134+
}

scripting-host/src/main/kotlin/Main.kt

Lines changed: 78 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616

1717
package net.edwardday.serverscript.scripthost
1818

19+
import com.github.ajalt.clikt.command.SuspendingCliktCommand
20+
import com.github.ajalt.clikt.command.main
21+
import com.github.ajalt.clikt.parameters.options.flag
22+
import com.github.ajalt.clikt.parameters.options.option
1923
import io.github.oshai.kotlinlogging.KotlinLogging
2024
import java.io.File
2125
import java.io.IOException
@@ -24,81 +28,96 @@ import java.util.*
2428

2529
private const val CONFIG_FILE_NAME = "kss.properties"
2630

27-
private fun loadProperties(): Properties {
28-
// load default config
29-
val defaultConfig = try {
30-
Thread.currentThread()
31+
suspend fun main(args: Array<String>) = Main().main(args)
32+
33+
private class Main : SuspendingCliktCommand() {
34+
private fun readPropertiesFromClasspath(fileName: String): Properties? {
35+
return Thread.currentThread()
3136
.getContextClassLoader()
32-
.getResourceAsStream(CONFIG_FILE_NAME)
37+
.getResourceAsStream(fileName)
3338
?.use<InputStream?, Properties> { stream ->
3439
Properties().apply {
3540
load(stream)
3641
}
3742
}
38-
?: error("Could not load default configuration")
39-
} catch (e: IOException) {
40-
error("Could not read default configuration because of ${e.localizedMessage}")
4143
}
44+
private fun loadProperties(): Properties {
45+
// load default config
46+
val defaultConfig = try {
47+
readPropertiesFromClasspath(CONFIG_FILE_NAME) ?: error("Could not load default configuration")
48+
} catch (e: IOException) {
49+
error("Could not read default configuration because of ${e.localizedMessage}")
50+
}
4251

43-
// load config file from working directory
44-
val workingDirectoryConfig = Properties(defaultConfig)
45-
try {
46-
File(CONFIG_FILE_NAME).takeIf(File::exists)?.bufferedReader()?.use(workingDirectoryConfig::load)
47-
} catch (e: IOException) {
48-
// Ignore for now, maybe log?
49-
}
52+
// load config file from working directory
53+
val workingDirectoryConfig = Properties(defaultConfig)
54+
try {
55+
File(CONFIG_FILE_NAME).takeIf(File::exists)?.bufferedReader()?.use(workingDirectoryConfig::load)
56+
} catch (e: IOException) {
57+
// Ignore for now, maybe log?
58+
}
5059

51-
// load config from system properties
52-
val commandLineConfig = Properties(workingDirectoryConfig)
53-
workingDirectoryConfig.keys.forEach { key ->
54-
val keyAsString = key.toString()
55-
System.getProperty(keyAsString)?.also { value -> commandLineConfig[keyAsString] = value }
60+
// load config from system properties
61+
val commandLineConfig = Properties(workingDirectoryConfig)
62+
workingDirectoryConfig.keys.forEach { key ->
63+
val keyAsString = key.toString()
64+
System.getProperty(keyAsString)?.also { value -> commandLineConfig[keyAsString] = value }
65+
}
66+
return commandLineConfig
5667
}
57-
return commandLineConfig
58-
}
68+
val version by option("-v", "--version", help = "Print current version").flag()
69+
70+
override suspend fun run() {
71+
if (version) {
72+
val appVersion = kotlin.runCatching {
73+
readPropertiesFromClasspath("version.properties")
74+
}.getOrNull()?.getProperty("version") ?: "<unknown>"
75+
echo("Version: $appVersion")
76+
return
77+
}
78+
val properties = loadProperties()
5979

60-
suspend fun main() {
61-
val properties = loadProperties()
80+
val loggingFile = properties.getProperty("logging.logback.configurationFile").orEmpty()
81+
if (loggingFile.isNotEmpty() && File(loggingFile).exists()) {
82+
System.setProperty("logback.configurationFile", loggingFile)
83+
}
6284

63-
val loggingFile = properties.getProperty("logging.logback.configurationFile").orEmpty()
64-
if (loggingFile.isNotEmpty() && File(loggingFile).exists()) {
65-
System.setProperty("logback.configurationFile", loggingFile)
66-
}
85+
val logger = KotlinLogging.logger {}
6786

68-
val logger = KotlinLogging.logger {}
6987

70-
val mavenDependenciesSettings = properties.getProperty("dependencies.maven.settingsFile").orEmpty()
71-
val mavenDependenciesHome = properties.getProperty("dependencies.maven.homeDirectory").orEmpty()
72-
if (mavenDependenciesSettings.isNotEmpty() && File(mavenDependenciesSettings).exists()) {
73-
if (mavenDependenciesHome.isNotEmpty()) {
74-
logger.warn { "'dependencies.maven.settingsFile' overwrites 'dependencies.maven.homeDirectory' setting." }
75-
}
76-
System.setProperty("org.apache.maven.user-settings", mavenDependenciesSettings)
77-
} else {
78-
val mavenDependenciesHomeDirectory = File(mavenDependenciesHome)
79-
if (mavenDependenciesHome.isNotEmpty() && mavenDependenciesHomeDirectory.isDirectory()) {
80-
if (mavenDependenciesHomeDirectory.canWrite()) {
81-
val settingsFile = File(mavenDependenciesHomeDirectory, "settings.xml")
82-
val repositoryDirectory = File(mavenDependenciesHomeDirectory, "repository")
83-
repositoryDirectory.mkdir()
84-
settingsFile.printWriter().use { writer ->
85-
writer.println("""<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"""")
86-
writer.println(""" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"""")
87-
writer.println(""" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">""")
88-
writer.println(""" <localRepository>${repositoryDirectory.absolutePath}</localRepository>""")
89-
writer.println("""</settings>""")
88+
val mavenDependenciesSettings = properties.getProperty("dependencies.maven.settingsFile").orEmpty()
89+
val mavenDependenciesHome = properties.getProperty("dependencies.maven.homeDirectory").orEmpty()
90+
if (mavenDependenciesSettings.isNotEmpty() && File(mavenDependenciesSettings).exists()) {
91+
if (mavenDependenciesHome.isNotEmpty()) {
92+
logger.warn { "'dependencies.maven.settingsFile' overwrites 'dependencies.maven.homeDirectory' setting." }
93+
}
94+
System.setProperty("org.apache.maven.user-settings", mavenDependenciesSettings)
95+
} else {
96+
val mavenDependenciesHomeDirectory = File(mavenDependenciesHome)
97+
if (mavenDependenciesHome.isNotEmpty() && mavenDependenciesHomeDirectory.isDirectory()) {
98+
if (mavenDependenciesHomeDirectory.canWrite()) {
99+
val settingsFile = File(mavenDependenciesHomeDirectory, "settings.xml")
100+
val repositoryDirectory = File(mavenDependenciesHomeDirectory, "repository")
101+
repositoryDirectory.mkdir()
102+
settingsFile.printWriter().use { writer ->
103+
writer.println("""<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"""")
104+
writer.println(""" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"""")
105+
writer.println(""" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd">""")
106+
writer.println(""" <localRepository>${repositoryDirectory.absolutePath}</localRepository>""")
107+
writer.println("""</settings>""")
108+
}
109+
System.setProperty("org.apache.maven.user-settings", settingsFile.absolutePath)
110+
} else {
111+
logger.warn { "User can't write in ${mavenDependenciesHomeDirectory.absolutePath}" }
90112
}
91-
System.setProperty("org.apache.maven.user-settings", settingsFile.absolutePath)
92-
} else {
93-
logger.warn { "User can't write in ${mavenDependenciesHomeDirectory.absolutePath}" }
94113
}
95114
}
96-
}
97-
val socket = properties.getProperty("socket.address") ?: "unix:/var/run/kss/kss.sock"
98-
val maxConnections = properties.getProperty("connections.max")?.toIntOrNull() ?: 4
115+
val socket = properties.getProperty("socket.address") ?: "unix:/var/run/kss/kss.sock"
116+
val maxConnections = properties.getProperty("connections.max")?.toIntOrNull() ?: 4
99117

100-
readFromSocket(
101-
socket = socket,
102-
maxConnections = maxConnections,
103-
)
118+
readFromSocket(
119+
socket = socket,
120+
maxConnections = maxConnections,
121+
)
122+
}
104123
}

0 commit comments

Comments
 (0)