/
artifact_creator.go
104 lines (93 loc) 路 2.31 KB
/
artifact_creator.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
package features
import (
"archive/zip"
"context"
"fmt"
"io"
"os"
"path/filepath"
"github.com/aws/codecatalyst-runner-cli/command-runner/pkg/common"
"github.com/aws/codecatalyst-runner-cli/command-runner/pkg/runner"
"github.com/rs/zerolog/log"
)
// ArtifactCreator zip up an artifact with all files added to the output directory from the action
func ArtifactCreator(artifactDir string, bindToPath string, envToSet string) runner.Feature {
return func(ctx context.Context, plan runner.Plan, e runner.PlanExecutor) error {
log.Ctx(ctx).Debug().Msg("ENTER ArtifactCreator")
if err := os.MkdirAll(artifactDir, 0755); err != nil {
return err
}
envCfg := plan.EnvironmentConfiguration()
if envCfg.Env == nil {
envCfg.Env = make(map[string]string)
}
if envToSet != "" {
if bindToPath != "" {
envCfg.Env[envToSet] = bindToPath
} else {
envCfg.Env[envToSet] = artifactDir
}
}
if bindToPath != "" {
envCfg.FileMaps = append(envCfg.FileMaps, &runner.FileMap{
SourcePath: artifactDir,
TargetPath: bindToPath,
Type: runner.FileMapTypeBind,
})
}
err := e(ctx)
if zipErr := newArtifactZipper(artifactDir)(ctx); zipErr != nil {
log.Ctx(ctx).Error().Err(zipErr).Msgf("unable to zip artifact")
}
log.Ctx(ctx).Debug().Msg("EXIT ArtifactCreator")
return err
}
}
func newArtifactZipper(artifactDir string) common.Executor {
zipPath := filepath.Join(filepath.Dir(artifactDir), fmt.Sprintf("%s.zip", filepath.Base(artifactDir)))
return func(ctx context.Context) error {
dstFile, err := os.Create(zipPath)
if err != nil {
return err
}
defer dstFile.Close()
zipWriter := zip.NewWriter(dstFile)
defer zipWriter.Close()
count := 0
walker := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
src, err := os.Open(path)
if err != nil {
return err
}
defer src.Close()
relPath, err := filepath.Rel(artifactDir, path)
if err != nil {
return err
}
dst, err := zipWriter.Create(relPath)
if err != nil {
return err
}
_, err = io.Copy(dst, src)
if err != nil {
return err
}
count++
return nil
}
err = filepath.Walk(artifactDir, walker)
if err != nil {
return err
}
if count == 0 {
os.Remove(zipPath)
}
return nil
}
}