sq/cli/cmd_remove.go

84 lines
2.0 KiB
Go
Raw Normal View History

2020-08-06 20:58:47 +03:00
package cli
import (
"github.com/neilotoole/sq/libsq/core/errz"
"github.com/neilotoole/sq/libsq/source"
"github.com/samber/lo"
2020-08-06 20:58:47 +03:00
"github.com/spf13/cobra"
)
func newRemoveCmd() *cobra.Command {
2020-08-06 20:58:47 +03:00
cmd := &cobra.Command{
Use: "rm @HANDLE|GROUP",
Short: "Remove data source or group",
Long: `Remove data source or group. Removing a group removes
all sources in that group. On return, the active source or active group
may have changed, if that source or group was removed.`,
Args: cobra.MinimumNArgs(1),
RunE: execRemove,
ValidArgsFunction: completeHandleOrGroup,
Example: ` # Remove @sakila source
$ sq rm @sakila_db
# Remove multiple data sources
$ sq rm @sakila/pg @sakila_my
# Remove the "prod" group (and all its children)
$ sq rm prod
# Remove a mix of sources and groups
$ sq rm @staging/sakila_db @staging/backup_db dev`,
2020-08-06 20:58:47 +03:00
}
cmd.Flags().BoolP(flagJSON, flagJSONShort, false, flagJSONUsage)
return cmd
2020-08-06 20:58:47 +03:00
}
// execRemove removes sources and groups. The elements of
// args can be a handle, or a group.
func execRemove(cmd *cobra.Command, args []string) error {
rc := RunContextFrom(cmd.Context())
cfg, ss := rc.Config, rc.Config.Sources
2020-08-06 20:58:47 +03:00
args = lo.Uniq(args)
var removed []*source.Source
for _, arg := range args {
switch {
case source.IsValidHandle(arg):
if source.Contains(removed, arg) {
// removed may already contain the handle
// by virtue of its group having been removed.
continue
}
src, err := ss.Get(arg)
if err != nil {
return err
}
err = ss.Remove(src.Handle)
if err != nil {
return err
}
removed = append(removed, src)
case source.IsValidGroup(arg):
removedViaGroup, err := ss.RemoveGroup(arg)
if err != nil {
return err
}
removed = append(removed, removedViaGroup...)
default:
return errz.Errorf("invalid arg: %s", arg)
}
2020-08-06 20:58:47 +03:00
}
if err := rc.ConfigStore.Save(cfg); err != nil {
2020-08-06 20:58:47 +03:00
return err
}
lo.Uniq(removed)
source.Sort(removed)
return rc.writers.srcw.Removed(removed...)
2020-08-06 20:58:47 +03:00
}