Skip to content

Commit

Permalink
Merge pull request #75 from fatih/fatih/test-for-flag-redefinitions
Browse files Browse the repository at this point in the history
Add test to detect duplicate flag names
  • Loading branch information
fatih authored Oct 25, 2020
2 parents 66ed821 + e437848 commit d4b34d8
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 32 deletions.
78 changes: 46 additions & 32 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,46 @@ func main() {
}

func realMain() error {
cfg, err := parseConfig(os.Args[1:])
if err != nil {
if err == flag.ErrHelp {
return nil
}
return err
}

err = cfg.validate()
if err != nil {
return err
}

node, err := cfg.parse()
if err != nil {
return err
}

start, end, err := cfg.findSelection(node)
if err != nil {
return err
}

rewrittenNode, errs := cfg.rewrite(node, start, end)
if errs != nil {
if _, ok := errs.(*rewriteErrors); !ok {
return errs
}
}

out, err := cfg.format(rewrittenNode, errs)
if err != nil {
return err
}

fmt.Println(out)
return nil
}

func parseConfig(args []string) (*config, error) {
var (
// file flags
flagFile = flag.String("file", "", "Filename to be parsed")
Expand Down Expand Up @@ -128,14 +168,15 @@ func realMain() error {
"Add the options per given key. i.e: json=omitempty,hcl=squash")
)

// don't output full help information if something goes wrong
flag.Usage = func() {}
flag.Parse()
// this fails if there are flags re-defined with the same name.
if err := flag.CommandLine.Parse(args); err != nil {
return nil, err
}

if flag.NFlag() == 0 {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
return nil
return nil, flag.ErrHelp
}

cfg := &config{
Expand Down Expand Up @@ -176,35 +217,8 @@ func realMain() error {
cfg.removeOptions = strings.Split(*flagRemoveOptions, ",")
}

err := cfg.validate()
if err != nil {
return err
}

node, err := cfg.parse()
if err != nil {
return err
}
return cfg, nil

start, end, err := cfg.findSelection(node)
if err != nil {
return err
}

rewrittenNode, errs := cfg.rewrite(node, start, end)
if errs != nil {
if _, ok := errs.(*rewriteErrors); !ok {
return errs
}
}

out, err := cfg.format(rewrittenNode, errs)
if err != nil {
return err
}

fmt.Println(out)
return nil
}

func (c *config) parse() (ast.Node, error) {
Expand Down
13 changes: 13 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -862,3 +862,16 @@ func TestParseLines(t *testing.T) {
})
}
}

func TestParseConfig(t *testing.T) {
// don't output help message during the test
flag.CommandLine.SetOutput(ioutil.Discard)

// The flag.CommandLine.Parse() call fails if there are flags re-defined
// with the same name. If there are duplicates, parseConfig() will return
// an error.
_, err := parseConfig([]string{"test"})
if err != nil {
t.Fatal(err)
}
}

0 comments on commit d4b34d8

Please sign in to comment.