Read environment variable in Kotlin/Native
Asked Answered
L

1

8

OK, so I want to create a native app to read some environment variables, and based on some business logic, change the value of them to something else. I decided to do it in Kotlin.

I managed to find out how to change the system environment variable, by creating the functions:

fun call(arg: String) = platform.posix.system(command)

fun setEnvironmentVariable(variable: String, value: String) {
    println("Changing value of $variable to $value")
    call("SETX $variable $value")
}

But it only changes the value. I would like to store it in a Kotlin variable and do some manipulations on it.

Issuing the statement call("SET $variable") prints the value to the command prompt, but I cant figure out how to capture it from Kotlin. I guess if there was a way to extract the output from command prompt to a String that would make it easier, even though Windows outputs it on the form myvariable=myvalue instead of just the value.

Thanks in advance

Lyte answered 5/3, 2019 at 10:4 Comment(6)
To spawn a subprocess to read the value of an environment variable is to use a sledgehammer to crack a nut. See #44320995Afterglow
@Afterglow System.getenv is Kotlin JVM, not nativeAsoka
I don't see how that page contains any answer to the problem here. The answers there suggests only either leveraging System.getenv() function (which I can't since I'm using Kotlin Native, not the JVM), or using a third party library for configuration that "uses properties gathered from multiple sources — built in resources, system properties, property files, environment variables, command-line arguments, etc" (which would be a sledgehammer all in and of itself). I might be missing something, so if that is the case and the linked page actually contains a fix to my problem then please tell me.Lyte
@KevinGalligan you're right, sorry.Afterglow
You could use "echo %$variable%" instead of the SET command. That way you won't get the variable=value pattern, but just the value itself. You'll also have to redirect stdout to the Kotlin process somehow. But probably you're better off using interop with C, then you can use C's getenv() call.Afterglow
That's right. Echo would return only the value. But how do I get it into the Kotlin process? Do I have to use some type of C library call or something? Seems weird there wouldn't be a built in method for this in a native framework.Lyte
S
11

Here's how to read an environment variable in Kotlin/Native:

import platform.posix.*
import kotlinx.cinterop.*

fun main() {
    val variable = "whatever..."
    println(getenv(variable)?.toKString())
}
Swordtail answered 5/3, 2019 at 11:56 Comment(3)
do i need to add any implementation in sourceSets to use platform.posix.*?Ioab
No, it's already available by default.Swordtail
what i was missing is implementation(kotlin("stdlib-common")) and implementation("org.jetbrains.kotlin:kotlin-stdlib-common")Ioab

© 2022 - 2024 — McMap. All rights reserved.