Skip to content

Commit

Permalink
move domain logic into workspace package
Browse files Browse the repository at this point in the history
  • Loading branch information
ianic committed Oct 16, 2021
1 parent cf99a9b commit 5e9e828
Show file tree
Hide file tree
Showing 14 changed files with 156 additions and 148 deletions.
2 changes: 1 addition & 1 deletion api/destroy/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (d *Destroy) terraformData() dto.StageTemplate {
Stage: d.StageName,
Bucket: d.Bucket,
Region: d.Region,
BucketPrefix: workspace.StageBucketPrefix(d.ProjectName, d.StageName),
BucketPrefix: d.BucketPrefix,
}
}

Expand Down
9 changes: 5 additions & 4 deletions api/dto/dto.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ type DeployResponse struct {
}

type DestroyRequest struct {
Bucket string
Region string
ProjectName string
StageName string
Bucket string
Region string
ProjectName string
StageName string
BucketPrefix string
}

const (
Expand Down
44 changes: 22 additions & 22 deletions cli/cmd/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,27 @@ func New(a Args) (*Cmd, error) {
}

func NewWithStage(fs *workspace.FileStore, stage *workspace.Stage) (*Cmd, error) {
awsClient, err := project.AWSClient(stage.Account(), stage.Project(), stage)
if err != nil {
return nil, log.Wrap(err)
}
d := &Cmd{
store: fs,
stage: stage,
awsClient: awsClient,
path: fs.ProjectRoot(),
store: fs,
stage: stage,
path: fs.ProjectRoot(),
}
if err := d.setAWSclient(); err != nil {
return nil, err
}
return d, nil
}

func (d *Cmd) setAWSclient() error {
stage := d.stage
awsClient, err := project.AWSClient(stage.Account(), stage.Project(), stage)
if err != nil {
return log.Wrap(err)
}
d.awsClient = awsClient
return nil
}

func (d *Cmd) Deploy() error {
if err := d.deploy(); err != nil {
return log.WithUserMessage(err, "Failed")
Expand All @@ -87,9 +95,7 @@ func (d *Cmd) deploy() error {
return log.Wrap(err)
}
ui.Info("")
if err := d.applyConfiguration(); err != nil {
return log.Wrap(err)
}
d.applyConfiguration()
if !d.HasUpdates() {
ui.Info("No changes - nothing to deploy")
return nil
Expand All @@ -116,6 +122,9 @@ func (d *Cmd) deploy() error {
}

if d.publicDiff.hasUpdates() {
if err := d.setAWSclient(); err != nil {
return log.Wrap(err)
}
ui.Info("==> Updating public content...")
if err := d.uploadTimer(func() error { return d.updatePublicSiteContent() }); err != nil {
return log.Wrap(err)
Expand All @@ -135,17 +144,8 @@ func (d *Cmd) deploy() error {
return nil
}

func (d *Cmd) applyConfiguration() error {
envChanged, err := d.stage.ApplyEnv(
d.path,
d.stage.Project().Name,
d.stage.Account().ResourceSuffix(),
)
if err != nil {
return log.Wrap(err)
}
d.configChanged = envChanged
return nil
func (d *Cmd) applyConfiguration() {
d.configChanged = d.stage.ApplyEnv()
}

func (d *Cmd) HasUpdates() bool {
Expand Down
11 changes: 3 additions & 8 deletions cli/cmd/deploy/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"github.com/mantil-io/mantil/cli/log"
"github.com/mantil-io/mantil/cli/ui"
"github.com/mantil-io/mantil/shell"
"github.com/mantil-io/mantil/workspace"
)

func (d *Cmd) functionUpdates() (resourceDiff, error) {
Expand All @@ -30,11 +29,8 @@ func (d *Cmd) functionUpdates() (resourceDiff, error) {
stageFuncs = append(stageFuncs, f.Name)
}
diff.added = diffArrays(localFuncs, stageFuncs)
for _, a := range diff.added {
if !workspace.FunctionNameAvailable(a) {
return diff, fmt.Errorf("api name \"%s\" is reserved", a)
}
d.stage.AddFunction(a)
if rerr := d.stage.AddFunctions(diff.added); rerr != nil {
return diff, log.WithUserMessage(rerr, "\"%s\" is reserved name", rerr.Name)
}
diff.removed = diffArrays(stageFuncs, localFuncs)
d.stage.RemoveFunctions(diff.removed)
Expand Down Expand Up @@ -79,8 +75,7 @@ func (d *Cmd) prepareFunctionsForDeploy() ([]string, error) {
}
if hash != f.Hash {
updatedFunctions = append(updatedFunctions, f.Name)
f.Hash = hash
f.SetS3Key(fmt.Sprintf("%s/functions/%s-%s.zip", workspace.StageBucketPrefix(d.stage.Project().Name, d.stage.Name), f.Name, f.Hash))
f.SetHash(hash)
d.functionsForUpload = append(d.functionsForUpload, uploadData{
name: f.Name,
s3Key: f.S3Key,
Expand Down
2 changes: 1 addition & 1 deletion cli/cmd/generate/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (

func Api(name string, methods []string) error {
if !workspace.FunctionNameAvailable(name) {
return log.Wrap(fmt.Errorf("could not generate api - name \"%s\" is reserved", name))
return log.Wrap(fmt.Errorf("Could not generate api - name \"%s\" is reserved", name))
}
projectPath, err := workspace.FindProjectRoot(".")
if err != nil {
Expand Down
7 changes: 5 additions & 2 deletions cli/cmd/project/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,15 @@ func AWSClient(account *workspace.Account, project *workspace.Project, stage *wo
return nil, log.Wrap(err)
}
q := url.Query()
q.Add(dto.ProjectNameQueryParam, project.Name)
// TODO zasto postavljemo prefix na razini projekta koji je use case da to gledam
logGroupPrefix := project.LogGroupPrefix()
q.Add(dto.CliRoleQueryParam, account.CliRole)
if stage != nil {
q.Add(dto.StageNameQueryParam, stage.Name)
logGroupPrefix = stage.LogGroupPrefix()
q.Add(dto.BucketQueryParam, stage.Public.Bucket)
q.Add(dto.BucketQueryParam, account.Bucket)
}
q.Add(dto.LogGroupsPrefixQueryParam, aws.LambdaLogGroup(logGroupPrefix))
url.RawQuery = q.Encode()

token := func() string {
Expand Down
9 changes: 5 additions & 4 deletions cli/cmd/stage.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,11 @@ func (c *stageCmd) destroyStage(stage *workspace.Stage) error {
func (c *stageCmd) destroyRequest(stage *workspace.Stage) error {
account := stage.Account()
req := &dto.DestroyRequest{
Bucket: account.Bucket,
Region: account.Region,
ProjectName: c.project.Name,
StageName: stage.Name,
Bucket: account.Bucket,
Region: account.Region,
ProjectName: c.project.Name,
StageName: stage.Name,
BucketPrefix: stage.BucketPrefix(),
}
backend, err := project.Backend(account)
if err != nil {
Expand Down
5 changes: 5 additions & 0 deletions workspace/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ func (f *Function) SetS3Key(key string) {
f.S3Key = key
}

func (f *Function) SetHash(hash string) {
f.Hash = hash
f.S3Key = fmt.Sprintf("%s/functions/%s-%s.zip", f.stage.BucketPrefix(), f.Name, f.Hash)
}

func (f *Function) LambdaName() string {
return fmt.Sprintf("%s-%s-%s-%s",
f.stage.project.Name,
Expand Down
2 changes: 2 additions & 0 deletions workspace/mantil.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
)

// TODO remove
// used in ws, set env variable of that function to know the name of other lambda function
func RuntimeResource(v ...string) string {
r := "mantil"
for _, n := range v {
Expand Down
50 changes: 9 additions & 41 deletions workspace/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"path/filepath"

"github.com/mantil-io/mantil/cli/log"
"gopkg.in/yaml.v2"
)

const (
Expand All @@ -27,9 +26,10 @@ const (
)

type Project struct {
Name string `yaml:"name"` // required
Stages []*Stage `yaml:"stages,omitempty"`
workspace *Workspace
Name string `yaml:"name"`
Stages []*Stage `yaml:"stages,omitempty"`
workspace *Workspace
environment *EnvironmentConfig
}

func (p *Project) ResourceTags() map[string]string {
Expand All @@ -38,32 +38,6 @@ func (p *Project) ResourceTags() map[string]string {
}
}

func SaveProject(p *Project, basePath string) error {
buf, err := yaml.Marshal(p)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Join(basePath, configDir), os.ModePerm); err != nil {
return err
}
if err := ioutil.WriteFile(configPath(basePath), buf, 0644); err != nil {
return err
}
return nil
}

func LoadProject(basePath string) (*Project, error) {
buf, err := ioutil.ReadFile(configPath(basePath))
if err != nil {
return nil, err
}
p := &Project{}
if err := yaml.Unmarshal(buf, p); err != nil {
return nil, err
}
return p, nil
}

func configPath(basePath string) string {
return filepath.Join(basePath, configDir, configName)
}
Expand Down Expand Up @@ -141,17 +115,6 @@ func (p *Project) NewStage(stageName, accountName string) (*Stage, error) {
return stage, nil
}

// TODO: workspace ovo se moze izbaciti tamo gdje se poziva
func (p *Project) UpsertStage(stage *Stage) {
for idx, s := range p.Stages {
if s.Name == stage.Name {
p.Stages[idx] = stage
return
}
}
p.Stages = append(p.Stages, stage)
}

func (p *Project) RemoveStage(stageName string) {
for idx, s := range p.Stages {
if s.Name == stageName {
Expand All @@ -160,6 +123,7 @@ func (p *Project) RemoveStage(stageName string) {
}
}

// TODO remove use function.LambdaName
func ProjectResource(projectName string, v ...string) string {
r := projectName
for _, n := range v {
Expand All @@ -168,6 +132,10 @@ func ProjectResource(projectName string, v ...string) string {
return r
}

func (p *Project) LogGroupPrefix() string {
return p.Name
}

func FindProjectRoot(initialPath string) (string, error) {
currentPath := initialPath
for {
Expand Down
42 changes: 15 additions & 27 deletions workspace/stage.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,7 @@ package workspace

import (
"fmt"
"io/ioutil"
"strings"

"github.com/mantil-io/mantil/cli/log"
"gopkg.in/yaml.v2"
)

const (
Expand Down Expand Up @@ -71,25 +67,13 @@ func (s *Stage) Project() *Project {
return s.project
}

// TODO switch to above method
func StageBucketPrefix(projectName, stageName string) string {
return fmt.Sprintf("stages/%s/%s", projectName, stageName)
}
func (s *Stage) ApplyEnv() bool {
ec := s.project.environment

func (s *Stage) ApplyEnv(basePath, projectName, workspaceKey string) (bool, error) {
path := environmentConfigPath(basePath)
buf, err := ioutil.ReadFile(path)
if err != nil {
return false, log.Wrap(err)
}
ec := &EnvironmentConfig{}
if err := yaml.Unmarshal(buf, ec); err != nil {
return false, log.Wrap(err)
}
changed := false
for _, f := range s.Functions {
envChain := []map[string]string{
s.defaultEnv(projectName, workspaceKey),
s.defaultEnv(),
ec.Project.Env,
}
for _, sc := range ec.Project.Stages {
Expand All @@ -110,26 +94,30 @@ func (s *Stage) ApplyEnv(basePath, projectName, workspaceKey string) (bool, erro
}
changed = f.mergeEnv(envChain...)
}
return changed, nil
return changed
}

func (s *Stage) defaultEnv(projectName, workspaceKey string) map[string]string {
func (s *Stage) defaultEnv() map[string]string {
env := map[string]string{
EnvProjectName: projectName,
EnvProjectName: s.project.Name,
EnvStageName: s.Name,
EnvWorkspaceKey: workspaceKey,
EnvWorkspaceKey: s.Account().ResourceSuffix(),
EnvMantilStageTags: strings.Join(MantilStageTags, ","),
}
return env
}

func (s *Stage) AddFunctionDefaults() {
for _, f := range s.Functions {
f.addDefaults()
func (s *Stage) AddFunctions(names []string) *ErrReservedName {
for _, name := range names {
if !FunctionNameAvailable(name) {
return &ErrReservedName{Name: name}
}
s.addFunction(name)
}
return nil
}

func (s *Stage) AddFunction(name string) {
func (s *Stage) addFunction(name string) {
f := &Function{
Name: name,
stage: s,
Expand Down
10 changes: 10 additions & 0 deletions workspace/validate.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package workspace

import "fmt"

var reservedFunctionNames = []string{
"public",
}
Expand All @@ -12,3 +14,11 @@ func FunctionNameAvailable(name string) bool {
}
return true
}

type ErrReservedName struct {
Name string
}

func (e *ErrReservedName) Error() string {
return fmt.Sprintf("name \"%s\" is reserved", e.Name)
}
Loading

0 comments on commit 5e9e828

Please sign in to comment.