diff --git a/core/src/main/java/com/facebook/ktfmt/cli/ParsedArgs.kt b/core/src/main/java/com/facebook/ktfmt/cli/ParsedArgs.kt index 069ea5fc..7286743c 100644 --- a/core/src/main/java/com/facebook/ktfmt/cli/ParsedArgs.kt +++ b/core/src/main/java/com/facebook/ktfmt/cli/ParsedArgs.kt @@ -48,7 +48,7 @@ data class ParsedArgs( return parseOptions(arguments) } - val HELP_TEXT = + val HELP_TEXT: String = """ |ktfmt - command line Kotlin source code pretty-printer | diff --git a/core/src/main/java/com/facebook/ktfmt/format/EnumEntryList.kt b/core/src/main/java/com/facebook/ktfmt/format/EnumEntryList.kt index 9d76c5f9..ec380de3 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/EnumEntryList.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/EnumEntryList.kt @@ -35,7 +35,7 @@ private constructor( ) { companion object { fun extractParentList(enumEntry: KtEnumEntry): EnumEntryList { - return extractChildList(enumEntry.parent as KtClassBody)!! + return checkNotNull(extractChildList(enumEntry.parent as KtClassBody)) } fun extractChildList(classBody: KtClassBody): EnumEntryList? { @@ -61,10 +61,12 @@ private constructor( var semicolon: PsiElement? = null var comma: PsiElement? = null val lastToken = - enumEntries - .last() - .lastChild - .getPrevSiblingIgnoringWhitespaceAndComments(withItself = true)!! + checkNotNull( + enumEntries + .last() + .lastChild + .getPrevSiblingIgnoringWhitespaceAndComments(withItself = true), + ) when (lastToken.text) { "," -> { comma = lastToken diff --git a/core/src/main/java/com/facebook/ktfmt/format/Formatter.kt b/core/src/main/java/com/facebook/ktfmt/format/Formatter.kt index aedb2a34..d1d47e70 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/Formatter.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/Formatter.kt @@ -104,7 +104,7 @@ object Formatter { .let { dropRedundantElements(it, options) } .let { prettyPrint(it, options, "\n") } .let { addRedundantElements(it, options) } - .let { convertLineSeparators(it, Newlines.guessLineSeparator(kotlinCode)!!) } + .let { convertLineSeparators(it, checkNotNull(Newlines.guessLineSeparator(kotlinCode))) } .let { if (shebang.isEmpty()) it else shebang + "\n" + it } } diff --git a/core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt b/core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt index f1efe5d7..c0bb120c 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInput.kt @@ -219,9 +219,9 @@ class KotlinInput(private val text: String, file: KtFile) : Input() { override fun getText(): String = text - override fun getLineNumber(inputPosition: Int) = + override fun getLineNumber(inputPosition: Int): Int = StringUtil.offsetToLineColumn(text, inputPosition).line + 1 - override fun getColumnNumber(inputPosition: Int) = + override fun getColumnNumber(inputPosition: Int): Int = StringUtil.offsetToLineColumn(text, inputPosition).column } diff --git a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt index c55c3e08..fdf9e486 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/KotlinInputAstVisitor.kt @@ -2427,9 +2427,9 @@ class KotlinInputAstVisitor( visit(enumEntry.modifierList) builder.token(enumEntry.nameIdentifier?.text ?: fail()) enumEntry.initializerList?.initializers?.forEach { visit(it) } - enumEntry.body?.let { + enumEntry.body?.let { enumBody -> builder.space() - visit(it) + visit(enumBody) } } } diff --git a/core/src/main/java/com/facebook/ktfmt/format/ParseError.kt b/core/src/main/java/com/facebook/ktfmt/format/ParseError.kt index 432c6643..6c19b524 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/ParseError.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/ParseError.kt @@ -30,7 +30,7 @@ class ParseError(val errorDescription: String, val lineColumn: LineColumn) : companion object { private fun positionOf(element: PsiElement): LineColumn { - val doc = element.containingFile.viewProvider.document!! + val doc = checkNotNull(element.containingFile.viewProvider.document) val offset = element.textOffset val lineZero = doc.getLineNumber(offset) val colZero = offset - doc.getLineStartOffset(lineZero) diff --git a/core/src/main/java/com/facebook/ktfmt/format/Parser.kt b/core/src/main/java/com/facebook/ktfmt/format/Parser.kt index d8e47914..16235883 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/Parser.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/Parser.kt @@ -61,9 +61,8 @@ object Parser { fun parse(code: String): KtFile { val virtualFile = LightVirtualFile("temp.kts", KotlinFileType.INSTANCE, code) val ktFile = PsiManager.getInstance(env.project).findFile(virtualFile) as KtFile - ktFile.collectDescendantsOfType().let { - if (it.isNotEmpty()) throwParseError(code, it[0]) - } + val descendants = ktFile.collectDescendantsOfType() + if (descendants.isNotEmpty()) throwParseError(code, descendants[0]) return ktFile } diff --git a/core/src/main/java/com/facebook/ktfmt/format/RedundantImportDetector.kt b/core/src/main/java/com/facebook/ktfmt/format/RedundantImportDetector.kt index 323ac347..21d59582 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/RedundantImportDetector.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/RedundantImportDetector.kt @@ -166,11 +166,11 @@ internal class RedundantImportDetector(val enabled: Boolean) { val identifierCounts = importCleanUpCandidates.groupBy { it.identifier }.mapValues { it.value.size } - return importCleanUpCandidates.filter { - val isUsed = it.identifier in usedReferences - val isFromThisPackage = it.importedFqName?.parent() == thisPackage - val hasAlias = it.alias != null - val isOverload = requireNotNull(identifierCounts[it.identifier]) > 1 + return importCleanUpCandidates.filter { importCandidate -> + val isUsed = importCandidate.identifier in usedReferences + val isFromThisPackage = importCandidate.importedFqName?.parent() == thisPackage + val hasAlias = importCandidate.alias != null + val isOverload = requireNotNull(identifierCounts[importCandidate.identifier]) > 1 // Remove if... !isUsed || (isFromThisPackage && !hasAlias && !isOverload) } diff --git a/core/src/main/java/com/facebook/ktfmt/format/WhitespaceTombstones.kt b/core/src/main/java/com/facebook/ktfmt/format/WhitespaceTombstones.kt index 816e137f..87e857c7 100644 --- a/core/src/main/java/com/facebook/ktfmt/format/WhitespaceTombstones.kt +++ b/core/src/main/java/com/facebook/ktfmt/format/WhitespaceTombstones.kt @@ -23,7 +23,7 @@ object WhitespaceTombstones { /** See [replaceTrailingWhitespaceWithTombstone]. */ const val SPACE_TOMBSTONE = '\u0003' - fun String.indexOfWhitespaceTombstone() = this.indexOf(SPACE_TOMBSTONE) + fun String.indexOfWhitespaceTombstone(): Int = this.indexOf(SPACE_TOMBSTONE) /** * Google-java-format removes trailing spaces when it emits formatted code, which is a problem for diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt index aba6176e..b767e1c1 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/CommentType.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/Escaping.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/Escaping.kt index d3d3c103..d37991a8 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/Escaping.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/Escaping.kt @@ -22,7 +22,7 @@ object Escaping { private const val STAR_SLASH_ESCAPE = "\u0005\u0004" - fun indexOfCommentEscapeSequences(s: String) = + fun indexOfCommentEscapeSequences(s: String): Int = s.indexOfAny(listOf(SLASH_STAR_ESCAPE, STAR_SLASH_ESCAPE)) /** diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/FormattingTask.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/FormattingTask.kt index 4f195db7..d0ceb1c6 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/FormattingTask.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/FormattingTask.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocCommentsHelper.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocCommentsHelper.kt index a9450a2a..313efb52 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocCommentsHelper.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocCommentsHelper.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright 2015 Google Inc. * @@ -33,11 +49,11 @@ class KDocCommentsHelper(private val lineSeparator: String, private val maxLineL private val kdocFormatter = KDocFormatter( - KDocFormattingOptions(maxLineLength, maxLineLength).also { - it.allowParamBrackets = true // TODO Do we want this? - it.convertMarkup = false - it.nestedListIndent = 4 - it.optimal = false // Use greedy line breaking for predictability. + KDocFormattingOptions(maxLineLength, maxLineLength).apply { + allowParamBrackets = true // TODO Do we want this? + convertMarkup = false + nestedListIndent = 4 + optimal = false // Use greedy line breaking for predictability. }) override fun rewrite(tok: Tok, maxWidth: Int, column0: Int): String { diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt index d44561ce..afc414d6 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * @@ -129,7 +145,7 @@ class KDocFormatter(private val options: KDocFormattingOptions) { } sb.append("*/") } else if (sb.endsWith(lineSeparator)) { - @Suppress("ReturnValueIgnored") sb.removeSuffix(lineSeparator) + @Suppress("NoOp", "ReturnValueIgnored") sb.removeSuffix(lineSeparator) } val formatted = diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocToken.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocToken.kt index 51801c88..8d4f5a84 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocToken.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocToken.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright 2016 Google Inc. * diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt index 8d7db5db..a70226df 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/KDocWriter.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright 2016 Google Inc. * diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/NestingCounter.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/NestingCounter.kt index e744089d..f5a8bbba 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/NestingCounter.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/NestingCounter.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright 2016 Google Inc. * diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/Paragraph.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/Paragraph.kt index a3e6cbd3..1ca0d141 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/Paragraph.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/Paragraph.kt @@ -38,8 +38,8 @@ class Paragraph(private val task: FormattingTask) { private val options: KDocFormattingOptions get() = task.options - var content = StringBuilder() - val text + var content: StringBuilder = StringBuilder() + val text: String get() = content.toString() var prev: Paragraph? = null @@ -348,7 +348,7 @@ class Paragraph(private val task: FormattingTask) { private fun reflow(words: List, lineWidth: Int, hangingIndentSize: Int): List { if (options.alternate || !options.optimal || - hanging && hangingIndentSize > 0 || + (hanging && hangingIndentSize > 0) || // An unbreakable long word may make other lines shorter and won't look good words.any { it.length > lineWidth }) { // Switch to greedy if explicitly turned on, and for hanging indent @@ -430,7 +430,7 @@ class Paragraph(private val task: FormattingTask) { if (!word.first().isLetter()) { val wordWithSpace = "$word " // for regex matching in below checks - if (wordWithSpace.isListItem() && !word.equals("
  • ", true) || wordWithSpace.isQuoted()) { + if ((wordWithSpace.isListItem() && !word.equals("
  • ", true)) || wordWithSpace.isQuoted()) { return false } } @@ -468,7 +468,7 @@ class Paragraph(private val task: FormattingTask) { val end = words.size while (from < end) { val start = - if (from == 0 && (quoted || hanging && !text.isKDocTag())) { + if (from == 0 && (quoted || (hanging && !text.isKDocTag()))) { from + 2 } else { from + 1 diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphList.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphList.kt index a45d73fa..476f46cb 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphList.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphList.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * @@ -22,7 +38,7 @@ package com.facebook.ktfmt.kdoc * front of it. */ class ParagraphList(private val paragraphs: List) : Iterable { - fun isSingleParagraph() = paragraphs.size <= 1 + fun isSingleParagraph(): Boolean = paragraphs.size <= 1 override fun iterator(): Iterator = paragraphs.iterator() diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphListBuilder.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphListBuilder.kt index 2ec9989d..c01a4479 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphListBuilder.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/ParagraphListBuilder.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * @@ -236,7 +252,7 @@ class ParagraphListBuilder( // Make sure it's not just deeply indented inside a different block (paragraph.prev == null || lineWithIndentation.length - lineWithoutIndentation.length >= - paragraph.prev!!.originalIndent + 4)) { + checkNotNull(paragraph.prev).originalIndent + 4)) { i = addPreformatted(i - 1, includeEnd = false, expectClose = false) { !it.startsWith(" ") } } else if (lineWithoutIndentation.startsWith("-") && lineWithoutIndentation.containsOnly('-', '|', ' ')) { @@ -361,7 +377,7 @@ class ParagraphListBuilder( }) newParagraph(i) } else if (lineWithoutIndentation.isListItem() || - lineWithoutIndentation.isKDocTag() && task.type == CommentType.KDOC || + (lineWithoutIndentation.isKDocTag() && task.type == CommentType.KDOC) || lineWithoutIndentation.isTodo()) { i-- newParagraph(i).hanging = true @@ -388,10 +404,10 @@ class ParagraphListBuilder( w.isLine() || w.isHeader() || // Not indented by at least two spaces following a blank line? - s.length > 2 && + (s.length > 2 && (!s[0].isWhitespace() || !s[1].isWhitespace()) && j < lines.size - 1 && - lineContent(lines[j - 1]).isBlank() + lineContent(lines[j - 1]).isBlank()) } }, shouldBreak = { w, _ -> w.isBlank() }, @@ -455,7 +471,7 @@ class ParagraphListBuilder( newParagraph(i - 1).block = true if (lineWithoutIndentation.equals("

    ", true) || lineWithoutIndentation.equals("

    ", true) || - options.convertMarkup && lineWithoutIndentation.equals("

    ", true)) { + (options.convertMarkup && lineWithoutIndentation.equals("

    ", true))) { if (options.convertMarkup) { // Replace

    with a blank line paragraph.separate = true @@ -630,8 +646,8 @@ class ParagraphListBuilder( override fun compare(l1: List, l2: List): Int { val p1 = l1.first() val p2 = l2.first() - val o1 = order[p1]!! - val o2 = order[p2]!! + val o1 = checkNotNull(order[p1]) + val o2 = checkNotNull(order[p2]) val isPriority1 = p1.doc && docTagIsPriority(p1.text) && o1 < firstNonPriorityDocTag val isPriority2 = p2.doc && docTagIsPriority(p2.text) && o2 < firstNonPriorityDocTag @@ -750,7 +766,7 @@ class ParagraphListBuilder( if (paragraph.doc || text.startsWith("

  • ", true) || text.isTodo()) { paragraph.hangingIndent = getIndent(options.hangingIndent) } else if (paragraph.continuation && paragraph.prev != null) { - paragraph.hangingIndent = paragraph.prev!!.hangingIndent + paragraph.hangingIndent = checkNotNull(paragraph.prev).hangingIndent // Dedent to match hanging indent val s = paragraph.text.trimStart() paragraph.content.clear() @@ -830,7 +846,7 @@ class ParagraphListBuilder( return } val last = paragraphs.last() - if (last.preformatted || last.doc || last.hanging && !last.continuation || last.isEmpty()) { + if (last.preformatted || last.doc || (last.hanging && !last.continuation) || last.isEmpty()) { return } @@ -862,7 +878,7 @@ fun String.containsOnly(vararg s: Char): Boolean { return true } -fun StringBuilder.startsWithUpperCaseLetter() = +fun StringBuilder.startsWithUpperCaseLetter(): Boolean = this.isNotEmpty() && this[0].isUpperCase() && this[0].isLetter() -fun Char.isCloseSquareBracket() = this == ']' +fun Char.isCloseSquareBracket(): Boolean = this == ']' diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/Table.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/Table.kt index a4c837cc..8d07cb3a 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/Table.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/Table.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * @@ -138,8 +154,8 @@ class Table( } val rowsAndDivider = rows + dividerRow - if (rowsAndDivider.all { - val first = it.cells.firstOrNull() + if (rowsAndDivider.all { row -> + val first = row.cells.firstOrNull() first != null && first.isBlank() }) { rowsAndDivider.forEach { if (it.cells.isNotEmpty()) it.cells.removeAt(0) } @@ -198,8 +214,8 @@ class Table( } else if (c == '-' && (s.startsWith("--", i) || s.startsWith("-:", i) || - i > 1 && s.startsWith(":-:", i - 2) || - i > 1 && s.startsWith(":--", i - 2))) { + (i > 1 && s.startsWith(":-:", i - 2)) || + (i > 1 && s.startsWith(":--", i - 2)))) { while (i < s.length && s[i] == '-') { i++ } @@ -265,6 +281,6 @@ class Table( } class Row { - val cells = mutableListOf() + val cells: MutableList = mutableListOf() } } diff --git a/core/src/main/java/com/facebook/ktfmt/kdoc/Utilities.kt b/core/src/main/java/com/facebook/ktfmt/kdoc/Utilities.kt index 4b0f9ec4..ff07200a 100644 --- a/core/src/main/java/com/facebook/ktfmt/kdoc/Utilities.kt +++ b/core/src/main/java/com/facebook/ktfmt/kdoc/Utilities.kt @@ -1,3 +1,19 @@ +/* + * Portions Copyright (c) Meta Platforms, Inc. and affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * Copyright (c) Tor Norbye. * @@ -57,7 +73,7 @@ fun String.isListItem(): Boolean { return startsWith("- ") || startsWith("* ") || startsWith("+ ") || - firstOrNull()?.isDigit() == true && numberPattern.matcher(this).find() || + (firstOrNull()?.isDigit() == true && numberPattern.matcher(this).find()) || startsWith("
  • ", ignoreCase = true) } @@ -108,8 +124,8 @@ fun String.isExpectingMore(): Boolean { * lines which has to be checked by the caller) */ fun String.isLine(minCount: Int = 3): Boolean { - return startsWith('-') && containsOnly('-', ' ') && count { it == '-' } >= minCount || - startsWith('_') && containsOnly('_', ' ') && count { it == '_' } >= minCount + return (startsWith('-') && containsOnly('-', ' ') && count { it == '-' } >= minCount) || + (startsWith('_') && containsOnly('_', ' ') && count { it == '_' } >= minCount) } fun String.isKDocTag(): Boolean { diff --git a/core/src/test/java/com/facebook/ktfmt/cli/ParsedArgsTest.kt b/core/src/test/java/com/facebook/ktfmt/cli/ParsedArgsTest.kt index a6994f58..e5babc4b 100644 --- a/core/src/test/java/com/facebook/ktfmt/cli/ParsedArgsTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/cli/ParsedArgsTest.kt @@ -166,7 +166,7 @@ class ParsedArgsTest { val file = root.resolve("existing-file") file.writeText("--google-style\n--dry-run\n--set-exit-if-changed\nFile1.kt\nFile2.kt\n") - val result = ParsedArgs.processArgs(arrayOf("@" + file.absolutePath)) + val result = ParsedArgs.processArgs(arrayOf("@" + file.canonicalPath)) assertThat(result).isInstanceOf(ParseResult.Ok::class.java) val parsed = (result as ParseResult.Ok).parsedValue diff --git a/core/src/test/java/com/facebook/ktfmt/kdoc/KDocFormatterTest.kt b/core/src/test/java/com/facebook/ktfmt/kdoc/KDocFormatterTest.kt index 2fa3cb6e..aa28129f 100644 --- a/core/src/test/java/com/facebook/ktfmt/kdoc/KDocFormatterTest.kt +++ b/core/src/test/java/com/facebook/ktfmt/kdoc/KDocFormatterTest.kt @@ -737,7 +737,7 @@ class KDocFormatterTest { } @Test - fun testWrapingOfLinkText() { + fun testWrappingOfLinkText() { val source = """ /** @@ -5072,7 +5072,7 @@ class KDocFormatterTest { end++ } val word = s.substring(i, end) - if (i > 0 && s[i - 1] == '@' || word == "http" || word == "https" || word == "com") { + if ((i > 0 && s[i - 1] == '@') || word == "http" || word == "https" || word == "com") { // Don't translate URL prefix/suffixes and doc tags sb.append(word) } else { diff --git a/core/src/test/java/com/facebook/ktfmt/testutil/KtfmtTruth.kt b/core/src/test/java/com/facebook/ktfmt/testutil/KtfmtTruth.kt index f8435161..299630df 100644 --- a/core/src/test/java/com/facebook/ktfmt/testutil/KtfmtTruth.kt +++ b/core/src/test/java/com/facebook/ktfmt/testutil/KtfmtTruth.kt @@ -81,6 +81,7 @@ fun assertThatFormatting(@Language("kts") code: String): FormattedCodeSubject { return Truth.assertAbout(codes()).that(code) } +@Suppress("ClassNameDoesNotMatchFileName") class FormattedCodeSubject(metadata: FailureMetadata, private val code: String) : Subject(metadata, code) { private var options: FormattingOptions = defaultTestFormattingOptions diff --git a/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettings.kt b/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettings.kt index e5c9f673..0284c89d 100644 --- a/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettings.kt +++ b/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettings.kt @@ -123,16 +123,16 @@ internal class KtfmtSettings(private val project: Project) : } internal class State : BaseState() { - @Deprecated("Deprecated in V2. Use enableKtfmt instead.") var enabled by string() + @Deprecated("Deprecated in V2. Use enableKtfmt instead.") var enabled: String? by string() - var enableKtfmt by enum(Unknown) - var uiFormatterStyle by enum(Meta) + var enableKtfmt: EnabledState by enum(Unknown) + var uiFormatterStyle: UiFormatterStyle by enum(Meta) - var customMaxLineLength by property(Formatter.META_FORMAT.maxWidth) - var customBlockIndent by property(Formatter.META_FORMAT.blockIndent) - var customContinuationIndent by property(Formatter.META_FORMAT.continuationIndent) - var customManageTrailingCommas by property(Formatter.META_FORMAT.manageTrailingCommas) - var customRemoveUnusedImports by property(Formatter.META_FORMAT.removeUnusedImports) + var customMaxLineLength: Int by property(Formatter.META_FORMAT.maxWidth) + var customBlockIndent: Int by property(Formatter.META_FORMAT.blockIndent) + var customContinuationIndent: Int by property(Formatter.META_FORMAT.continuationIndent) + var customManageTrailingCommas: Boolean by property(Formatter.META_FORMAT.manageTrailingCommas) + var customRemoveUnusedImports: Boolean by property(Formatter.META_FORMAT.removeUnusedImports) fun applyCustomFormattingOptions(formattingOptions: FormattingOptions) { customMaxLineLength = formattingOptions.maxWidth diff --git a/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettingsMigration.kt b/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettingsMigration.kt index 84353733..39447452 100644 --- a/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettingsMigration.kt +++ b/ktfmt_idea_plugin/src/main/kotlin/com/facebook/ktfmt/intellij/KtfmtSettingsMigration.kt @@ -38,7 +38,7 @@ internal class KtfmtSettingsMigration : // // v2 enabled [bool] -> enableKtfmt [enum], custom styles (0.52+) // v1 initial version - enabled is a boolean, only preset styles - var stateVersion + var stateVersion: Int get() = state.stateVersion.takeIf { it > 0 } ?: 1 set(value) { state.stateVersion = value @@ -63,7 +63,7 @@ internal class KtfmtSettingsMigration : } class MigrationState : BaseState() { - var stateVersion by property(-1) + var stateVersion: Int by property(-1) } companion object {