feat: added downloading templated archives

This commit is contained in:
David Allen 2025-08-28 12:25:45 -06:00
parent 1ebea8cb73
commit 98f9acad5d
Signed by: towk
GPG key ID: 0430CDBE22619155
5 changed files with 48 additions and 23 deletions

View file

@ -3,6 +3,7 @@ package archive
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"os"
"strings"
@ -37,27 +38,47 @@ func Expand(path string) error {
func addToArchive(tw *tar.Writer, filename string, hooks []makeshift.Hook) error {
var (
hook makeshift.Hook
file *os.File
data any
err error
tempfile = fmt.Sprintf("%s.tmp", filename)
file *os.File
contents []byte
data any
err error
)
// open file to write to archive
file, err = os.Open(filename)
if err != nil {
return err
}
defer file.Close()
// run pre-hooks to modify the contents of the file
// before archiving using plugins
for _, hook := range hooks {
// set the file in the data store before running hook
contents, err = os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read '%s' to download: %v", filename, err)
}
hook.Data.Set("file", contents)
err = hook.Run()
if err != nil {
return err
}
// create temporary file to use to add to archive
hook = hooks[len(hooks)-1]
data, err = hook.Data.Get("out")
if err != nil {
return fmt.Errorf("failed to get output data from '%s' plugin: %v", hook.Plugin.Name(), err)
}
err = os.WriteFile(tempfile, data.([]byte), 0o777)
if err != nil {
return fmt.Errorf("failed to write temporary file: %v", err)
}
}
// open file to write to archive
file, err = os.Open(tempfile)
if err != nil {
return fmt.Errorf("failed to open temporary file: %v", err)
}
defer file.Close()
// get FileInfo for file size, mode, etc.
info, err := file.Stat()
if err != nil {
@ -72,7 +93,7 @@ func addToArchive(tw *tar.Writer, filename string, hooks []makeshift.Hook) error
// create a tar Header from the FileInfo data
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
return fmt.Errorf("failed to create FileInfoHeader: %v", err)
}
// use full path as name (FileInfoHeader only takes the basename) to
@ -86,15 +107,14 @@ func addToArchive(tw *tar.Writer, filename string, hooks []makeshift.Hook) error
return err
}
// take the contents from the last hook and update files
hook = hooks[len(hooks)-1]
data, err = hook.Data.Get("out")
// copy file content to tar archive
_, err = io.Copy(tw, strings.NewReader(string(data.([]byte))))
if err != nil {
return err
}
// copy file content to tar archive
_, err = io.Copy(tw, strings.NewReader(data.(string)))
// delete the temporary file since we're done with it
err = os.Remove(tempfile)
if err != nil {
return err
}