buildr/internal/archive/tar.go

97 lines
1.7 KiB
Go
Raw Normal View History

2023-04-11 20:30:48 +00:00
package archive
import (
"archive/tar"
"errors"
"fmt"
2023-04-11 20:30:48 +00:00
"io"
"io/fs"
"path/filepath"
"code.icb4dc0.de/buildr/buildr/internal/ignore"
2023-04-11 20:30:48 +00:00
)
var ErrEmptyArchive = errors.New("no files were added to the archive")
2023-04-11 20:30:48 +00:00
type Tar struct {
Ignorer *ignore.Ignorer
root *archiveNode
2023-04-11 20:30:48 +00:00
}
func (t *Tar) Write(writer io.Writer) error {
if t.root == nil {
return ErrEmptyArchive
}
tarWriter := tar.NewWriter(writer)
if err := t.root.writeToTar(tarWriter, t.Ignorer, ""); err != nil {
2023-04-11 20:30:48 +00:00
return err
}
return tarWriter.Close()
}
func (t *Tar) Remove(path string) bool {
if t.root == nil {
return false
}
return t.root.remove(path)
}
func (t *Tar) Add(srcPath, destPath string) error {
2023-04-11 20:30:48 +00:00
if t.root == nil {
t.root = newNode()
}
info, err := t.Ignorer.Stat(srcPath)
2023-04-11 20:30:48 +00:00
if err != nil {
return fmt.Errorf("failed to get file information for %s: %w", srcPath, err)
2023-04-11 20:30:48 +00:00
}
if info.IsDir() {
return t.addDir(srcPath, destPath)
}
t.addFile(srcPath, destPath)
return nil
}
func (t *Tar) addFile(srcPath, destPath string) {
if t.root == nil {
t.root = newNode()
}
t.root.addFile(srcPath, destPath)
}
func (t *Tar) addDir(srcPath, destPath string) error {
if t.root == nil {
t.root = newNode()
2023-04-11 20:30:48 +00:00
}
err := t.Ignorer.WalkDir(srcPath, func(path string, d fs.DirEntry, err error) error {
2023-04-11 20:30:48 +00:00
if err != nil {
return err
}
relativeToSource, err := filepath.Rel(srcPath, path)
if err != nil {
return fmt.Errorf("failed to determine relative path for %s: %w", path, err)
}
2023-04-11 20:30:48 +00:00
if d.IsDir() {
t.root.addDir(filepath.Join(destPath, relativeToSource))
2023-04-11 20:30:48 +00:00
} else {
t.root.addFile(path, filepath.Join(destPath, relativeToSource))
2023-04-11 20:30:48 +00:00
}
return nil
})
if err != nil {
return fmt.Errorf("failed to add dir %s recursively: %w", srcPath, err)
}
return nil
2023-04-11 20:30:48 +00:00
}