From ea572856f8b1b141a61801f685708e72816f85ef Mon Sep 17 00:00:00 2001 From: Marcos Lilljedahl Date: Thu, 28 May 2020 00:53:44 -0300 Subject: [PATCH] Implement prune --- cmd/prune.go | 17 +++++++++++++++-- pkg/config/config.go | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/cmd/prune.go b/cmd/prune.go index fe5ad2c..f524a01 100644 --- a/cmd/prune.go +++ b/cmd/prune.go @@ -1,6 +1,10 @@ package cmd import ( + "os" + + "github.com/apex/log" + "github.com/marcosnils/bin/pkg/config" "github.com/spf13/cobra" ) @@ -21,8 +25,17 @@ func newPruneCmd() *pruneCmd { SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - //TODO implement prune - return nil + cfg := config.Get() + + pathsToDel := []string{} + for _, b := range cfg.Bins { + if _, err := os.Stat(b.Path); os.IsNotExist(err) { + log.Infof("%s not found removing", b.Path) + pathsToDel = append(pathsToDel, b.Path) + } + } + + return config.RemoveBinaries(pathsToDel) }, } diff --git a/pkg/config/config.go b/pkg/config/config.go index 2403561..5b47004 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -59,6 +59,28 @@ func AddBinary(c *Binary) error { return nil } +// RemoveBinaries removes the specified paths +// from bin configuration. It doesn't care about the order +func RemoveBinaries(paths []string) error { + if len(paths) > 0 { + k := 0 + for _, cb := range cfg.Bins { + for _, p := range paths { + if cb.Path != p { + cfg.Bins[k] = cb + k++ + } + } + } + + cfg.Bins = cfg.Bins[:k] + + return write() + } + + return nil +} + func write() error { u, _ := user.Current() f, err := os.OpenFile(filepath.Join(u.HomeDir, ".bin/config.json"), os.O_RDWR|os.O_CREATE, 0666)