about summary refs log tree commit diff stats
path: root/internal/builder/files.go
blob: 57d4d2e8e7274b4b9172848f42197fc0272af784 (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
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
package builder

import (
	"compress/gzip"
	"io"
	"os"

	"github.com/andybalholm/brotli"
)

const (
	gzipLevel   = 6
	brotliLevel = 9
)

type MultiWriteCloser struct {
	writers     []io.WriteCloser
	multiWriter io.Writer
}

func (mw *MultiWriteCloser) Write(p []byte) (n int, err error) {
	return mw.multiWriter.Write(p)
}

func (mw *MultiWriteCloser) Close() error {
	var lastErr error
	for _, w := range mw.writers {
		err := w.Close()
		if err != nil {
			lastErr = err
		}
	}
	return lastErr
}

func openFileWrite(filename string) (*os.File, error) {
	return os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
}

func openFileGz(filename string) (*gzip.Writer, error) {
	filenameGz := filename + ".gz"
	f, err := openFileWrite(filenameGz)
	if err != nil {
		return nil, err
	}
	return gzip.NewWriterLevel(f, gzipLevel)
}

func openFileBrotli(filename string) (*brotli.Writer, error) {
	filenameBrotli := filename + ".br"
	f, err := openFileWrite(filenameBrotli)
	if err != nil {
		return nil, err
	}
	return brotli.NewWriterLevel(f, brotliLevel), nil
}

func multiOpenFile(filename string) (*MultiWriteCloser, error) {
	r, err := openFileWrite(filename)
	if err != nil {
		return nil, err
	}
	gz, err := openFileGz(filename)
	if err != nil {
		return nil, err
	}
	br, err := openFileBrotli(filename)
	if err != nil {
		return nil, err
	}
	return &MultiWriteCloser{
		writers:     []io.WriteCloser{r, gz, br},
		multiWriter: io.MultiWriter(r, gz, br),
	}, nil
}

func openFileAndVariants(filename string) (io.WriteCloser, error) {
	if compressFiles {
		return multiOpenFile(filename)
	} else {
		return openFileWrite(filename)
	}
}