searcherside/core/services/tar_zst_index_archiver.go

52 lines
1.2 KiB
Go
Raw Normal View History

2024-06-06 20:08:51 +00:00
package services
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/klauspost/compress/zstd"
"code.icb4dc0.de/prskr/searcherside/core/ports"
"code.icb4dc0.de/prskr/searcherside/internal/archive"
)
var _ ports.Archiver = (*TarZSTIndexArchiver)(nil)
type TarZSTIndexArchiver struct {
DataDirectory string
}
func (a TarZSTIndexArchiver) ArchiveIndex(req ports.ArchiveIndexRequest) (err error) {
archiveFile, err := os.Create(filepath.Join(a.DataDirectory, strings.Join([]string{req.Hash, req.Type.String(), "tar.zst"}, ".")))
if err != nil {
return fmt.Errorf("failed to create archive file: %w", err)
}
defer func() {
err = errors.Join(err, archiveFile.Close())
}()
encoder, err := zstd.NewWriter(archiveFile, zstd.WithEncoderLevel(zstd.SpeedBestCompression))
if err != nil {
return fmt.Errorf("failed to create zst encoder: %w", err)
}
defer func() {
err = errors.Join(err, encoder.Close())
}()
relativePath, err := filepath.Rel(a.DataDirectory, req.Path)
if err != nil {
return fmt.Errorf("failed to get relative path: %w", err)
}
return archive.TarDirectory(
os.DirFS(a.DataDirectory),
filepath.ToSlash(relativePath),
archiveFile,
)
}