package test import ( "archive/tar" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" "testing" "gotest.tools/v3/fs" "edge-infra.dev/pkg/sds/patching/common" ) func NewConfig(t *testing.T) common.Config { dir := fs.NewDir(t, "testing") MountPath := dir.Path() c := common.Config{ MountPath: MountPath, ArtefactsPath: MountPath + "/versions", ArtefactsTempPath: MountPath + "/versions/.tmp", LiveBootPath: MountPath + "/live", ScriptsPath: MountPath + "/patching", ScriptsTempPath: MountPath + "/patching/.tmp", EnvFilePath: MountPath + "/patching/patching.env", LegacyScriptsPath: MountPath + "/upgrade", BootFiles: MountPath + "/boot/", ScriptFiles: MountPath + "/patching/", PatchsetMount: MountPath + "/mnt/patchset", RebootPath: MountPath + "/mnt/run/reboot-required", } return c } func CreateFileTree(cfg common.Config) error { items := []string{ cfg.MountPath, cfg.ArtefactsPath, cfg.ArtefactsTempPath, cfg.LiveBootPath, cfg.ScriptsPath, cfg.ScriptsTempPath, cfg.LegacyScriptsPath, cfg.BootFiles, cfg.ScriptFiles, cfg.MountPath + "/mnt", cfg.MountPath + "/mnt/run", cfg.MountPath + "/boot", } for _, item := range items { if err := os.MkdirAll(item, 0744); err != nil { return err } } return nil } func CreateTempFile(dir string, count int) ([]os.File, error) { tempFiles := make([]os.File, count) for i := 0; i < count; i++ { tempFile, err := os.CreateTemp(dir, "") if err != nil { return nil, fmt.Errorf("error creating tempfile: %s", err) } tempFiles[i] = *tempFile tempFile.Close() } return tempFiles, nil } func SetupTarArchive(filePath string, tempFiles []os.File, cfg common.Config) (*os.File, error) { writeArchive, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0744) if err != nil { return nil, fmt.Errorf("error opening archive file: %s", err) } gw := gzip.NewWriter(writeArchive) defer gw.Close() tw := tar.NewWriter(gw) defer tw.Close() for _, f := range tempFiles { file, err := os.Open(f.Name()) if err != nil { return nil, fmt.Errorf("error opening tempfile: %s", err) } tempFileInfo, err := file.Stat() if err != nil { return nil, fmt.Errorf("%s", err) } header, err := tar.FileInfoHeader(tempFileInfo, tempFileInfo.Name()) if err != nil { return nil, fmt.Errorf("error creating tempfile header: %s", err) } header.Name = strings.TrimPrefix(strings.Replace(file.Name(), cfg.MountPath, "", -1), string(filepath.Separator)) err = tw.WriteHeader(header) if err != nil { return nil, fmt.Errorf("error writing header to archive: %s", err) } _, err = io.Copy(tw, file) if err != nil { return nil, fmt.Errorf("error copying tempfile to archive: %s", err) } if err := file.Close(); err != nil { return nil, fmt.Errorf("error closing tempfile: %s", err) } } readArchive, err := os.OpenFile(filePath, os.O_RDONLY, 0744) if err != nil { return nil, fmt.Errorf("error opening archive file: %s", err) } return readArchive, nil }