fix: fallback to stdin automatically if no url provided by flag

This commit is contained in:
Robert Kaussow 2023-07-21 00:25:45 +02:00
parent 0af993f5b1
commit 510fca6348
Signed by: xoxys
GPG Key ID: 4E692A2EAECC03C0
2 changed files with 8 additions and 28 deletions

View File

@ -37,12 +37,6 @@ func main() {
EnvVars: []string{"URL_PARSER_URL"},
Destination: &cfg.URL,
},
&cli.BoolFlag{
Name: "stdin",
Usage: "read url to parse from stdin",
EnvVars: []string{"URL_PARSER_STDIN"},
Destination: &cfg.Stdin,
},
},
Commands: []*cli.Command{
{
@ -103,31 +97,19 @@ func main() {
},
},
Before: func(ctx *cli.Context) error {
if cfg.URL == "" && !cfg.Stdin {
_ = cli.ShowAppHelp(ctx)
return fmt.Errorf("error: %w", config.ErrRequiredFlagsNotSet)
}
if cfg.URL != "" && cfg.Stdin {
_ = cli.ShowAppHelp(ctx)
return fmt.Errorf("error: %w", config.ErrExclusiveFlags)
}
if cfg.Stdin {
if cfg.URL == "" {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
stdin, err := io.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("error: %w: %w", config.ErrEmptyStdin, err)
return fmt.Errorf("error: %w: %w", config.ErrReadStdin, err)
}
cfg.URL = strings.TrimSuffix(string(stdin), "\n")
}
}
if cfg.URL == "" {
return fmt.Errorf("error: %w", config.ErrEmptyStdin)
}
if cfg.URL == "" {
return fmt.Errorf("error: %w", config.ErrEmptyURL)
}
return nil

View File

@ -3,11 +3,9 @@ package config
import "errors"
var (
ErrRequiredFlagsNotSet = errors.New("either \"url\" or \"stdin\" must be set")
ErrExclusiveFlags = errors.New("\"url\" and \"stdin\" are mutually exclusive")
ErrEmptyStdin = errors.New("\"stdin\" must not be empty")
ErrReadStdin = errors.New("failed to read \"stdin\"")
ErrParseURL = errors.New("failed to parse url")
ErrEmptyURL = errors.New("no url provided either by \"url\" or \"stdin\"")
ErrReadStdin = errors.New("failed to read \"stdin\"")
ErrParseURL = errors.New("failed to parse url")
)
type Config struct {