aboutsummaryrefslogtreecommitdiff
path: root/tar.go
blob: ba7f3a5861daec70c153d1c3c0a2666aba521db6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"archive/tar"
	"io"
	"os"

	"github.com/n-peugnet/dna-backup/logger"
)

func streamFilesTar(files []File, stream io.WriteCloser) {
	tarStream := tar.NewWriter(stream)
	for _, f := range files {
		file, err := os.Open(f.Path)
		if err != nil {
			logger.Errorf("reading file '%s': %s", f.Path, err)
			continue
		}
		stat, err := file.Stat()
		if err != nil {
			logger.Errorf("getting stat of file '%s': %s", f.Path, err)
			continue
		}
		hdr, err := tar.FileInfoHeader(stat, "")
		if err != nil {
			logger.Errorf("creating tar header for file '%s': %s", f.Path, err)
			continue
		}
		if err := tarStream.WriteHeader(hdr); err != nil {
			logger.Panicf("writing tar header to stream for file '%s': %s", f.Path, err)
		}
		if _, err := io.Copy(tarStream, file); err != nil {
			logger.Panicf("writing file to stream '%s': %s", f.Path, err)
		}
	}
	if err := tarStream.Close(); err != nil {
		logger.Panic("closing tar stream:", err)
	}
	if err := stream.Close(); err != nil {
		logger.Panic("closing stream:", err)
	}
}