-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
266 lines (219 loc) · 7.38 KB
/
generator.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
MIT License
Copyright (c) 2020 akhettar
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"text/template"
"time"
"gopkg.in/yaml.v2"
)
// RepoName is the repo name to be processed
const RepoName = "repo"
// Config the Github action config
type Config struct {
Description string `yaml:"description"`
Repositories []Repositories `yaml:"repositories"`
}
// Repository type
type Repository = map[string]string
// Repositories type
type Repositories struct {
Repo Repository `yaml:"repo,omitempty"`
}
// TemplateGenerator type
type TemplateGenerator struct {
conf *Config
client *GitClient
}
// Report holds information about the processing of the repo
type Report struct {
name string
err error
}
// Generartor creates an instance of the Templater
func Generartor() *TemplateGenerator {
// make sure we are always starting from fresh git repo
clearUp("repos/")
// assert the presence of the required environment variable
validate()
// read the Github action template. At the moment only one config with all the defined the repositories to be processed
data, err := ioutil.ReadFile("./config.yml")
if err != nil {
log.Fatal(err)
}
var config Config
if err = yaml.NewDecoder(bytes.NewReader(data)).Decode(&config); err != nil {
log.Fatal(err)
}
return &TemplateGenerator{conf: &config, client: NewGitClient()}
}
// generates all github action config for all the repos
func (t *TemplateGenerator) run() []Report {
var wg sync.WaitGroup
reportChan := make(chan Report, len(t.conf.Repositories))
repo := os.Getenv(RepoName)
for _, r := range t.conf.Repositories {
repoName := getRepoName(r.Repo["url"])
repoPath := fmt.Sprintf("repos/%s", repoName)
branch := fmt.Sprintf("%s-%d", "githubAction", time.Now().UnixNano())
// escaping the repos if the flag is set to process only one given repository
if repo != "" && repoName != repo {
log.Printf("[repo flag] %s", repo)
log.Printf("[repo] %s", repoName)
continue
}
log.Printf("processing repo: %s", r.Repo["url"])
wg.Add(1)
// process all the repositories in parallel
go func(wg *sync.WaitGroup, result chan Report, r Repository) {
defer wg.Done()
//1. Prepare the repo
url := r["url"]
if err := t.client.prepareRepo(repoPath, branch, url); err != nil {
log.Println("failed to prepare the repo")
result <- Report{url, err}
clearUp(repoPath)
return
}
// 2. render the template write it the repo path
if err := renderTemplate(r, repoPath); err != nil {
result <- Report{url, err}
clearUp(repoPath)
return
}
// 3. push and commit
if err := t.client.push(branch, url); err != nil {
result <- Report{url, err}
clearUp(repoPath)
return
}
// clean up
if dryRun, _ := strconv.ParseBool(os.Getenv(DryRun)); !dryRun {
clearUp(repoPath)
}
// everything went well publish report in the chanel
result <- Report{url, nil}
}(&wg, reportChan, r.Repo)
}
// wait for all the reports to come through
wg.Wait()
close(reportChan)
// print out the report
reports := make([]Report, len(t.conf.Repositories), len(t.conf.Repositories))
for r := range reportChan {
if r.err != nil {
log.Printf("failed to process the repo: %v with error: %v %v", r.name, r.err, "❌")
reports = append(reports, r)
} else {
log.Printf("repo: %s was successfully processed: %v", r.name, "✅")
}
}
log.Println("successfully completed processing of all the repositories")
return reports
}
func renderTemplate(repo Repository, repoLocation string) error {
gitHubDir := fmt.Sprintf("%s/%s", repoLocation, ".github")
workflowDir := fmt.Sprintf("%s/%s", repoLocation, ".github/workflows")
os.Mkdir(gitHubDir, os.ModePerm)
os.Mkdir(workflowDir, os.ModePerm)
err := filepath.Walk("templates/", func(path string, info os.FileInfo, err error) error {
if filepath.Ext(path) == ".yml" {
templateBytes, err := ioutil.ReadFile(path)
t := template.Must(template.New("githubAction").Funcs(templateFunc()).Delims("{[", "]}").Parse(string(templateBytes)))
//overwrite the config file with the template
filePath := fmt.Sprintf("%s/.github/workflows/%s", repoLocation, filepath.Base(path))
log.Printf("processing template: %s", filePath)
banner, err := ioutil.ReadFile("banner")
fileToWrite, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
fileToWrite.Write(banner)
if err != nil {
log.Fatalf("failed to render the template, error: %v", err.Error())
return err
}
defer fileToWrite.Close()
if err = t.Execute(fileToWrite, repo); err != nil {
return err
}
}
return nil
})
if err != nil {
log.Println("failed to load the templates")
return err
}
return nil
}
// Template function to be called from the template
// exp: {[template "DEPLOYMENT" map "Env" "dev" "Name" .Name "AWSAccountNumber" "326458601802" ]}
func templateFunc() template.FuncMap {
return template.FuncMap{
"ToUpper": strings.ToUpper,
"map": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid map call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("map keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
},
}
}
// Asserts the presence of all the required environment variables
func validate() {
// overriding the environement variables if new ones set as flags
token := flag.String(GithubAuthToken, os.Getenv(GithubAuthToken), "Github token")
if *token == "" {
log.Fatalf("%s is required", GithubAuthToken)
}
email := flag.String(GithubEmail, os.Getenv(GithubEmail), "Github email")
if *email == "" {
log.Fatalf("%s is required", GithubEmail)
}
pwd := flag.String(GPGPassword, os.Getenv(GPGPassword), "GPG password")
repo := flag.String(RepoName, "", "repo name to be processed")
dryrun := flag.String(DryRun, "false", "flag to disable pushing the changes to the branch and creating pull request")
flag.Parse()
os.Setenv(GPGPassword, *pwd)
os.Setenv(RepoName, *repo)
os.Setenv(GithubAuthToken, *token)
os.Setenv(GithubEmail, *email)
os.Setenv(DryRun, *dryrun)
}
func clearUp(path string) {
if err := os.RemoveAll(path); err != nil {
log.Printf("failed to delete the generated local repository: %s", path)
}
}