fix: better errors and import spacing
ci/woodpecker/tag/goreleaser Pipeline was successful Details

Signed-off-by: jolheiser <john.olheiser@gmail.com>
main v0.0.2
jolheiser 2022-12-23 13:25:38 -06:00
parent 81144edfe4
commit 37925d9220
Signed by: jolheiser
GPG Key ID: B853ADA5DA7BBF7A
3 changed files with 14 additions and 9 deletions

View File

@ -2,13 +2,14 @@ package format
import (
"errors"
"fmt"
"regexp"
"strings"
)
var (
importRe = regexp.MustCompile(`(?ms)import \(([^)]+)\)`)
otherRe = regexp.MustCompile(`(?:var|const|func)\s`)
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
ErrNoImports = errors.New("no imports found")
)
@ -16,17 +17,17 @@ var (
func Source(src []byte, module string) ([]byte, error) {
importStart := importRe.FindIndex(src)
if importStart == nil {
return nil, ErrNoImports
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)
}
otherStart := otherRe.FindIndex(src)
if otherStart != nil && otherStart[0] < importStart[0] {
return nil, ErrNoImports
return nil, fmt.Errorf("found non-imports before imports: %w", ErrNoImports)
}
groups := importRe.FindStringSubmatch(string(src))
if groups[0] == "" {
return nil, ErrNoImports
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)
}
imports := strings.Split(groups[1], "\n")

View File

@ -42,11 +42,11 @@ func (i importBlock) String() string {
var decl strings.Builder
decl.WriteString(strings.Join(importItemSlice(i.Stdlib), "\n\t"))
if len(i.Stdlib) > 0 {
if len(i.Module) > 0 {
decl.WriteString("\n\n\t")
}
decl.WriteString(strings.Join(importItemSlice(i.Module), "\n\t"))
if len(i.Module) > 0 {
if len(i.Other) > 0 {
decl.WriteString("\n\n\t")
}
decl.WriteString(strings.Join(importItemSlice(i.Other), "\n\t"))

10
imp.go
View File

@ -3,6 +3,7 @@ package main
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
@ -45,15 +46,18 @@ func runImp(root, ignore string, write bool) error {
data, err := os.ReadFile(walkPath)
if err != nil {
return err
return fmt.Errorf("could not read file %q: %w", walkPath, err)
}
formatted, err := format.Source(data, module)
if err != nil {
return err
return fmt.Errorf("could not format file %q: %w", walkPath, err)
}
if write {
return os.WriteFile(walkPath, formatted, walkInfo.Mode())
if err := os.WriteFile(walkPath, formatted, walkInfo.Mode()); err != nil {
return fmt.Errorf("could not write file %q: %w", walkPath, err)
}
return nil
}
if !bytes.Equal(data, formatted) {