diff --git a/pkg/gimps/gimps.go b/pkg/gimps/gimps.go index a84043c..627f170 100644 --- a/pkg/gimps/gimps.go +++ b/pkg/gimps/gimps.go @@ -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)) diff --git a/pkg/gimps/testdata/comments-directives/config.yaml b/pkg/gimps/testdata/comments-directives/config.yaml new file mode 100644 index 0000000..a5a7544 --- /dev/null +++ b/pkg/gimps/testdata/comments-directives/config.yaml @@ -0,0 +1,4 @@ +# This testcase reproduces +# https://github.com/xrstf/gimps/issues/1 + +projectName: go.xrstf.de/gimps/test diff --git a/pkg/gimps/testdata/comments-directives/main.go.expected b/pkg/gimps/testdata/comments-directives/main.go.expected new file mode 100644 index 0000000..9aaa9c4 --- /dev/null +++ b/pkg/gimps/testdata/comments-directives/main.go.expected @@ -0,0 +1,11 @@ +package main + +import ( + "fmt" //nolint:typecheck + "log" +) + +func main() { + fmt.Println("hello world") + log.Println("foo") +} diff --git a/pkg/gimps/testdata/comments-directives/main.go.input b/pkg/gimps/testdata/comments-directives/main.go.input new file mode 100644 index 0000000..a58ec18 --- /dev/null +++ b/pkg/gimps/testdata/comments-directives/main.go.input @@ -0,0 +1,14 @@ +package main + +import ( + "log" +) + +import ( + "fmt" //nolint:typecheck +) + +func main() { + fmt.Println("hello world") + log.Println("foo") +}