fix: fallback to stdin automatically if no url provided by flag
This commit is contained in:
parent
0af993f5b1
commit
510fca6348
|
@ -37,12 +37,6 @@ func main() {
|
||||||
EnvVars: []string{"URL_PARSER_URL"},
|
EnvVars: []string{"URL_PARSER_URL"},
|
||||||
Destination: &cfg.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{
|
Commands: []*cli.Command{
|
||||||
{
|
{
|
||||||
|
@ -103,31 +97,19 @@ func main() {
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
Before: func(ctx *cli.Context) error {
|
Before: func(ctx *cli.Context) error {
|
||||||
if cfg.URL == "" && !cfg.Stdin {
|
if cfg.URL == "" {
|
||||||
_ = 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 {
|
|
||||||
stat, _ := os.Stdin.Stat()
|
stat, _ := os.Stdin.Stat()
|
||||||
if (stat.Mode() & os.ModeCharDevice) == 0 {
|
if (stat.Mode() & os.ModeCharDevice) == 0 {
|
||||||
stdin, err := io.ReadAll(os.Stdin)
|
stdin, err := io.ReadAll(os.Stdin)
|
||||||
if err != nil {
|
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")
|
cfg.URL = strings.TrimSuffix(string(stdin), "\n")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if cfg.URL == "" {
|
if cfg.URL == "" {
|
||||||
return fmt.Errorf("error: %w", config.ErrEmptyStdin)
|
return fmt.Errorf("error: %w", config.ErrEmptyURL)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
@ -3,11 +3,9 @@ package config
|
||||||
import "errors"
|
import "errors"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrRequiredFlagsNotSet = errors.New("either \"url\" or \"stdin\" must be set")
|
ErrEmptyURL = errors.New("no url provided either by \"url\" or \"stdin\"")
|
||||||
ErrExclusiveFlags = errors.New("\"url\" and \"stdin\" are mutually exclusive")
|
ErrReadStdin = errors.New("failed to read \"stdin\"")
|
||||||
ErrEmptyStdin = errors.New("\"stdin\" must not be empty")
|
ErrParseURL = errors.New("failed to parse url")
|
||||||
ErrReadStdin = errors.New("failed to read \"stdin\"")
|
|
||||||
ErrParseURL = errors.New("failed to parse url")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
|
Loading…
Reference in New Issue