diff --git a/format/format.go b/format/format.go index 1cf20ac..c5709c3 100644 --- a/format/format.go +++ b/format/format.go @@ -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") diff --git a/format/struct.go b/format/struct.go index 8ef07d8..574327b 100644 --- a/format/struct.go +++ b/format/struct.go @@ -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")) diff --git a/imp.go b/imp.go index b391640..eeb7df8 100644 --- a/imp.go +++ b/imp.go @@ -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) {