-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
237 lines (205 loc) · 7.33 KB
/
main.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
/*
* MIT License
*
* Copyright (c) 2020 TCorp BV
*
* 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 (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
)
const (
langGo Language = "go"
)
var (
// Which directories in the mono repo that should be ignored
ignoredDirectories = map[string]struct{}{".git": {}, ".idea": {}, "tools": {}}
// Which files and directories in the generated repos that should be ignored
noReset = map[string]struct{}{"README": {}, "README.md": {}, "readme.md": {}, "LICENSE": {}, "license": {}, ".git": {}}
)
// Only "go" supported for now,
type Language string
// Marshalled version of .proto.yaml
type Package struct {
Version string `yaml:"version"`
Languages []LanguageDef `yaml:"languages"`
}
// A language section of .proto.yaml. Contains information about which language code should be generated for and to which repository.
type LanguageDef struct {
// The language, only "go" for now
Language Language `yaml:"language"`
// The repository "https" and ".git" should be omitted for now.
Repository string `yaml:"repository"`
}
// Gets the
func (ld *LanguageDef) RepoURI() string {
return fmt.Sprintf("https://%s.git", ld.Repository)
}
// The definition of an actual package in the file tree
type PackageDef struct {
// The description of the package per .proto.yaml
Package Package
// The directory fileinfo (contains the name of the directory, eg. "greeter"
Directory os.FileInfo
// the list of proto files in this directory, eg. "greeter.proto" (these are not validated!)
Protos []os.FileInfo
}
// Handle the deployment of a subdirectory: Checks that the file contains a.proto.yaml, reads it and deploys to all the target directories.
func (h *Handler) handleDir(dir os.FileInfo) error {
if _, ok := ignoredDirectories[dir.Name()]; ok { // Just skip on the ignored directories
return nil
}
bytes, err := ioutil.ReadFile(filepath.Join(h.Path, dir.Name(), ".proto.yaml"))
if err != nil {
return err
}
var pack Package
if err := yaml.Unmarshal(bytes, &pack); err != nil {
return err
}
packDef := PackageDef{Package: pack, Directory: dir}
// Traverse the files and add .proto files to the Protos field of the PackageDef
contents, err := ioutil.ReadDir(filepath.Join(h.Path, dir.Name()))
for _, content := range contents {
if content.Mode().IsRegular() && filepath.Ext(content.Name()) == ".proto" {
packDef.Protos = append(packDef.Protos, content)
}
}
return h.handlePackage(packDef)
}
// Handles the deployment of all languages in a package (directory)
func (h *Handler) handlePackage(def PackageDef) error {
for _, lang := range def.Package.Languages {
if err := h.handleLang(def, lang); err != nil {
return err
}
}
return nil
}
// Clone the repository, error out if it does not exist. Reset the repository. Generate code into the repository and push the generated code to the repository.
func (h *Handler) handleLang(def PackageDef, lang LanguageDef) error {
fmt.Printf("Handling language %s for %s...\n", lang.Language, def.Directory.Name())
gitDir, err := ioutil.TempDir(os.TempDir(), filepath.Base(h.Path)+"-")
println(gitDir)
//defer func() {
// _ = os.Remove(gitDir)
//}()
if err != nil {
return err
}
cloneCmd := exec.Command("git", "clone", lang.RepoURI(), gitDir)
if err := cloneCmd.Run(); err != nil {
return fmt.Errorf("git clone error: %v. Please make sure %s exists and git has access to it", err, lang.RepoURI())
}
// Remove all contents except the ones in noReset (This way we overwrite the repository)
contents, err := ioutil.ReadDir(gitDir)
if err != nil {
return err
}
for _, content := range contents {
if _, ok := noReset[content.Name()]; ok {
continue
}
_ = os.RemoveAll(filepath.Join(gitDir, content.Name()))
}
for _, protoFile := range def.Protos {
var args []string
switch lang.Language {
case langGo:
args = append(args, "--go_out=plugins=grpc:"+gitDir)
default:
return fmt.Errorf("language %s not found", lang.Language)
}
args = append(args, filepath.Join(def.Directory.Name(), protoFile.Name()))
protocCmd := exec.Command("protoc", args...)
fmt.Printf("Executing %s\n", protocCmd.String())
if str, err := protocCmd.CombinedOutput(); err != nil {
fmt.Printf("%s\n", string(str))
return fmt.Errorf("protoc error: %v", err)
}
}
addCmd := exec.Command("git", "-C", gitDir, "add", "-A", ".")
if err := addCmd.Run(); err != nil {
return fmt.Errorf("git add error: %v", err)
}
commitCmd := exec.Command("git", "-C", gitDir, "commit", "-m", "'Automatically updated library from protorepo'")
if err := commitCmd.Run(); err != nil {
return nil // We do nothing when the commit returns an error, we assume this means "nothing to commit"
}
tagCmd := exec.Command("git", "-C", gitDir, "tag", def.Package.Version)
if str, err := tagCmd.CombinedOutput(); err != nil {
return fmt.Errorf("git tag error: %v, %s", err, string(str))
}
fmt.Printf("Deploying %s to %s!\n", def.Package.Version, lang.RepoURI())
pushCmd := exec.Command("git", "-C", gitDir, "push", "--tags", "origin", "master")
if err := pushCmd.Run(); err != nil {
return fmt.Errorf("git push error: %v", err)
}
return nil
}
// Manages the deployment of the generated code
type Handler struct {
Version string
// The path to the root directory
Path string
// All subdirectories, these may not contain a .proto.yaml file
Dirs []os.FileInfo
}
// Load in all subdirectories (depth 1)
func (h *Handler) setup() error {
path, err := os.Getwd()
h.Path = filepath.Clean(path)
if err != nil {
return err
}
contents, err := ioutil.ReadDir(h.Path)
for _, content := range contents {
if content.IsDir() {
h.Dirs = append(h.Dirs, content)
}
}
return err
}
// Traverse all directories in the current directory, check that there is a .proto.yaml file and generate code according to it and the proto files in the directory.
func run() error {
h := Handler{}
if err := h.setup(); err != nil {
return err
}
for _, dir := range h.Dirs {
if err := h.handleDir(dir); err != nil {
fmt.Printf("Issue handling .proto.yaml from %s: %v\n", dir.Name(), err)
}
}
return nil
}
// Requires git credentials to be setup by the environment like:
// git config credential.helper '!f() { sleep 1; echo "username=${GIT_USER}"; echo "password=${GIT_PASSWORD}"; }; f'
func main() {
if err := run(); err != nil {
log.Panic(err)
}
}