This repository has been archived on 2023-11-08. You can view files and clone it, but cannot push or open issues/pull-requests.
imp/format/format.go

41 lines
919 B
Go

package format
import (
"errors"
"regexp"
"strings"
)
var (
importRe = regexp.MustCompile(`(?ms)import \(([^)]+)\)`)
otherRe = regexp.MustCompile(`(?:var|const|func)\s`)
ErrNoImports = errors.New("no imports found")
)
// Source formats a given src's imports
func Source(src []byte, module string) ([]byte, error) {
importStart := importRe.FindIndex(src)
if importStart == nil {
return nil, ErrNoImports
}
otherStart := otherRe.FindIndex(src)
if otherStart != nil && otherStart[0] < importStart[0] {
return nil, ErrNoImports
}
groups := importRe.FindStringSubmatch(string(src))
if groups[0] == "" {
return nil, ErrNoImports
}
imports := strings.Split(groups[1], "\n")
for idx, i := range imports {
imports[idx] = strings.TrimSpace(i)
}
block := parseBlock(module, imports)
replaced := strings.Replace(string(src), groups[0], block.String(), 1)
return []byte(replaced), nil
}