Skip to content

Commit d71487b

Browse files
strulovichfacebook-github-bot
authored andcommitted
Support shebang for KTS files
Summary: This was crashing in JavaInput, so let's just remove it and add it back at the end. Reviewed By: cortinico Differential Revision: D36987246 fbshipit-source-id: e404d213d9ba5a916caaa63cba850066d1d77436
1 parent e40bc15 commit d71487b

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

core/src/main/java/com/facebook/ktfmt/format/Formatter.kt

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,15 @@ object Formatter {
7878
@JvmStatic
7979
@Throws(FormatterException::class, ParseError::class)
8080
fun format(options: FormattingOptions, code: String): String {
81-
checkEscapeSequences(code)
81+
val (shebang, kotlinCode) =
82+
if (code.startsWith("#!")) {
83+
code.split("\n".toRegex(), limit = 2)
84+
} else {
85+
listOf("", code)
86+
}
87+
checkEscapeSequences(kotlinCode)
8288

83-
val lfCode = StringUtilRt.convertLineSeparators(code)
89+
val lfCode = StringUtilRt.convertLineSeparators(kotlinCode)
8490
val sortedImports = sortedAndDistinctImports(lfCode)
8591
val pretty = prettyPrint(sortedImports, options, "\n")
8692
val noRedundantElements =
@@ -89,7 +95,9 @@ object Formatter {
8995
} catch (e: ParseError) {
9096
throw IllegalStateException("Failed to re-parse code after pretty printing:\n $pretty", e)
9197
}
92-
return prettyPrint(noRedundantElements, options, Newlines.guessLineSeparator(code)!!)
98+
val prettyCode =
99+
prettyPrint(noRedundantElements, options, Newlines.guessLineSeparator(kotlinCode)!!)
100+
return if (shebang.isNotEmpty()) shebang + "\n" + prettyCode else prettyCode
93101
}
94102

95103
/** prettyPrint reflows 'code' using google-java-format's engine. */

core/src/test/java/com/facebook/ktfmt/format/FormatterTest.kt

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ class FormatterTest {
4949
|args.forEach { println(File + "-") }
5050
|""".trimMargin())
5151

52+
@Test
53+
fun `support script (kts) files with a shebang`() =
54+
assertFormatted(
55+
"""
56+
|#!/usr/bin/env kscript
57+
|package foo
58+
|
59+
|println("Called")
60+
|""".trimMargin())
61+
5262
@Test
5363
fun `call chains`() =
5464
assertFormatted(

0 commit comments

Comments
 (0)