-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.go
48 lines (41 loc) · 933 Bytes
/
package.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package snips
import (
"os"
"path/filepath"
"strings"
)
func PackageName(dir string) (name string) {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".templ") {
content, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), "package ") {
name = strings.TrimSpace(strings.TrimPrefix(line, "package"))
return filepath.SkipAll // stop walking, we found a package name
}
}
}
return nil
})
if err != nil || name == "" {
return fallback(dir)
}
return name
}
func fallback(dir string) (name string) {
var (
parts = strings.Split(filepath.ToSlash(dir), "/")
n = len(parts)
)
if n > 1 {
return parts[n-1]
}
return "main"
}