71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
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)
|
|
}
|
|
}
|
|
}
|