From b47d6e3da6e34607f7f06b3acfceb74f62d5a6a6 Mon Sep 17 00:00:00 2001 From: Alex Flint Date: Fri, 1 Oct 2021 04:35:15 -0700 Subject: [PATCH] put name of environment variable in error message --- parse.go | 6 +++++- parse_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/parse.go b/parse.go index 1ebb2a4..7588dfb 100644 --- a/parse.go +++ b/parse.go @@ -653,7 +653,11 @@ func (p *Parser) process(args []string) error { } if spec.required { - return fmt.Errorf("%s is required", name) + msg := fmt.Sprintf("%s is required", name) + if spec.env != "" { + msg += " (or environment variable " + spec.env + ")" + } + return errors.New(msg) } if spec.defaultVal != "" { err := scalar.ParseValue(p.val(spec.dest), spec.defaultVal) diff --git a/parse_test.go b/parse_test.go index 284e386..2d0ef7a 100644 --- a/parse_test.go +++ b/parse_test.go @@ -203,6 +203,14 @@ func TestRequired(t *testing.T) { require.Error(t, err, "--foo is required") } +func TestRequiredWithEnv(t *testing.T) { + var args struct { + Foo string `arg:"required,env:FOO"` + } + err := parse("", &args) + require.Error(t, err, "--foo is required (or environment variable FOO)") +} + func TestShortFlag(t *testing.T) { var args struct { Foo string `arg:"-f"`