wand/exec.go

96 lines
1.8 KiB
Go
Raw Normal View History

2025-08-18 14:24:31 +02:00
package wand
import (
"errors"
"fmt"
"github.com/iancoleman/strcase"
"io"
2025-08-24 01:45:25 +02:00
"os"
2025-08-18 14:24:31 +02:00
"path/filepath"
2025-08-24 01:45:25 +02:00
"strconv"
2025-08-18 14:24:31 +02:00
)
2025-08-24 01:45:25 +02:00
func exec(stdin io.Reader, stdout, stderr io.Writer, exit func(int), cmd Cmd, conf Config, env, args []string) {
2025-08-18 14:24:31 +02:00
cmd = insertHelp(cmd)
_, cmd.name = filepath.Split(args[0])
cmd.name = strcase.ToKebab(cmd.name)
2025-08-24 01:45:25 +02:00
if err := validateCommand(cmd, conf); err != nil {
2025-08-18 14:24:31 +02:00
panic(err)
}
2025-08-24 01:45:25 +02:00
if os.Getenv("wandgenerate") == "man" {
if err := generateMan(stdout, cmd); 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, level); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
2025-08-18 14:24:31 +02:00
e := readEnv(cmd.name, env)
2025-08-24 01:45:25 +02:00
cmd, fullCmd, args := selectCommand(cmd, args[1:])
2025-08-18 14:24:31 +02:00
if cmd.impl == nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, errors.New("subcommand not specified"))
2025-08-18 14:24:31 +02:00
suggestHelp(stderr, cmd, fullCmd)
exit(1)
return
}
if cmd.helpRequested {
2025-08-24 01:45:25 +02:00
if err := showHelp(stdout, cmd, fullCmd); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
2025-08-18 14:24:31 +02:00
return
}
bo := boolOptions(cmd)
cl := readArgs(bo, args)
if hasHelpOption(cmd, cl.options) {
2025-08-24 01:45:25 +02:00
if err := showHelp(stdout, cmd, fullCmd); 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)
2025-08-18 14:24:31 +02:00
return
}
2025-08-24 01:45:25 +02:00
if err := validateInput(cmd, conf, c, e, cl); err != nil {
fmt.Fprintln(stderr, err)
2025-08-18 14:24:31 +02:00
suggestHelp(stderr, cmd, fullCmd)
exit(1)
return
}
2025-08-24 01:45:25 +02:00
output, err := apply(stdin, stdout, cmd, c, e, cl)
2025-08-18 14:24:31 +02:00
if err != nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, err)
2025-08-18 14:24:31 +02:00
exit(1)
return
}
if err := printOutput(stdout, output); err != nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, err)
2025-08-18 14:24:31 +02:00
exit(1)
return
}
}