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