Skip to content

Commit

Permalink
UX Changes in litmusctl using promptui library. (litmuschaos#156)
Browse files Browse the repository at this point in the history
* added the ux changes

Signed-off-by: deep-poharkar <[email protected]>

* removed local setup changes

Signed-off-by: deep-poharkar <[email protected]>

* removed commented code and fixed casing

Signed-off-by: deep-poharkar <[email protected]>

* updated readme and create project now shows id

Signed-off-by: deep-poharkar <[email protected]>

* typo fixed

Signed-off-by: deep-poharkar <[email protected]>

---------

Signed-off-by: deep-poharkar <[email protected]>
deep-poharkar authored Nov 15, 2023

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 28f4744 commit 6b68c4d
Showing 14 changed files with 378 additions and 132 deletions.
109 changes: 84 additions & 25 deletions Usage_0.23.0.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


> Notes:
>
> - For litmusctl v0.23.0 or latest
@@ -39,7 +37,7 @@ Next, you need to enter ChaosCenter details to login into your ChaosCenter accou

> Example, https://preview.litmuschaos.io/
**Username:** Enter your ChaosCenter username.
**Username:** Enter your ChaosCenter username.
**Password:** Enter your ChaosCenter password.

```
@@ -162,10 +160,10 @@ After verification of these details, you can proceed with the connection of the
```
Enter service account [Default: litmus]:
📌 Summary
📌 Summary
Chaos Infra Name: test4
Chaos EnvironmentID: test
Chaos Infra Description:
Chaos Infra Description:
Chaos Infra SSL/TLS Skip: false
Platform Name: Others
Namespace: litmuwrq (new)
@@ -194,15 +192,18 @@ To verify, if the connection process was successful you can view the list of con

### Steps to create a Chaos Experiment

* To setup an account with litmusctl
- To setup an account with litmusctl

```shell
litmusctl config set-account --endpoint="" --username="" --password=""
```

* To create a Chaos Experiment by passing a manifest file
> Note:
> * To get `project-id`, apply `litmusctl get projects`
> * To get `chaos-infra-id`, apply `litmusctl get chaos-infra --project-id=""`
- To create a Chaos Experiment by passing a manifest file
> Note:
>
> - To get `project-id`, apply `litmusctl get projects`
> - To get `chaos-infra-id`, apply `litmusctl get chaos-infra --project-id=""`
```shell
litmusctl create chaos-experiment -f custom-chaos-experiment.yml --project-id="" --chaos-infra-id=""
```
@@ -212,17 +213,21 @@ litmusctl create chaos-experiment -f custom-chaos-experiment.yml --project-id=""
```shell
litmusctl save chaos-experiment -f custom-litmus-experiment.yaml
```

> Note:
> * Experiment Name can also be passed through the Manifest file
>
> - Experiment Name can also be passed through the Manifest file
```shell
Enter the Project ID: eb7fc0a0-5878-4454-a9db-b67d283713bc
Enter the Chaos Infra ID: e7eb0386-085c-49c2-b550-8d85b58fd
Experiment Description:
Experiment Description:

🚀 Chaos Experiment/experiment-1 successfully created 🎉
```

- To Run a chaos Experiment:

```shell
litmusctl run chaos-experiment

@@ -233,7 +238,6 @@ Enter the Chaos Experiment ID: test_exp
🚀 Chaos Experiment running successfully 🎉
```


### Additional commands

- To view the current configuration of `.litmusconfig`, type:
@@ -282,6 +286,8 @@ litmusctl config use-account
Host endpoint where litmus is installed: https://preview.litmuschaos.io

Username: admin

✅ Successfully set the current account to 'account-name' at 'URL'
```

- To create a project, apply the following command :
@@ -290,20 +296,24 @@ Username: admin
litmusctl create project

Enter a project name: new

Project 'project-name' created successfully!🎉
```

- To create a new Environment, apply the following command :

```shell
litmusctl create environment
litmusctl create environment

Enter the Project ID: eb7fc0a0-5878-4454-a9db-b67d283713bc

Enter the Environment Name: test2

🚀New Chaos Environment creation successful!! 🎉
🚀 New Chaos Environment creation successful!! 🎉
```


- To view all the projects with the user, use the `get projects` command.

```shell
litmusctl get projects
```
@@ -314,6 +324,7 @@ litmusctl get projects
PROJECT ID PROJECT NAME CREATEDAT
50addd40-8767-448c-a91a-5071543a2d8e Developer Project 2021-07-21 14:38:51 +0530 IST
7a4a259a-1ae5-4204-ae83-89a8838eaec3 DevOps Project 2021-07-21 14:39:14 +0530 IST
Press Enter to show the next page (or type 'q' to quit): q
```

- To get an overview of the Chaos Infrastructures available within a project, issue the following command.
@@ -327,13 +338,13 @@ Enter the Project ID: 50addd40-8767-448c-a91a-5071543a2d8e
**Output:**

```
CHAOS Infrastructure ID CHAOS Infrastructure NAME STATUS
55ecc7f2-2754-43aa-8e12-6903e4c6183a chaos-infra-1 ACTIVE
13dsf3d1-5324-54af-4g23-5331g5v2364f chaos-infra-2 INACTIVE
CHAOS Infrastructure ID CHAOS Infrastructure NAME STATUS
55ecc7f2-2754-43aa-8e12-6903e4c6183a chaos-infra-1 ACTIVE
13dsf3d1-5324-54af-4g23-5331g5v2364f chaos-infra-2 INACTIVE
```

- To disconnect an Chaos Infrastructure, issue the following command..

* To disconnect an Chaos Infrastructure, issue the following command..
```shell
litmusctl disconnect chaos-infra <chaos-infra-id> --project-id=""
```
@@ -344,12 +355,24 @@ litmusctl disconnect chaos-infra <chaos-infra-id> --project-id=""
🚀 Chaos Infrastructure successfully disconnected.
```

- To list the created Chaos Experiments within a project, issue the following command.

Using Flag :

* To list the created Chaos Experiments within a project, issue the following command.
```shell
litmusctl get chaos-experiment --project-id=""
```

Using UI :

```shell
Enter the Project ID: "project-id"
Select an output format:
table
json
yaml
```

**Output:**

```
@@ -359,10 +382,22 @@ litmusctl get chaos-experiment --project-id=""
Showing 1 of 1 Chaos Experiments
```

- To list all the Chaos Experiment runs within a project, issue the following command.

```shell
litmusctl get chaos-experiment-runs --project-id=""
```

- To list all the Chaos Experiment runs within a specific experiment, issue the following command.

```shell
litmusctl get chaos-experiment-runs --project-id="" --experiment-id=""
```

- To list the Chaos Experiment run with a specific experiment-run-id , issue the following command.

* To list all the Chaos Experiment runs within a project, issue the following command.
```shell
litmusctl get chaos-experiments-runs --project-id=""
litmusctl get chaos-experiment-runs --project-id="" --experiment-run-id=""
```

**Output:**
@@ -374,12 +409,25 @@ CHAOS EXPERIMENT RUN ID STATUS RESILIENCY SCORE CHAOS EXPERIMENT ID CHAOS
Showing 1 of 1 Chaos Experiments runs
```

- To describe a particular Chaos Experiment, issue the following command.

Using Flag :

* To describe a particular Chaos Experiment, issue the following command.
```shell
litmusctl describe chaos-experiment <chaos-experiment-id> --project-id=""
```

Using UI :

```shell
litmusctl describe chaos-experiment
Enter the Project ID: "project-id"
Enter the Chaos Experiment ID: "chaos-experiment-id"
Select an output format :
yaml
json
```

**Output:**

```
@@ -398,12 +446,23 @@ spec:
...
```

- To delete a particular Chaos Experiment, issue the following commands.

Using Flag :

* To delete a particular Chaos Experiment, issue the following command.
```shell
litmusctl delete chaos-experiment <chaos-experiment-id> --project-id=""
```

Using UI :

```shell
litmusctl delete chaos-experiment
Enter the Project ID: "project-id"
Enter the Chaos Experiment ID: "chaos-experiment-id"
Are you sure you want to delete this Chaos Experiment? (y/n): y
```

**Output:**

```
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -9,6 +9,7 @@ require (
github.com/gorhill/cronexpr v0.0.0-20180427100037-88b0669f7d75
github.com/litmuschaos/chaos-operator v0.0.0-20230109130222-de7c74a937a9
github.com/litmuschaos/litmus/chaoscenter/graphql/server v0.0.0-20230720053327-bca5e97f553f
github.com/manifoldco/promptui v0.9.0
github.com/mitchellh/go-homedir v1.1.0
github.com/spf13/cobra v1.3.0
github.com/spf13/viper v1.10.1
@@ -30,6 +31,7 @@ require (
github.com/Azure/go-autorest/tracing v0.6.0 // indirect
github.com/PuerkitoBio/purell v1.1.1 // indirect
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful v2.16.0+incompatible // indirect
github.com/form3tech-oss/jwt-go v3.2.3+incompatible // indirect
@@ -66,6 +68,8 @@ require (
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/term v0.5.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
golang.org/x/time v0.0.0-20220210224613-90d013bbcef8 // indirect
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -102,8 +102,14 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM=
github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI=
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag=
github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
@@ -353,6 +359,8 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
@@ -621,6 +629,7 @@ golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -688,6 +697,7 @@ golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
28 changes: 14 additions & 14 deletions pkg/apis/project.go
Original file line number Diff line number Diff line change
@@ -28,10 +28,10 @@ import (
"github.com/litmuschaos/litmusctl/pkg/types"
)

type createProjectResponse struct {
type CreateProjectResponse struct {
Data struct {
Name string `json:"name"`
ID string `json:"id"`
ID string `json:"projectID"`
} `json:"data"`
Errors []struct {
Message string `json:"message"`
@@ -40,50 +40,50 @@ type createProjectResponse struct {
}

type createProjectPayload struct {
ProjectName string `json:"project_name"`
ProjectName string `json:"projectName"`
}

func CreateProjectRequest(projectName string, cred types.Credentials) (createProjectResponse, error) {
func CreateProjectRequest(projectName string, cred types.Credentials) (CreateProjectResponse, error) {
payloadBytes, err := json.Marshal(createProjectPayload{
ProjectName: projectName,
})

if err != nil {
return createProjectResponse{}, err
return CreateProjectResponse{}, err
}
resp, err := SendRequest(SendRequestParams{cred.Endpoint + utils.AuthAPIPath + "/create_project", "Bearer " + cred.Token}, payloadBytes, string(types.Post))
if err != nil {
return createProjectResponse{}, err
return CreateProjectResponse{}, err
}

bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return createProjectResponse{}, err
return CreateProjectResponse{}, err
}

defer resp.Body.Close()

if resp.StatusCode == http.StatusOK {
var project createProjectResponse
var project CreateProjectResponse
err = json.Unmarshal(bodyBytes, &project)
if err != nil {
return createProjectResponse{}, err
return CreateProjectResponse{}, err
}

if len(project.Errors) > 0 {
return createProjectResponse{}, errors.New(project.Errors[0].Message)
return CreateProjectResponse{}, errors.New(project.Errors[0].Message)
}

utils.White_B.Println("project/" + project.Data.Name + " created")
return project, nil
} else {
return createProjectResponse{}, errors.New("Unmatched status code:" + string(bodyBytes))
return CreateProjectResponse{}, errors.New("Unmatched status code:" + string(bodyBytes))
}
}

type listProjectResponse struct {
Data []struct {
ID string `json:"projectID"`
ID string `json:"ProjectID"`
Name string `json:"Name"`
CreatedAt int64 `json:"CreatedAt"`
} `json:"data"`
@@ -144,9 +144,9 @@ type Member struct {
}

type Project struct {
ID string `json:"projectID"`
ID string `json:"ProjectID"`
Name string `json:"Name"`
CreatedAt int64 `json:"createdAt"`
CreatedAt int64 `json:"CreatedAt"`
Members []Member `json:"Members"`
}

44 changes: 21 additions & 23 deletions pkg/cmd/config/setAccount.go
Original file line number Diff line number Diff line change
@@ -29,8 +29,8 @@ import (
"github.com/litmuschaos/litmusctl/pkg/config"
"github.com/litmuschaos/litmusctl/pkg/types"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"golang.org/x/term"
)

// setAccountCmd represents the setAccount command
@@ -49,14 +49,18 @@ var setAccountCmd = &cobra.Command{
err error
)

authInput.Endpoint, err = cmd.Flags().GetString("endpoint")
utils.PrintError(err)

authInput.Username, err = cmd.Flags().GetString("username")
// prompts for account details
promptEndpoint := promptui.Prompt{
Label: "Host endpoint where litmus is installed",
}
authInput.Endpoint, err = promptEndpoint.Run()
utils.PrintError(err)

authInput.Password, err = cmd.Flags().GetString("password")
// Validate and format the endpoint URL
ep := strings.TrimRight(authInput.Endpoint, "/")
newURL, err := url.Parse(ep)
utils.PrintError(err)
authInput.Endpoint = newURL.String()

if authInput.Endpoint == "" {
utils.White_B.Print("\nHost endpoint where litmus is installed: ")
@@ -74,26 +78,20 @@ var setAccountCmd = &cobra.Command{
authInput.Endpoint = newUrl.String()
}

if authInput.Username == "" {
utils.White_B.Print("\nUsername [Default: ", utils.DefaultUsername, "]: ")
fmt.Scanln(&authInput.Username)
if authInput.Username == "" {
authInput.Username = utils.DefaultUsername
}
promptUsername := promptui.Prompt{
Label: "Username [Default: " + utils.DefaultUsername + "]",
Default: utils.DefaultUsername,
}
authInput.Username, err = promptUsername.Run()
utils.PrintError(err)

if authInput.Password == "" {
utils.White_B.Print("\nPassword: ")
pass, err := term.ReadPassword(0)
utils.PrintError(err)

if pass == nil {
utils.Red.Println("\n⛔ Password cannot be empty!")
os.Exit(1)
}

authInput.Password = string(pass)
promptPassword := promptui.Prompt{
Label: "Password",
Mask: '*',
}
pass, err := promptPassword.Run()
utils.PrintError(err)
authInput.Password = pass

if authInput.Endpoint != "" && authInput.Username != "" && authInput.Password != "" {
exists := config.FileExists(configFilePath)
2 changes: 2 additions & 0 deletions pkg/cmd/config/useAccount.go
Original file line number Diff line number Diff line change
@@ -79,7 +79,9 @@ var useAccountCmd = &cobra.Command{
CurrentAccount: endpoint,
CurrentUser: username,
}, configFilePath)

utils.PrintError(err)
fmt.Printf("\n✅ Successfully set the current account to '%s' at '%s'\n", username, endpoint)
} else {
utils.Red.Println("\n⛔ Account not exists")
os.Exit(1)
7 changes: 4 additions & 3 deletions pkg/cmd/create/experiment.go
Original file line number Diff line number Diff line change
@@ -17,12 +17,13 @@ package create

import (
"fmt"
"os"
"strings"

models "github.com/litmuschaos/litmus/chaoscenter/graphql/server/graph/model"
"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"github.com/litmuschaos/litmusctl/pkg/utils"
"os"
"strings"

"github.com/spf13/cobra"
)
@@ -134,7 +135,7 @@ var experimentCmd = &cobra.Command{
}

//Successful creation
utils.White_B.Println("\n🚀 Chaos Experiment successfully created🎉")
utils.White_B.Println("\n🚀 Chaos Experiment successfully created and experiment run is scheduled 🎉")
},
}

29 changes: 23 additions & 6 deletions pkg/cmd/create/project.go
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ import (
"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/utils"

"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)

@@ -40,14 +41,30 @@ var projectCmd = &cobra.Command{

projectName, err := cmd.Flags().GetString("name")
utils.PrintError(err)

if projectName == "" {
utils.White_B.Print("\nEnter a project name: ")
fmt.Scanln(&projectName)
}
// prompt to ask project name
prompt := promptui.Prompt{
Label: "Enter a project name",
AllowEdit: true,
}

_, err = apis.CreateProjectRequest(projectName, credentials)
utils.PrintError(err)
result, err := prompt.Run()
if err != nil {
utils.Red.Printf("Error: %v\n", err)
return
}

projectName = result
}
var response apis.CreateProjectResponse
response, err = apis.CreateProjectRequest(projectName, credentials)
if err != nil {
utils.Red.Printf("❌ Error creating project: %v\n", err)
} else {
fmt.Printf("Response: %+v\n", response)
projectID := response.Data.ID
utils.White_B.Printf("Project '%s' created successfully with project ID - '%s'!🎉\n", projectName, projectID)
}
},
}

61 changes: 45 additions & 16 deletions pkg/cmd/delete/experiment.go
Original file line number Diff line number Diff line change
@@ -16,13 +16,14 @@ limitations under the License.
package delete

import (
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"os"

"github.com/litmuschaos/litmusctl/pkg/apis/experiment"

"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/utils"

"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)

@@ -36,38 +37,49 @@ var experimentCmd = &cobra.Command{
Note: The default location of the config file is $HOME/.litmusconfig, and can be overridden by a --config flag
`,
Args: cobra.ExactArgs(1),

Run: func(cmd *cobra.Command, args []string) {

// Fetch user credentials
credentials, err := utils.GetCredentials(cmd)
utils.PrintError(err)

experimentID := ""
projectID, err := cmd.Flags().GetString("project-id")
utils.PrintError(err)

// Handle blank input for project ID
if projectID == "" {
utils.White_B.Print("\nEnter the Project ID: ")
fmt.Scanln(&projectID)

if projectID == "" {
utils.Red.Println("⛔ Project ID can't be empty!!")
if projectID == "" {
prompt := promptui.Prompt{
Label: "Enter the Project ID",
}
result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}
projectID = result
}

experimentID := args[0]
if len(args) == 0 {
prompt := promptui.Prompt{
Label: "Enter the Chaos Experiment ID",
}
result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}
experimentID = result
} else {
experimentID = args[0]
}

// Handle blank input for Chaos Experiment ID
if experimentID == "" {
utils.White_B.Print("\nEnter the Chaos Experiment ID: ")
fmt.Scanln(&experimentID)

if experimentID == "" {
utils.Red.Println("⛔ Chaos Experiment ID can't be empty!!")
os.Exit(1)
}
utils.Red.Println("⛔ Chaos Experiment ID can't be empty!!")
os.Exit(1)
}

// Perform authorization
@@ -90,6 +102,23 @@ var experimentCmd = &cobra.Command{
os.Exit(1)
}

// confirm before deletion

prompt := promptui.Prompt{
Label: "Are you sure you want to delete this Chaos Experiment? (y/n)",
AllowEdit: true,
}
result, err := prompt.Run()
if err != nil {
utils.Red.Println("⛔ Error:", err)
os.Exit(1)
}

if result != "y" {
utils.White_B.Println("\n❌ Chaos Experiment was not deleted.")
os.Exit(0)
}

// Make API call
deleteExperiment, err := experiment.DeleteChaosExperiment(projectID, &experimentID, credentials)
if err != nil {
66 changes: 57 additions & 9 deletions pkg/cmd/describe/experiment.go
Original file line number Diff line number Diff line change
@@ -13,16 +13,20 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// */

package describe

import (
"bytes"
"encoding/json"
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"os"
"strings"

"github.com/litmuschaos/litmus/chaoscenter/graphql/server/graph/model"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
)
@@ -42,19 +46,28 @@ var experimentCmd = &cobra.Command{
utils.PrintError(err)

if pid == "" {
utils.White_B.Print("\nEnter the Project ID: ")
fmt.Scanln(&pid)

for pid == "" {
utils.Red.Println("⛔ Project ID can't be empty!!")
prompt := promptui.Prompt{
Label: "Enter the Project ID",
}
result, err := prompt.Run()
if err != nil {
utils.PrintError(err)
os.Exit(1)
}
pid = result
}

var experimentID string
if len(args) == 0 {
utils.White_B.Print("\nEnter the Chaos Experiment ID: ")
fmt.Scanln(&experimentID)
prompt := promptui.Prompt{
Label: "Enter the Chaos Experiment ID",
}
result, err := prompt.Run()
if err != nil {
utils.PrintError(err)
os.Exit(1)
}
experimentID = result
} else {
experimentID = args[0]
}
@@ -88,7 +101,42 @@ var experimentCmd = &cobra.Command{
utils.Red.Println("❌ Error parsing Chaos Experiment manifest: " + err.Error())
os.Exit(1)
}
utils.PrintInYamlFormat(string(yamlManifest))

// Add an output format prompt
prompt := promptui.Select{
Label: "Select an output format",
Items: []string{"YAML", "JSON"},
}
i, _, err := prompt.Run()
if err != nil {
utils.PrintError(err)
os.Exit(1)
}

switch i {
case 0:
// Output as YAML (default)
utils.PrintInYamlFormat(string(yamlManifest))
case 1:
// Output as JSON
jsonData, err := yaml.YAMLToJSON(yamlManifest)
if err != nil {
utils.Red.Println("❌ Error converting YAML to JSON: " + err.Error())
os.Exit(1)
}

var prettyJSON bytes.Buffer
err = json.Indent(&prettyJSON, jsonData, "", " ") // Adjust the indentation as needed
if err != nil {
utils.Red.Println("❌ Error formatting JSON: " + err.Error())
os.Exit(1)
}

fmt.Println(prettyJSON.String())
default:
utils.Red.Println("❌ Invalid output format selected")
os.Exit(1)
}
},
}

22 changes: 21 additions & 1 deletion pkg/cmd/get/experimentruns.go
Original file line number Diff line number Diff line change
@@ -17,13 +17,14 @@ package get

import (
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"os"
"strconv"
"strings"
"text/tabwriter"
"time"

"github.com/litmuschaos/litmusctl/pkg/apis/experiment"

"github.com/litmuschaos/litmus/chaoscenter/graphql/server/graph/model"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/spf13/cobra"
@@ -54,6 +55,22 @@ var experimentRunsCmd = &cobra.Command{
}
}

// experiment ID flag
experimentID, err := cmd.Flags().GetString("experiment-id")
utils.PrintError(err)
if experimentID != "" {
listExperimentRunsRequest.ExperimentIDs = []*string{&experimentID}

}

// experiment run ID flag
experimentRunID, err := cmd.Flags().GetString("experiment-run-id")
utils.PrintError(err)
if experimentRunID != "" {
listExperimentRunsRequest.ExperimentRunIDs = []*string{&experimentRunID}

}

listAllExperimentRuns, _ := cmd.Flags().GetBool("all")
if !listAllExperimentRuns {
listExperimentRunsRequest.Pagination = &model.Pagination{}
@@ -119,5 +136,8 @@ func init() {
experimentRunsCmd.Flags().Int("count", 30, "Set the count of Chaos Experiments runs to display. Default value is 30")
experimentRunsCmd.Flags().BoolP("all", "A", false, "Set to true to display all Chaos Experiments runs")

experimentRunsCmd.Flags().String("experiment-id", "", "Set the experiment ID to list experiment runs within a specific experiment")
experimentRunsCmd.Flags().String("experiment-run-id", "", "Set the experiment run ID to list a specific experiment run")

experimentRunsCmd.Flags().StringP("output", "o", "", "Output format. One of:\njson|yaml")
}
68 changes: 47 additions & 21 deletions pkg/cmd/get/experiments.go
Original file line number Diff line number Diff line change
@@ -17,15 +17,17 @@ package get

import (
"fmt"
"github.com/litmuschaos/litmusctl/pkg/apis/experiment"
"os"
"strings"
"text/tabwriter"
"time"

"github.com/litmuschaos/litmusctl/pkg/apis/experiment"

"github.com/gorhill/cronexpr"
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/graph/model"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)

@@ -75,39 +77,63 @@ var experimentsCmd = &cobra.Command{
}
}

output, err := cmd.Flags().GetString("output")
outputFormat := ""
outputPrompt := promptui.Select{
Label: "Select an output format",
Items: []string{"table", "json", "yaml"},
}
_, outputFormat, err = outputPrompt.Run()
utils.PrintError(err)

switch output {
switch outputFormat {
case "json":
utils.PrintInJsonFormat(experiments.Data)

case "yaml":
utils.PrintInYamlFormat(experiments.Data)

case "":
case "table":
itemsPerPage := 5
page := 1
totalExperiments := len(experiments.Data.ListExperimentDetails.Experiments)

for {
// calculating the start and end indices for the current page
start := (page - 1) * itemsPerPage
end := start + itemsPerPage
if end > totalExperiments {
end = totalExperiments
}
writer := tabwriter.NewWriter(os.Stdout, 4, 8, 1, '\t', 0)
utils.White_B.Fprintln(writer, "CHAOS EXPERIMENT ID\tCHAOS EXPERIMENT NAME\tCHAOS EXPERIMENT TYPE\tNEXT SCHEDULE\tCHAOS INFRASTRUCTURE ID\tCHAOS INFRASTRUCTURE NAME\tLAST UPDATED By")

for _, experiment := range experiments.Data.ListExperimentDetails.Experiments[start:end] {
if experiment.CronSyntax != "" {
utils.White.Fprintln(
writer,
experiment.ExperimentID+"\t"+experiment.Name+"\tCron Chaos Experiment\t"+cronexpr.MustParse(experiment.CronSyntax).Next(time.Now()).Format("January 2 2006, 03:04:05 pm")+"\t"+experiment.Infra.InfraID+"\t"+experiment.Infra.Name+"\t"+experiment.UpdatedBy.Username)
} else {
utils.White.Fprintln(
writer,
experiment.ExperimentID+"\t"+experiment.Name+"\tNon Cron Chaos Experiment\tNone\t"+experiment.Infra.InfraID+"\t"+experiment.Infra.Name+"\t"+experiment.UpdatedBy.Username)
}
}
writer.Flush()
paginationPrompt := promptui.Prompt{
Label: "Press Enter to show the next page (or type 'q' to quit)",
AllowEdit: true,
Default: "",
}

writer := tabwriter.NewWriter(os.Stdout, 4, 8, 1, '\t', 0)
utils.White_B.Fprintln(writer, "CHAOS EXPERIMENT ID\tCHAOS EXPERIMENT NAME\tCHAOS EXPERIMENT TYPE\tNEXT SCHEDULE\tCHAOS INFRASTRUCTURE ID\tCHAOS INFRASTRUCTURE NAME\tLAST UPDATED By")
userInput, err := paginationPrompt.Run()
utils.PrintError(err)

for _, experiment := range experiments.Data.ListExperimentDetails.Experiments {
if experiment.CronSyntax != "" {
utils.White.Fprintln(
writer,
experiment.ExperimentID+"\t"+experiment.Name+"\tCron Chaos Experiment\t"+cronexpr.MustParse(experiment.CronSyntax).Next(time.Now()).Format("January 2 2006, 03:04:05 pm")+"\t"+experiment.Infra.InfraID+"\t"+experiment.Infra.Name+"\t"+experiment.UpdatedBy.Username)
if userInput == "q" {
break
} else {
utils.White.Fprintln(
writer,
experiment.ExperimentID+"\t"+experiment.Name+"\tNon Cron Chaos Experiment\tNone\t"+experiment.Infra.InfraID+"\t"+experiment.Infra.Name+"\t"+experiment.UpdatedBy.Username)
page++
}
}

if listAllExperiments || (experiments.Data.ListExperimentDetails.TotalNoOfExperiments <= listExperimentRequest.Pagination.Limit) {
utils.White_B.Fprintln(writer, fmt.Sprintf("\nShowing %d of %d Chaos experiments", experiments.Data.ListExperimentDetails.TotalNoOfExperiments, experiments.Data.ListExperimentDetails.TotalNoOfExperiments))
} else {
utils.White_B.Fprintln(writer, fmt.Sprintf("\nShowing %d of %d Chaos experiments", listExperimentRequest.Pagination.Limit, experiments.Data.ListExperimentDetails.TotalNoOfExperiments))
}
writer.Flush()
}
},
}
55 changes: 43 additions & 12 deletions pkg/cmd/get/projects.go
Original file line number Diff line number Diff line change
@@ -22,6 +22,7 @@ import (

"github.com/litmuschaos/litmusctl/pkg/apis"
"github.com/litmuschaos/litmusctl/pkg/utils"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)

@@ -33,31 +34,61 @@ var projectsCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
credentials, err := utils.GetCredentials(cmd)
utils.PrintError(err)
projects, err := apis.ListProject(credentials)
utils.PrintError(err)

output, err := cmd.Flags().GetString("output")
//promptui to ask the user for the output format
outputFormat := ""

projects, err := apis.ListProject(credentials)
utils.PrintError(err)

switch output {
switch outputFormat {
case "json":
utils.PrintInJsonFormat(projects.Data)

case "yaml":
utils.PrintInYamlFormat(projects.Data)

case "":
writer := tabwriter.NewWriter(os.Stdout, 8, 8, 8, '\t', tabwriter.AlignRight)
utils.White_B.Fprintln(writer, "PROJECT ID\tPROJECT NAME\tCREATED AT")
for _, project := range projects.Data {
intTime := project.CreatedAt
utils.PrintError(err)

humanTime := time.Unix(intTime, 0)
itemsPerPage := 5
page := 1
totalProjects := len(projects.Data)

for {
// calculating the start and end indices for the current page
start := (page - 1) * itemsPerPage
end := start + itemsPerPage
if end > totalProjects {
end = totalProjects

}

// displaying the projects for the current page
writer := tabwriter.NewWriter(os.Stdout, 8, 8, 8, '\t', tabwriter.AlignRight)
utils.White_B.Fprintln(writer, "PROJECT ID\tPROJECT NAME\tCREATED AT")
for _, project := range projects.Data[start:end] {
intTime := project.CreatedAt
humanTime := time.Unix(intTime, 0)
utils.White.Fprintln(writer, project.ID+"\t"+project.Name+"\t"+humanTime.String()+"\t")
}
writer.Flush()

// pagination prompt
paginationPrompt := promptui.Prompt{
Label: "Press Enter to show the next page (or type 'q' to quit)",
AllowEdit: true,
Default: "",
}

userInput, err := paginationPrompt.Run()
utils.PrintError(err)

utils.White.Fprintln(writer, project.ID+"\t"+project.Name+"\t"+humanTime.String()+"\t")
if userInput == "q" {
break
} else {
page++
}
}
writer.Flush()
}
},
}
5 changes: 3 additions & 2 deletions pkg/cmd/root/root.go
Original file line number Diff line number Diff line change
@@ -19,12 +19,13 @@ import (
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/litmuschaos/litmusctl/pkg/cmd/run"
"github.com/litmuschaos/litmusctl/pkg/cmd/save"
"io/ioutil"
"net/http"
"os"

"github.com/litmuschaos/litmusctl/pkg/cmd/run"
"github.com/litmuschaos/litmusctl/pkg/cmd/save"

"github.com/litmuschaos/litmusctl/pkg/cmd/connect"
"github.com/litmuschaos/litmusctl/pkg/cmd/delete"
"github.com/litmuschaos/litmusctl/pkg/cmd/describe"

0 comments on commit 6b68c4d

Please sign in to comment.