Improve Formatter API (#1505)

- pass `GrammarVersion` to constructor instead of passing it to each
`format` method
- replace `format(Path): String` with `format(Reader, Appendable)`
- instead of picking which overloads besides `format(String): String`
might be useful, offer a single generalized method that streams input
and output
- add `@Throws(IOException::class)` to ensure that Java callers can
catch this exception
- deprecate old methods
This commit is contained in:
odenix
2026-04-07 14:16:12 -07:00
committed by GitHub
parent 99cbd07518
commit 09435af54f
5 changed files with 68 additions and 34 deletions
@@ -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.
@@ -17,6 +17,7 @@ package org.pkl.formatter
import java.nio.file.Path
import kotlin.io.path.isRegularFile
import kotlin.io.path.readText
import kotlin.reflect.KClass
import org.pkl.commons.test.InputOutputTestEngine
import org.pkl.parser.ParserError
@@ -58,16 +59,10 @@ abstract class AbstractFormatterSnippetTestsEngine : InputOutputTestEngine() {
class FormatterSnippetTestsEngine : AbstractFormatterSnippetTestsEngine() {
override val testClass: KClass<*> = FormatterSnippetTests::class
override fun generateOutputFor(inputFile: Path): Pair<Boolean, String> {
val formatter = Formatter()
val (success, output) =
try {
val res = formatter.format(inputFile)
true to res
} catch (_: ParserError) {
false to ""
}
return success to output
}
override fun generateOutputFor(inputFile: Path): Pair<Boolean, String> =
try {
true to Formatter().format(inputFile.readText())
} catch (_: ParserError) {
false to ""
}
}
@@ -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.
@@ -120,4 +120,12 @@ class FormatterTest {
assertThat(format(src)).isEqualTo("\n")
}
}
@Test
fun `read from Reader and write to Appendable`() {
val input = " x = 42".reader()
val output = StringBuilder()
Formatter().format(input, output)
assertThat(output.toString()).isEqualTo("x = 42\n")
}
}