1package cmd 2 3import ( 4 "fmt" 5 "os" 6 "text/template" 7 8 "github.com/spf13/cobra" 9 "github.com/spf13/cobra/cobra/tpl" 10) 11 12// Project contains name, license and paths to projects. 13type Project struct { 14 // v2 15 PkgName string 16 Copyright string 17 AbsolutePath string 18 Legal License 19 Viper bool 20 AppName string 21} 22 23type Command struct { 24 CmdName string 25 CmdParent string 26 *Project 27} 28 29func (p *Project) Create() error { 30 // check if AbsolutePath exists 31 if _, err := os.Stat(p.AbsolutePath); os.IsNotExist(err) { 32 // create directory 33 if err := os.Mkdir(p.AbsolutePath, 0754); err != nil { 34 return err 35 } 36 } 37 38 // create main.go 39 mainFile, err := os.Create(fmt.Sprintf("%s/main.go", p.AbsolutePath)) 40 if err != nil { 41 return err 42 } 43 defer mainFile.Close() 44 45 mainTemplate := template.Must(template.New("main").Parse(string(tpl.MainTemplate()))) 46 err = mainTemplate.Execute(mainFile, p) 47 if err != nil { 48 return err 49 } 50 51 // create cmd/root.go 52 if _, err = os.Stat(fmt.Sprintf("%s/cmd", p.AbsolutePath)); os.IsNotExist(err) { 53 cobra.CheckErr(os.Mkdir(fmt.Sprintf("%s/cmd", p.AbsolutePath), 0751)) 54 } 55 rootFile, err := os.Create(fmt.Sprintf("%s/cmd/root.go", p.AbsolutePath)) 56 if err != nil { 57 return err 58 } 59 defer rootFile.Close() 60 61 rootTemplate := template.Must(template.New("root").Parse(string(tpl.RootTemplate()))) 62 err = rootTemplate.Execute(rootFile, p) 63 if err != nil { 64 return err 65 } 66 67 // create license 68 return p.createLicenseFile() 69} 70 71func (p *Project) createLicenseFile() error { 72 data := map[string]interface{}{ 73 "copyright": copyrightLine(), 74 } 75 licenseFile, err := os.Create(fmt.Sprintf("%s/LICENSE", p.AbsolutePath)) 76 if err != nil { 77 return err 78 } 79 defer licenseFile.Close() 80 81 licenseTemplate := template.Must(template.New("license").Parse(p.Legal.Text)) 82 return licenseTemplate.Execute(licenseFile, data) 83} 84 85func (c *Command) Create() error { 86 cmdFile, err := os.Create(fmt.Sprintf("%s/cmd/%s.go", c.AbsolutePath, c.CmdName)) 87 if err != nil { 88 return err 89 } 90 defer cmdFile.Close() 91 92 commandTemplate := template.Must(template.New("sub").Parse(string(tpl.AddCommandTemplate()))) 93 err = commandTemplate.Execute(cmdFile, c) 94 if err != nil { 95 return err 96 } 97 return nil 98} 99