-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck.go
85 lines (71 loc) · 2.53 KB
/
check.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
package main
import (
"errors"
"fmt"
"github.com/jo3-l/markpdf/internal/easypdf"
)
type Check interface {
AppendErrors([]error, *easypdf.BookmarkTree, *easypdf.PDFInfo) []error
}
var AllChecks = []Check{
&NonEmptyCheck{},
&MonotonicallyIncreasingPageNumsCheck{},
&UniqueTitlesCheck{},
&ValidPageNumsCheck{},
}
func RunChecks(checks []Check, bookmarks *easypdf.BookmarkTree, p *easypdf.PDFInfo) []error {
var errs []error
for _, c := range checks {
errs = c.AppendErrors(errs, bookmarks, p)
}
return errs
}
// pdfcpu doesn't support calling AddBookmarks with an empty slice; see
// https://github.com/pdfcpu/pdfcpu/blob/a9afcfe683880972fbbb576e12ef74688005ed3a/pkg/api/bookmark.go#L40.
type NonEmptyCheck struct{}
func (*NonEmptyCheck) AppendErrors(errs []error, bookmarks *easypdf.BookmarkTree, _ *easypdf.PDFInfo) []error {
if bookmarks.Count() == 0 {
return append(errs, errors.New("no bookmarks specified"))
}
return errs
}
// pdfcpu requires page numbers of bookmarks to be monotonically increasing; see
// https://github.com/pdfcpu/pdfcpu/issues/376.
type MonotonicallyIncreasingPageNumsCheck struct{}
func (*MonotonicallyIncreasingPageNumsCheck) AppendErrors(errs []error, bookmarks *easypdf.BookmarkTree, _ *easypdf.PDFInfo) []error {
var prev *easypdf.Bookmark
bookmarks.Inspect(func(b *easypdf.Bookmark) {
if prev != nil && b.Page < prev.Page {
err := fmt.Errorf("bookmark %q (pg %d) appears after bookmark %q (pg %d) but has lower page number; this is not supported",
b.Title, b.Page,
prev.Title, prev.Page)
errs = append(errs, err)
}
prev = b
})
return errs
}
// pdfcpu has a bug where AddBookmarks will panic given duplicate titles; see
// https://github.com/pdfcpu/pdfcpu/issues/664.
type UniqueTitlesCheck struct{}
func (*UniqueTitlesCheck) AppendErrors(errs []error, bookmarks *easypdf.BookmarkTree, _ *easypdf.PDFInfo) []error {
count := make(map[string]int)
bookmarks.Inspect(func(b *easypdf.Bookmark) {
count[b.Title] += 1
})
for title, occurrences := range count {
if occurrences > 1 {
errs = append(errs, fmt.Errorf("bookmark title %q is duplicated %d times; titles must be unique", title, occurrences))
}
}
return errs
}
type ValidPageNumsCheck struct{}
func (*ValidPageNumsCheck) AppendErrors(errs []error, bookmarks *easypdf.BookmarkTree, p *easypdf.PDFInfo) []error {
bookmarks.Inspect(func(b *easypdf.Bookmark) {
if b.Page < 1 || b.Page > p.PageCount {
errs = append(errs, fmt.Errorf("page number %d out of range (must be between 1-%d)", b.Page, p.PageCount))
}
})
return errs
}