-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
245 lines (206 loc) · 6.58 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
238
239
240
241
242
243
244
245
package main
import (
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
repotools "github.com/awslabs/aws-go-multi-module-repository-tools"
"github.com/awslabs/aws-go-multi-module-repository-tools/gomod"
"github.com/awslabs/aws-go-multi-module-repository-tools/manifest"
"golang.org/x/mod/modfile"
)
const manifestFileName = "generated.json"
var config = struct {
BuildArtifactPath string
PluginDirectory string
CopyArtifact bool
PrepareTargetDirectory bool
}{}
func init() {
flag.StringVar(&config.BuildArtifactPath, "build", "", "build artifact path")
flag.StringVar(&config.PluginDirectory, "plugin-dir", "go-codegen",
"path individual module source is nested under build artifact.")
flag.BoolVar(&config.CopyArtifact, "copy-artifact", true,
"copies the artifact from the build path to the repo root relative to the artifact's import path")
flag.BoolVar(&config.PrepareTargetDirectory, "prepare-target-dir", true,
"initializes the target directory, deleting previously generated files.")
}
func main() {
flag.Parse()
if len(config.BuildArtifactPath) == 0 {
log.Fatalf("expect build artifact path to be provided")
}
if stat, err := os.Stat(filepath.Join(config.BuildArtifactPath)); err != nil {
log.Fatalf("failed to stat build artifact path: %v", err)
} else if !stat.IsDir() {
log.Fatalf("build artifact path must be a directory")
}
repoRoot, err := repotools.GetRepoRoot()
if err != nil {
log.Fatalf("failed to get repository root: %v", err)
}
rootMod, err := gomod.LoadModuleFile(repoRoot, nil, true)
if err != nil {
log.Fatalf("failed to read repo root go module, %v", err)
}
rootModulePath, err := gomod.GetModulePath(rootMod)
if err != nil {
log.Fatalf("unable to determine repo root module path, %v", err)
}
av := manifest.NewSmithyArtifactPaths(config.PluginDirectory)
if err = filepath.Walk(config.BuildArtifactPath, av.Walk); err != nil {
log.Fatalf("failed to walk build artifacts: %v", err)
}
artifactPaths := av.ArtifactPaths()
if len(artifactPaths) == 0 {
log.Printf("no build artifacts found: %v", err)
return
}
if err := createArtifactModule(artifactPaths, rootModulePath, repoRoot); err != nil {
log.Fatalf("failed to copy build artifacts: %v", err)
}
}
func createArtifactModule(paths []string, rootModulePath string, repoRoot string) error {
for _, artifactPath := range paths {
buildManifest, err := manifest.LoadManifest(filepath.Join(artifactPath, manifestFileName))
if err != nil {
return fmt.Errorf("failed to load manifest: %w", err)
}
if !strings.HasPrefix(buildManifest.Module, rootModulePath) {
return fmt.Errorf("%v is not a sub-module of %v", buildManifest.Module, rootModulePath)
}
var targetPath string
if config.CopyArtifact {
moduleRelativePath := strings.TrimPrefix(strings.TrimPrefix(buildManifest.Module, rootModulePath), "/")
if moduleRelativePath == "" {
moduleRelativePath = "."
}
targetPath = filepath.Join(repoRoot, moduleRelativePath)
} else {
targetPath = filepath.Join(config.BuildArtifactPath, config.PluginDirectory)
}
if config.PrepareTargetDirectory {
if err := prepareTargetDirectory(targetPath, buildManifest); err != nil {
return fmt.Errorf("failed to prepare target directory: %w", err)
}
}
if config.CopyArtifact {
if err := copyBuildArtifactToPath(artifactPath, targetPath, buildManifest); err != nil {
return fmt.Errorf("failed to copy build artifact to target: %w", err)
}
}
generated, err := generateModuleDefinition(buildManifest)
if err != nil {
return fmt.Errorf("failed to generate go module file: %w", err)
}
err = gomod.WriteModuleFile(targetPath, generated)
if err != nil {
return fmt.Errorf("failed to write go module file: %w", err)
}
}
return nil
}
func generateModuleDefinition(m manifest.Manifest) (*modfile.File, error) {
mod := modfile.File{
Syntax: &modfile.FileSyntax{},
}
if err := mod.AddModuleStmt(m.Module); err != nil {
return nil, fmt.Errorf("failed to set module path: %v", err)
}
if err := mod.AddGoStmt(m.Go); err != nil {
return nil, fmt.Errorf("failed to set Go version: %v", err)
}
for depPath, depVersion := range m.Dependencies {
depPath := path.Clean(depPath)
if err := mod.AddRequire(depPath, depVersion); err != nil {
return nil, fmt.Errorf("failed to add dependency %v@%v", depPath, depVersion)
}
}
return &mod, nil
}
func prepareTargetDirectory(path string, buildManifest manifest.Manifest) error {
if _, err := os.Stat(path); err != nil && os.IsNotExist(err) {
return os.MkdirAll(path, 0755)
} else if err != nil {
return err
}
targetManifest, err := manifest.LoadManifest(filepath.Join(path, manifestFileName))
var notFoundErr *manifest.NoManifestFound
if err != nil && !errors.As(err, ¬FoundErr) {
return err
}
var (
targetModule string
cleanupList []string
)
if err == nil {
targetModule = targetManifest.Module
cleanupList = targetManifest.Files
} else {
log.Printf("[WARN] target directory %v is missing generated.json, will only remove files present in build artifact", path)
if ok, err := gomod.IsGoModPresent(path); err != nil {
return err
} else if ok {
moduleFile, err := gomod.LoadModuleFile(path, nil, true)
if err != nil {
return err
}
targetModule, err = gomod.GetModulePath(moduleFile)
if err != nil {
return err
}
if targetModule != buildManifest.Module {
return fmt.Errorf("target module %v does not match build artifact %v", targetModule, buildManifest.Module)
}
}
cleanupList = buildManifest.Files
}
for _, fileName := range cleanupList {
filePath := filepath.Join(path, fileName)
if err := os.Remove(filePath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove %v: %w", filePath, err)
}
}
return nil
}
func copyBuildArtifactToPath(source, target string, m manifest.Manifest) error {
for _, fp := range m.Files {
sfp := filepath.Join(source, fp)
tfp := filepath.Join(target, fp)
if err := copyArtifact(sfp, tfp); err != nil {
return err
}
}
return nil
}
func copyArtifact(sourcePath, targetPath string) (err error) {
dirs, _ := filepath.Split(targetPath)
if len(dirs) != 0 {
err = os.MkdirAll(dirs, 0755)
if err != nil {
return err
}
}
sourceFile, err := os.Open(sourcePath)
if err != nil {
return err
}
defer sourceFile.Close()
targetFile, err := os.OpenFile(targetPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer func() {
fErr := targetFile.Close()
if fErr != nil && err == nil {
err = fErr
}
}()
_, err = io.Copy(targetFile, sourceFile)
return err
}