/
use.go
103 lines (82 loc) · 2.56 KB
/
use.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package cmd
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
cli "github.com/spf13/cobra"
"github.com/4thel00z/templatectl/pkg/templatectl"
"github.com/4thel00z/templatectl/pkg/template"
"github.com/4thel00z/templatectl/pkg/util/exit"
"github.com/4thel00z/templatectl/pkg/util/osutil"
"github.com/4thel00z/templatectl/pkg/util/validate"
)
// TemplateInRegistry checks whether the given name exists in the template registry.
func TemplateInRegistry(name string) (bool, error) {
names, err := ListTemplates()
if err != nil {
return false, err
}
_, ok := names[name]
return ok, nil
}
// TODO add --use-cache flag to execute a template from previous answers to prompts
// Use contains the cli-command for using templates located in the local template registry.
var Use = &cli.Command{
Use: "use <template-tag> <target-dir>",
Short: "Execute a project template in the given directory",
Run: func(cmd *cli.Command, args []string) {
MustValidateArgs(args, []validate.Argument{
{"template-tag", validate.UnixPath},
{"target-dir", validate.UnixPath},
})
MustValidateTemplateDir()
tmplName := args[0]
targetDir, err := filepath.Abs(args[1])
if err != nil {
exit.Fatal(fmt.Errorf("use: %s", err))
}
templateFound, err := TemplateInRegistry(tmplName)
if err != nil {
exit.Fatal(fmt.Errorf("use: %s", err))
}
if !templateFound {
exit.Fatal(fmt.Errorf("Template %q couldn't be found in the template registry", tmplName))
}
tmplPath, err := templatectl.TemplatePath(tmplName)
if err != nil {
exit.Fatal(fmt.Errorf("use: %s", err))
}
tmpl, err := template.Get(tmplPath)
if err != nil {
exit.Fatal(fmt.Errorf("use: %s", err))
}
if shouldUseDefaults := GetBoolFlag(cmd, "use-defaults"); shouldUseDefaults {
tmpl.UseDefaultValues()
}
executeTemplate := func() error {
parentDir := filepath.Dir(targetDir)
exists, err := osutil.DirExists(parentDir)
if err != nil {
return err
}
if !exists {
return fmt.Errorf("use: parent directory %q doesn't exist", parentDir)
}
tmpDir, err := ioutil.TempDir("", "templatectl-use-template")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
if err := tmpl.Execute(tmpDir); err != nil {
return err
}
// Complete the template execution transaction by copying the temporary dir to the target directory.
return osutil.CopyRecursively(tmpDir, targetDir)
}
if err := executeTemplate(); err != nil {
exit.Fatal(fmt.Errorf("use: %v", err))
}
exit.OK("Successfully executed the project template %v in %v", tmplName, targetDir)
},
}