-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
59 lines (50 loc) · 1.25 KB
/
reader.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
package snapshot
import (
"bufio"
"encoding/json"
"fmt"
"github.com/Miguel-Dorta/gkup-core/pkg/common"
"os"
)
// Reader represents a snapshot reader
type Reader struct {
Meta Metadata
d *json.Decoder
f *os.File
filesRead uint64
}
// NewReader will take the path of a snapshot and return a reader of it
func NewReader(path string) (*Reader, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("error opening snapshot: %w", err)
}
defer f.Close()
r := &Reader{
d: json.NewDecoder(bufio.NewReaderSize(f, 128*1024)),
f: f,
filesRead: 0,
}
if err := r.d.Decode(&r.Meta); err != nil {
return nil, fmt.Errorf("error decoding metadata: %w", err)
}
return r, nil
}
// More returns if there are more files
func (r *Reader) More() bool {
return r.Meta.NumberOfFiles > r.filesRead
}
// Next returns the next file.
// As a consequence of the common.File serialization, the AbsPath of the file returned will be empty.
func (r *Reader) Next() (*common.File, error) {
var f common.File
if err := r.d.Decode(&f); err != nil {
return nil, fmt.Errorf("error decoding file: %w", err)
}
r.filesRead++
return &f, nil
}
// Close closes the reader
func (r *Reader) Close() error {
return r.f.Close()
}