github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/plugins/tools/ox/model/generator.go (about) 1 package model 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "path/filepath" 8 9 "errors" 10 11 "github.com/gobuffalo/flect" 12 "github.com/wawandco/ox/internal/log" 13 ) 14 15 var ( 16 ErrModelAlreadyExists error = errors.New("model already exists") 17 ErrModelDirNotFound error = errors.New("models folder do not exists on your buffalo app, please ensure the folder exists in order to proceed") 18 ) 19 20 // Generator allows to identify model as a plugin 21 type Generator struct{} 22 23 // Name returns the name of the plugin 24 func (g Generator) Name() string { 25 return "buffalo/generate-model" 26 } 27 28 // InvocationName is used to identify the generator when 29 // the generate command is called. 30 func (g Generator) InvocationName() string { 31 return "model" 32 } 33 34 // Generate generates an empty [name].plush.html file 35 func (g Generator) Generate(ctx context.Context, root string, args []string) error { 36 if len(args) < 3 { 37 return fmt.Errorf("no name specified, please use `ox generate model [name]`") 38 } 39 40 dirPath := filepath.Join(root, "app", "models") 41 if !g.exists(dirPath) { 42 return ErrModelDirNotFound 43 } 44 45 filename := flect.Singularize(flect.Underscore(args[2])) 46 47 if g.exists(filepath.Join(dirPath, filename+".go")) { 48 return ErrModelAlreadyExists 49 } 50 51 model := New(dirPath, args[2], args[3:]) 52 if err := model.Create(); err != nil { 53 return fmt.Errorf("creating models error: %w", err) 54 } 55 56 log.Infof("Model generated in: \n-- app/models/%s.go\n-- app/models/%s_test.go\n", filename, filename) 57 58 return nil 59 } 60 61 func (g Generator) exists(path string) bool { 62 _, err := os.Stat(path) 63 64 return !os.IsNotExist(err) 65 }