Handle lexer errors in pkl format (#1430)

Resolves #1421
This commit is contained in:
Jen Basch
2026-02-19 10:00:00 -08:00
committed by GitHub
parent 72a57af164
commit e07868b404
2 changed files with 26 additions and 2 deletions

View File

@@ -33,6 +33,7 @@ import org.pkl.core.util.IoUtils
import org.pkl.formatter.Formatter
import org.pkl.formatter.GrammarVersion
import org.pkl.parser.GenericParserError
import org.pkl.parser.ParserError
class CliFormatterCommand
@JvmOverloads
@@ -127,7 +128,10 @@ constructor(
consoleWriter.write(formatted)
consoleWriter.flush()
}
} catch (pe: GenericParserError) {
} catch (pe: ParserError) { // thrown by the lexer
writeErrLine("Could not format `$pathStr`: $pe")
status.update(ERROR)
} catch (pe: GenericParserError) { // thrown by the generic parser
writeErrLine("Could not format `$pathStr`: $pe")
status.update(ERROR)
} catch (e: IOException) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright © 2025 Apple Inc. and the Pkl project authors. All rights reserved.
* Copyright © 2025-2026 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,9 @@ import java.nio.file.Path
import kotlin.io.path.writeText
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir
import org.pkl.commons.cli.CliBugException
import org.pkl.commons.cli.CliException
import org.pkl.core.util.StringBuilderWriter
import org.pkl.formatter.GrammarVersion
@@ -44,4 +46,22 @@ class CliFormatterTest {
} catch (_: CliException) {}
assertThat(sb.toString()).isEqualTo("foo = 1\n")
}
@Test
fun `parse errors do not result in bug exceptions`(@TempDir tempDir: Path) {
val file = tempDir.resolve("foo.pkl").also { it.writeText("foo = \"/foo/\\\${BAR}/baz\"") }
val sb = StringBuilder()
val writer = StringBuilderWriter(sb)
val cmd =
CliFormatterCommand(
listOf(file),
GrammarVersion.latest(),
overwrite = false,
diffNameOnly = false,
silent = false,
consoleWriter = writer,
)
val exc = assertThrows<CliException> { cmd.run() }
assertThat(exc).isNotInstanceOf(CliBugException::class.java)
}
}