Skip to content

Commit 6d4690f

Browse files
committed
extract k=v flag parsing to a func
1 parent ebeb93e commit 6d4690f

3 files changed

Lines changed: 20 additions & 21 deletions

File tree

cmd/contacts.go

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package cmd
33
import (
44
"fmt"
55
"strconv"
6-
"strings"
76

87
"github.com/loops-so/cli/internal/api"
98
"github.com/loops-so/cli/internal/cmdutil"
@@ -73,16 +72,11 @@ func contactFieldParamsFromCmd(cmd *cobra.Command) (contactFieldParams, error) {
7372
params.ContactProperties = contactProps
7473
}
7574
propPairs, _ := cmd.Flags().GetStringArray("prop")
76-
for _, pair := range propPairs {
77-
idx := strings.IndexByte(pair, '=')
78-
if idx < 0 {
79-
return params, fmt.Errorf("--prop %q: expected KEY=value", pair)
80-
}
81-
if params.ContactProperties == nil {
82-
params.ContactProperties = make(map[string]any)
83-
}
84-
params.ContactProperties[pair[:idx]] = pair[idx+1:]
75+
props, err := cmdutil.ParseKeyValuePairs("prop", propPairs, params.ContactProperties)
76+
if err != nil {
77+
return params, err
8578
}
79+
params.ContactProperties = props
8680

8781
return params, nil
8882
}

cmd/transactional.go

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,7 @@ func parseDataVars(vars []string, jsonFile string) (map[string]any, error) {
2323
return nil, err
2424
}
2525
}
26-
for _, pair := range vars {
27-
idx := strings.IndexByte(pair, '=')
28-
if idx < 0 {
29-
return nil, fmt.Errorf("--var %q: expected KEY=value", pair)
30-
}
31-
if m == nil {
32-
m = make(map[string]any)
33-
}
34-
m[pair[:idx]] = pair[idx+1:]
35-
}
36-
return m, nil
26+
return cmdutil.ParseKeyValuePairs("var", vars, m)
3727
}
3828

3929
func attachmentFromPath(path string) (api.Attachment, error) {

internal/cmdutil/parse.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,23 @@ import (
44
"encoding/json"
55
"fmt"
66
"os"
7+
"strings"
78
)
89

10+
func ParseKeyValuePairs(flag string, pairs []string, dst map[string]any) (map[string]any, error) {
11+
for _, pair := range pairs {
12+
idx := strings.IndexByte(pair, '=')
13+
if idx < 0 {
14+
return nil, fmt.Errorf("--%s %q: expected KEY=value", flag, pair)
15+
}
16+
if dst == nil {
17+
dst = make(map[string]any)
18+
}
19+
dst[pair[:idx]] = pair[idx+1:]
20+
}
21+
return dst, nil
22+
}
23+
924
func ParseJSONFile(flag, path string) (map[string]any, error) {
1025
data, err := os.ReadFile(path)
1126
if err != nil {

0 commit comments

Comments
 (0)