diff options
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 123 |
1 files changed, 123 insertions, 0 deletions
diff --git a/main.go b/main.go new file mode 100644 index 0000000..ed23069 --- /dev/null +++ b/main.go @@ -0,0 +1,123 @@ +package main + +import ( + "context" + "fmt" + "log" + "net/url" + "os" + "path/filepath" + + "github.com/a-h/templ" + "github.com/pelletier/go-toml/v2" +) + +type Config struct { + Title string + Domain string + Forge string + Menu []*Link + Packages []*Package +} + +type Link struct { + Name string + URL string +} + +type Package struct { + Name string + URL string +} + +func must[T any](t T, err error) T { + if err != nil { + panic(err) + } + return t +} + +func fatal(err error) { + if err != nil { + log.Fatal(err) + } +} + +func importString(config *Config, pkg Package) string { + return fmt.Sprintf("%s git %s", + must(url.JoinPath(config.Domain, pkg.Name)), + must(url.JoinPath(config.Forge, pkg.Name)), + ) +} + +func sourceString(config *Config, pkg Package) string { + return fmt.Sprintf("%s _ %s %s", + must(url.JoinPath(config.Domain, pkg.Name)), + must(url.JoinPath(config.Forge, pkg.Name, "tree/main{/dir}")), + must(url.JoinPath(config.Forge, pkg.Name, "tree/main{/dir}/{file}#n{line}")), + ) +} + +func godocURL(config *Config, pkg *Package) string { + return must(url.JoinPath("https://pkg.go.dev", packageImportPath(config, pkg))) +} + +func packageImportPath(config *Config, pkg *Package) string { + return must(url.JoinPath(config.Domain, pkg.Name)) +} + +func packageForgeURL(config *Config, pkg *Package) string { + return must(url.JoinPath(config.Forge, pkg.Name)) +} + +func getConfig(filename string) (cfg *Config, err error) { + cfg = new(Config) + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer file.Close() + dec := toml.NewDecoder(file) + err = dec.Decode(cfg) + if err != nil { + return nil, err + } + + return cfg, nil +} + +const destDir = "dist" + +func renderToFile(c templ.Component, filename string) error { + pathname := filepath.Join(destDir, filename) + err := os.MkdirAll(filepath.Dir(pathname), 0755) + if err != nil { + return err + } + file, err := os.Create(pathname) + if err != nil { + return err + } + defer file.Close() + + return c.Render(context.Background(), file) +} + +func main() { + cfg, err := getConfig("vanity.toml") + fatal(err) + + err = renderToFile( + ListPage(cfg), + "index.html", + ) + fatal(err) + + for _, pkg := range cfg.Packages { + err = renderToFile( + PackagePage(cfg, pkg), + filepath.Join(pkg.Name, "index.html"), + ) + fatal(err) + } +} |