Skip to content

Commit

Permalink
prevent unparsed flags (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Aug 18, 2020
1 parent 73f6637 commit 86f00e0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
15 changes: 13 additions & 2 deletions aconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package aconfig

import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
Expand Down Expand Up @@ -41,6 +42,7 @@ type loaderConfig struct {
EnvPrefix string
FlagPrefix string

FailOnNotParsedFlags bool
ShouldStopOnFileError bool
Files []string
}
Expand Down Expand Up @@ -108,6 +110,14 @@ func (l *Loader) WithEnvPrefix(prefix string) *Loader {
return l
}

// FailOnNotParsedFlags to not forget parse flags explicitly.
// Use `l.FlagSet().Parse(os.Args[1:])` in your code for this.
//
func (l *Loader) FailOnNotParsedFlags() *Loader {
l.config.FailOnNotParsedFlags = true
return l
}

// StopOnFileError to stop configuration loading on file error.
func (l *Loader) StopOnFileError() *Loader {
l.config.ShouldStopOnFileError = true
Expand Down Expand Up @@ -267,9 +277,10 @@ func (l *Loader) loadEnvironment() error {

func (l *Loader) loadFlags() error {
if !l.flagSet.Parsed() {
if err := l.flagSet.Parse(os.Args[1:]); err != nil {
return err
if l.config.FailOnNotParsedFlags {
return errors.New("aconfig: flags must be parsed")
}
return nil
}

actualFlags := map[string]*flag.Flag{}
Expand Down
11 changes: 11 additions & 0 deletions aconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,17 @@ func TestBadDefauts(t *testing.T) {
}{})
}

func TestNotParsedFlags(t *testing.T) {
loader := LoaderFor(&TestConfig{}).
FailOnNotParsedFlags().
Build()

var cfg TestConfig
if err := loader.Load(&cfg); err == nil {
t.Fatal(err)
}
}

func TestBadFiles(t *testing.T) {
f := func(filepath string) {
t.Helper()
Expand Down

0 comments on commit 86f00e0

Please sign in to comment.