forked from xalanq/cf-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen.go
99 lines (87 loc) · 2.53 KB
/
gen.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
package cmd
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/fatih/color"
"github.com/xalanq/cf-tool/client"
"github.com/xalanq/cf-tool/config"
"github.com/xalanq/cf-tool/util"
)
func parseTemplate(source string, cln *client.Client) string {
now := time.Now()
source = strings.ReplaceAll(source, "$%U%$", cln.Handle)
source = strings.ReplaceAll(source, "$%Y%$", fmt.Sprintf("%v", now.Year()))
source = strings.ReplaceAll(source, "$%M%$", fmt.Sprintf("%02v", int(now.Month())))
source = strings.ReplaceAll(source, "$%D%$", fmt.Sprintf("%02v", now.Day()))
source = strings.ReplaceAll(source, "$%h%$", fmt.Sprintf("%02v", now.Hour()))
source = strings.ReplaceAll(source, "$%m%$", fmt.Sprintf("%02v", now.Minute()))
source = strings.ReplaceAll(source, "$%s%$", fmt.Sprintf("%02v", now.Second()))
return source
}
func readTemplateSource(path string, cln *client.Client) (source string, err error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return
}
source = parseTemplate(string(b), cln)
return
}
func gen(source, currentPath, ext string) error {
path := filepath.Join(currentPath, filepath.Base(currentPath))
savePath := path + ext
i := 1
for _, err := os.Stat(savePath); err == nil; _, err = os.Stat(savePath) {
tmpPath := fmt.Sprintf("%v%v%v", path, i, ext)
fmt.Printf("%v exists. Rename to %v\n", filepath.Base(savePath), filepath.Base(tmpPath))
savePath = tmpPath
i++
}
err := ioutil.WriteFile(savePath, []byte(source), 0644)
if err == nil {
color.Green("Generated! See %v", filepath.Base(savePath))
}
return err
}
// Gen command
func Gen() (err error) {
cfg := config.Instance
if len(cfg.Template) == 0 {
return errors.New("You have to add at least one code template by `cf config`")
}
alias := Args.Alias
var path string
if alias != "" {
templates := cfg.TemplateByAlias(alias)
if len(templates) < 1 {
return fmt.Errorf("Cannot find any template with alias %v", alias)
} else if len(templates) == 1 {
path = templates[0].Path
} else {
fmt.Printf("There are multiple templates with alias %v\n", alias)
for i, template := range templates {
fmt.Printf(`%3v: "%v"`, i, template.Path)
fmt.Println()
}
i := util.ChooseIndex(len(templates))
path = templates[i].Path
}
} else {
path = cfg.Template[cfg.Default].Path
}
cln := client.Instance
source, err := readTemplateSource(path, cln)
if err != nil {
return
}
currentPath, err := os.Getwd()
if err != nil {
return
}
ext := filepath.Ext(path)
return gen(source, currentPath, ext)
}