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 (
|
|
|
|
importRe = regexp.MustCompile(`(?ms)import \(([^)]+)\)`)
|
2022-12-23 19:25:38 +00:00
|
|
|
otherRe = regexp.MustCompile(`^(?:var|const|func)\s`)
|
2022-08-09 18:46:36 +00:00
|
|
|
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 {
|
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
|
|
|
|
}
|