-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathproject.go
More file actions
409 lines (356 loc) · 9.9 KB
/
project.go
File metadata and controls
409 lines (356 loc) · 9.9 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package project
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"log/slog"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/evanw/esbuild/pkg/api"
"github.com/sst/sst/v3/internal/fs"
"github.com/sst/sst/v3/internal/util"
"github.com/sst/sst/v3/pkg/flag"
"github.com/sst/sst/v3/pkg/js"
"github.com/sst/sst/v3/pkg/process"
"github.com/sst/sst/v3/pkg/project/provider"
"github.com/sst/sst/v3/pkg/runtime"
"github.com/sst/sst/v3/pkg/runtime/golang"
"github.com/sst/sst/v3/pkg/runtime/node"
"github.com/sst/sst/v3/pkg/runtime/python"
"github.com/sst/sst/v3/pkg/runtime/rust"
"github.com/sst/sst/v3/pkg/runtime/worker"
)
type App struct {
Name string `json:"name"`
Stage string `json:"stage"`
Removal string `json:"removal"`
Providers map[string]interface{} `json:"providers"`
Home string `json:"home"`
Version string `json:"version"`
Protect bool `json:"protect"`
Watch []string `json:"watch"`
TypeIgnore []string `json:"typeIgnore"`
// Deprecated: Backend is now Home
Backend string `json:"backend"`
// Deprecated: RemovalPolicy is now Removal
RemovalPolicy string `json:"removalPolicy"`
}
type Project struct {
version string
lock ProviderLock
root string
config string
app *App
home provider.Home
env map[string]string
loadedProviders map[string]provider.Provider
Runtime *runtime.Collection
}
func Discover() (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
cfgPath, err := fs.FindUp(cwd, "sst.config.ts")
if err != nil {
return "", err
}
err = os.MkdirAll(ResolveWorkingDir(cfgPath), 0755)
if err != nil {
return "", err
}
return cfgPath, nil
}
func ResolveWorkingDir(cfgPath string) string {
return filepath.Join(filepath.Dir(cfgPath), ".sst")
}
func ResolvePlatformDir(cfgPath string) string {
return filepath.Join(ResolveWorkingDir(cfgPath), "platform")
}
func ResolveLogDir(cfgPath string) string {
return filepath.Join(ResolveWorkingDir(cfgPath), "log")
}
type ProjectConfig struct {
Version string
Stage string
Config string
}
var ErrInvalidStageName = fmt.Errorf("ErrInvalidStageName")
var ErrInvalidAppName = fmt.Errorf("ErrInvalidAppName")
var ErrAppNameChanged = fmt.Errorf("ErrAppNameChanged")
var ErrV2Config = fmt.Errorf("ErrV2Config")
var ErrVersionInvalid = fmt.Errorf("ErrVersionInvalid")
type ErrVersionMismatch struct {
Needed string
Received string
}
func (err *ErrVersionMismatch) Error() string {
return "ErrorVersionMismatch"
}
type ErrBuildFailed struct {
msg string
Errors []api.Message
}
func (err *ErrBuildFailed) Error() string {
return err.msg
}
var InvalidStageRegex = regexp.MustCompile(`[^a-zA-Z0-9-]`)
var InvalidAppRegex = regexp.MustCompile(`^[^a-zA-Z]|[^a-zA-Z0-9-]`)
func New(input *ProjectConfig) (*Project, error) {
if InvalidStageRegex.MatchString(input.Stage) {
return nil, ErrInvalidStageName
}
rootPath := filepath.Dir(input.Config)
proj := &Project{
version: input.Version,
root: rootPath,
config: input.Config,
env: map[string]string{},
Runtime: runtime.NewCollection(
input.Config,
node.New(input.Version),
worker.New(),
python.New(),
golang.New(),
rust.New(),
),
}
tmp := proj.PathWorkingDir()
_, err := os.Stat(tmp)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
err := os.Mkdir(tmp, 0755)
if err != nil {
return nil, err
}
}
inputBytes, err := json.Marshal(map[string]string{
"stage": input.Stage,
})
buildResult, err := js.Build(
js.EvalOptions{
Dir: proj.PathRoot(),
Banner: `function $config(input) { return input }`,
Define: map[string]string{
"$input": string(inputBytes),
},
Code: fmt.Sprintf(`
import mod from '%s';
if (mod.stacks || mod.config) {
console.log("~v2")
process.exit(0)
}
console.log("~j" + JSON.stringify(await mod.app({
stage: $input.stage || undefined,
})))`,
filepath.ToSlash(input.Config)),
},
)
if err != nil {
if buildResult.Errors != nil {
return nil, &ErrBuildFailed{msg: err.Error(), Errors: buildResult.Errors}
}
return nil, err
}
defer js.Cleanup(buildResult)
slog.Info("evaluating config")
node := process.Command("node", "--no-warnings", string(buildResult.OutputFiles[1].Path))
output, err := node.CombinedOutput()
slog.Info("config evaluated")
if err != nil {
return nil, fmt.Errorf("Error evaluating config: %w\n%s", err, output)
}
scanner := bufio.NewScanner(bytes.NewReader(output))
for scanner.Scan() {
line := scanner.Text()
if line == "~v2" {
return nil, ErrV2Config
}
if strings.HasPrefix(line, "~j") {
var parsed App
err = json.Unmarshal([]byte(line[2:]), &parsed)
if err != nil {
return nil, err
}
proj.app = &parsed
proj.app.Stage = input.Stage
if proj.app.Providers == nil {
proj.app.Providers = map[string]interface{}{}
}
for name, args := range proj.app.Providers {
if _, ok := args.(bool); ok {
return nil, util.NewReadableError(nil,
fmt.Sprintf(`Setting providers.%s to true is deprecated. Specify the version explicitly instead.`, name),
)
}
if argsString, ok := args.(string); ok {
proj.app.Providers[name] = map[string]interface{}{
"version": argsString,
}
}
if argsMap, ok := args.(map[string]interface{}); ok {
if _, hasVersion := argsMap["version"]; !hasVersion && name != "aws" && name != "cloudflare" {
return nil, util.NewReadableError(nil,
fmt.Sprintf(`Provider %s is missing a version. Specify the version explicitly instead.`, name),
)
}
}
}
if proj.app.Name == "" {
return nil, fmt.Errorf("Project name is required")
}
if InvalidAppRegex.MatchString(proj.app.Name) {
return nil, ErrInvalidAppName
}
// Check if app name has changed by comparing the folder name inside ".pulumi/stacks"
// and the app name in the config file.
stacksDir := filepath.Join(proj.PathWorkingDir(), ".pulumi", "stacks")
files, err := os.ReadDir(stacksDir)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
files = []os.DirEntry{}
}
if len(files) > 0 {
appName := files[0].Name()
if appName != proj.app.Name {
return nil, ErrAppNameChanged
}
}
if proj.app.Home == "" {
return nil, util.NewReadableError(nil, `You must specify a "home" provider in the project configuration file.`)
}
if _, ok := proj.app.Providers[proj.app.Home]; !ok && proj.app.Home != "local" {
proj.app.Providers[proj.app.Home] = map[string]interface{}{}
}
if proj.app.RemovalPolicy != "" {
return nil, util.NewReadableError(nil, `The "removalPolicy" has been renamed to "removal"`)
}
if proj.app.Removal == "" {
proj.app.Removal = "retain"
}
if proj.app.Version != "" && input.Version != "dev" {
constraint, err := semver.NewConstraint(proj.app.Version)
if err != nil {
return nil, ErrVersionInvalid
}
version, err := semver.NewVersion(input.Version)
if err != nil {
return nil, ErrVersionInvalid
}
if !constraint.Check(version) {
return nil, &ErrVersionMismatch{Needed: input.Version, Received: proj.app.Version}
}
}
if proj.app.Removal != "remove" && proj.app.Removal != "retain" && proj.app.Removal != "retain-all" {
return nil, fmt.Errorf("Removal must be one of: remove, retain, retain-all")
}
continue
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
err = proj.loadProviderLock()
if err != nil {
return nil, err
}
return proj, nil
}
func (proj *Project) LoadHome() error {
slog.Info("loading home")
loadedProviders := make(map[string]provider.Provider)
for key, args := range proj.app.Providers {
var match provider.Provider
switch key {
case "cloudflare":
match = &provider.CloudflareProvider{}
case "aws":
match = provider.NewAwsProvider()
}
if match == nil {
continue
}
err := match.Init(proj.app.Name, proj.app.Stage, args.(map[string]interface{}))
if err != nil {
return util.NewReadableError(err, key+": "+err.Error())
}
env, err := match.Env()
if err != nil {
return err
}
for key, value := range env {
proj.env[key] = value
}
loadedProviders[key] = match
}
var home provider.Home
switch proj.app.Home {
case "local":
home = provider.NewLocalHome()
case "aws":
home = provider.NewAwsHome(loadedProviders["aws"].(*provider.AwsProvider))
case "cloudflare":
home = provider.NewCloudflareHome(loadedProviders["cloudflare"].(*provider.CloudflareProvider))
default:
return fmt.Errorf("Home provider %s is invalid", proj.app.Home)
}
err := home.Bootstrap()
if err != nil {
return fmt.Errorf("Error initializing %s:\n %w", proj.app.Home, err)
}
proj.home = home
proj.loadedProviders = loadedProviders
return nil
}
func (p Project) getPath(path ...string) string {
paths := append([]string{p.PathWorkingDir()}, path...)
return filepath.Join(paths...)
}
func (p Project) PathWorkingDir() string {
return filepath.Join(p.root, ".sst")
}
func (p Project) PathPlatformDir() string {
return filepath.Join(p.PathWorkingDir(), "platform")
}
func (p Project) PathRoot() string {
return p.root
}
func (p Project) PathConfig() string {
return p.config
}
func (p Project) Version() string {
return p.version
}
func (p Project) App() *App {
return p.app
}
func (p Project) Backend() provider.Home {
return p.home
}
func (p Project) Env() map[string]string {
return p.env
}
func (p *Project) Provider(name string) (provider.Provider, bool) {
result, ok := p.loadedProviders[name]
return result, ok
}
func (p *Project) Cleanup() error {
if flag.SST_NO_CLEANUP {
return nil
}
return nil
}
func (p *Project) PathLog(name string) string {
if name == "" {
return filepath.Join(p.PathWorkingDir(), "log")
}
return filepath.Join(p.PathWorkingDir(), "log", name+".log")
}