Something went wrong. Try again.
parse flags directly into a struct
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763package slag
import ( "fmt" "reflect" "testing" "time"
"github.com/stretchr/testify/assert")
type Foo struct { Bar string}
func TestArgsParser(t *testing.T) { type Test struct { expected map[string]any input []string err error }
// @Todo: not use the nil array and just nil // var nilArry []string
cases := []Test{ { expected: map[string]any{ "person": map[string]any{ "name": "mar", "age": "23", "gender": "false", "animes": map[string]any{ "frieren": map[string]any{"is-there-yuri": "kindaaaowo", "quality": "10"}, "lycoris-recoil": "11", "me-enamore-de-la-villana": "20", "adachi-to-shimamura": "4", }, }, "artists": []string{"chappell roan", "olivia rodrigo", "mon laferte", "mikayla geier", "cariño"}, }, // "hobbies": []string{"being alive (not very good at it tho)" input: []string{ "-person", ".name", "mar", ".age", "23", ".gender", "false", // ".animes", ".frieren", ".is-there-yuri", "kindaaaowo", ".quality", "10", _END_OBJ, ".lycoris-recoil", "11", ".me-enamore-de-la-villana", "20", ".adachi-to-shimamura", "4", // "-artists", "chappell roan", "olivia rodrigo", "mon laferte", "mikayla geier", "cariño", // "-hobbies", "being alive (not very good at it tho)", }, err: nil, }, { input: []string{ "-name", "marcig", "madoka", "homura", "-number", "67", "420", "192", "-decimal64", "23.4565463546", }, expected: map[string]any{ "name": []string{"marcig", "madoka", "homura"}, "number": []string{"67", "420", "192"}, "decimal64": []string{"23.4565463546"}, }, err: nil, }, { expected: map[string]any{ "name": []string{"marcig", "yay"}, "nya": []string{"true"}, }, input: []string{"-name", "marcig", "yay", "-nya", "true"}, err: nil, }, { expected: map[string]any{ "name": []string{"marcig", "yay"}, "nya": nil, }, input: []string{"-name", "marcig", "yay", "-nya"}, err: nil, }, // // @Todo: i want the parser to detect this kind of situations // // having two flags like this is probably not desired ux // // mainly because if these were boolean flags they would be // // together in one, so, keep track if the previouts arg was also // // a - flag (name or boolean flag name indicator) // // { // // expected: make(map[string][]string), // // input: []string{"-name", "-nya"}, // // err: errFlagValueIsMissing("-name"), // // }, { expected: make(map[string]any), input: []string{"-", "value"}, err: ErrInvalidFlagName, }, { expected: make(map[string]any), input: []string{"value"}, err: ErrNoFlagsProvided, }, { expected: make(map[string]any), input: []string{"foo", "bar"}, err: ErrNoFlagsProvided, }, { expected: map[string]any{ "name": []string{"marcig", "yay", "!@#$!@#$!@#$", "fuck", "cock", "balls", "'this is a string'", "\"this is another string\""}, "nya": []string{"true"}, }, input: []string{ "-name", "marcig", "yay", "!@#$!@#$!@#$", "fuck", "cock", "balls", "'this is a string'", `"this is another string"`, "-nya", "true", }, err: nil, }, }
for i, c := range cases { result, err := parseArgs(c.input) t.Logf("TEST:[%v]", i) if c.err == nil { assert.ErrorIs(t, err, c.err) } else { assert.ErrorContains(t, err, c.err.Error()) } assert.EqualValues(t, c.expected, result) }
}
func TestSlagUnmarshal(t *testing.T) {
type Foo struct { Name string Number int Decimal64 float64 Origins []string GreedSeeds []int BoolSlice []bool SmallFloatsSlice []float32 BigFloatsSlice []float64 }
type Test struct { out any expected any args []string err error }
cases := []Test{ { args: []string{ "-name", "marcig", "-number", "192", "-decimal64", "23.4565463546", "-bool-slice", "true", "false", "false", "true", "-small-floats-slice", "0.23", "0.26", "0.28", "0.30", "-big-floats-slice", "0.2348397", "0.2348399", "0.2348402", "-origins", "mexico", "japon", "korea", "oaxaca", "tabasco", "-greed-seeds", "1", "2", "2", }, expected: Foo{ Name: "marcig", Number: 192, Decimal64: 23.4565463546, Origins: []string{ "mexico", "japon", "korea", "oaxaca", "tabasco", }, GreedSeeds: []int{1, 2, 2}, BoolSlice: []bool{true, false, false, true}, SmallFloatsSlice: []float32{ 0.23, 0.26, 0.28, 0.30, }, BigFloatsSlice: []float64{ 0.2348397, 0.2348399, 0.2348402, }, }, err: nil, }, }
for i, c := range cases { out := Foo{} SetArgsSeparator(" ") result, err := parseArgs(c.args) t.Logf("TEST:[%v]", i)
if c.err == nil { assert.ErrorIs(t, err, c.err) } else { assert.ErrorContains(t, err, c.err.Error()) }
err = Unmarshal(&out, result)
assert.NoError(t, err) assert.EqualValues(t, c.expected, out)
}
}
func TestSlagParseWithDefaults(t *testing.T) {
type Foo struct { Name string Number int Decimal64 float64 Origins []string GreedSeeds []int BoolSlice []bool SmallFloatsSlice []float32 BigFloatsSlice []float64 }
type Test struct { expected any defaults any args []string err error }
cases := []Test{ { args: []string{}, expected: Foo{ Name: "<noname>", Number: 69, Decimal64: 69.67, Origins: []string{"lapaz", "bcs", "uwu"}, GreedSeeds: []int{1, 2, 3, 4}, BoolSlice: []bool{false, true}, SmallFloatsSlice: []float32{1.23, 543.32}, BigFloatsSlice: []float64{1.238923, 54.2323, 3.2378432}, }, defaults: Foo{ Name: "<noname>", Number: 69, Decimal64: 69.67, Origins: []string{"lapaz", "bcs", "uwu"}, GreedSeeds: []int{1, 2, 3, 4}, BoolSlice: []bool{false, true}, SmallFloatsSlice: []float32{1.23, 543.32}, BigFloatsSlice: []float64{1.238923, 54.2323, 3.2378432}, }, err: nil, }, { args: []string{"-name", "marcig", "-number", "4", "-origins", "japan", "chametla", "filipinas"}, expected: Foo{ Name: "marcig", Number: 4, Decimal64: 69.67, Origins: []string{"japan", "chametla", "filipinas"}, GreedSeeds: []int{1, 2, 3, 4}, BoolSlice: []bool{false, true}, SmallFloatsSlice: []float32{1.23, 543.32}, BigFloatsSlice: []float64{1.238923, 54.2323, 3.2378432}, }, defaults: Foo{ Name: "<noname>", Number: 69, Decimal64: 69.67, Origins: []string{"lapaz", "bcs", "uwu"}, GreedSeeds: []int{1, 2, 3, 4}, BoolSlice: []bool{false, true}, SmallFloatsSlice: []float32{1.23, 543.32}, BigFloatsSlice: []float64{1.238923, 54.2323, 3.2378432}, }, err: nil, }, }
for i, c := range cases { out := Foo{} err := Parse(&out, c.defaults, c.args, DefaultConfig) t.Logf("TEST:[%v]", i) if c.err == nil { assert.ErrorIs(t, err, c.err) } else { assert.ErrorContains(t, err, c.err.Error()) }
assert.NoError(t, err) assert.EqualValues(t, c.expected, out) }
}
func TestSlagAutogeneratedHelpMessage(t *testing.T) {
type Foo struct { Name string `help:"the name of the project"` Number int `help:"number for cool stuff"` Decimal64 float64 `help:"decimal number cause decimals are great"` Origins []string `help:"the allowed origins to make requests"` }
type Test struct { defaults any strc any args []string err error }
cases := []Test{ { args: []string{"-help"}, defaults: Foo{ Name: "marcig", Number: 4, Decimal64: 69.67, Origins: []string{"japan", "chametla", "filipinas"}, }, strc: Foo{ Name: "<noname>", Number: 69, Decimal64: 69.67, Origins: []string{"lapaz", "bcs", "uwu"}, }, err: nil, }, }
for _, c := range cases { msg, err := GetHelpMessage(c.strc, c.defaults, "help") assert.NoError(t, err, "GetHelpMessage failed :sob:") t.Logf("\n%v\n", msg) }
}
func TestSlagGetStructFieldHelpMessage(t *testing.T) {
type Kyosaya struct { Kyoko string `help:"this is kyoko field"` Sayaka string `help:"this is sayaka field"` }
type Madohomu struct { Madoka string `help:"this is madoka field"` Homura string `help:"this is homura field"` Kyosaya Kyosaya `help:"kyosaya"` }
type Foo struct { Name string `help:"the name of the project"` Number int `help:"number for cool stuff"` Decimal64 float64 `help:"decimal number cause decimals are great"` Origins []string `help:"the allowed origins to make requests"` Madohomu *Madohomu `help:"the bar object for anime functionalities"` }
var f Foo
dfts := Foo{ Name: "hello world", Number: 69, Decimal64: 20.123, Origins: []string{"yay"}, Madohomu: &Madohomu{ Madoka: "m4d0k4", Homura: "h0mUr4", Kyosaya: Kyosaya{ Kyoko: "ky0k0", Sayaka: "s9y9k9", }, }, }
v := reflect.TypeOf(f) d := reflect.ValueOf(dfts)
expected := []HelpMessage{ {FlagName: "name", Message: "the name of the project", DefaultValue: "hello world"}, {FlagName: "number", Message: "number for cool stuff", DefaultValue: 69}, {FlagName: "decimal64", Message: "decimal number cause decimals are great", DefaultValue: 20.123}, {FlagName: "origins", Message: "the allowed origins to make requests", DefaultValue: []string{"yay"}}, {FlagName: "madohomu", Inner: []HelpMessage{ {FlagName: "madoka", Message: "this is madoka field", DefaultValue: "m4d0k4"}, {FlagName: "homura", Message: "this is homura field", DefaultValue: "h0mUr4"}, {FlagName: "kyosaya", Inner: []HelpMessage{ {FlagName: "kyoko", Message: "this is kyoko field", DefaultValue: "ky0k0"}, {FlagName: "sayaka", Message: "this is sayaka field", DefaultValue: "s9y9k9"}, }}, }}, }
out := getStructFieldHelpMessage(v, d) assert.EqualValues(t, expected, out)
}
// func TestNewParser(t *testing.T) {// consumeFlagSimpleValues("")// }
func TestSlagObjectParsing(t *testing.T) {
type Test struct { input []string value any expected any defaults any error error }
type MoreDetails struct { Crushes string // CompletedThings float64 }
type Details struct { Kind string ManeColor string EyesColor string MoreDetails MoreDetails }
type Gender string const ( GenderFemale Gender = "female" GenderNonBinary Gender = "NonBinary" GenderMale Gender = "male" )
type Foo struct { Name string Age int Height float64 IsMexican bool Details Details // Gender Gender }
tests := []Test{{ value: &Foo{}, input: []string{ "-name", "Twilight Sparkle", "-age", "21", "-height", "1.7", "-is-mexican", "false", "-details", ".kind", "unicorn", ".mane-color", "lilac", ".eyes-color", "purple", ".more-details", ".crushes", "Sunset Shimmer", },
expected: Foo{ Name: "Twilight Sparkle", Age: 21, Height: 1.7, IsMexican: false, Details: Details{ Kind: "unicorn", ManeColor: "lilac", EyesColor: "purple", MoreDetails: MoreDetails{ Crushes: "Sunset Shimmer", }, }, }, defaults: Foo{}, }}
for i, test := range tests { t.Logf("TestSlag [%v]: %v", i, test.input) err := Parse( test.value, test.defaults, test.input, DefaultConfig, )
msg := fmt.Sprintf("break /home/mar/moids/slag/slag_test.go:453\ncondition 1 i == %v", i) assert.NoError(t, err, msg) v := reflect.ValueOf(test.value).Elem().Interface() assert.EqualValues(t, test.expected, v, msg) }
}
func TestTimeAndTypeAliases(t *testing.T) {
type Test struct { input []string value any expected any defaults any error error }
type MoreDetails struct { Crushes string // CompletedThings float64 }
type Details struct { Kind string ManeColor string EyesColor string MoreDetails MoreDetails }
type Gender string const ( GenderFemale Gender = "female" GenderNonBinary Gender = "non-binary" GenderMale Gender = "male" )
type Foo struct { TokenDuration time.Duration }
type Bar struct { TokenDuration time.Duration Name string Age int Height float64 IsMexican bool Details Details Gender Gender }
dur, _ := time.ParseDuration("15m")
tests := []Test{{ value: &Foo{}, input: []string{ "-token-duration", "15m", }, expected: Foo{ TokenDuration: dur, }, defaults: Foo{}, }, { value: &Bar{}, input: []string{ "-name", "Twilight Sparkle", "-age", "21", "-token-duration", "15m", "-height", "1.7", "-is-mexican", "false", "-details", ".kind", "unicorn", ".mane-color", "lilac", ".eyes-color", "purple", ".more-details", ".crushes", "Sunset Shimmer", "-gender", "female", }, expected: Bar{ Name: "Twilight Sparkle", TokenDuration: dur, Age: 21, Height: 1.7, IsMexican: false, Gender: "female", Details: Details{ Kind: "unicorn", ManeColor: "lilac", EyesColor: "purple", MoreDetails: MoreDetails{ Crushes: "Sunset Shimmer", }, }, }, }, }
for i, test := range tests { t.Logf("TestTimeAndTypeAliases [%v]: %v", i, test.input) err := Parse( test.value, test.defaults, test.input, DefaultConfig, )
msg := fmt.Sprintf("break /home/mar/moids/slag/slag_test.go:604\ncondition 1 i == %v", i) assert.NoError(t, err, msg) v := reflect.ValueOf(test.value).Elem().Interface() assert.EqualValues(t, test.expected, v, msg) }
}
func TestCurrent(t *testing.T) { // func TestDefaults()
type Test struct { input []string value any expected any defaults any error error }
type MoreDetails struct { Crushes string // CompletedThings float64 }
type Details struct { Kind string ManeColor string EyesColor string MoreDetails MoreDetails }
type Gender string const ( GenderFemale Gender = "female" GenderNonBinary Gender = "non-binary" GenderMale Gender = "male" )
type Foo struct { TokenDuration time.Duration }
type Bar struct { TokenDuration time.Duration Name string Age int Height float64 IsMexican bool Details Details Gender Gender }
dur, _ := time.ParseDuration("15m")
test := Test{ value: &Bar{}, defaults: Bar{ TokenDuration: dur, Name: "Rainbow Dash", Age: 21, Height: 1.6, IsMexican: true, Details: Details{ Kind: "pegasi", ManeColor: "cyan", EyesColor: "pink", MoreDetails: MoreDetails{ Crushes: "applejack", }, }, Gender: GenderFemale, }, input: []string{ "-details", ".kind", "unicorn", ".mane-color", "lilac", ".more-details", ".crushes", "Sunset Shimmer", }, expected: Bar{ TokenDuration: dur, Name: "Rainbow Dash", Age: 21, Height: 1.6, IsMexican: true, Details: Details{ Kind: "unicorn", ManeColor: "lilac", EyesColor: "pink", MoreDetails: MoreDetails{ Crushes: "Sunset Shimmer", }, }, Gender: GenderFemale, }, }
t.Logf("TestDefaults: %v", test.input) err := Parse( test.value, test.defaults, test.input, DefaultConfig, )
msg := "break /home/mar/moids/slag/slag_test.go:768" assert.NoError(t, err, msg) v := reflect.ValueOf(test.value).Elem().Interface() assert.EqualValues(t, test.expected, v, msg)
}