fix: check for single import
ci/woodpecker/push/goreleaser Pipeline was successful Details
ci/woodpecker/tag/goreleaser Pipeline was successful Details

Signed-off-by: jolheiser <john.olheiser@gmail.com>
main v0.0.3
jolheiser 2023-01-10 11:35:59 -06:00
parent 37925d9220
commit 08f9985010
Signed by: jolheiser
GPG Key ID: B853ADA5DA7BBF7A
2 changed files with 16 additions and 3 deletions

View File

@ -8,13 +8,18 @@ import (
) )
var ( var (
importRe = regexp.MustCompile(`(?ms)import \(([^)]+)\)`) importRe = regexp.MustCompile(`(?ms)^import \(([^)]+)\)`)
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`) singleImportRe = regexp.MustCompile(`(?ms)^import "[^"]+"`)
ErrNoImports = errors.New("no imports found") otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
ErrNoImports = errors.New("no imports found")
) )
// Source formats a given src's imports // Source formats a given src's imports
func Source(src []byte, module string) ([]byte, error) { func Source(src []byte, module string) ([]byte, error) {
if singleImportRe.Match(src) {
return src, nil
}
importStart := importRe.FindIndex(src) importStart := importRe.FindIndex(src)
if importStart == nil { if importStart == nil {
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports) return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)

View File

@ -22,6 +22,9 @@ func TestSource(t *testing.T) {
formatted, err := Source(before, module) formatted, err := Source(before, module)
assert.NoErr(err) // Should be able to format before block assert.NoErr(err) // Should be able to format before block
assert.True(bytes.Equal(formatted, after)) // Formatted should match after block assert.True(bytes.Equal(formatted, after)) // Formatted should match after block
_, err = Source(singleImport, module)
assert.NoErr(err) // Should not get an error for single import
} }
var ( var (
@ -34,6 +37,11 @@ func main() {
s := "import \"fmt\"" s := "import \"fmt\""
_ = s _ = s
}`) }`)
singleImport = []byte(`package main
import "fmt"
func main() {}`)
before = []byte(`package main before = []byte(`package main
import ( import (