forked from mirror/oddmu
91 lines
2.3 KiB
Go
91 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"flag"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/google/subcommands"
|
|
)
|
|
|
|
type htmlCmd struct {
|
|
template string
|
|
}
|
|
|
|
func (*htmlCmd) Name() string { return "html" }
|
|
func (*htmlCmd) Synopsis() string { return "render a page as HTML" }
|
|
func (*htmlCmd) Usage() string {
|
|
return `html [-template <template name>] <page name> ...:
|
|
Render one or more pages as HTML.
|
|
Use a single - to read Markdown from stdin.
|
|
`
|
|
}
|
|
|
|
func (cmd *htmlCmd) SetFlags(f *flag.FlagSet) {
|
|
f.StringVar(&cmd.template, "template", "",
|
|
"use the given HTML file as a template (probably view.html or static.html).")
|
|
}
|
|
|
|
func (cmd *htmlCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
|
|
return htmlCli(os.Stdout, cmd.template, f.Args())
|
|
}
|
|
|
|
func htmlCli(w io.Writer, template string, args []string) subcommands.ExitStatus {
|
|
if len(args) == 1 && args[0] == "-" {
|
|
body, err := io.ReadAll(os.Stdin)
|
|
if err != nil {
|
|
fmt.Fprintf(w, "Cannot read from stdin: %s\n", err)
|
|
return subcommands.ExitFailure
|
|
}
|
|
p := &Page{Name: "stdin", Body: body}
|
|
return p.printHTML(w, template)
|
|
}
|
|
for _, name := range args {
|
|
if !strings.HasSuffix(name, ".md") {
|
|
fmt.Fprintf(os.Stderr, "%s does not end in '.md'\n", name)
|
|
return subcommands.ExitFailure
|
|
}
|
|
name = name[0 : len(name)-3]
|
|
p, err := loadPage(name)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Cannot load %s: %s\n", name, err)
|
|
return subcommands.ExitFailure
|
|
}
|
|
status := p.printHTML(w, template)
|
|
if status != subcommands.ExitSuccess {
|
|
return status
|
|
}
|
|
}
|
|
return subcommands.ExitSuccess
|
|
}
|
|
|
|
func (p *Page) printHTML(w io.Writer, fn string) subcommands.ExitStatus {
|
|
if fn == "" {
|
|
// do not handle title
|
|
p.renderHTML()
|
|
_, err := fmt.Fprintln(w, p.HTML)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Cannot write to stdout: %s\n", err)
|
|
return subcommands.ExitFailure
|
|
}
|
|
return subcommands.ExitSuccess
|
|
}
|
|
p.handleTitle(true)
|
|
p.renderHTML()
|
|
t, err := template.ParseFiles(fn)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Cannot parse template %s for %s: %s\n", fn, p.Name, err)
|
|
return subcommands.ExitFailure
|
|
}
|
|
err = t.Execute(w, p)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Cannot execute template %s for %s: %s\n", fn, p.Name, err)
|
|
return subcommands.ExitFailure
|
|
}
|
|
return subcommands.ExitSuccess
|
|
}
|