This repository was archived by the owner on Dec 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmanifest.go
240 lines (204 loc) · 6.3 KB
/
manifest.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package bagins
/*
"Oft in lies truth is hidden."
- Glorfindel
*/
import (
"bufio"
"errors"
"fmt"
"github.com/APTrust/bagins/bagutil"
"hash"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
/*
Manifest represents information about a BagIt manifest file. As of BagIt spec
0.97 this means only manifest-<algo>.txt and tagmanifest-<algo>.txt files.
For more information see:
manifest: http://tools.ietf.org/html/draft-kunze-bagit-09#section-2.1.3
tagmanifest: http://tools.ietf.org/html/draft-kunze-bagit-09#section-2.2.1
*/
type Manifest struct {
name string // Path to the manifest file
manifestType string // payload manifest or tag manifest?
Data map[string]string // Key is file path, value is checksum
hashName string
hashFunc func() hash.Hash
}
const (
PayloadManifest = "payload_manifest"
TagManifest = "tag_manifest"
)
// Returns a pointer to a new manifest or returns an error if improperly named.
func NewManifest(pathToFile string, hashName string, manifestType string) (*Manifest, error) {
if manifestType != PayloadManifest && manifestType != TagManifest {
return nil, fmt.Errorf("Param manifestType must be either bagins.PayloadManifest " +
"or bagins.TagManifest")
}
if _, err := os.Stat(filepath.Dir(pathToFile)); err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Unable to create manifest. Path does not exist: %s", pathToFile)
} else {
return nil, fmt.Errorf("Unexpected error creating manifest: %s", err)
}
}
m := new(Manifest)
m.hashName = strings.ToLower(hashName)
hashFunc, err := bagutil.LookupHash(hashName)
if err != nil {
return nil, err
}
m.hashFunc = hashFunc
m.Data = make(map[string]string)
// Older versions allow pathToFile to be empty...
if !strings.HasSuffix(pathToFile, "manifest-" + hashName + ".txt") {
if manifestType == PayloadManifest {
pathToFile = filepath.Join(pathToFile, "manifest-" + m.hashName +".txt")
} else {
pathToFile = filepath.Join(pathToFile, "tagmanifest-" + m.hashName + ".txt")
}
}
m.name = pathToFile
m.manifestType = PayloadManifest
if manifestType == TagManifest {
m.manifestType = TagManifest
}
return m, nil
}
/*
Opens a manifest file, parses attemps to parse the hashtype from the filename, parses
the file contents and returns a pointer to a Manifest. Error slice may comprise multiple
parsing errors when attempting to read data for fault tolerance.
*/
func ReadManifest(name string) (*Manifest, []error) {
var errs []error
hashName, err := parseAlgoName(name)
if err != nil {
return nil, append(errs, err)
}
file, err := os.Open(name)
if err != nil {
return nil, append(errs, err)
}
data, e := parseManifestData(file)
if e != nil {
errs = append(errs, e...)
}
manifestType := PayloadManifest
if strings.HasPrefix(path.Base(name), "tagmanifest-") {
manifestType = TagManifest
}
m, err := NewManifest(name, hashName, manifestType)
if err != nil {
return nil, append(errs, err)
}
m.Data = data
return m, errs
}
/*
Calculates a checksum for files listed in the manifest and compares it to the value
stored in manifest file. Returns an error for each file that fails the fixity check.
*/
func (m *Manifest) RunChecksums() []error {
var invalidSums []error
for key, sum := range m.Data {
pathToFile := filepath.Join(filepath.Dir(m.name), key)
fileChecksum, err := bagutil.FileChecksum(pathToFile, m.hashFunc())
if sum != fileChecksum {
invalidSums = append(invalidSums, fmt.Errorf("File checksum %s is not valid for %s:%s", sum, key, fileChecksum))
}
if err != nil {
invalidSums = append(invalidSums, err)
}
}
return invalidSums
}
// Writes key value pairs to a manifest file.
func (m *Manifest) Create() error {
if m.Name() == "" {
return errors.New("Manifest must have values for basename and algo set to create a file.")
}
// Create directory if needed.
basepath := filepath.Dir(m.name)
if err := os.MkdirAll(basepath, 0777); err != nil {
return err
}
// Create the tagfile.
fileOut, err := os.Create(m.name)
if err != nil {
return err
}
defer fileOut.Close()
// Write fields and data to the file.
for fName, ckSum := range m.Data {
_, err := fmt.Fprintln(fileOut, ckSum, fName)
if err != nil {
return errors.New("Error writing line to manifest: " + err.Error())
}
}
return nil
}
// Returns the contents of the manifest in the form of a string.
// Useful if you don't want to write directly to disk.
func (m *Manifest) ToString() string {
str := ""
for fName, ckSum := range m.Data {
str += fmt.Sprintf("%s %s\n", ckSum, fName)
}
return str
}
// Returns a sting of the filename for this manifest file based on Path, BaseName and Algo
func (m *Manifest) Name() string {
return filepath.Clean(m.name)
}
// Returns the name of the manifest's hashing algorithm.
// "sha256", "md5", etc.
func (m *Manifest) Algorithm() string {
return m.hashName
}
// Returns the type of manifest. Either 'payload' or 'tag'.
func (m *Manifest) Type() string {
return m.manifestType
}
// Tries to parse the algorithm name from a manifest filename. Returns
// an error if unable to do so.
func parseAlgoName(name string) (string, error) {
filename := filepath.Base(name)
re, err := regexp.Compile(`(^.*\-)(.*)(\.txt$)`)
if err != nil {
return "", err
}
matches := re.FindStringSubmatch(filename)
if len(matches) < 2 {
return "", errors.New("Unable to determine algorithm from filename!")
}
algo := matches[2]
return algo, nil
}
// Reads the contents of file and parses checksum and file information in manifest format as
// per the bagit specification.
func parseManifestData(file *os.File) (map[string]string, []error) {
var errs []error
// See regexp examples at http://play.golang.org/p/_msLJ-lBEu
// Regex matches these reqs from the bagit spec: "One or
// more linear whitespace characters (spaces or tabs) MUST separate
// CHECKSUM from FILENAME." as specified here:
// http://tools.ietf.org/html/draft-kunze-bagit-10#section-2.1.3
re := regexp.MustCompile(`^(\S*)\s*(.*)`)
scanner := bufio.NewScanner(file)
values := make(map[string]string)
for scanner.Scan() {
line := scanner.Text()
if re.MatchString(line) {
data := re.FindStringSubmatch(line)
values[data[2]] = data[1]
} else {
errs = append(errs, fmt.Errorf("Unable to parse data from line: %s", line))
}
}
return values, errs
}