2022-08-09 18:46:36 +00:00
|
|
|
package format
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2022-12-23 19:25:38 +00:00
|
|
|
"fmt"
|
2022-08-09 18:46:36 +00:00
|
|
|
"regexp"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-01-10 17:35:59 +00:00
|
|
|
importRe = regexp.MustCompile(`(?ms)^import \(([^)]+)\)`)
|
|
|
|
singleImportRe = regexp.MustCompile(`(?ms)^import "[^"]+"`)
|
|
|
|
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
|
|
|
|
ErrNoImports = errors.New("no imports found")
|
2022-08-09 18:46:36 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Source formats a given src's imports
|
|
|
|
func Source(src []byte, module string) ([]byte, error) {
|
2023-01-10 17:35:59 +00:00
|
|
|
if singleImportRe.Match(src) {
|
|
|
|
return src, nil
|
|
|
|
}
|
|
|
|
|
2022-08-09 18:46:36 +00:00
|
|
|
importStart := importRe.FindIndex(src)
|
|
|
|
if importStart == nil {
|
2022-12-23 19:25:38 +00:00
|
|
|
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)
|
2022-08-09 18:46:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
otherStart := otherRe.FindIndex(src)
|
|
|
|
if otherStart != nil && otherStart[0] < importStart[0] {
|
2022-12-23 19:25:38 +00:00
|
|
|
return nil, fmt.Errorf("found non-imports before imports: %w", ErrNoImports)
|
2022-08-09 18:46:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
groups := importRe.FindStringSubmatch(string(src))
|
|
|
|
if groups[0] == "" {
|
2022-12-23 19:25:38 +00:00
|
|
|
return nil, fmt.Errorf("could not find imports: %w", ErrNoImports)
|
2022-08-09 18:46:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|