Skip to content

Commit

Permalink
extract reader and classpath helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Carmine DiMascio committed Jan 1, 2018
1 parent 8293397 commit 3a458ad
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package io.github.cdimascio.dotenv.internal

import io.github.cdimascio.dotenv.DotEnvException
import java.io.IOException
import java.io.InputStream
import java.util.*
import java.util.stream.Stream

internal object ClasspathHelper {
fun loadFileFromClasspath(location: String): Stream<String> {
val loader = ClasspathHelper::class.java
val inputStream: InputStream? =
loader.getResourceAsStream(location)
?: loader.getResourceAsStream(location)
?: ClassLoader.getSystemResourceAsStream(location)
if (inputStream != null) {
try {
val scanner = Scanner(inputStream, "utf-8")
val lines = mutableListOf<String>()
while (scanner.hasNext()) {
lines.add(scanner.nextLine())
}
return lines.stream()
} catch (e: IOException) {
throw DotEnvException("Could not parse $location from the classpath")
}
}
throw DotEnvException("Could not find $location on the classpath")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.github.cdimascio.dotenv.internal

import java.net.URI
import java.nio.file.Files
import java.nio.file.Paths
import java.util.stream.Stream

internal class DotenvReader(
private val directory: String,
private val filename: String
) {
fun read(): Stream<String> {
var dir = directory.replace("""\\""".toRegex(), "/")
dir = if (dir.endsWith("/")) dir.substring(0, dir.length - 1) else dir
dir = if (dir.endsWith(".env")) dir.substring(0, dir.length - 4) else dir
val location = "$dir/$filename"
val path = if (location.toLowerCase().startsWith("file:")) {
Paths.get(URI.create(location))
} else {
Paths.get(location)
}
return if (Files.exists(path)) Files.lines(path)
else ClasspathHelper.loadFileFromClasspath(location)
}
}

0 comments on commit 3a458ad

Please sign in to comment.