-
Notifications
You must be signed in to change notification settings - Fork 0
/
seed.seeder.go
83 lines (63 loc) · 1.89 KB
/
seed.seeder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package commands
import (
"fmt"
"reflect"
cfgstructs "github.com/spacetab-io/configuration-structs-go/v2"
)
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
}