89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
_ "embed"
|
|
"flag"
|
|
"html/template"
|
|
"log"
|
|
"os"
|
|
"path"
|
|
"regexp"
|
|
)
|
|
|
|
// A struct based on fs.DirEntry
|
|
type Entry struct {
|
|
Name string
|
|
IsDir bool
|
|
}
|
|
|
|
//go:embed index.html.tmpl
|
|
var indexTemplate string
|
|
|
|
// Return the list of entries inside a specified directory
|
|
func getEntries(dirPath string) ([]Entry, error) {
|
|
dirEntries, err := os.ReadDir(dirPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
entryList := []Entry{}
|
|
for _, entry := range dirEntries {
|
|
// Of course we want to ignore index.html file in the directory listing
|
|
if entry.Name() != "index.html" {
|
|
entryName := entry.Name()
|
|
if entry.IsDir() {
|
|
entryName = entryName + "/"
|
|
}
|
|
entryList = append(entryList, Entry{Name: entryName, IsDir: entry.IsDir()})
|
|
}
|
|
}
|
|
|
|
return entryList, nil
|
|
}
|
|
|
|
// Output an index.html file listing entries to a specified destination
|
|
func renderIndexHTML(entries []Entry, root string, dest string, isHomePage bool) error {
|
|
// Get rid of ./out/ prefix from find(1) result
|
|
re := regexp.MustCompile(`^\.\/` + root + `\/`)
|
|
dirPath := re.ReplaceAllString(dest, "")
|
|
|
|
tmpl, err := template.New(dirPath).Parse(indexTemplate)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
data := struct {
|
|
Path string
|
|
Entries []Entry
|
|
IsHomePage bool
|
|
}{Path: dirPath, Entries: entries, IsHomePage: isHomePage}
|
|
|
|
destFile, err := os.Create(path.Join(dest, "index.html"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return tmpl.Execute(destFile, data)
|
|
}
|
|
|
|
func main() {
|
|
rootDir := flag.String("root", "out", "Directory indicating the root of the website")
|
|
isHomePage := flag.Bool("home", false, "Whether the directory is the top-level website's index")
|
|
flag.Parse()
|
|
|
|
dirPath := flag.Arg(0)
|
|
if dirPath == "" {
|
|
log.Fatalln("Missing argument: directory to output the index.html file")
|
|
}
|
|
|
|
entries, err := getEntries(dirPath)
|
|
if err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
|
|
err = renderIndexHTML(entries, *rootDir, dirPath, *isHomePage)
|
|
if err != nil {
|
|
log.Fatalln(err)
|
|
}
|
|
}
|