Skip to content

Commit

Permalink
FileFormat: Add read functions that do not throw on empty files
Browse files Browse the repository at this point in the history
Especially for user-facing configuration files, empty files should be
handled leniently, and these functions allows that.

Signed-off-by: Sebastian Schuberth <[email protected]>
  • Loading branch information
sschuberth committed Apr 23, 2021
1 parent ea9d48f commit 8852d70
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions model/src/main/kotlin/FileFormat.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ package org.ossreviewtoolkit.model

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.module.kotlin.treeToValue

import java.io.File

Expand Down Expand Up @@ -83,6 +84,23 @@ fun File.mapper() = FileFormat.forFile(this).mapper
*/
inline fun <reified T : Any> File.readValue(): T = mapper().readValue(this)

/**
* Use the Jackson mapper returned from [File.mapper] to read an object of type [T] from this file, or return null if
* the file has no content.
*/
inline fun <reified T : Any> File.readValueOrNull(): T? =
mapper().readTree(this)?.let {
// Parse the file in a two-step process to avoid readValue() throwing an exception on empty files. Also see
// https://github.com/FasterXML/jackson-databind/issues/1406#issuecomment-252676674.
mapper().treeToValue(it)
}

/**
* Use the Jackson mapper returned from [File.mapper] to read an object of type [T] from this file, or return the
* [default] value if the file has no content.
*/
inline fun <reified T : Any> File.readValueOrDefault(default: T): T = readValueOrNull() ?: default

/**
* Use the Jackson mapper returned from [File.mapper] to write an object of type [T] to this file. [prettyPrint]
* indicates whether to use pretty printing or not. The function also ensures that the parent directory exists.
Expand Down

0 comments on commit 8852d70

Please sign in to comment.