-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
104 lines (89 loc) · 1.89 KB
/
file.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package dotc1z
import (
"errors"
"io"
"os"
"path/filepath"
"syscall"
"github.com/klauspost/compress/zstd"
"go.uber.org/zap"
)
func loadC1z(filePath string, tmpDir string) (string, error) {
workingDir, err := os.MkdirTemp(tmpDir, "c1z")
if err != nil {
return "", err
}
dbFilePath := filepath.Join(workingDir, "db")
dbFile, err := os.Create(dbFilePath)
if err != nil {
return "", err
}
defer dbFile.Close()
if stat, err := os.Stat(filePath); err == nil && stat.Size() != 0 {
c1zFile, err := os.Open(filePath)
if err != nil {
return "", err
}
defer c1zFile.Close()
r, err := NewDecoder(c1zFile)
if err != nil {
return "", err
}
_, err = io.Copy(dbFile, r)
if err != nil {
return "", err
}
err = r.Close()
if err != nil {
return "", err
}
}
return dbFilePath, nil
}
func saveC1z(dbFilePath string, outputFilePath string) error {
if outputFilePath == "" {
return errors.New("c1z: output file path not configured")
}
dbFile, err := os.Open(dbFilePath)
if err != nil {
return err
}
defer func() {
err = dbFile.Close()
if err != nil {
zap.L().Error("failed to close db file", zap.Error(err))
}
// Cleanup the database filepath. This should always be a file within a temp directory, so we remove the entire dir.
err = os.RemoveAll(filepath.Dir(dbFilePath))
if err != nil {
zap.L().Error("failed to remove db dir", zap.Error(err))
}
}()
outFile, err := os.OpenFile(outputFilePath, os.O_RDWR|os.O_CREATE|syscall.O_TRUNC, 0644)
if err != nil {
return err
}
defer outFile.Close()
// Write the magic file header
_, err = outFile.Write(C1ZFileHeader)
if err != nil {
return err
}
c1z, err := zstd.NewWriter(outFile)
if err != nil {
return err
}
_, err = io.Copy(c1z, dbFile)
if err != nil {
return err
}
err = c1z.Flush()
if err != nil {
return err
}
err = c1z.Close()
if err != nil {
return err
}
return nil
}