aboutsummaryrefslogtreecommitdiff
path: root/steam/archive.go
blob: 72bab10d9713c5a6ae5d6636c63faed48280ff35 (plain) (blame)
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
package steam

import (
	"archive/tar"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func tarWalkfn(writer *tar.Writer, prefix string) filepath.WalkFunc {
	return func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		f, err := os.Open(path)
		if err != nil {
			return err
		}
		defer f.Close()

		// Let's strip out all of the leading parts of the path
		// to create a tarball realative to the root of the steam library
		tarPth := strings.TrimPrefix(path, prefix)
		tarPth = strings.ReplaceAll(tarPth, "\\", "/")
		tarPth = strings.TrimPrefix(tarPth, "/")

		h := &tar.Header{
			Name: tarPth,
			Size: info.Size(),
			// I don't like it... but it helps with platform compatibility
			Mode:    0664,
			ModTime: info.ModTime(),
		}

		err = writer.WriteHeader(h)
		if err != nil {
			return err
		}

		_, err = io.Copy(writer, f)
		if err != nil {
			return fmt.Errorf("While copying %s: %w", path, err)
		}

		return nil
	}
}