Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions cmd/resources/resource_cmds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,56 @@ func TestCreateTeam(t *testing.T) {
assert.Contains(t, s, "would be making a post request to /api/v2/teams here, with args: map[data:map[key:team-key name:Team Name] expand:]\n")
})
}

func TestPathParamsFillPlaceholdersByName(t *testing.T) {
tests := map[string]struct {
args []string
wantPath string
}{
"flag before environment in the path": {
args: []string{
"flags", "list-expiring-context-targets",
"--project", "my-project",
"--flag", "my-flag",
"--environment", "production",
},
wantPath: "http://localhost/api/v2/flags/my-project/my-flag/expiring-targets/production",
},
"segment before environment in the path": {
args: []string{
"segments", "list-expiring-targets",
"--project", "my-project",
"--segment", "my-segment",
"--environment", "production",
},
wantPath: "http://localhost/api/v2/segments/my-project/my-segment/expiring-targets/production",
},
"id param whose placeholder is capitalised differently": {
args: []string{
"flag-triggers", "delete",
"--project", "my-project",
"--flag", "my-flag",
"--environment", "production",
"--id", "my-trigger",
},
wantPath: "http://localhost/api/v2/flags/my-project/my-flag/triggers/production/my-trigger",
},
}

for name, tt := range tests {
t.Run(name, func(t *testing.T) {
mockClient := &resources.MockClient{Response: []byte(`{"items": []}`)}
args := append(tt.args, "--access-token", "abcd1234", "--base-uri", "http://localhost")

_, err := cmd.CallCmd(
t,
cmd.APIClients{ResourcesClient: mockClient},
analytics.NoopClientFn{}.Tracker(),
args,
)

require.NoError(t, err)
assert.Equal(t, tt.wantPath, mockClient.Path)
})
}
}
28 changes: 16 additions & 12 deletions cmd/resources/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,17 +282,19 @@ func (op *OperationCmd) initFlags() error {
return nil
}

func buildURLWithParams(baseURI, path string, urlParams []string) string {
var pathPlaceholder = regexp.MustCompile(`{(\w+)}`)

// buildURLWithParams fills each {placeholder} in path with the path param of the same name.
// Names are compared case-insensitively, so a "trigger-id" param fills {triggerID}.
func buildURLWithParams(baseURI, path string, pathParams map[string]string) string {
baseURI = strings.TrimSuffix(baseURI, "/")
s := make([]interface{}, len(urlParams))
for i, v := range urlParams {
s[i] = v
}

re := regexp.MustCompile(`{\w+}`)
format := re.ReplaceAllString(path, "%s")
resolved := pathPlaceholder.ReplaceAllStringFunc(path, func(placeholder string) string {
name := pathPlaceholder.FindStringSubmatch(placeholder)[1]
return pathParams[strings.ToLower(name)]
})

return baseURI + fmt.Sprintf(format, s...)
return baseURI + resolved
}

func (op *OperationCmd) makeRequest(cmd *cobra.Command, args []string) error {
Expand All @@ -309,21 +311,23 @@ func (op *OperationCmd) makeRequest(cmd *cobra.Command, args []string) error {
}

query := url.Values{}
var urlParms []string
pathParams := map[string]string{}
var lastPathParam string
for _, p := range op.Params {
flagName := getFlagName(p.Name)
val := viper.GetString(flagName)
if val != "" {
switch p.In {
case "path":
urlParms = append(urlParms, val)
pathParams[strings.ToLower(strcase.ToLowerCamel(p.Name))] = val
lastPathParam = val
case "query":
query.Add(strcase.ToLowerCamel(p.Name), val)
}
}
}

path := buildURLWithParams(viper.GetString(cliflags.BaseURIFlag), op.Path, urlParms)
path := buildURLWithParams(viper.GetString(cliflags.BaseURIFlag), op.Path, pathParams)

contentType := "application/json"
if viper.GetBool("semantic-patch") {
Expand All @@ -350,7 +354,7 @@ func (op *OperationCmd) makeRequest(cmd *cobra.Command, args []string) error {
}
// assuming the key to be deleted/replaced is last in the list of params,
// e.g. contexts delete-instances or code-refs replace-branch
res = []byte(fmt.Sprintf(`{"key": %q}`, urlParms[len(urlParms)-1]))
res = []byte(fmt.Sprintf(`{"key": %q}`, lastPathParam))
}

output, err := output.CmdOutput(cmd.Use, cliflags.GetOutputKind(cmd), res, output.CmdOutputOpts{
Expand Down
2 changes: 2 additions & 0 deletions internal/resources/mock_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
type MockClient struct {
Err error
Input []byte
Path string
Query url.Values
Response []byte
StatusCode int
Expand All @@ -22,6 +23,7 @@ func (c *MockClient) MakeRequest(
isBeta bool,
) ([]byte, error) {
c.Input = data
c.Path = path
c.Query = query

if c.StatusCode > http.StatusBadRequest {
Expand Down