This repository was archived by the owner on Oct 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcook.go
183 lines (147 loc) · 4.46 KB
/
cook.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
// Cook generate projects from templates based on github repositories.
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
var regex, _ = regexp.Compile("{{(\\s|)cook?\\w+\\.\\w+(\\s|)}}")
// Get fetch a git repository to current directory and returns a directory name
func Get(repoName string) string {
repoURL := "https://github.com/" + repoName + "/archive/master.zip"
dirName := strings.Split(repoName, "/")[1]
downloadFromUrl(repoURL)
unzip("master.zip", "")
os.Rename(dirName+"-master", dirName)
return dirName
}
// Parse a json config file to ask user to new values
func Parse(repoPath string) map[string]interface{} {
var configJSON map[string]interface{}
configNames := [2]string{"cook.json", "cookiecutter.json"}
for index := range configNames {
config, err := ioutil.ReadFile(repoPath + string(os.PathSeparator) + configNames[index])
if err != nil {
continue
}
json.Unmarshal([]byte(config), &configJSON)
}
if len(configJSON) == 0 {
panic("This is not a valid repository.")
}
return configJSON
}
// Ask receive a config map, iterate over and update user project data
func Ask(config map[string]interface{}) map[string]interface{} {
for k, v := range config {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter ", k, " (default: ", v, "): ")
text, _ := reader.ReadString('\n')
if len(strings.TrimSpace(text)) > 0 {
text = strings.TrimSuffix(text, "\n")
config[k] = text
}
}
return config
}
// getKey receive a string with a placeholder, parse and return a key string
func getKey(placeholder string) string {
placeholder = regex.FindString(placeholder)
strParts := strings.Split(placeholder, ".")[1]
key := strings.Replace(strParts, "}}", "", -1)
key = strings.TrimSpace(key)
return key
}
// getPaths receive a repository path and returns a slice with template files/dirs path
func getPaths(repoPath string) []string {
var paths = make([]string, 0)
filepath.Walk(repoPath, func(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err) // can't walk here,
return nil // but continue walking elsewhere
}
matched := regex.MatchString(fi.Name())
if matched {
paths = append(paths, fp)
}
return nil
})
return paths
}
// ReplacePaths receives a slices of paths and a config map to replace
// variables with config values
func ReplacePaths(paths []string, config map[string]interface{}) string {
var newFolder string
// reverse paths list to rename files/dirs without lost references
for i := len(paths) - 1; i >= 0; i-- {
parts := strings.Split(paths[i], string(os.PathSeparator))
replacePart := parts[len(parts)-1]
originalPart := parts[len(parts)-1]
key := getKey(replacePart)
value := config[key].(string)
originalPart = regex.ReplaceAllString(originalPart, value)
parts[len(parts)-1] = originalPart
newPath := strings.Join(parts, string(os.PathSeparator))
os.Rename(paths[i], newPath)
if i == 0 {
folderParts := strings.Split(newPath, string(os.PathSeparator))
oldFolder := folderParts[0]
newFolder = folderParts[1]
os.Rename(newPath, newFolder)
os.RemoveAll(oldFolder)
}
}
return newFolder
}
//ReplaceContent receives a config map to replace all files with your variables
func ReplaceContent(repoPath string, config map[string]interface{}) {
filepath.Walk(repoPath, func(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err) // can't walk here,
return nil // but continue walking elsewhere
}
if !!fi.IsDir() {
return nil // not a file. ignore.
}
file, err := ioutil.ReadFile(fp)
if err != nil {
fmt.Println(err)
}
lines := strings.Split(string(file), "\n")
for i, line := range lines {
placeholders := regex.FindAllString(line, -1)
for _, ph := range placeholders {
key := getKey(ph)
value := config[key].(string)
lines[i] = strings.Replace(lines[i], ph, value, 1)
}
}
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(fp, []byte(output), 0644)
if err != nil {
fmt.Println(err)
}
return nil
})
}
func main() {
var repoName, repoPath string
if len(os.Args) > 1 {
repoName = os.Args[1]
} else {
fmt.Println("You must provide a github <username>/<repository>")
return
}
repoPath = Get(repoName)
config := Parse(repoPath)
config = Ask(config)
paths := getPaths(repoPath)
repoPath = ReplacePaths(paths, config)
ReplaceContent(repoPath, config)
fmt.Println("Project genereated: ", repoPath)
}