Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support cuddle http body close with error check #37

Merged
merged 1 commit into from
Oct 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions wsl.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,25 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) {
continue
}

// Special treatment of deferring body closes after error checking
// according to best practices. See
// https://github.com/bombsimon/wsl/issues/31 which links to
// discussion about error handling after HTTP requests. This is hard
// coded and very specific but for now this is to be seen as a
// special case. What this does is that it *only* allows a defer
// statement with `Close` on the right hand side to be cuddled with
// an if-statement to support this:
// resp, err := client.Do(req)
// if err != nil {
// return err
// }
// defer resp.Body.Close()
if _, ok := previousStatement.(*ast.IfStmt); ok {
if atLeastOneInListsMatch(rightHandSide, []string{"Close"}) {
continue
}
}

if moreThanOneStatementAbove() {
p.addError(t.Pos(), "only one cuddle assignment allowed before defer statement")

Expand Down
12 changes: 12 additions & 0 deletions wsl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,18 @@ func TestShouldAddEmptyLines(t *testing.T) {
"block should not end with a whitespace (or comment)",
},
},
{
description: "allow http body close best practice",
code: []byte(`package main

func main() {
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
}`),
},
}

for _, tc := range cases {
Expand Down