-
Notifications
You must be signed in to change notification settings - Fork 3
/
oxum.go
96 lines (79 loc) · 1.9 KB
/
oxum.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
package go_bagit
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type Oxum struct {
Size int64
Count int
}
func (o Oxum) String() string {
return fmt.Sprintf("%d.%d", o.Size, o.Count)
}
func ParseOxumString(oxum string) (Oxum, error) {
o := Oxum{}
splitOxum := strings.Split(oxum, ".")
var err error
o.Size, err = strconv.ParseInt(splitOxum[0], 10, 64)
if err != nil {
return o, err
}
o.Count, err = strconv.Atoi(splitOxum[1])
if err != nil {
return o, err
}
return o, nil
}
func GetOxum(bagLocation string) (string, error) {
f, err := os.Open(filepath.Join(bagLocation, "bag-info.txt"))
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
before, after, _ := strings.Cut(line, ":")
if before == "Payload-Oxum" {
return strings.TrimSpace(after), nil
}
}
return "", fmt.Errorf("%s did not contain a payload-oxum", f.Name())
}
func ValidateOxum(bagLocation string, oxum string) error {
storedOxum, err := ParseOxumString(oxum)
if err != nil {
return err
}
calculatedOxum, err := CalculateOxum(bagLocation)
if err != nil {
return err
}
if calculatedOxum.Size != storedOxum.Size || calculatedOxum.Count != storedOxum.Count {
return fmt.Errorf("%s is invalid: Payload-Oxum validation failed. Expected %d files and %v bytes but found %d files and %v bytes",
bagLocation, storedOxum.Count, storedOxum.Size, calculatedOxum.Count, calculatedOxum.Size)
}
return nil
}
func CalculateOxum(bagLocation string) (Oxum, error) {
dataDir := filepath.Join(bagLocation, "data")
var size int64 = 0
var count int = 0
if err := filepath.Walk(dataDir, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
size += info.Size()
count += 1
}
return err
}); err != nil {
return Oxum{}, err
}
return Oxum{size, count}, nil
}