Files
s/build/generate-index.go

101 lines
2.2 KiB
Go
Raw Normal View History

2025-10-08 15:02:13 -07:00
package main
import (
2025-10-08 15:19:18 -07:00
"flag"
2025-10-08 15:02:13 -07:00
"fmt"
"html/template"
"os"
"path/filepath"
"sort"
2025-10-08 15:19:18 -07:00
"strings"
2025-10-08 15:02:13 -07:00
)
type IndexData struct {
2025-10-08 15:19:18 -07:00
Dir string
Files []FileEntry
RootURL string
2025-10-08 15:02:13 -07:00
}
2025-10-08 15:19:18 -07:00
type FileEntry struct {
Name string
URL string
}
func generateIndex(dir string, rootURL string) error {
2025-10-08 15:02:13 -07:00
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read directory: %w", err)
}
2025-10-08 15:19:18 -07:00
// Normalize root URL (remove trailing slash)
rootURL = strings.TrimSuffix(rootURL, "/")
var fileNames []string
2025-10-08 15:02:13 -07:00
for _, entry := range entries {
name := entry.Name()
// Skip the index.html itself and hidden files
if name != "index.html" && !filepath.HasPrefix(name, ".") {
2025-10-08 15:19:18 -07:00
fileNames = append(fileNames, name)
2025-10-08 15:02:13 -07:00
}
}
2025-10-08 15:19:18 -07:00
sort.Strings(fileNames)
// Build file entries with absolute URLs
var files []FileEntry
dirName := filepath.Base(dir)
for _, name := range fileNames {
// URL encode the filename for the path
url := fmt.Sprintf("%s/%s/%s", rootURL, dirName, name)
files = append(files, FileEntry{
Name: name,
URL: url,
})
}
2025-10-08 15:02:13 -07:00
templatePath := "build/index.html.tmpl"
tmpl, err := template.ParseFiles(templatePath)
if err != nil {
return fmt.Errorf("failed to parse template: %w", err)
}
indexPath := filepath.Join(dir, "index.html")
f, err := os.Create(indexPath)
if err != nil {
return fmt.Errorf("failed to create index.html: %w", err)
}
defer f.Close()
data := IndexData{
2025-10-08 15:19:18 -07:00
Dir: dirName,
Files: files,
RootURL: rootURL,
2025-10-08 15:02:13 -07:00
}
if err := tmpl.Execute(f, data); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
fmt.Printf("Generated index.html in %s\n", dir)
return nil
}
func main() {
2025-10-08 15:19:18 -07:00
rootURL := flag.String("root", "https://ss-6r6jq.ondigitalocean.app", "Root domain URL for absolute links")
flag.Parse()
dirs := flag.Args()
if len(dirs) == 0 {
fmt.Println("Usage: generate-index [-root <url>] <directory> [<directory>...]")
fmt.Println(" -root string")
fmt.Println(" Root domain URL for absolute links (default \"https://ss-6r6jq.ondigitalocean.app\")")
2025-10-08 15:02:13 -07:00
os.Exit(1)
}
2025-10-08 15:19:18 -07:00
for _, dir := range dirs {
if err := generateIndex(dir, *rootURL); err != nil {
2025-10-08 15:02:13 -07:00
fmt.Fprintf(os.Stderr, "Error processing %s: %v\n", dir, err)
os.Exit(1)
}
}
}