Skip to content

Commit

Permalink
Simplifying seedCmd usage
Browse files Browse the repository at this point in the history
  • Loading branch information
Maya Sergeeva committed Dec 10, 2021
1 parent 31d9466 commit 44ebcfa
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 46 deletions.
17 changes: 17 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package commands

type CommandContextKey string

const (
CommandContextCfgKey CommandContextKey = "cfg"
CommandContextCfgKeyDB = CommandContextCfgKey + ".db"
CommandContextCfgKeyLog = CommandContextCfgKey + ".log"
CommandContextCfgKeyAppInfo = CommandContextCfgKey + ".appInfo"
CommandContextCfgKeyStage = CommandContextCfgKey + ".stage"
)

const (
CommandContextObjectKey CommandContextKey = "obj"
CommandContextObjectKeySeeder = CommandContextObjectKey + ".seeder"
CommandContextObjectKeyConfig = CommandContextObjectKey + ".config"
)
12 changes: 12 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package commands

import "errors"

var (
ErrNoMethodFound = errors.New("seed method is not exists")
ErrSeedIsDisabled = errors.New("seed method is disabled in config")
ErrSeedClassNameNotRegistered = errors.New("seed class name not registered")
ErrSeedClassIsNotValid = errors.New("seed class name not valid")
ErrSeedClassNotImplementInterface = errors.New("seed class name not implements commands.SeedInterface")
ErrBadContextValue = errors.New("context value is empty or has wrong type")
)
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ require (
github.com/jackc/pgx/v4 v4.13.0
github.com/pressly/goose v2.7.0+incompatible
github.com/spacetab-io/configuration-go v1.2.0
github.com/spacetab-io/configuration-structs-go v0.0.1
github.com/spacetab-io/configuration-structs-go v0.1.1
github.com/spacetab-io/logs-go/v2 v2.1.0
github.com/spf13/cobra v1.2.1
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -378,8 +378,8 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/spacetab-io/configuration-go v1.2.0 h1:RDoruNQfe508DpHKj5NaLdtWtCGg5e4gnhD9EOUgQ7Y=
github.com/spacetab-io/configuration-go v1.2.0/go.mod h1:242FyTS40EpL9c/zv+qjimoWh1TtAPYljZgxMsFJ4wY=
github.com/spacetab-io/configuration-structs-go v0.0.1 h1:2evzu+CH5oUJS0y6edAlJr1UTRC3oJZG8NoSPQqmI7k=
github.com/spacetab-io/configuration-structs-go v0.0.1/go.mod h1:inP70vRNRW0euxR3ndNE8/H2qXL3hmQdPkcgRfjj6AA=
github.com/spacetab-io/configuration-structs-go v0.1.1 h1:LA7up+68aaY3Ghl5wXKQ2DJeDNibZ4gNfK6PfURxH5Q=
github.com/spacetab-io/configuration-structs-go v0.1.1/go.mod h1:inP70vRNRW0euxR3ndNE8/H2qXL3hmQdPkcgRfjj6AA=
github.com/spacetab-io/logs-go/v2 v2.1.0 h1:8kRAudrGlqnU8sXzauRlS6uz9UBr5K9zM8g3qjwIuk4=
github.com/spacetab-io/logs-go/v2 v2.1.0/go.mod h1:or/5vcOpnWRGA2KUJbJ6o+R2WU4XIjc4w7FDBcm7z2I=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
Expand Down
26 changes: 0 additions & 26 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,5 @@
package commands

import (
"errors"
)

type CommandContextKey string

const (
CommandContextCfgKey CommandContextKey = "cfg"
CommandContextCfgKeyDB = CommandContextCfgKey + ".db"
CommandContextCfgKeyLog = CommandContextCfgKey + ".log"
CommandContextCfgKeyAppInfo = CommandContextCfgKey + ".appInfo"
CommandContextCfgKeyStage = CommandContextCfgKey + ".stage"
)

const (
CommandContextObjectKey CommandContextKey = "obj"
CommandContextObjectKeySeeder = CommandContextObjectKey + ".seeder"
CommandContextObjectKeyConfig = CommandContextObjectKey + ".config"
)

var (
ErrNoMethodFound = errors.New("seed method is not exists")
ErrSeedIsDisabled = errors.New("seed method is disabled in config")
ErrBadContextValue = errors.New("context value is empty or has wrong type")
)

// nolint: gochecknoinits // 🤷
func init() {
MigrateCmd.SetUsageFunc(migrateUsage)
Expand Down
24 changes: 7 additions & 17 deletions seed.go → seed.cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,6 @@ import (
"github.com/spf13/cobra"
)

type SeedsInterface interface {
GetMethods() map[string]SeedInterface
GetMethod(name string) (SeedInterface, error)
SeedsList() []string
}

type SeedInterface interface {
Enabled() bool
Name() string
Seed() error
}

// SeedCmd is a database seeding wrapper command.
var (
SeedCmd = &cobra.Command{
Expand All @@ -45,7 +33,7 @@ var (
)

// seedUsage shows seed command usage.
// Add it to SeedCmd like SeedCmd.SetUsageFunc(seedUsage).
// Add it to SeedCmd like SeedCmd.SetUsageFunc(SeedUsage).
func seedUsage(cmd *cobra.Command) error {
w := cmd.OutOrStderr()
if _, err := w.Write([]byte(fmt.Sprintf(`Usage:
Expand All @@ -56,12 +44,13 @@ Args:
run-all applies all seeds
list shows available seeds list
`, cmd.Parent().Name(), cmd.Name()))); err != nil {
return fmt.Errorf("seedUsage err: %w", err)
return fmt.Errorf("SeedUsage err: %w", err)
}

return nil
}

// seedList returns seeds list.
func seedList(cmd *cobra.Command, _ []string) error {
s, err := getAppSeeder(cmd.Context())
if err != nil {
Expand All @@ -73,6 +62,7 @@ func seedList(cmd *cobra.Command, _ []string) error {
return nil
}

// seedRun Execute exact seed for passed method name.
func seedRun(cmd *cobra.Command, args []string) error {
s, err := getAppSeeder(cmd.Context())
if err != nil {
Expand All @@ -96,7 +86,7 @@ func seedRun(cmd *cobra.Command, args []string) error {
return nil
}

// Execute all seeders if no method name is given.
// seedRunAll Execute all seeds if no method name is given.
func seedRunAll(cmd *cobra.Command, _ []string) error {
s, err := getAppSeeder(cmd.Context())
if err != nil {
Expand All @@ -117,8 +107,8 @@ func seedRunAll(cmd *cobra.Command, _ []string) error {
return nil
}

func getAppSeeder(ctx context.Context) (SeedsInterface, error) {
s, ok := ctx.Value(CommandContextObjectKeySeeder).(SeedsInterface)
func getAppSeeder(ctx context.Context) (SeederInterface, error) {
s, ok := ctx.Value(CommandContextObjectKeySeeder).(SeederInterface)
if !ok {
return nil, fmt.Errorf("%w: app seed (cfg.appInfo)", ErrBadContextValue)
}
Expand Down
19 changes: 19 additions & 0 deletions seed.interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package commands

import (
cfgstructs "github.com/spacetab-io/configuration-structs-go"
)

type SeedInterface interface {
Enabled() bool
Name() string
Seed() error
SetRepo(r interface{})
SetCfg(c cfgstructs.SeedInfo)
}

type SeederInterface interface {
GetMethods() map[string]SeedInterface
GetMethod(name string) (SeedInterface, error)
SeedsList() []string
}
83 changes: 83 additions & 0 deletions seed.seeder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package commands

import (
"fmt"
"reflect"

cfgstructs "github.com/spacetab-io/configuration-structs-go"
)

type Seeder struct {
seeds []cfgstructs.SeedInfo
methods map[string]SeedInterface
}

// SeedMethodType checks SeedInterface implementation and returns Seed object reflect.Type.
func SeedMethodType(seed SeedInterface) reflect.Type {
return reflect.ValueOf(seed).Elem().Type()
}

// NewSeeder initiates new Seeder object.
func NewSeeder(cfg cfgstructs.SeedingCfg, seeds map[string]reflect.Type, repo interface{}) (SeederInterface, error) {
s := Seeder{seeds: cfg.Seeds, methods: make(map[string]SeedInterface)}

for _, seedCfg := range s.seeds {
if !seedCfg.Enabled {
continue
}

seedType, ok := seeds[seedCfg.ClassName]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrSeedClassNameNotRegistered, seedCfg.ClassName)
}

seedValue := reflect.New(seedType)
if !seedValue.IsValid() {
return nil, fmt.Errorf("%w: %s", ErrSeedClassIsNotValid, seedCfg.ClassName)
}

seed, ok := seedValue.Interface().(SeedInterface)
if !ok || seed == nil {
return nil, fmt.Errorf("%w: %s", ErrSeedClassNotImplementInterface, seedCfg.ClassName)
}

seed.SetCfg(seedCfg)
seed.SetRepo(repo)

s.methods[seedCfg.Name] = seed
}

return s, nil
}

func (s Seeder) GetMethods() map[string]SeedInterface {
return s.methods
}

func (s Seeder) GetMethod(name string) (SeedInterface, error) {
m, ok := s.methods[name]
if !ok {
return nil, fmt.Errorf("Seeder.GetMethod %s error: %w", name, ErrNoMethodFound)
}

if !m.Enabled() {
return nil, fmt.Errorf("Seeder.GetMethod %s error: %w", name, ErrSeedIsDisabled)
}

return m, nil
}

func (s Seeder) SeedsList() []string {
result := make([]string, 0)

for _, seed := range s.seeds {
status := "+"
if !seed.Enabled {
status = "-"
}

result = append(result, fmt.Sprintf("[%s] %s - %s", status, seed.Name, seed.Description))
}

return result
}

0 comments on commit 44ebcfa

Please sign in to comment.