diff --git a/wsl.go b/wsl.go index afbd485..63aa030 100644 --- a/wsl.go +++ b/wsl.go @@ -485,6 +485,10 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { continue } + if _, ok := previousStatement.(*ast.DeclStmt); ok && p.config.AllowCuddleDeclaration { + continue + } + // If the assignment is from a type or variable called on the line // above we can allow it by setting AllowAssignAndCallCuddle to // true. @@ -505,6 +509,10 @@ func (p *Processor) parseBlockStatements(statements []ast.Stmt) { case *ast.ExprStmt: switch previousStatement.(type) { case *ast.DeclStmt, *ast.ReturnStmt: + if p.config.AllowAssignAndCallCuddle && p.config.AllowCuddleDeclaration { + continue + } + p.addError(t.Pos(), reasonExpressionCuddledWithDeclOrRet) case *ast.IfStmt, *ast.RangeStmt, *ast.SwitchStmt: p.addError(t.Pos(), reasonExpressionCuddledWithBlock) diff --git a/wsl_test.go b/wsl_test.go index 0c5820a..bdfa149 100644 --- a/wsl_test.go +++ b/wsl_test.go @@ -1718,6 +1718,55 @@ func TestWithConfig(t *testing.T) { }`), expectedErrorStrings: []string{reasonOnlyCuddleIfWithAssign}, }, + { + description: "allow cuddling of declaration (#83)", + code: []byte(`package main + + func main() { + var first = 1 + var second = 2 + + var config Configuration + if err := conf.Load(config); err != nil { + panic(err) + } + + var config Configuration + conf.Load(&config) + + var config Configuration + err = json.Unmarshal(body, &config) + + var notUsed bool + err = json.Unmarshal(body, &something) + + var x = 1 + if x > 0 { + // ... + } + + // This one fails because we're not using y in the if statement. + var y = 1 + if first > 0 { + // ... + } + + // This one fails because we cuddled too many + var z = 1 + var zz = 2 + if zz > z { + // ... + } + }`), + customConfig: &Configuration{ + AllowAssignAndCallCuddle: true, + AllowCuddleDeclaration: true, + }, + expectedErrorStrings: []string{ + reasonOnlyCuddleWithUsedAssign, + reasonOnlyOneCuddle, + }, + }, } for _, tc := range cases {