Index generation

This commit is contained in:
Ian Gulliver
2025-10-08 15:02:13 -07:00
parent 16267aff64
commit 6f4cf627c6
4 changed files with 163 additions and 0 deletions

70
build/generate-index.go Normal file
View File

@@ -0,0 +1,70 @@
package main
import (
"fmt"
"html/template"
"os"
"path/filepath"
"sort"
)
type IndexData struct {
Dir string
Files []string
}
func generateIndex(dir string) error {
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read directory: %w", err)
}
var files []string
for _, entry := range entries {
name := entry.Name()
// Skip the index.html itself and hidden files
if name != "index.html" && !filepath.HasPrefix(name, ".") {
files = append(files, name)
}
}
sort.Strings(files)
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{
Dir: filepath.Base(dir),
Files: files,
}
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() {
if len(os.Args) < 2 {
fmt.Println("Usage: generate-index <directory> [<directory>...]")
os.Exit(1)
}
for _, dir := range os.Args[1:] {
if err := generateIndex(dir); err != nil {
fmt.Fprintf(os.Stderr, "Error processing %s: %v\n", dir, err)
os.Exit(1)
}
}
}

28
build/index.html.tmpl Normal file
View File

@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index of {{.Dir}}</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 0 20px;
}
h1 { color: #333; }
ul { list-style: none; padding: 0; }
li { padding: 8px 0; border-bottom: 1px solid #eee; }
a { text-decoration: none; color: #0066cc; }
a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>Index of {{.Dir}}</h1>
<ul>
{{- range .Files}}
<li><a href="{{.}}">{{.}}</a></li>
{{- end}}
</ul>
</body>
</html>