~emersion/drmdb

ref: 1863c385ab10d14368e69b4f91fada6e04e588b7 drmdb/snapshot.go -rw-r--r-- 966 bytes View raw
                                                                                
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
package drmdb

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

const licenseFile = "LICENSE"

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 writeSnapshot(w io.Writer) error {
	gw := gzip.NewWriter(w)
	defer gw.Close()

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

	if err := writeSnapshotFile(tw, licenseFile, nil); err != nil {
		return err
	}

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

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

	return nil
}