-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitignore.go
79 lines (71 loc) · 1.88 KB
/
gitignore.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
package filter
import (
"bufio"
"bytes"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5/plumbing/format/gitignore"
)
var separator = string(filepath.Separator)
type Gitignore struct {
PathMatchers []gitignore.Pattern
}
var _ FileExp = (*Gitignore)(nil)
func NewGitIgnore(rootDir string, filePath string) (*Gitignore, error) {
domain := strings.Split(rootDir, separator)
if len(domain) > 0 && domain[0] == "." {
domain = domain[1:]
}
buf, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
var ignores []gitignore.Pattern
reader := bufio.NewReader(bytes.NewReader(buf))
for {
b, _, err := reader.ReadLine()
if errors.Is(err, io.EOF) {
break
}
if len(b) == 0 ||
b[0] == '#' {
continue
}
ignores = append(ignores, gitignore.ParsePattern(string(b), domain))
}
return &Gitignore{PathMatchers: ignores}, nil
}
func (g *Gitignore) Match(path string, info fs.DirEntry) (bool, error) {
var match bool
splitPath := strings.Split(path, separator)
for i := range g.PathMatchers {
if m := g.PathMatchers[i].Match(splitPath, info.IsDir()); m > gitignore.NoMatch {
match = m == gitignore.Exclude
}
}
return match, nil
}
func (g *Gitignore) Add(src *Gitignore) *Gitignore {
if (g == nil || len(g.PathMatchers) == 0) &&
(src == nil || len(src.PathMatchers) == 0) {
return nil
}
if src == nil || len(src.PathMatchers) == 0 {
dst := make([]gitignore.Pattern, len(g.PathMatchers))
copy(dst, g.PathMatchers)
return &Gitignore{PathMatchers: dst}
}
if g == nil || len(g.PathMatchers) == 0 {
dst := make([]gitignore.Pattern, len(src.PathMatchers))
copy(dst, src.PathMatchers)
return &Gitignore{PathMatchers: dst}
}
dst := make([]gitignore.Pattern, len(src.PathMatchers)+len(g.PathMatchers))
copy(dst, g.PathMatchers)
copy(dst[len(g.PathMatchers):], src.PathMatchers)
return &Gitignore{PathMatchers: dst}
}