Skip to content

Commit d7d1e5b

Browse files
feat: Add a sub-command for docker - container (#27)
* Add command to stop with all flag * Add command to rename * Add command to delete with all flag
1 parent 872a4b8 commit d7d1e5b

12 files changed

+425
-14
lines changed

cmd/docker/container/container.go

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package container
2+
3+
import (
4+
"log"
5+
6+
"github.com/spf13/cobra"
7+
)
8+
9+
var (
10+
runnnigContainer = []string{}
11+
)
12+
13+
// containerCmd represents the container command
14+
var ContainerCmd = &cobra.Command{
15+
Use: "container [command] [flags]",
16+
Short: "Container related commands",
17+
Run: func(cmd *cobra.Command, args []string) {
18+
err := cmd.Help()
19+
if err != nil {
20+
log.Fatal(err)
21+
}
22+
},
23+
}

cmd/docker/container/delete.go

+108
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package container
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"strings"
7+
8+
"github.com/docker/docker/api/types"
9+
"github.com/manifoldco/promptui"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
var (
14+
deleteAll bool
15+
)
16+
17+
// deleteContainerCmd represents the delete command
18+
var deleteContainerCmd = &cobra.Command{
19+
Use: "delete",
20+
Short: "Delete a running container",
21+
Run: func(cmd *cobra.Command, args []string) {
22+
deleteContainer()
23+
},
24+
}
25+
26+
func deleteContainer() {
27+
ctx, cli := dockerClient()
28+
containerList := runnnigContainerList(cli, ctx)
29+
30+
if len(containerList) == 0 {
31+
fmt.Println("No container running")
32+
return
33+
}
34+
35+
// If the flag --all is set, delete all containers
36+
if deleteAll {
37+
38+
prompt := promptui.Select{
39+
Label: "Are you sure you want to delete all containers?",
40+
Items: []string{"Yes", "No"},
41+
}
42+
43+
_, option, err := prompt.Run()
44+
checkErr(err)
45+
46+
if option == "Yes" {
47+
48+
for _, container := range containerList {
49+
fmt.Printf("Deleting container %s (%s)...\n", container.Names[0][1:], container.ID[:6])
50+
err = cli.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{Force: true})
51+
checkErr(err)
52+
}
53+
54+
fmt.Println("Deleted all containers")
55+
return
56+
} else {
57+
fmt.Println("Containers not removed")
58+
return
59+
}
60+
61+
}
62+
63+
// If the flag --all is not set, delete a specific container
64+
for _, container := range containerList {
65+
runnnigContainer = append(runnnigContainer, container.Names[0][1:]+" - "+container.ID[:6])
66+
67+
}
68+
69+
prompt := promptui.Select{
70+
Label: "Select a containe to delete",
71+
Items: runnnigContainer,
72+
}
73+
74+
_, conSelection, err := prompt.Run()
75+
checkErr(err)
76+
77+
prompt = promptui.Select{
78+
Label: "Are you sure you want to delete " + conSelection + " ?",
79+
Items: []string{"Yes", "No"},
80+
}
81+
82+
_, option, err := prompt.Run()
83+
checkErr(err)
84+
85+
if option == "Yes" {
86+
slpit := strings.Split(conSelection, " - ")
87+
88+
err = cli.ContainerRemove(ctx, slpit[1], types.ContainerRemoveOptions{Force: true})
89+
checkErr(err)
90+
91+
fmt.Printf("Container %s deleted successfully\n", slpit[0])
92+
} else {
93+
fmt.Println("Container not removed")
94+
return
95+
}
96+
97+
}
98+
99+
func checkErr(err error) {
100+
if err != nil {
101+
log.Fatal(err)
102+
}
103+
}
104+
105+
func init() {
106+
ContainerCmd.AddCommand(deleteContainerCmd)
107+
deleteContainerCmd.Flags().BoolVarP(&deleteAll, "all", "a", false, "Delete all containers")
108+
}

cmd/docker/container/helper.go

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package container
2+
3+
import (
4+
"context"
5+
6+
"github.com/docker/docker/api/types"
7+
"github.com/docker/docker/client"
8+
)
9+
10+
// dockerClient returns a docker client
11+
func dockerClient() (context.Context, *client.Client) {
12+
ctx := context.Background()
13+
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
14+
checkErr(err)
15+
defer cli.Close()
16+
17+
return ctx, cli
18+
}
19+
20+
// runnnigContainerList returns a list of running containers
21+
func runnnigContainerList(cli *client.Client, ctx context.Context) []types.Container {
22+
23+
containerList, err := cli.ContainerList(ctx, types.ContainerListOptions{})
24+
checkErr(err)
25+
return containerList
26+
27+
}

cmd/docker/container/rename.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package container
2+
3+
import (
4+
"bufio"
5+
"fmt"
6+
"os"
7+
"strings"
8+
9+
"github.com/manifoldco/promptui"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
// renameCmd represents the rename command
14+
var renameCmd = &cobra.Command{
15+
Use: "rename",
16+
Short: "Rename a container",
17+
Run: func(cmd *cobra.Command, args []string) {
18+
renameContainer()
19+
},
20+
}
21+
22+
func renameContainer() {
23+
ctx, cli := dockerClient()
24+
containerList := runnnigContainerList(cli, ctx)
25+
26+
if len(containerList) == 0 {
27+
fmt.Println("No container running")
28+
return
29+
}
30+
31+
for _, container := range containerList {
32+
runnnigContainer = append(runnnigContainer, container.Names[0][1:]+" - "+container.ID[:6])
33+
34+
}
35+
36+
// Prompt the user to select a container
37+
fmt.Println("CONTAINER NAME - CONTAINER ID")
38+
prompt := promptui.Select{
39+
Label: "Select a container to rename",
40+
Items: runnnigContainer,
41+
}
42+
43+
_, result, err := prompt.Run()
44+
checkErr(err)
45+
46+
// Get new name from the command line
47+
scanner := bufio.NewScanner(os.Stdin)
48+
fmt.Print("Enter new name: ")
49+
scanner.Scan()
50+
newName := scanner.Text()
51+
52+
newName = strings.TrimSpace(newName)
53+
54+
if newName == "" {
55+
fmt.Println("New name cannot be empty")
56+
return
57+
}
58+
59+
slpit := strings.Split(result, " - ")
60+
61+
// Rename the container
62+
err = cli.ContainerRename(ctx, slpit[0], newName)
63+
checkErr(err)
64+
65+
fmt.Printf("Container %s renamed to %s\n", slpit[0], newName)
66+
67+
}
68+
69+
func init() {
70+
ContainerCmd.AddCommand(renameCmd)
71+
72+
}

cmd/docker/container/stop.go

+119
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
package container
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"strings"
7+
8+
containertypes "github.com/docker/docker/api/types/container"
9+
"github.com/manifoldco/promptui"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
var (
14+
stopall bool
15+
)
16+
17+
// deleteallcontainerCmd represents the deleteallcontainer command
18+
var stopAllContainersCmd = &cobra.Command{
19+
Use: "stop",
20+
Short: "Stop a running container",
21+
Run: func(cmd *cobra.Command, args []string) {
22+
stopContainers()
23+
},
24+
}
25+
26+
func stopContainers() {
27+
ctx, cli := dockerClient()
28+
containerList := runnnigContainerList(cli, ctx)
29+
30+
if len(containerList) == 0 {
31+
fmt.Println("No container running")
32+
return
33+
}
34+
35+
// If the flag --all is set, delete all containers
36+
if stopall {
37+
38+
prompt := promptui.Select{
39+
Label: "Are you sure you want to stop all containers?",
40+
Items: []string{"Yes", "No"},
41+
}
42+
43+
_, option, err := prompt.Run()
44+
45+
if err != nil {
46+
log.Fatal(err)
47+
}
48+
49+
if option == "Yes" {
50+
51+
for _, container := range containerList {
52+
fmt.Printf("Stopping container %s (%s)...\n", container.Names[0][1:], container.ID[:6])
53+
noWaitTimeout := 5 // to not wait for the container to exit gracefully
54+
err := cli.ContainerStop(ctx, container.ID, containertypes.StopOptions{Timeout: &noWaitTimeout})
55+
if err != nil {
56+
log.Fatal(err)
57+
}
58+
59+
}
60+
fmt.Println("Stopped all containers")
61+
return
62+
63+
} else {
64+
fmt.Println("Aborted")
65+
return
66+
}
67+
68+
}
69+
70+
// If the flag --all is not set, delete a specific container
71+
for _, container := range containerList {
72+
runnnigContainer = append(runnnigContainer, container.Names[0][1:]+" - "+container.ID[:6])
73+
}
74+
75+
// Prompt the user to select a container
76+
fmt.Println("CONTAINER NAME - CONTAINER ID")
77+
prompt := promptui.Select{
78+
Label: "Select a container to stop",
79+
Items: runnnigContainer,
80+
}
81+
82+
_, result, err := prompt.Run()
83+
if err != nil {
84+
log.Fatal(err)
85+
}
86+
87+
prompt = promptui.Select{
88+
Label: "Are you sure you want to stop " + result + "?",
89+
Items: []string{"Yes", "No"},
90+
}
91+
92+
_, option, err := prompt.Run()
93+
if err != nil {
94+
log.Fatal(err)
95+
}
96+
97+
if option == "Yes" {
98+
99+
split := strings.Split(result, " - ")
100+
101+
noWaitTimeout := 5 // to not wait for the container to exit gracefully
102+
err := cli.ContainerStop(ctx, split[1], containertypes.StopOptions{Timeout: &noWaitTimeout})
103+
if err != nil {
104+
log.Fatal(err)
105+
}
106+
107+
fmt.Println("Container + " + split[0] + " stopped successfully")
108+
109+
}
110+
111+
}
112+
113+
func init() {
114+
115+
ContainerCmd.AddCommand(stopAllContainersCmd)
116+
117+
stopAllContainersCmd.Flags().BoolVarP(&stopall, "all", "a", false, "Delete all containers")
118+
119+
}

cmd/docker/docker-file.go

-2
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,6 @@ func createDockerfile(lang string) {
4848
}
4949

5050
func init() {
51-
DockerCmd.AddCommand(dockerfileCmd)
52-
5351
dockerfileCmd.Flags().StringVarP(&language, "lang", "l", "", "Programming language to generate Dockerfile for.")
5452
err := dockerfileCmd.MarkFlagRequired("lang")
5553
checkNilErr(err)

cmd/docker/docker.go

+6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package docker
22

33
import (
4+
"github.com/Pradumnasaraf/candy/cmd/docker/container"
45
"github.com/spf13/cobra"
56
)
67

@@ -13,3 +14,8 @@ var DockerCmd = &cobra.Command{
1314
checkNilErr(err)
1415
},
1516
}
17+
18+
func init() {
19+
DockerCmd.AddCommand(container.ContainerCmd)
20+
DockerCmd.AddCommand(dockerfileCmd)
21+
}

cmd/kubernetes/kubernetes-manifest.go

-2
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,6 @@ func createManifestFile(filename string, obj string) {
5454
}
5555

5656
func init() {
57-
KubernetesCmd.AddCommand(kubernetesManifestCmd)
58-
5957
kubernetesManifestCmd.Flags().StringVarP(&k8Obj, "obj", "o", "", "Kubernetes object to generate manifest for.")
6058
err := kubernetesManifestCmd.MarkFlagRequired("obj")
6159
checkNilErr(err)

cmd/kubernetes/kubernetes.go

+4
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,7 @@ var KubernetesCmd = &cobra.Command{
1313
checkNilErr(err)
1414
},
1515
}
16+
17+
func init() {
18+
KubernetesCmd.AddCommand(kubernetesManifestCmd)
19+
}

0 commit comments

Comments
 (0)