From: James Mills <1290234+prologic@users.noreply.github.com> Date: Sat, 1 Apr 2023 00:47:02 +0000 (+1000) Subject: Add zs generate command for generating partial fragments X-Git-Tag: 0.4.0~2 X-Git-Url: http://10.10.0.4:5575/?a=commitdiff_plain;h=1fa555ea4388475f28b90ebc2c32ae2dce5705fa;p=aya.git Add zs generate command for generating partial fragments --- diff --git a/main.go b/main.go index 2e21264..8da7525 100644 --- a/main.go +++ b/main.go @@ -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)