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