xonecas.io
62159
Sy

symb / files

symb / internal / filesearch / gitignore.go

4.6 KB
1package filesearch
2
3import (
4	"bufio"
5	"os"
6	"path/filepath"
7	"regexp"
8	"strings"
9)
10
11// GitignoreMatcher matches paths against gitignore patterns.
12type GitignoreMatcher struct {
13	patterns []*gitignorePattern
14}
15
16type gitignorePattern struct {
17	pattern  string
18	regex    *regexp.Regexp
19	negation bool
20	dirOnly  bool
21	anchored bool
22}
23
24// NewGitignoreMatcher creates a new gitignore matcher from a .gitignore file.
25func NewGitignoreMatcher(gitignorePath string) (*GitignoreMatcher, error) {
26	matcher := &GitignoreMatcher{}
27
28	if gitignorePath == "" {
29		return matcher, nil
30	}
31
32	file, err := os.Open(gitignorePath)
33	if err != nil {
34		if os.IsNotExist(err) {
35			return matcher, nil
36		}
37		return nil, err
38	}
39	defer file.Close()
40
41	scanner := bufio.NewScanner(file)
42	for scanner.Scan() {
43		line := strings.TrimSpace(scanner.Text())
44
45		// Skip empty lines and comments
46		if line == "" || strings.HasPrefix(line, "#") {
47			continue
48		}
49
50		pattern := parseGitignorePattern(line)
51		if pattern != nil {
52			matcher.patterns = append(matcher.patterns, pattern)
53		}
54	}
55
56	if err := scanner.Err(); err != nil {
57		return nil, err
58	}
59
60	return matcher, nil
61}
62
63// Matches checks if a path should be ignored.
64func (m *GitignoreMatcher) Matches(path string, isDir bool) bool {
65	if m == nil || len(m.patterns) == 0 {
66		return false
67	}
68
69	// Normalize path separators to forward slashes
70	path = filepath.ToSlash(path)
71
72	var lastMatch bool
73	for _, pattern := range m.patterns {
74		// For directory-only patterns, check if path is or is within that directory
75		if pattern.dirOnly {
76			if isDir && pattern.regex.MatchString(path) {
77				lastMatch = !pattern.negation
78			} else if !isDir && pattern.regex.MatchString(filepath.Dir(path)) {
79				// File within directory
80				lastMatch = !pattern.negation
81			}
82			continue
83		}
84
85		// For anchored patterns, only match against full path
86		if pattern.anchored {
87			if pattern.regex.MatchString(path) {
88				lastMatch = !pattern.negation
89			}
90		} else {
91			// For non-anchored, try both full path and basename
92			if pattern.regex.MatchString(path) || pattern.regex.MatchString(filepath.Base(path)) {
93				lastMatch = !pattern.negation
94			}
95		}
96	}
97
98	return lastMatch
99}
100
101// parseGitignorePattern converts a gitignore pattern to a regex.
102func parseGitignorePattern(pattern string) *gitignorePattern {
103	original := pattern
104	negation := false
105	dirOnly := false
106	anchored := false
107
108	// Handle negation
109	if strings.HasPrefix(pattern, "!") {
110		negation = true
111		pattern = pattern[1:]
112	}
113
114	// Check for anchored pattern
115	if strings.HasPrefix(pattern, "/") {
116		anchored = true
117	}
118
119	// Handle directory-only patterns
120	if strings.HasSuffix(pattern, "/") {
121		dirOnly = true
122		pattern = strings.TrimSuffix(pattern, "/")
123	}
124
125	// Convert gitignore glob to regex
126	regexPattern := gitignoreGlobToRegex(pattern)
127	regex, err := regexp.Compile(regexPattern)
128	if err != nil {
129		// If pattern is invalid, skip it
130		return nil
131	}
132
133	return &gitignorePattern{
134		pattern:  original,
135		regex:    regex,
136		negation: negation,
137		dirOnly:  dirOnly,
138		anchored: anchored,
139	}
140}
141
142// gitignoreGlobToRegex converts a gitignore glob pattern to a regex.
143func gitignoreGlobToRegex(pattern string) string {
144	var result strings.Builder
145
146	anchored := false
147	if strings.HasPrefix(pattern, "/") {
148		result.WriteString("^")
149		pattern = pattern[1:]
150		anchored = true
151	} else {
152		result.WriteString("(^|/)")
153	}
154
155	for i := 0; i < len(pattern); {
156		i += convertGlobChar(&result, pattern, i)
157	}
158
159	if anchored {
160		result.WriteString("$")
161	} else {
162		result.WriteString("(/.*)?$")
163	}
164	return result.String()
165}
166
167// convertGlobChar writes the regex equivalent of pattern[i] into b and returns
168// the number of characters consumed.
169func convertGlobChar(b *strings.Builder, pattern string, i int) int {
170	ch := pattern[i]
171	switch ch {
172	case '*':
173		return convertGlobStar(b, pattern, i)
174	case '?':
175		b.WriteString("[^/]")
176		return 1
177	case '.', '+', '(', ')', '|', '^', '$', '@', '%':
178		b.WriteByte('\\')
179		b.WriteByte(ch)
180		return 1
181	case '[':
182		return convertGlobCharClass(b, pattern, i)
183	case '\\':
184		if i+1 < len(pattern) {
185			b.WriteByte('\\')
186			b.WriteByte(pattern[i+1])
187			return 2
188		}
189		b.WriteString("\\\\")
190		return 1
191	default:
192		b.WriteByte(ch)
193		return 1
194	}
195}
196
197func convertGlobStar(b *strings.Builder, pattern string, i int) int {
198	if i+1 < len(pattern) && pattern[i+1] == '*' {
199		if i+2 < len(pattern) && pattern[i+2] == '/' {
200			b.WriteString("(.*/)?")
201			return 3
202		}
203		b.WriteString(".*")
204		return 2
205	}
206	b.WriteString("[^/]*")
207	return 1
208}
209
210func convertGlobCharClass(b *strings.Builder, pattern string, i int) int {
211	j := i + 1
212	for j < len(pattern) && pattern[j] != ']' {
213		j++
214	}
215	if j < len(pattern) {
216		b.WriteString(pattern[i : j+1])
217		return j + 1 - i
218	}
219	b.WriteString("\\[")
220	return 1
221}