Skip to content

Commit

Permalink
Merge pull request #58 from uzzu/all-variables-or-null
Browse files Browse the repository at this point in the history
DotEnvRoot#allVariables for null variables
  • Loading branch information
uzzu authored Nov 25, 2023
2 parents 9c6b980 + 7670b0c commit f562840
Show file tree
Hide file tree
Showing 10 changed files with 155 additions and 7 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added

- `(Map<String, String?>) env.allVariablesOrNull()` to get all environment variables includes variables specified in `.env` includes null variables.
- The Plugin set key if defined in .env template files, but it could not be retrieved as nullable value entries by using allVariables()
- By using allVariablesOrNull instead of allVariables, it is possible to retrieve all environment variables, including those that are only defined in the .env template (which means their values are null).

### Deprecated

- `val (Map<String, String>) env.allVariables`
- Replace to use a method `(Map<String, String>) env.allVariables()` instead.

## [2.0.0] - 2022-03-02

### Added
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ Support subproject-only variables and extensions.
if environment variable was not set.
- `(String?) env.fetchOrNull(name: String)` : Returns an environment variable, or null if environment variable was not
set.
- `(Map<String, String) env.allVariables` : Returns all environment variables.
- `(Map<String, String) env.allVariables()` : Returns all environment variables.
- `(Map<String, String?) env.allVariablesOrNull()` : Returns all environment variables includes null values.
- [See more examples](/examples)

## License
Expand Down
17 changes: 16 additions & 1 deletion examples/basic/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ plugins {
id("co.uzzu.dotenv.gradle") version "2.0.0"
}

val keys = listOf(
"FOO",
"BAR",
"BAZ",
"QUX"
)

println(env.FOO.orElse("default_foo"))
println(env.BAR.orNull())
try {
Expand All @@ -13,4 +20,12 @@ try {
println(env.QUX.value)

// All environment variables which are merged with variables specified in .env files.
env.allVariables
print("#allVariables() (filtered by keys in .env.template and .env): ")
println(env.allVariables().filterKeys { keys.contains(it) })

// All environment variables which are merged with variables specified in .env files includes null.
// The Plugin set key if defined in .env template files, but it could not be retrieved as nullable value entries by using allVariables()
// By using allVariablesOrNull instead of allVariables, it is possible to retrieve all environment variables, including those that are only defined in the .env template (which means their values are null).
env.allVariablesOrNull()
print("#allVariablesOrNull() (filtered by keys in .env.template and .env): ")
println(env.allVariablesOrNull().filterKeys { keys.contains(it) })
12 changes: 11 additions & 1 deletion plugin/src/main/kotlin/co/uzzu/dotenv/EnvProviders.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,22 @@ interface EnvProvider {
* @return All environment variables.
*/
fun getenv(): Map<String, String>

/**
* @return All environment variables includes null values.
*/
fun getenvOrNull(): Map<String, String?>
}

/**
* EnvProvider implementation using System#getenv
*/
class SystemEnvProvider : EnvProvider {
override fun getenv(name: String): String? = System.getenv(name)
override fun getenv(): Map<String, String> = System.getenv().filterValues { it != null }

override fun getenv(): Map<String, String> = System.getenv()
.mapNotNull { (key, value) -> value?.let { key to it } }
.toMap()

override fun getenvOrNull(): Map<String, String?> = System.getenv()
}
29 changes: 29 additions & 0 deletions plugin/src/main/kotlin/co/uzzu/dotenv/gradle/DotEnvProperties.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ open class DotEnvRoot(
/**
* @return All environment variables which are merged with variables specified in .env files.
*/
@Deprecated("Replace to use DotEnvRoot#allVariables()")
val allVariables: Map<String, String>
get() {
val results = envProvider.getenv().toMutableMap()
Expand Down Expand Up @@ -55,6 +56,34 @@ open class DotEnvRoot(
fun fetchOrNull(name: String): String? =
envProvider.getenv()[name]
?: dotenvMap[name]

/**
* @return All environment variables which are merged with variables specified in .env files.
*/
fun allVariables(): Map<String, String> {
val results = envProvider.getenv().toMutableMap()
dotenvMap.forEach { (key, value) ->
if (value != null && results[key] == null) {
results[key] = value
}
}
return results.toMap()
}

/**
* @return All environment variables which are merged with variables specified in .env files, and which includes null values.
* The Plugin set key if defined in .env template files, but it could not be retrieved as nullable value entries by using allVariables()
* By using allVariablesOrNull instead of allVariables, it is possible to retrieve all environment variables, including those that are only defined in the .env template (which means their values are null).
*/
fun allVariablesOrNull(): Map<String, String?> {
val results = envProvider.getenvOrNull().toMutableMap()
dotenvMap.forEach { (key, value) ->
if (results[key] == null) {
results[key] = value
}
}
return results.toMap()
}
}

/**
Expand Down
7 changes: 6 additions & 1 deletion plugin/src/test/kotlin/co/uzzu/dotenv/InMemoryEnvProvider.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package co.uzzu.dotenv

class InMemoryEnvProvider(
private val map: Map<String, String>
private val map: Map<String, String?>
) : EnvProvider {
override fun getenv(name: String): String? = map[name]

override fun getenv(): Map<String, String> = map
.mapNotNull { (key, value) -> value?.let { key to it } }
.toMap()

override fun getenvOrNull(): Map<String, String?> = map.toMap()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package co.uzzu.dotenv.gradle

import assertk.assertThat
import assertk.assertions.contains
import org.gradle.testkit.runner.GradleRunner
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File

class AllVariablesOrNullTest {

@TempDir
lateinit var projectDir: File

@Test
fun nullValuesDefinedByTemplate() {
RootProject(projectDir) {
settingsGradle()
buildGradle(
"""
plugins {
base
id("co.uzzu.dotenv.gradle")
}
println("Result: ${'$'}{env.allVariablesOrNull().filterKeys { it == "HOGE" }}")
""".trimIndent()
)
file(
".env.template",
"""
HOGE=
""".trimIndent()
)
file(
".env",
"""
""".trimIndent()
)
}

val result = GradleRunner.create()
.withPluginClasspath()
.withProjectDir(projectDir)
.build()

assertThat(result.output).contains("Result: {HOGE=null}")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File

@Suppress("UnstableApiUsage") // GradleRunner#withPluginClasspath
class BasicUsageTest {

@TempDir
Expand Down
33 changes: 32 additions & 1 deletion plugin/src/test/kotlin/co/uzzu/dotenv/gradle/DotEnvRootTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class DotEnvRootTest {
"QUUX" to null
)
)
val allVariables = root.allVariables
val allVariables = root.allVariables()
assertAll(
{ assertEquals("env", allVariables["FOO"]) },
{ assertEquals("env", allVariables["BAR"]) },
Expand All @@ -121,4 +121,35 @@ class DotEnvRootTest {
{ assertEquals(null, allVariables["CORGE"]) }
)
}

@Test
fun allVariablesOrNull() {
val envProvider = InMemoryEnvProvider(
mapOf(
"FOO" to "env",
"BAR" to "env",
"CORGE" to null,
)
)
val root = DotEnvRoot(
envProvider,
mapOf(
"BAR" to "dotenv",
"BAZ" to "dotenv",
"QUX" to "dotenv",
"QUUX" to null,
)
)
val allVariables = root.allVariablesOrNull()
assertAll(
{ assertEquals("env", allVariables["FOO"]) },
{ assertEquals("env", allVariables["BAR"]) },
{ assertEquals("dotenv", allVariables["BAZ"]) },
{ assertEquals("dotenv", allVariables["QUX"]) },
{ assertEquals(null, allVariables["QUUX"]) },
{ assertTrue(allVariables.containsKey("QUUX")) },
{ assertEquals(null, allVariables["CORGE"]) },
{ assertTrue(allVariables.containsKey("CORGE")) },
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File

@Suppress("UnstableApiUsage") // GradleRunner#withPluginClasspath
class HierarchicalDotEnvDefinitionsTest {

@TempDir
Expand Down

0 comments on commit f562840

Please sign in to comment.