Skip to content

Commit 290ad2b

Browse files
authored
Merge pull request #16 from adamnfish/copilot/fix-empty-user-config-parsing
Handle empty user config files in YAML parser
2 parents 1270721 + fc6f89d commit 290ad2b

3 files changed

Lines changed: 37 additions & 4 deletions

File tree

core/src/main/scala/com/gu/devenv/Config.scala

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,14 @@ object Config {
3939
} yield projectConfig
4040

4141
def parseUserConfig(contents: String): Try[UserConfig] =
42-
for {
43-
json <- parser.parse(contents).toTry
44-
userConfig <- json.as[UserConfig].toTry
45-
} yield userConfig
42+
if (yamlIsEmpty(contents)) {
43+
scala.util.Success(UserConfig(None, None))
44+
} else {
45+
for {
46+
json <- parser.parse(contents).toTry
47+
userConfig <- json.as[UserConfig].toTry
48+
} yield userConfig
49+
}
4650

4751
def mergeConfigs(
4852
projectConfig: ProjectConfig,
@@ -177,6 +181,15 @@ object Config {
177181
envList.map(env => env.name -> Json.fromString(env.value)): _*
178182
)
179183

184+
/** Parsing an empty YAML file throws an exception, but an empty YAML file is valid and should
185+
* result in an empty configuration. We check for empty contents here.
186+
*/
187+
private def yamlIsEmpty(text: String): Boolean =
188+
text.linesIterator
189+
.map(_.trim)
190+
.filter(_.nonEmpty)
191+
.forall(_.startsWith("#"))
192+
180193
private def applyPlugins(
181194
projectPlugins: Plugins,
182195
userPlugins: Option[Plugins]

core/src/main/scala/com/gu/devenv/models.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ case class UserConfig(
3030
plugins: Option[Plugins],
3131
dotfiles: Option[Dotfiles]
3232
)
33+
object UserConfig {
34+
val empty = UserConfig(None, None)
35+
}
3336

3437
enum ForwardPort {
3538
case SamePort(port: Int)

core/src/test/scala/com/gu/devenv/ConfigTest.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,23 @@ class ConfigTest
9292
)
9393
)
9494
}
95+
96+
"parses an empty user config file" in {
97+
val emptyConfig = ""
98+
val Success(userConfig) =
99+
Config.parseUserConfig(emptyConfig).success
100+
userConfig shouldBe UserConfig.empty
101+
}
102+
103+
"parses a user config file with only comments" in {
104+
val commentsOnlyConfig = """# This is a comment
105+
|# Another comment
106+
|""".stripMargin
107+
val Success(userConfig) =
108+
Config.parseUserConfig(commentsOnlyConfig).success
109+
110+
userConfig shouldBe UserConfig.empty
111+
}
95112
}
96113

97114
"mergeConfigs" - {

0 commit comments

Comments
 (0)