~emersion/drmdb

drmdb/snapshot.go -rw-r--r-- 1.2 KiB
b2b4bd96Simon Ser Upgrade dependencies 25 days ago
                                                                                
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 drmdb

import (
	"archive/tar"
	"compress/gzip"
	_ "embed"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"git.sr.ht/~emersion/drmdb/database"
)

//go:embed LICENSE
var license string

func writeSnapshotFile(tw *tar.Writer, p string, fi os.FileInfo) error {
	f, err := os.Open(p)
	if err != nil {
		return err
	}
	defer f.Close()

	if fi == nil {
		fi, err = f.Stat()
		if err != nil {
			return err
		}
	}

	h, err := tar.FileInfoHeader(fi, "")
	if err != nil {
		return err
	}

	if err := tw.WriteHeader(h); err != nil {
		return err
	}

	_, err = io.Copy(tw, f)
	return err
}

func writeLicenseFile(tw *tar.Writer) error {
	h := tar.Header{
		Name: "LICENSE",
		Mode: 0644,
		Size: int64(len(license)),
	}
	if err := tw.WriteHeader(&h); err != nil {
		return err
	}

	_, err := io.WriteString(tw, license)
	return err
}

func writeSnapshot(w io.Writer) error {
	gw := gzip.NewWriter(w)
	defer gw.Close()

	tw := tar.NewWriter(gw)
	defer tw.Close()

	if err := writeLicenseFile(tw); err != nil {
		return err
	}

	files, err := ioutil.ReadDir(database.Dir)
	if err != nil {
		return err
	}

	for _, fi := range files {
		p := filepath.Join(database.Dir, fi.Name())
		if err := writeSnapshotFile(tw, p, fi); err != nil {
			return err
		}
	}

	return nil
}