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
|
package main
import (
"bufio"
"os"
"path/filepath"
"strings"
ignore "github.com/sabhiram/go-gitignore"
)
type gitignoreLayer struct {
dir string
posRules *ignore.GitIgnore
negRules *ignore.GitIgnore
}
type GitignoreStack struct {
rootDir string
layers []gitignoreLayer
}
func NewGitignoreStack(rootDir string) *GitignoreStack {
stack := &GitignoreStack{rootDir: rootDir}
stack.loadAndPush(rootDir)
return stack
}
func (s *GitignoreStack) Push(dir string) {
s.loadAndPush(dir)
}
func (s *GitignoreStack) Pop() {
if len(s.layers) > 0 {
s.layers = s.layers[:len(s.layers)-1]
}
}
func (s *GitignoreStack) IsIgnored(relPath string) bool {
absPath := filepath.Join(s.rootDir, relPath)
result := false
for _, layer := range s.layers {
childRel, err := filepath.Rel(layer.dir, absPath)
if err != nil {
continue
}
childRel = filepath.ToSlash(childRel)
if strings.HasPrefix(childRel, "../") {
continue
}
posMatch := layer.posRules != nil && (layer.posRules.MatchesPath(childRel) || layer.posRules.MatchesPath(childRel+"/"))
negMatch := layer.negRules != nil && (layer.negRules.MatchesPath(childRel) || layer.negRules.MatchesPath(childRel+"/"))
if negMatch {
result = false
} else if posMatch {
result = true
}
}
return result
}
func (s *GitignoreStack) ParentIgnored(dir string) bool {
parent := filepath.Dir(dir)
if parent == dir {
return false
}
parentRel, err := filepath.Rel(s.rootDir, parent)
if err != nil {
return false
}
if parentRel == "." {
return false
}
return s.IsIgnored(parentRel)
}
func (s *GitignoreStack) loadAndPush(dir string) {
gitignorePath := filepath.Join(dir, ".gitignore")
if _, err := os.Stat(gitignorePath); os.IsNotExist(err) {
return
}
f, err := os.Open(gitignorePath)
if err != nil {
return
}
defer f.Close()
var posLines, negLines []string
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
if strings.HasPrefix(trimmed, "!") {
negLines = append(negLines, trimmed[1:])
} else {
posLines = append(posLines, trimmed)
}
}
var posRules, negRules *ignore.GitIgnore
if len(posLines) > 0 {
posRules = ignore.CompileIgnoreLines(posLines...)
}
if len(negLines) > 0 {
negRules = ignore.CompileIgnoreLines(negLines...)
}
s.layers = append(s.layers, gitignoreLayer{
dir: dir,
posRules: posRules,
negRules: negRules,
})
}
func hasGitignore(dir string) bool {
_, err := os.Stat(filepath.Join(dir, ".gitignore"))
return err == nil
}
func isGitDir(path string) bool {
return path == ".git" || strings.HasPrefix(path, ".git"+string(filepath.Separator))
}
|