-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
462 lines (382 loc) · 14.5 KB
/
main.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package main
import (
"errors"
"fmt"
"github.com/nyulibraries/go-ead-indexer/pkg/ead"
"github.com/nyulibraries/go-ead-indexer/pkg/ead/collectiondoc"
"github.com/nyulibraries/go-ead-indexer/pkg/ead/component"
"github.com/nyulibraries/go-ead-indexer/pkg/ead/eadutil"
"github.com/nyulibraries/go-ead-indexer/pkg/util"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"time"
)
const actualFileSuffix = "-add.xml"
const diffFileSuffix = "-add.txt"
const goldenFileSuffix = "-add.txt"
var diffsDirPath string
var eadDirPath string
var goldenFilesDirPath string
var rootPath string
var tmpFilesDirPath string
var httpHeadersRegExp = regexp.MustCompile("(?ms)^POST.*\r\n\r\n")
// For https://jira.nyu.edu/browse/DLFA-243
// Can't use this:
// <em>(?!.*<em>)(.*?)&lt;/unittitle&gt;</em>
// ...because Go does not support negative lookahead. We instead allow this
// regexp to capture the largest match which would include the nested sub-match
// we need to actually work with, and let a separate non-regexp-based process
// take care of the rest.
var emUnittitleMassage = regexp.MustCompile(`<em>(.*?)&lt;/unittitle&gt;</em>`)
// Go \s metachar is [\t\n\f\r ], and does not include NBSP.
// Source: https://pkg.go.dev/regexp/syntax
var multipleConsecutiveWhitespace = regexp.MustCompile(`[\s ]{2}\s*`)
var leadingWhitespaceInFieldContent = regexp.MustCompile(`>[\s ]+`)
var trailingWhitespaceInFieldContent = regexp.MustCompile(`[\s ]+</field>`)
// We need to get the absolute path to this package in order to get the absolute
// path to the tmp/ directory. We don't want the wrong directories clobbered by
// the output if this script is run from somewhere outside of this directory.
func init() {
// The `filename` string is the absolute path to this source file, which should
// be located at the root of the package directory.
_, filename, _, ok := runtime.Caller(0)
if !ok {
log.Panic("ERROR: `runtime.Caller(0)` failed")
}
rootPath = filepath.Dir(filename)
}
func abortBadUsage(err error) {
if err != nil {
log.Println(err.Error())
}
usage()
os.Exit(1)
}
func clean() error {
err := os.RemoveAll(diffsDirPath)
if err != nil {
return err
}
err = os.MkdirAll(diffsDirPath, 0700)
if err != nil {
return err
}
err = os.RemoveAll(tmpFilesDirPath)
if err != nil {
return err
}
err = os.MkdirAll(tmpFilesDirPath, 0700)
if err != nil {
return err
}
_, err = os.Create(filepath.Join(tmpFilesDirPath, ".gitkeep"))
if err != nil {
return err
}
return nil
}
func getEADValue(testEAD string) (string, error) {
return getTestdataFileContents(getEADFilePath(testEAD))
}
func getEADFilePath(testEAD string) string {
return filepath.Join(eadDirPath, testEAD+".xml")
}
func getGoldenFileIDs(eadID string) []string {
goldenFileIDs := []string{}
err := filepath.WalkDir(filepath.Join(goldenFilesDirPath, eadID),
func(path string, dirEntry fs.DirEntry, err error) error {
if !dirEntry.IsDir() &&
filepath.Ext(path) == goldenFileSuffix &&
!strings.HasSuffix(path, "-commit-add") {
goldenFileIDs = append(goldenFileIDs, strings.TrimSuffix(filepath.Base(path),
"-add.txt"))
}
return nil
})
if err != nil {
log.Panic(fmt.Sprintf(`getGoldenFileIDs("%s") failed: %s`, eadID, err))
}
// The slice might already be sorted, but just in case, sort it.
// Sorting helps with gauging progress by tailing the logs, and helps with
// debugging in case log messages don't clearly indicate where an error
// occurred -- in such cases the last successfully tested EAD file lets us
// know where to start looking.
slices.Sort(goldenFileIDs)
return goldenFileIDs
}
func getGoldenFilePath(testEAD string, fileID string) string {
return filepath.Join(goldenFilesDirPath, testEAD, fileID+"-add.txt")
}
func getGoldenFileValue(eadID string, fileID string) (string, error) {
fileContents, err := getTestdataFileContents(getGoldenFilePath(eadID, fileID))
if err != nil {
return "", err
}
xmlBody := httpHeadersRegExp.ReplaceAllString(fileContents, "")
return xmlBody, nil
}
func getTestdataFileContents(filename string) (string, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return filename, err
}
return string(bytes), nil
}
func getTestEADs() []string {
testEADs := []string{}
err := filepath.WalkDir(eadDirPath, func(path string, dirEntry fs.DirEntry, err error) error {
if !dirEntry.IsDir() && filepath.Ext(path) == ".xml" {
repositoryCode := filepath.Base(filepath.Dir(path))
eadID := strings.TrimSuffix(filepath.Base(path), filepath.Ext(path))
testEADs = append(testEADs, fmt.Sprintf("%s/%s", repositoryCode, eadID))
}
return nil
})
if err != nil {
log.Panic(fmt.Sprintf(`getTestEADs() failed: %s`, err))
}
return testEADs
}
func isDirectory(path string) bool {
fileInfo, err := os.Stat(path)
if err != nil {
log.Panic(fmt.Sprintf(`isDirectory("%s") failed with error: %s`, path, err))
}
return fileInfo.IsDir()
}
// https://jira.nyu.edu/browse/DLFA-243
// Applied to all golden files without exception.
func massageGoldenAll(golden string) string {
// DLFA-243: "Convert all " " strings in golden files to actual NBSP characters."
massagedGolden := strings.ReplaceAll(golden, "&nbsp;", " ")
// DLFA-243: "Remove erroneously inserted EAD tags in Solr field content from golden files."
// This is the second part of the massage. The first part is dealt with in
// `massageGoldenFileIDSpecific()`.
// Example of what's being fixed here:
// This:
// <unittitle><title render="italic">Ayuda Medica Internacional</title>(photocopied clippings and notes) <title render="italic"></title></unittitle>
// ...is mangled by v1 indexer into:
// <field name="unittitle_ssm"><em>Ayuda Medica Internacional</em>(photocopied clippings and notes) <em>&lt;/unittitle&gt;</em></field>
//
// This first set of matches might include the nested sub-match we actually
// care about. Go does not support negative lookahead so we settle for this
// wide net casting and then use non-regexp-based processing to take care of
// the rest.
matches := emUnittitleMassage.FindStringSubmatch(massagedGolden)
if len(matches) == 2 {
// Isolate the rightmost match.
lastOccurrenceIndex := strings.LastIndex(matches[0], "<em>")
lastOccurrence := matches[0][lastOccurrenceIndex:]
// Set up the replacement based on the rightmost match.
matches = emUnittitleMassage.FindStringSubmatch(lastOccurrence)
cleanString := "<em></em>" + matches[1]
// Do the replacement everywhere.
massagedGolden = strings.ReplaceAll(massagedGolden, lastOccurrence, cleanString)
} else {
// Do nothing.
}
// Whitespace massages
massagedGolden = strings.ReplaceAll(massagedGolden, "\n", " ")
massagedGolden = multipleConsecutiveWhitespace.ReplaceAllString(
massagedGolden, " ")
massagedGolden = strings.ReplaceAll(massagedGolden,
"</em> <em>", "</em><em>")
massagedGolden = leadingWhitespaceInFieldContent.ReplaceAllString(
massagedGolden, ">")
massagedGolden = trailingWhitespaceInFieldContent.ReplaceAllString(
massagedGolden, `</field>`)
return massagedGolden
}
// https://jira.nyu.edu/browse/DLFA-243
func massageGoldenFileIDSpecific(golden string, fileID string) string {
var massagedGolden = golden
// These changes couldn't be handled by the code which deals with the
// general case for this v1 indexer bug:
// https://jira.nyu.edu/browse/DLFA-211?focusedCommentId=11487878&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11487878
// Since it's only a couple of files, we brute force them.
if fileID == "alba_218aspace_ref45" {
massagedGolden = strings.ReplaceAll(massagedGolden,
"<em>(some with &lt;title render=\"italic\"/&gt;annotations by Friedman)&lt;/unittitle&gt;</em>",
"<em></em>(some with <em></em>annotations by Friedman)",
)
} else if fileID == "alba_236aspace_ref26" {
massagedGolden = strings.ReplaceAll(massagedGolden,
"<em>George Seldes, &lt;title render=\"italic\"&gt;\"</em>",
"<em></em>George Seldes, <em>\"</em>",
)
}
return massagedGolden
}
func parseEADID(testEAD string) string {
return filepath.Base(testEAD)
}
func parseRepositoryCode(testEAD string) string {
return filepath.Dir(testEAD)
}
func setDirectoryPaths() {
args := os.Args
if len(args) < 3 {
abortBadUsage(fmt.Errorf("Wrong number of args"))
}
// Declare `err` instead of doing `eadDirPath, err :=`, which shadows package
// level var `eadDirPath`.
var err error
eadDirPath, err = filepath.Abs(args[1])
// Very basic validation of directories:
// - No error when resolving to absolute path
// - Is a directory and not a symlink -- because `filepath.WalkDir` does not
// work on symlinks.
// - Directory name matches repo name. This is not strictly necessary, because
// we should be able to rename the directory if we want, but this is just
// a one-off test (for now -- maybe we'll make a permanent one later).
// This also has the benefit of preventing possible accidental use of the
// FABified repo, which has a different name.
if err != nil || !isDirectory(eadDirPath) || !strings.HasSuffix(eadDirPath, "findingaids_eads_v2") {
abortBadUsage(fmt.Errorf(`Path "%s" is not a valid findingaids_eads_v2 repo path`, args[1]))
}
goldenFilesDirPath, err = filepath.Abs(args[2])
if err != nil || !isDirectory(goldenFilesDirPath) || !strings.HasSuffix(goldenFilesDirPath, "http-requests") {
abortBadUsage(fmt.Errorf(`Path "%s" is not a valid dlfa-188_v1-indexer-http-requests repo http-requests/ subdirectory`, args[2]))
}
diffsDirPath = filepath.Join(rootPath, "diffs")
tmpFilesDirPath = filepath.Join(rootPath, "tmp", "actual")
}
func testCollectionDocSolrAddMessage(testEAD string,
solrAddMessage collectiondoc.SolrAddMessage) error {
eadID := parseEADID(testEAD)
return testSolrAddMessageXML(testEAD, eadID, fmt.Sprintf("%s", solrAddMessage))
}
func testComponentSolrAddMessage(testEAD string, fileID string,
solrAddMessage component.SolrAddMessage) error {
return testSolrAddMessageXML(testEAD, fileID, fmt.Sprintf("%s", solrAddMessage))
}
func testNoMissingComponents(testEAD string, componentIDs []string) error {
missingComponents := []string{}
goldenFileIDs := getGoldenFileIDs(testEAD)
goldenFileIDs = slices.DeleteFunc(goldenFileIDs, func(goldenFileID string) bool {
return goldenFileID == parseEADID(testEAD)
})
for _, goldenFileID := range goldenFileIDs {
if !slices.Contains(componentIDs, goldenFileID) {
missingComponents = append(missingComponents, goldenFileID)
}
}
if len(missingComponents) > 0 {
slices.SortStableFunc(missingComponents, func(a string, b string) int {
return strings.Compare(a, b)
})
failMessage := fmt.Sprintf("`EAD.Components` for testEAD %s is missing the following component IDs:\n%s",
testEAD, strings.Join(missingComponents, "\n"))
return fmt.Errorf(failMessage)
}
return nil
}
func testSolrAddMessageXML(testEAD string, fileID string,
actualValue string) error {
goldenValue, err := getGoldenFileValue(testEAD, fileID)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// This is a test fail, not a fatal test execution error.
// A missing golden file means that a Solr add message was created
// for a component that shouldn't exist.
return fmt.Errorf("No golden file exists for \"%s\": %s",
fileID, err)
} else {
return fmt.Errorf("Error retrieving golden value for \"%s\": %s",
fileID, err)
}
}
// https://jira.nyu.edu/browse/DLFA-243
massageGoldenValueStep1 := massageGoldenFileIDSpecific(goldenValue, fileID)
massagedGoldenValue := massageGoldenAll(massageGoldenValueStep1)
if actualValue != massagedGoldenValue {
err := writeActualSolrXMLToTmp(testEAD, fileID, actualValue)
if err != nil {
return fmt.Errorf("Error writing actual temp file for test case \"%s/%s\": %s",
testEAD, fileID, err)
}
prettifiedMassagedGolden := eadutil.PrettifySolrAddMessageXML(massagedGoldenValue)
prettifiedActual := eadutil.PrettifySolrAddMessageXML(actualValue)
diff := util.DiffStrings("golden [PRETTIFIED]", prettifiedMassagedGolden,
"actual [PRETTIFIED]", prettifiedActual)
err = writeDiffFile(testEAD, fileID, diff)
if err != nil {
return fmt.Errorf("Error writing diff file for test case \"%s/%s\": %s",
testEAD, fileID, err)
}
return fmt.Errorf("%s golden and actual values do not match\n", fileID)
}
return nil
}
func diffFile(testEAD string, fileID string) string {
return filepath.Join(diffsDirPath, testEAD, fileID+diffFileSuffix)
}
func tmpFile(testEAD string, fileID string) string {
return filepath.Join(tmpFilesDirPath, testEAD, fileID+actualFileSuffix)
}
func usage() {
log.Println("usage: go run main.go [path to findingaids_eads_v2] [path to dlfa-188_v1-indexer-http-requests-xml/http-requests/]")
}
func writeActualSolrXMLToTmp(testEAD string, fileID string, actual string) error {
tmpFile := tmpFile(testEAD, fileID)
err := os.MkdirAll(filepath.Dir(tmpFile), 0755)
if err != nil {
return err
}
return os.WriteFile(tmpFile, []byte(actual), 0644)
}
func writeDiffFile(testEAD string, fileID string, diff string) error {
diffFile := diffFile(testEAD, fileID)
err := os.MkdirAll(filepath.Dir(diffFile), 0755)
if err != nil {
return err
}
return os.WriteFile(diffFile, []byte(diff), 0644)
}
func main() {
setDirectoryPaths()
err := clean()
if err != nil {
log.Panic("clean() error: " + err.Error())
}
testEADs := getTestEADs()
for _, testEAD := range testEADs {
fmt.Printf("[ %s ] Testing %s\n", time.Now().Format("2006-01-02 15:04:05"), testEAD)
eadXML, err := getEADValue(testEAD)
if err != nil {
log.Println(fmt.Sprintf(`getEADValue("%s") failed: %s`, testEAD, err))
}
repositoryCode := parseRepositoryCode(testEAD)
eadToTest, err := ead.New(repositoryCode, eadXML)
if err != nil {
log.Println(fmt.Sprintf(`ead.New("%s", [EADXML for %s ]) failed: %s`, repositoryCode, testEAD, err))
}
err = testCollectionDocSolrAddMessage(testEAD, eadToTest.CollectionDoc.SolrAddMessage)
if err != nil {
log.Println(err.Error())
}
if eadToTest.Components == nil {
fmt.Println(testEAD + " has no components. Skipping component tests")
continue
}
componentIDs := []string{}
for _, component := range *eadToTest.Components {
componentIDs = append(componentIDs, component.ID)
err = testComponentSolrAddMessage(testEAD, component.ID,
component.SolrAddMessage)
if err != nil {
log.Println(err.Error())
}
}
err = testNoMissingComponents(testEAD, componentIDs)
if err != nil {
log.Println(err.Error())
}
}
}