81 lines
1.9 KiB
Go
81 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"io/fs"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
inDir := flag.String("in", "docs", "Input directory containing .typ files")
|
|
outFile := flag.String("out", "acl.json", "Output acl.json file")
|
|
flag.Parse()
|
|
|
|
acl := make(map[string][]string)
|
|
|
|
// Match: #let access-groups = ("group1", "group2")
|
|
// The regex handles optional spaces and varying number of groups.
|
|
re := regexp.MustCompile(`(?m)^#let\s+access-groups\s*=\s*\(([^)]*)\)`)
|
|
|
|
err := filepath.WalkDir(*inDir, func(path string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !d.IsDir() && filepath.Ext(path) == ".typ" {
|
|
content, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return fmt.Errorf("reading %s: %w", path, err)
|
|
}
|
|
|
|
relPath, err := filepath.Rel(*inDir, path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Map .typ to .html in the final URL structure
|
|
urlPath := "/" + strings.TrimSuffix(relPath, ".typ") + ".html"
|
|
// Ensure forward slashes for URLs
|
|
urlPath = strings.ReplaceAll(urlPath, "\\", "/")
|
|
|
|
matches := re.FindSubmatch(content)
|
|
if len(matches) > 1 {
|
|
groupsStr := string(matches[1])
|
|
var groups []string
|
|
// Split by comma and clean up quotes/spaces
|
|
for _, g := range strings.Split(groupsStr, ",") {
|
|
g = strings.TrimSpace(g)
|
|
g = strings.Trim(g, `"'`)
|
|
if g != "" {
|
|
groups = append(groups, g)
|
|
}
|
|
}
|
|
if len(groups) > 0 {
|
|
acl[urlPath] = groups
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
|
|
if err != nil {
|
|
log.Fatalf("Error scanning directory: %v", err)
|
|
}
|
|
|
|
outData, err := json.MarshalIndent(acl, "", " ")
|
|
if err != nil {
|
|
log.Fatalf("Error generating JSON: %v", err)
|
|
}
|
|
|
|
if err := os.WriteFile(*outFile, outData, 0644); err != nil {
|
|
log.Fatalf("Error writing %s: %v", *outFile, err)
|
|
}
|
|
|
|
fmt.Printf("Successfully generated %s with %d rules\n", *outFile, len(acl))
|
|
}
|