fix: Handle one-liner functions correctly in suggested fix#8
Merged
Conversation
When -fix is applied to a one-liner function like
func (...) Write(b []byte) (int, error) { return r.body.Write(b) }
the previous implementation inserted the defer statement right after
'{' without adding a newline before the existing statement, producing
invalid Go syntax:
{ defer errstk.Wrap(&err) return r.body.Write(b) }
Now buildDeferTextEdit detects when the opening and closing braces are
on the same line and reformats the entire body to multi-line, placing
the defer at the top and the original statement below it.
Also adds a test case (d_one_liner.go + golden file) to cover this.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
-fixを適用すると構文エラーが発生するバグを修正buildDeferTextEditに1ライナー検出ロジックを追加し、関数ボディを複数行に展開してからdeferを挿入するよう変更d_one_liner.goと golden ファイルd_one_liner.go.goldenを追加設計の背景
従来の
buildDeferTextEditは{の直後に\n\tdefer errstk.Wrap(&err)を挿入するだけだった。通常の複数行関数では
{の次にすでに改行があるため問題ないが、1ライナー関数では{の次に空白とreturnが続くため、のように
deferとreturnが同じ行に並び、Go の構文エラーになっていた。修正では
{と}が同じ行にあるかをpass.Fset.Positionで検出し、1ライナーの場合は{から}の直前までの内容を取り出して空白をトリムしたうえで複数行形式に再構築する。検討した代替案
}の前に改行を挿入する別の TextEdit を追加する案:return文の前にも改行が必要で、TextEdit が複数箇所に分散して管理が複雑になるため不採用Test plan
go test ./errstklint/...がパスすることを確認済みTestAnalyzerWithSuggestedFixesが新規テストケース(d_one_liner.go)を含めてパスすることを確認済み🤖 Generated with Claude Code