File: tarwriter.go

package info (click to toggle)
golang-github-tonistiigi-fsutil 0.0~git20240424.91a3fc4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 664 kB
  • sloc: sh: 59; makefile: 5
file content (85 lines) | stat: -rw-r--r-- 1,813 bytes parent folder | download | duplicates (11)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package fsutil

import (
	"archive/tar"
	"context"
	"io"
	"os"
	"path/filepath"
	"strings"
	"syscall"

	"github.com/pkg/errors"
	"github.com/tonistiigi/fsutil/types"
)

func WriteTar(ctx context.Context, fs FS, w io.Writer) error {
	tw := tar.NewWriter(w)
	err := fs.Walk(ctx, "/", func(path string, entry os.DirEntry, err error) error {
		if err != nil && !errors.Is(err, os.ErrNotExist) {
			return err
		}

		fi, err := entry.Info()
		if err != nil {
			return err
		}
		stat, ok := fi.Sys().(*types.Stat)
		if !ok {
			return errors.WithStack(&os.PathError{Path: path, Err: syscall.EBADMSG, Op: "fileinfo without stat info"})
		}
		hdr, err := tar.FileInfoHeader(fi, stat.Linkname)
		if err != nil {
			return err
		}

		name := filepath.ToSlash(path)
		if fi.IsDir() && !strings.HasSuffix(name, "/") {
			name += "/"
		}
		hdr.Name = name

		hdr.Uid = int(stat.Uid)
		hdr.Gid = int(stat.Gid)
		hdr.Devmajor = stat.Devmajor
		hdr.Devminor = stat.Devminor
		hdr.Linkname = stat.Linkname
		if hdr.Linkname != "" {
			hdr.Size = 0
			if fi.Mode()&os.ModeSymlink != 0 {
				hdr.Typeflag = tar.TypeSymlink
			} else {
				hdr.Typeflag = tar.TypeLink
			}
		}

		if len(stat.Xattrs) > 0 {
			hdr.PAXRecords = map[string]string{}
		}
		for k, v := range stat.Xattrs {
			hdr.PAXRecords["SCHILY.xattr."+k] = string(v)
		}

		if err := tw.WriteHeader(hdr); err != nil {
			return errors.Wrapf(err, "failed to write file header %s", name)
		}

		if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 && hdr.Linkname == "" {
			rc, err := fs.Open(path)
			if err != nil {
				return err
			}
			if _, err := io.Copy(tw, rc); err != nil {
				return errors.WithStack(err)
			}
			if err := rc.Close(); err != nil {
				return errors.WithStack(err)
			}
		}
		return nil
	})
	if err != nil {
		return err
	}
	return tw.Close()
}