-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from silphid/add-tidy-command
add tidy command
- Loading branch information
Showing
4 changed files
with
77 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package tidy | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"path/filepath" | ||
"strings" | ||
|
||
"github.com/spf13/cobra" | ||
|
||
yey "github.com/silphid/yey/src/internal" | ||
"github.com/silphid/yey/src/internal/docker" | ||
) | ||
|
||
// New creates a cobra command | ||
func New() *cobra.Command { | ||
return &cobra.Command{ | ||
Use: "tidy", | ||
Short: "Removes unreferenced containers", | ||
Args: cobra.NoArgs, | ||
RunE: func(cmd *cobra.Command, args []string) error { | ||
return run(cmd.Context()) | ||
}, | ||
} | ||
} | ||
|
||
func run(ctx context.Context) error { | ||
contexts, err := yey.LoadContexts() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
validNames := make(map[string]struct{}) | ||
for _, name := range contexts.GetNames() { | ||
ctx, err := contexts.GetContext(name) | ||
if err != nil { | ||
return err | ||
} | ||
validNames[yey.ContainerName(contexts.Path, ctx)] = struct{}{} | ||
} | ||
|
||
prefix := fmt.Sprintf( | ||
"yey-%s-%s", | ||
filepath.Base(filepath.Dir(contexts.Path)), | ||
yey.Hash(contexts.Path), | ||
) | ||
|
||
names, err := docker.ListContainers(ctx) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
for _, container := range names { | ||
if !strings.HasPrefix(container, prefix) { | ||
continue | ||
} | ||
if _, ok := validNames[container]; ok { | ||
continue | ||
} | ||
if err := docker.Remove(ctx, container); err != nil { | ||
return err | ||
} | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters