Skip to content

Commit 251e409

Browse files
committed
refactor: shell type unmarshalling logic
1 parent 45f52df commit 251e409

File tree

1 file changed

+44
-13
lines changed

1 file changed

+44
-13
lines changed

types/shell.go

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,23 +25,54 @@ type Shell []string
2525

2626
// UnmarshalJSON implements custom unmarshaling for Shell
2727
func (s *Shell) UnmarshalJSON(data []byte) error {
28-
var single string
29-
if err := json.Unmarshal(data, &single); err == nil {
30-
// INFO: It means shell provided is a single string i.e. shell alias
31-
shell, ok := shellAliasMap[single]
28+
var v any
29+
if err := json.Unmarshal(data, &v); err != nil {
30+
return fmt.Errorf("invalid shell format: %w", err)
31+
}
32+
33+
switch val := v.(type) {
34+
case string:
35+
shell, ok := shellAliasMap[val]
3236
if !ok {
3337
return fmt.Errorf("invalid shell alias")
3438
}
3539
*s = Shell(shell)
36-
return nil
37-
}
38-
39-
var multiple []string
40-
if err := json.Unmarshal(data, &multiple); err == nil {
41-
// If it's a slice, assign it directly
42-
*s = Shell(multiple)
43-
return nil
40+
case []any:
41+
// INFO: json unmarshals array as []any
42+
var shells []string
43+
for _, item := range val {
44+
str, ok := item.(string)
45+
if !ok {
46+
return fmt.Errorf("invalid shell values, must be an []string")
47+
}
48+
shells = append(shells, str)
49+
}
50+
*s = Shell(shells)
51+
default:
52+
return fmt.Errorf("unexpected JSON type for shell")
4453
}
4554

46-
return fmt.Errorf("invalid shell format")
55+
return nil
4756
}
57+
58+
// func (s *Shell) UnmarshalJSON(data []byte) error {
59+
// var single string
60+
// if err := json.Unmarshal(data, &single); err == nil {
61+
// // INFO: It means shell provided is a single string i.e. shell alias
62+
// shell, ok := shellAliasMap[single]
63+
// if !ok {
64+
// return fmt.Errorf("invalid shell alias")
65+
// }
66+
// *s = Shell(shell)
67+
// return nil
68+
// }
69+
//
70+
// var multiple []string
71+
// if err := json.Unmarshal(data, &multiple); err == nil {
72+
// // If it's a slice, assign it directly
73+
// *s = Shell(multiple)
74+
// return nil
75+
// }
76+
//
77+
// return fmt.Errorf("invalid shell format")
78+
// }

0 commit comments

Comments
 (0)