Repository navigation
Expand file tree
/
Copy pathoptions.go
More file actions
63 lines (56 loc) · 1.48 KB
/
Copy pathoptions.go
File metadata and controls
63 lines (56 loc) · 1.48 KB
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
package gitignore
import (
"io"
"os"
"strconv"
)
// Option configures a Matcher at construction time.
type Option func(*Matcher)
// MaxIgnoreFileSize limits the bytes read from each ignore file. Nonpositive
// values are unlimited. AddPatterns is unaffected because its data is already
// in memory.
func MaxIgnoreFileSize(n int64) Option {
return func(m *Matcher) { m.maxIgnoreFileSize = n }
}
// IgnoreFileSizeError reports an ignore file that exceeded its byte limit.
type IgnoreFileSizeError struct {
Path string
Limit int64
}
func (e *IgnoreFileSizeError) Error() string {
return e.Path + ": " + e.message()
}
func (e *IgnoreFileSizeError) message() string {
return "ignore file exceeds size limit of " + strconv.FormatInt(e.Limit, 10) + " bytes"
}
func readIgnoreFile(path string, limit int64) ([]byte, error) {
if limit <= 0 {
return os.ReadFile(path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
info, err := f.Stat()
if err != nil {
return nil, err
}
if info.Size() > limit {
return nil, &IgnoreFileSizeError{Path: path, Limit: limit}
}
data, err := io.ReadAll(io.LimitReader(f, limit))
if err != nil {
return nil, err
}
if int64(len(data)) < limit {
return data, nil
}
// The file can grow after Stat. Probe without overflowing limit+1.
if n, err := io.CopyN(io.Discard, f, 1); n != 0 {
return nil, &IgnoreFileSizeError{Path: path, Limit: limit}
} else if err != io.EOF {
return nil, err
}
return data, nil
}