Skip to content

Commit

Permalink
don't break //export and //foo:bar directives
Browse files Browse the repository at this point in the history
Fixes #7.
  • Loading branch information
mvdan committed Apr 11, 2019
1 parent e34e48b commit 7cf08f7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 10 deletions.
26 changes: 16 additions & 10 deletions internal/gofumpt.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"go/parser"
"go/token"
"reflect"
"regexp"
"sort"
"strings"
"unicode"
Expand Down Expand Up @@ -155,6 +156,14 @@ func (f *fumpter) printLength(node ast.Node) int {
return int(count)
}

// rxCommentDirective covers all common Go comment directives:
//
// //go: | standard Go directives, like go:noinline
// //someword: | similar to the syntax above, like lint:ignore
// //line | inserted line information for cmd/compile
// //export | to mark cgo funcs for exporting
var rxCommentDirective = regexp.MustCompile(`^([a-z]+:|line\b|export\b)`)

func (f *fumpter) visit(node ast.Node) {
switch node := node.(type) {
case *ast.File:
Expand Down Expand Up @@ -192,16 +201,13 @@ func (f *fumpter) visit(node ast.Node) {
// /*-style comment
break
}
switch {
case strings.HasPrefix(body, "go:"):
// standard go:foobar directive
case strings.HasPrefix(body, "line "):
// cmd/compile line directive
default:
r, _ := utf8.DecodeRuneInString(body)
if unicode.IsLetter(r) || unicode.IsNumber(r) {
node.Text = "// " + body
}
if rxCommentDirective.MatchString(body) {
// this comment is a directive
break
}
r, _ := utf8.DecodeRuneInString(body)
if unicode.IsLetter(r) || unicode.IsNumber(r) {
node.Text = "// " + body
}

case *ast.GenDecl:
Expand Down
12 changes: 12 additions & 0 deletions testdata/scripts/comment-spaced.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ package p

//go:unknowndirective

//lint:disablefoo

//not actually: a directive

//export CgoFunc

//line 123

//foo is foo.
Expand All @@ -36,6 +42,12 @@ package p

//go:unknowndirective

//lint:disablefoo

// not actually: a directive

//export CgoFunc

//line 123

// foo is foo.
Expand Down

0 comments on commit 7cf08f7

Please sign in to comment.