artifacts/internal/pull/pull.go
Louis Seubert abdb555e1a
All checks were successful
default / test artifact actions (push) Successful in 29s
wip
2026-09-13 17:39:28 +02:00

133 lines
2.7 KiB
Go

package pull
import (
"archive/zip"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"code.geekeey.de/actions/sdk"
"code.geekeey.de/actions/sdk/artifact"
)
type Action struct {
*sdk.Action
}
func New(action *sdk.Action) *Action {
return &Action{Action: action}
}
type Config struct {
Name string
Path string
}
func ParseConfig(get func(string) string) (*Config, error) {
name := get("name")
if len(name) == 0 {
return nil, fmt.Errorf("input 'name': is empty")
}
path := get("path")
if len(path) == 0 {
path = "."
}
return &Config{Name: name, Path: path}, nil
}
func (a *Action) Run(ctx context.Context) error {
cfg, err := ParseConfig(a.GetInput)
if err != nil {
return err
}
run, job, err := artifact.JobInfo()
if err != nil {
return fmt.Errorf("unable to get job info: %v", err)
}
client := artifact.NewClientFromEnv(os.Getenv)
signed, err := client.GetSignedArtifactURL(ctx, artifact.GetSignedArtifactURLRequest{
RunID: run,
JobRunID: job,
Name: cfg.Name,
})
if err != nil {
return fmt.Errorf("cannot get signed artifact URL: %w", err)
}
if signed.SignedUrl == "" {
return fmt.Errorf("no signed URL for artifact %q", cfg.Name)
}
tmp, err := os.CreateTemp("", "artifact-*.zip")
if err != nil {
return fmt.Errorf("cannot create temporary file: %w", err)
}
defer os.Remove(tmp.Name())
defer tmp.Close()
res, err := artifact.PullBlob(ctx, nil, tmp, signed.SignedUrl)
if err != nil {
return fmt.Errorf("cannot download artifact: %w", err)
}
if err := ExtractArchive(tmp.Name(), cfg.Path); err != nil {
return fmt.Errorf("cannot extract artifact: %w", err)
}
a.Noticef("downloaded artifact %s (%d bytes)", cfg.Name, res.Size)
return nil
}
// ExtractArchive extracts the zip file at zipPath into dest. Entries that would
// escape dest are rejected.
func ExtractArchive(zipPath, dest string) error {
r, err := zip.OpenReader(zipPath)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
if err := extractFile(f, dest); err != nil {
return err
}
}
return nil
}
func extractFile(f *zip.File, dest string) error {
cleanDest := filepath.Clean(dest)
target := filepath.Join(cleanDest, f.Name)
if target != cleanDest && !strings.HasPrefix(target, cleanDest+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path %q", f.Name)
}
if f.FileInfo().IsDir() {
return os.MkdirAll(target, 0o755)
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, rc)
return err
}