wand/exec.go
2025-08-24 04:46:54 +02:00

96 lines
1.8 KiB
Go

package wand
import (
"errors"
"fmt"
"github.com/iancoleman/strcase"
"io"
"os"
"path/filepath"
"strconv"
)
func exec(stdin io.Reader, stdout, stderr io.Writer, exit func(int), cmd Cmd, conf Config, env, args []string) {
cmd = insertHelp(cmd)
_, cmd.name = filepath.Split(args[0])
cmd.name = strcase.ToKebab(cmd.name)
if err := validateCommand(cmd, conf); err != nil {
panic(err)
}
if os.Getenv("wandgenerate") == "man" {
if err := generateMan(stdout, cmd, conf); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
if os.Getenv("wandgenerate") == "markdown" {
level, _ := strconv.Atoi(os.Getenv("wandmarkdownlevel"))
if err := generateMarkdown(stdout, cmd, conf, level); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
e := readEnv(cmd.name, env)
cmd, fullCmd, args := selectCommand(cmd, args[1:])
if cmd.impl == nil {
fmt.Fprintln(stderr, errors.New("subcommand not specified"))
suggestHelp(stderr, cmd, fullCmd)
exit(1)
return
}
if cmd.helpRequested {
if err := showHelp(stdout, cmd, fullCmd, conf); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
bo := boolOptions(cmd)
cl := readArgs(bo, args)
if hasHelpOption(cmd, cl.options) {
if err := showHelp(stdout, cmd, fullCmd, conf); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
c, err := readConfig(cmd, cl, conf)
if err != nil {
fmt.Fprintf(stderr, "configuration error: %v", err)
exit(1)
return
}
if err := validateInput(cmd, conf, c, e, cl); err != nil {
fmt.Fprintln(stderr, err)
suggestHelp(stderr, cmd, fullCmd)
exit(1)
return
}
output, err := apply(stdin, stdout, cmd, c, e, cl)
if err != nil {
fmt.Fprintln(stderr, err)
exit(1)
return
}
if err := printOutput(stdout, output); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
return
}
}