github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/plugins/base/new/command.go (about) 1 package new 2 3 import ( 4 "context" 5 "errors" 6 "os" 7 "path/filepath" 8 9 "github.com/spf13/pflag" 10 11 "github.com/wawandco/ox/plugins/core" 12 ) 13 14 var _ core.Command = (*Command)(nil) 15 var _ core.PluginReceiver = (*Command)(nil) 16 var ErrNoNameProvided = errors.New("the name for the new app is needed") 17 18 // Command to generate New applications. 19 type Command struct { 20 // force tells whether to remove or not 21 // the folder when found. 22 force bool 23 24 initializers []Initializer 25 afterInitializers []AfterInitializer 26 27 flags *pflag.FlagSet 28 } 29 30 func (d Command) Name() string { 31 return "new" 32 } 33 34 func (d Command) ParentName() string { 35 return "" 36 } 37 38 // HelpText returns the help Text of build function 39 func (d Command) HelpText() string { 40 return "Generates a new app with registered plugins" 41 } 42 43 // Run each of the initializers and afterinitializers to 44 // compose the initial ox application. 45 func (d *Command) Run(ctx context.Context, root string, args []string) error { 46 if len(args) < 2 { 47 return ErrNoNameProvided 48 } 49 50 name := d.AppName(args) 51 folder := filepath.Join(root, name) 52 53 if _, err := os.Stat(folder); err == nil && !d.force { 54 return errors.New("folder already exist") 55 } 56 57 err := os.RemoveAll(folder) 58 if err != nil { 59 return err 60 } 61 62 options := Options{ 63 Args: args, 64 Root: root, 65 Folder: folder, 66 Name: name, 67 Module: args[1], 68 } 69 70 for _, ini := range d.initializers { 71 err := ini.Initialize(ctx, options) 72 if err != nil { 73 return err 74 } 75 } 76 77 for _, aini := range d.afterInitializers { 78 err := aini.AfterInitialize(ctx, options) 79 if err != nil { 80 return err 81 } 82 } 83 84 return nil 85 } 86 87 // Receive and store initializers 88 func (d *Command) Receive(plugins []core.Plugin) { 89 for _, tool := range plugins { 90 i, ok := tool.(Initializer) 91 if ok { 92 d.initializers = append(d.initializers, i) 93 } 94 95 ai, ok := tool.(AfterInitializer) 96 if ok { 97 d.afterInitializers = append(d.afterInitializers, ai) 98 } 99 } 100 } 101 func (d *Command) AppName(args []string) string { 102 return filepath.Base(args[1]) 103 } 104 105 func (d *Command) ParseFlags(args []string) { 106 d.flags = pflag.NewFlagSet(d.Name(), pflag.ContinueOnError) 107 d.flags.Usage = func() {} 108 d.flags.BoolVarP(&d.force, "force", "f", false, "clear existing folder if found.") 109 d.flags.Parse(args) //nolint:errcheck,we don't care hence the flag 110 } 111 112 func (d *Command) Flags() *pflag.FlagSet { 113 return d.flags 114 } 115 116 func (d *Command) FindRoot() string { 117 wd, err := os.Getwd() 118 if err != nil { 119 return "" 120 } 121 122 return wd 123 }