Skip to content

Commit

Permalink
Merge pull request #8 from conduktor/add_various_command
Browse files Browse the repository at this point in the history
Add various command
  • Loading branch information
strokyl authored Feb 23, 2024
2 parents 6fd989d + 2d33576 commit f994e51
Show file tree
Hide file tree
Showing 14 changed files with 565 additions and 44 deletions.
56 changes: 51 additions & 5 deletions client/client.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package client

import (
"encoding/json"
"fmt"
"github.com/conduktor/ctl/printutils"
"github.com/conduktor/ctl/resource"
"github.com/go-resty/resty/v2"
"os"
Expand All @@ -13,15 +15,15 @@ type Client struct {
client *resty.Client
}

func Make(token string, baseUrl string) Client {
func Make(token string, baseUrl string, debug bool) Client {
return Client{
token: token,
baseUrl: baseUrl,
client: resty.New(),
client: resty.New().SetDebug(debug).SetHeader("Authorization", "Bearer "+token),
}
}

func MakeFromEnv() Client {
func MakeFromEnv(debug bool) Client {
token := os.Getenv("CDK_TOKEN")
if token == "" {
fmt.Fprintln(os.Stderr, "Please set CDK_TOKEN")
Expand All @@ -33,14 +35,58 @@ func MakeFromEnv() Client {
os.Exit(2)
}

return Make(token, baseUrl)
return Make(token, baseUrl, debug)
}

func (client *Client) Apply(resource *resource.Resource) error {
url := client.baseUrl + "/" + resource.Kind
resp, err := client.client.R().SetHeader("Authentication", "Bearer "+client.token).SetBody(resource.Json).Put(url)
resp, err := client.client.R().SetBody(resource.Json).Put(url)
if resp.IsError() {
return fmt.Errorf("Error applying resource %s/%s, got status code: %d:\n %s", resource.Kind, resource.Name, resp.StatusCode(), string(resp.Body()))
}
return err
}

func printResponseAsYaml(bytes []byte) error {
var data interface{}
err := json.Unmarshal(bytes, &data)
if err != nil {
return err
}
return printutils.PrintResourceLikeYamlFile(os.Stdout, data)
}

func (client *Client) Get(kind string) error {
url := client.baseUrl + "/" + kind
resp, err := client.client.R().Get(url)
if resp.IsError() {
return fmt.Errorf("Error listing resources of kind %s, got status code: %d:\n %s", kind, resp.StatusCode(), string(resp.Body()))
}
if err != nil {
return err
}
return printResponseAsYaml(resp.Body())
}
func (client *Client) Describe(kind, name string) error {
url := client.baseUrl + "/" + kind + "/" + name
resp, err := client.client.R().Get(url)
if resp.IsError() {
return fmt.Errorf("Error describing resources %s/%s, got status code: %d:\n %s", kind, name, resp.StatusCode(), string(resp.Body()))
}
if err != nil {
return err
}
return printResponseAsYaml(resp.Body())
}

func (client *Client) Delete(kind, name string) error {
url := client.baseUrl + "/" + kind + "/" + name
resp, err := client.client.R().Delete(url)
if resp.IsError() {
return fmt.Errorf("Error deleting resources %s/%s, got status code: %d:\n %s", kind, name, resp.StatusCode(), string(resp.Body()))
} else {
fmt.Printf("%s/%s deleted\n", kind, name)
}

return err
}
187 changes: 175 additions & 12 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import (
)

func TestApplyShouldWork(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl)
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
Expand All @@ -19,17 +20,17 @@ func TestApplyShouldWork(t *testing.T) {
}

topic := resource.Resource{
Json: []byte(`{"yolo": "data"}`),
Kind: "topic",
Name: "toto",
ApiVersion: "v1",
Json: []byte(`{"yolo": "data"}`),
Kind: "topic",
Name: "toto",
Version: "v1",
}

httpmock.RegisterMatcherResponderWithQuery(
"PUT",
"http://baseUrl/api/topic",
nil,
httpmock.HeaderIs("Authentication", "Bearer "+token).
httpmock.HeaderIs("Authorization", "Bearer "+token).
And(httpmock.BodyContainsBytes(topic.Json)),
responder,
)
Expand All @@ -41,9 +42,10 @@ func TestApplyShouldWork(t *testing.T) {
}

func TestApplyShouldFailIfNo2xx(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl)
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
Expand All @@ -53,17 +55,17 @@ func TestApplyShouldFailIfNo2xx(t *testing.T) {
}

topic := resource.Resource{
Json: []byte(`{"yolo": "data"}`),
Kind: "topic",
Name: "toto",
ApiVersion: "v1",
Json: []byte(`{"yolo": "data"}`),
Kind: "topic",
Name: "toto",
Version: "v1",
}

httpmock.RegisterMatcherResponderWithQuery(
"PUT",
"http://baseUrl/api/topic",
nil,
httpmock.HeaderIs("Authentication", "Bearer "+token).
httpmock.HeaderIs("Authorization", "Bearer "+token).
And(httpmock.BodyContainsBytes(topic.Json)),
responder,
)
Expand All @@ -73,3 +75,164 @@ func TestApplyShouldFailIfNo2xx(t *testing.T) {
t.Failed()
}
}

func TestGetShouldWork(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(200, "[]")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"GET",
"http://baseUrl/api/application",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Get("application")
if err != nil {
t.Error(err)
}
}

func TestGetShouldFailIfN2xx(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(404, "")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"GET",
"http://baseUrl/api/application",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Get("application")
if err == nil {
t.Failed()
}
}

func TestDescribeShouldWork(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(200, "[]")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"GET",
"http://baseUrl/api/application/yo",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Describe("application", "yo")
if err != nil {
t.Error(err)
}
}

func TestDescribeShouldFailIfNo2xx(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(500, "[]")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"GET",
"http://baseUrl/api/application/yo",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Describe("application", "yo")
if err == nil {
t.Failed()
}
}

func TestDeleteShouldWork(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(200, "[]")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"DELETE",
"http://baseUrl/api/application/yo",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Delete("application", "yo")
if err != nil {
t.Error(err)
}
}
func TestDeleteShouldFailOnNot2XX(t *testing.T) {
defer httpmock.Reset()
baseUrl := "http://baseUrl/api"
token := "aToken"
client := Make(token, baseUrl, false)
httpmock.ActivateNonDefault(
client.client.GetClient(),
)
responder, err := httpmock.NewJsonResponder(404, "[]")
if err != nil {
panic(err)
}

httpmock.RegisterMatcherResponderWithQuery(
"DELETE",
"http://baseUrl/api/application/yo",
nil,
httpmock.HeaderIs("Authorization", "Bearer "+token),
responder,
)

err = client.Delete("application", "yo")
if err == nil {
t.Fail()
}
}
2 changes: 1 addition & 1 deletion cmd/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var applyCmd = &cobra.Command{
fmt.Fprintf(os.Stderr, "%s\n", error)
os.Exit(1)
}
client := client.MakeFromEnv()
client := client.MakeFromEnv(*debug)
for _, resource := range resources {
err := client.Apply(&resource)
if err != nil {
Expand Down
28 changes: 28 additions & 0 deletions cmd/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package cmd

import (
"fmt"
"github.com/conduktor/ctl/client"
"github.com/spf13/cobra"
"os"
)

// applyCmd represents the apply command
var deleteCmd = &cobra.Command{
Use: "delete",
Short: "delete resource of a given kind and name",
Long: ``,
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
client := client.MakeFromEnv(*debug)
err := client.Delete(args[0], args[1])
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
},
}

func init() {
rootCmd.AddCommand(deleteCmd)
}
33 changes: 33 additions & 0 deletions cmd/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cmd

import (
"fmt"
"github.com/conduktor/ctl/client"
"github.com/spf13/cobra"
"os"
)

// applyCmd represents the apply command
var getCmd = &cobra.Command{
Use: "get kind [name]",
Short: "get resource of a given kind",
Long: ``,
Args: cobra.MatchAll(cobra.MinimumNArgs(1), cobra.MaximumNArgs(2)),
Run: func(cmd *cobra.Command, args []string) {
client := client.MakeFromEnv(*debug)
var err error
if len(args) == 1 {
err = client.Get(args[0])
} else if len(args) == 2 {
err = client.Describe(args[0], args[1])
}
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
},
}

func init() {
rootCmd.AddCommand(getCmd)
}
Loading

0 comments on commit f994e51

Please sign in to comment.