2022-09-18 16:49:34 +02:00
|
|
|
package actions
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"time"
|
|
|
|
|
2022-09-21 22:55:52 +02:00
|
|
|
"git.front.kjuulh.io/kjuulh/octopush/internal/schema"
|
|
|
|
"git.front.kjuulh.io/kjuulh/octopush/internal/services/providers"
|
|
|
|
"git.front.kjuulh.io/kjuulh/octopush/internal/services/storage"
|
2022-09-18 16:49:34 +02:00
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
ActionCreatorOps struct {
|
|
|
|
RepositoryUrl string
|
|
|
|
Branch string
|
|
|
|
Path string
|
|
|
|
}
|
|
|
|
|
|
|
|
ActionCreator struct {
|
|
|
|
logger *zap.Logger
|
|
|
|
storage *storage.Service
|
2022-09-21 22:55:52 +02:00
|
|
|
git *providers.GoGit
|
2022-09-18 16:49:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
ActionCreatorDeps interface {
|
|
|
|
GetStorageService() *storage.Service
|
2022-09-21 22:55:52 +02:00
|
|
|
GetGitProvider() *providers.GoGit
|
2022-09-18 16:49:34 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewActionCreator(logger *zap.Logger, deps ActionCreatorDeps) *ActionCreator {
|
|
|
|
return &ActionCreator{
|
|
|
|
logger: logger,
|
|
|
|
storage: deps.GetStorageService(),
|
|
|
|
git: deps.GetGitProvider(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ac *ActionCreator) Prepare(ctx context.Context, ops *ActionCreatorOps) (*Action, error) {
|
|
|
|
area, err := ac.storage.CreateArea(ctx)
|
|
|
|
if err != nil {
|
|
|
|
ac.logger.Error("failed to allocate area", zap.Error(err))
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
cloneCtx, _ := context.WithTimeout(ctx, time.Second*10)
|
|
|
|
_, err = ac.git.CloneBranch(cloneCtx, area, ops.RepositoryUrl, ops.Branch)
|
|
|
|
if err != nil {
|
|
|
|
ac.logger.Error("could not clone repo", zap.Error(err))
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
executorUrl := path.Join(area.Path, ops.Path)
|
|
|
|
if _, err = os.Stat(executorUrl); os.IsNotExist(err) {
|
|
|
|
return nil, fmt.Errorf("path is invalid: %s", ops.Path)
|
|
|
|
}
|
|
|
|
|
2022-09-21 22:55:52 +02:00
|
|
|
contents, err := os.ReadFile(path.Join(executorUrl, "octopush.yml"))
|
2022-09-18 16:49:34 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-09-21 22:55:52 +02:00
|
|
|
octopushSchema, err := schema.Unmarshal(string(contents))
|
2022-09-18 16:49:34 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ac.logger.Debug("Action creator done")
|
|
|
|
return &Action{
|
2022-09-21 22:55:52 +02:00
|
|
|
Schema: octopushSchema,
|
2022-09-18 16:49:34 +02:00
|
|
|
SchemaPath: executorUrl,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ac *ActionCreator) Cleanup(ctx context.Context, area *storage.Area) {
|
|
|
|
ac.logger.Debug("Removing area", zap.String("path", area.Path))
|
|
|
|
err := ac.storage.RemoveArea(ctx, area)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|