Add zs generate command for generating partial fragments

This commit is contained in:
James Mills 2023-04-01 10:47:02 +10:00
parent 3c1f7fdf56
commit 1fa555ea43
No known key found for this signature in database
GPG Key ID: AC4C014F1440EBD6

37
main.go
View File

@ -199,6 +199,22 @@ var BuildCmd = &cobra.Command{
},
}
// GenerateCmd is the generate sub-command that builds partial fragments
var GenerateCmd = &cobra.Command{
Use: "generate",
Aliases: []string{"gen"},
Short: "Generates partial fragments",
Long: `The generate command parses and renders partial fragments from stdin and writes to stdout`,
Args: cobra.RangeArgs(0, 1),
RunE: func(cmd *cobra.Command, args []string) error {
if err := generate(os.Stdin, os.Stdout, globals()); err != nil {
return fmt.Errorf("error generating fragment: %w", err)
}
return nil
},
}
// ServeCmd is the serve sub-command that performs whole builds or single builds
var ServeCmd = &cobra.Command{
Use: "serve [flags]",
@ -632,6 +648,26 @@ func buildAll(ctx context.Context, watch bool) error {
}
}
// gen generates partial fragments
func generate(r io.Reader, w io.Writer, v Vars) error {
data, err := io.ReadAll(r)
if err != nil {
return err
}
body := string(data)
source, err := render(body, v)
if err != nil {
return err
}
if err := Parser.Convert([]byte(source), w); err != nil {
return err
}
return nil
}
// serve runs a static web server and builds and continuously watches for changes to rebuild
func serve(ctx context.Context, bind, root string) error {
os.Mkdir(root, 0755)
@ -700,6 +736,7 @@ func init() {
ServeCmd.Flags().StringP("root", "r", PUBDIR, "set the root directory to serve")
RootCmd.AddCommand(BuildCmd)
RootCmd.AddCommand(GenerateCmd)
RootCmd.AddCommand(ServeCmd)
RootCmd.AddCommand(VarCmd)
RootCmd.AddCommand(WatchCmd)