Skip to content

Commit

Permalink
fix(command-args): parsing arguments correctly, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ldebruijn committed Sep 16, 2024
1 parent a3a84d9 commit 02aa2d7
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 14 deletions.
39 changes: 25 additions & 14 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,39 +27,50 @@ var (
},
[]string{"version", "go_version", "short_hash"},
)

ErrNoSubCommand = errors.New("Subcommand expected. Options are `serve`, `validate`, `version` or `help`")
)

func init() {
prometheus.MustRegister(appInfo)
}

func main() {
if len(os.Args) < 2 {
log2.Println("Subcommand expected. Options are `serve`, `validate`, `version` or `help`")
os.Exit(1)
}
log2.Println("Initialized with arguments: ", os.Args)

action := strings.ToLower(os.Args[1])

flagSet := flag.NewFlagSet("", flag.ExitOnError)
configPath := flagSet.String("f", "./protect.yml", "Defines the path at which the configuration file can be found")
err := flagSet.Parse(os.Args[2:])
action, configPath, err := parseFlags()
if err != nil {
fmt.Printf("Error parsing flags %v\n", err)
log2.Println(err)
os.Exit(1)
return
}

log2.Println("Reading configuration from", *configPath)
log2.Println("Reading configuration from", configPath)

err = startup(action, *configPath)
err = startup(action, configPath)
if err != nil {
log2.Println("Subcommand expected. Options are `serve`, `validate`, `version` or `help`")
os.Exit(1)
}
os.Exit(0)
}

func parseFlags() (string, string, error) {
args := os.Args
if len(os.Args) < 2 {
return "", "", ErrNoSubCommand
}
log2.Println("Initialized with arguments: ", args)

action := strings.ToLower(os.Args[1])

flagSet := flag.NewFlagSet("", flag.ContinueOnError)
configPath := flagSet.String("f", "./protect.yml", "Defines the path at which the configuration file can be found")
err := flagSet.Parse(os.Args[2:])
if err != nil {
return "", "", err
}
return action, *configPath, nil
}

func startup(action string, path string) error {
// cfg
cfg, err := config.NewConfig(path)
Expand Down
65 changes: 65 additions & 0 deletions cmd/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/ldebruijn/graphql-protect/internal/app/config"
"github.com/ldebruijn/graphql-protect/internal/business/protect"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -837,3 +838,67 @@ func TestMainInitialization(t *testing.T) {
})
}
}

func Test_parseFlags(t *testing.T) {
type args struct {
flags []string
}
tests := []struct {
name string
args args
wantCommand string
wantConfigPath string
wantErr error
}{
{
name: "requires a subcommand",
args: args{
flags: nil,
},
wantCommand: "",
wantConfigPath: "",
wantErr: ErrNoSubCommand,
},
{
name: "correctly picks up subcommand and uses default configpath value",
args: args{
flags: []string{"serve"},
},
wantCommand: "serve",
wantConfigPath: "./protect.yml",
wantErr: nil,
},
{
name: "correctly picks up subcommand and uses explicitly specified configpath value",
args: args{
flags: []string{"serve", "-f", "foo-bar.yml"},
},
wantCommand: "serve",
wantConfigPath: "foo-bar.yml",
wantErr: nil,
},
{
name: "correctly picks up subcommand and uses explicitly specified configpath value",
args: args{
flags: []string{"serve", "-f"},
},
wantCommand: "",
wantConfigPath: "",
wantErr: fmt.Errorf("flag needs an argument: -f"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()

os.Args = append([]string{"binary"}, tt.args.flags...)

command, configPath, err := parseFlags()

assert.Equal(t, tt.wantErr, err)
assert.Equalf(t, tt.wantCommand, command, "parseFlags()")
assert.Equalf(t, tt.wantConfigPath, configPath, "parseFlags()")
})
}
}

0 comments on commit 02aa2d7

Please sign in to comment.