github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/plugins/tools/soda/generator.go (about) 1 package soda 2 3 import ( 4 "context" 5 "errors" 6 "os" 7 "path/filepath" 8 "strings" 9 10 "github.com/gobuffalo/flect" 11 "github.com/spf13/pflag" 12 "github.com/wawandco/ox/internal/log" 13 "github.com/wawandco/ox/plugins/core" 14 ) 15 16 var ( 17 // These are the interfaces we know that this 18 // plugin must satisfy for its correct functionality 19 _ core.Plugin = (*Generator)(nil) 20 _ core.FlagParser = (*Generator)(nil) 21 ) 22 23 // Generator allows to identify model as a plugin 24 type Generator struct { 25 creators Creators 26 27 flags *pflag.FlagSet 28 migrationType string 29 } 30 31 // Name returns the name of the plugin 32 func (g Generator) Name() string { 33 return "pop/generate-migration" 34 } 35 36 // InvocationName is used to identify the generator when 37 // the generate command is called. 38 func (g Generator) InvocationName() string { 39 return "migration" 40 } 41 42 // Generate generates an empty [name].plush.html file 43 func (g Generator) Generate(ctx context.Context, root string, args []string) error { 44 if len(args) < 3 { 45 log.Info("No name specified, please use `ox generate migration [name] [columns?] --type=[sql|fizz]`") 46 return nil 47 } 48 49 cr := g.creators.CreatorFor(g.migrationType) 50 if cr == nil { 51 return errors.New("type not found") 52 } 53 54 dirPath := filepath.Join(root, "migrations") 55 if !g.exists(dirPath) { 56 if err := os.MkdirAll(dirPath, 0755); err != nil { 57 return err 58 } 59 } 60 61 name := flect.Underscore(flect.Pluralize(g.flags.Args()[2])) 62 columns := g.parseColumns(g.flags.Args()[3:]) 63 64 err := cr.Create(dirPath, name, columns) 65 if err != nil { 66 return err 67 } 68 69 return nil 70 } 71 72 func (g *Generator) ParseFlags(args []string) { 73 g.flags = pflag.NewFlagSet("type", pflag.ContinueOnError) 74 g.flags.Usage = func() {} 75 g.flags.StringVarP(&g.migrationType, "type", "t", "fizz", "the type of the migration") 76 g.flags.Parse(args) //nolint:errcheck,we don't care hence the flag 77 } 78 79 func (g *Generator) Flags() *pflag.FlagSet { 80 return g.flags 81 } 82 83 func (g *Generator) Receive(pls []core.Plugin) { 84 for _, v := range pls { 85 cr, ok := v.(Creator) 86 if !ok { 87 continue 88 } 89 90 g.creators = append(g.creators, cr) 91 } 92 } 93 94 func (g Generator) exists(path string) bool { 95 _, err := os.Stat(path) 96 97 return !os.IsNotExist(err) 98 } 99 100 func (g *Generator) parseColumns(args []string) []string { 101 var columns []string 102 for _, arg := range args { 103 if !strings.HasPrefix(arg, "-") { 104 columns = append(columns, arg) 105 } 106 } 107 108 return columns 109 }