Skip to content

Commit

Permalink
fix handling directive comments
Browse files Browse the repository at this point in the history
  • Loading branch information
xrstf committed Oct 25, 2023
1 parent 3f4cfce commit 2f56d82
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/gimps/gimps.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,15 @@ func removeEmptyImportNode(file *ast.File) {
func importWithComment(imprt string, imports map[string]*importMetadata) string {
var comment string
if metadata, ok := imports[imprt]; ok && metadata.Comment != nil && len(metadata.Comment.List) > 0 {
// comments can be normal comments ("// foo bar") or special comments like "//foo bar";
// special comments will return an empty string if Text() is called.
// TODO: use TrimSpace() ? Can this be a multiline comment?
comment = fmt.Sprintf("// %s", strings.ReplaceAll(metadata.Comment.Text(), "\n", ""))
formatted := strings.ReplaceAll(metadata.Comment.Text(), "\n", "")
if len(formatted) == 0 {
comment = metadata.Comment.List[0].Text
} else {
comment = fmt.Sprintf("// %s", formatted)
}
}

return strings.TrimSpace(fmt.Sprintf("%s %s", imprt, comment))
Expand Down
4 changes: 4 additions & 0 deletions pkg/gimps/testdata/comments-directives/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# This testcase reproduces
# https://github.com/xrstf/gimps/issues/1

projectName: go.xrstf.de/gimps/test
11 changes: 11 additions & 0 deletions pkg/gimps/testdata/comments-directives/main.go.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

import (
"fmt" //nolint:typecheck
"log"
)

func main() {
fmt.Println("hello world")
log.Println("foo")
}
14 changes: 14 additions & 0 deletions pkg/gimps/testdata/comments-directives/main.go.input
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

import (
"log"
)

import (
"fmt" //nolint:typecheck
)

func main() {
fmt.Println("hello world")
log.Println("foo")
}

0 comments on commit 2f56d82

Please sign in to comment.