wand/exec.go

109 lines
2.0 KiB
Go
Raw Normal View History

2025-08-18 14:24:31 +02:00
package wand
import (
"errors"
"fmt"
"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])
2025-08-24 01:45:25 +02:00
if err := validateCommand(cmd, conf); err != nil {
2025-08-26 03:21:35 +02:00
fmt.Fprintf(stderr, "program error: %v\n", err)
exit(1)
return
2025-08-18 14:24:31 +02:00
}
2025-09-01 02:07:48 +02:00
if os.Getenv("_wandgenerate") == "man" {
2025-08-24 04:46:54 +02:00
if err := generateMan(stdout, cmd, conf); err != nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
2025-09-01 02:07:48 +02:00
if os.Getenv("_wandgenerate") == "markdown" {
level, _ := strconv.Atoi(os.Getenv("_wandmarkdownlevel"))
2025-08-24 04:46:54 +02:00
if err := generateMarkdown(stdout, cmd, conf, level); err != nil {
2025-08-24 01:45:25 +02:00
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-26 03:21:35 +02:00
if cmd.isHelp {
if err := showHelp(stdout, cmd, conf, fullCmd); err != nil {
fmt.Fprintln(stderr, err)
exit(1)
}
2025-08-18 14:24:31 +02:00
return
}
2025-08-26 03:21:35 +02:00
if cmd.version != "" {
if err := showVersion(stdout, cmd); err != nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, err)
exit(1)
}
2025-08-18 14:24:31 +02:00
return
}
2025-08-26 03:21:35 +02:00
var bo []string
if cmd.impl != nil {
bo = boolOptions(cmd)
}
2025-08-18 14:24:31 +02:00
cl := readArgs(bo, args)
if hasHelpOption(cmd, cl.options) {
2025-08-26 03:21:35 +02:00
if err := showHelp(stdout, cmd, conf, fullCmd); err != nil {
2025-08-24 01:45:25 +02:00
fmt.Fprintln(stderr, err)
exit(1)
}
return
}
2025-08-26 03:21:35 +02:00
if cmd.impl == nil {
fmt.Fprintln(stderr, errors.New("subcommand not specified"))
suggestHelp(stderr, cmd, fullCmd)
exit(1)
return
}
2025-08-24 01:45:25 +02:00
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
}
}