Add commend to interactively remove docker images.

This commit is contained in:
2024-09-25 09:17:45 +02:00
parent d524f36101
commit 4feb23031f
4 changed files with 204 additions and 35 deletions

View File

@ -0,0 +1,61 @@
package commands
import (
"fmt"
"strings"
"time"
"github.com/Iilun/survey/v2"
"github.com/dustin/go-humanize"
docker "github.com/fsouza/go-dockerclient"
"github.com/urfave/cli/v2"
)
func CmdDockerRemoveImages(c *cli.Context) error {
client, err := docker.NewClientFromEnv()
if err != nil {
return err
}
imgs, err := client.ListImages(docker.ListImagesOptions{All: false})
if err != nil {
return err
}
imageNames := []string{}
for _, img := range imgs {
imageNames = append(imageNames, fmt.Sprintf("%s | %s | %s | %s", strings.Join(img.RepoTags, ", "), humanize.Bytes(uint64(img.Size)), time.Unix(img.Created, 0).Format("2006-01-02 15:04:05"), img.ID))
}
prompt := &survey.MultiSelect{
Message: "What days do you prefer:",
Options: imageNames,
PageSize: 20,
Filter: func(filter, value string, index int) bool {
filter = strings.TrimSpace(filter)
parts := strings.Split(value, " | ")
return strings.Contains(strings.ToLower(parts[0]), strings.ToLower(filter))
},
}
selection := []string{}
survey.AskOne(prompt, &selection, survey.WithKeepFilter(true))
if len(selection) == 0 {
return nil
}
for _, image := range selection {
parts := strings.Split(image, " | ")
id := parts[len(parts)-1]
err = client.RemoveImage(id)
if err != nil {
fmt.Printf("Error removing image \"%s\": %v\n", parts[0], err)
} else {
fmt.Printf("Image \"%s\" was removed\n", parts[0])
}
}
return nil
}

View File

@ -13,8 +13,6 @@ import (
)
func Execute() {
conf.LoadConfig(filepath.Join(findHomeDir(), ".hoster.yml"))
app := &cli.App{
Name: "hoster",
Usage: "Hoster",
@ -42,8 +40,22 @@ func Execute() {
Required: true,
},
},
Before: func(c *cli.Context) error {
conf.LoadConfig(filepath.Join(findHomeDir(), ".hoster.yml"))
return nil
},
Action: commands.CmdNew,
},
{
Name: "docker",
Subcommands: []*cli.Command{
{
Name: "rmi",
Usage: "Select images to remove",
Action: commands.CmdDockerRemoveImages,
},
},
},
{
Name: "check",
Usage: "Check if newer versions of docker images are available",