Adding handling of leading slash + test case
Also adding a debug version of the match fn for easier debug
diff --git a/ignore.go b/ignore.go
index 5063aeb..edea144 100644
--- a/ignore.go
+++ b/ignore.go
@@ -98,12 +98,16 @@
}
// Handle [Rule 2, 4], when # or ! is escaped with a \
- // Handle [Rule 8], strip leading /
// Handle [Rule 4] once we tag negatePattern, strip the leading ! char
- if regexp.MustCompile(`^(\#|\!|/)`).MatchString(line) {
+ if regexp.MustCompile(`^(\#|\!)`).MatchString(line) {
line = line[1:]
}
+ // Handle [Rule 8], strip leading / and enforce path checking if its present
+ if regexp.MustCompile(`^/`).MatchString(line) {
+ line = "^" + line[1:]
+ }
+
// If we encounter a foo/*.blah in a folder, prepend the ^ char
if regexp.MustCompile(`([^\/+])/.*\*\.`).MatchString(line) {
line = "^" + line
@@ -158,7 +162,7 @@
func (g GitIgnore) IncludesPath(f string) bool {
includesPath := true
for idx, pattern := range g.patterns {
- if pattern.MatchString(f) {
+ if pattern.MatchString(f) {
if !g.negate[idx] {
includesPath = false
} else if !includesPath {
@@ -169,6 +173,28 @@
return includesPath
}
+/* DEBUG VERSION OF ABOVE FUNCTION *\
+func (g GitIgnore) IncludesPath(f string) bool {
+ includesPath := true
+ fmt.Println("Matching path for: " + f)
+ for idx, pattern := range g.patterns {
+ fmt.Printf(" with pattern: " + pattern.String())
+ if pattern.MatchString(f) {
+ if !g.negate[idx] {
+ fmt.Println( " MATCHED +")
+ includesPath = false
+ } else if !includesPath {
+ fmt.Println( " MATCHED -")
+ includesPath = true
+ }
+ } else {
+ fmt.Println( " NOT MATCHED")
+ }
+ }
+ return includesPath
+}
+\* END OF DEBUG VERSION */
+
// IgnoresPath is an interface function for the IgnoreParser interface.
// It returns true if the given GitIgnore structure would reject the path
// being queried against
diff --git a/ignore_test.go b/ignore_test.go
index 08692f1..250c447 100644
--- a/ignore_test.go
+++ b/ignore_test.go
@@ -207,3 +207,18 @@
assert.Equal(test, true, object.IgnoresPath("bar"), "bar should be ignored")
assert.Equal(test, true, object.IgnoresPath("baz/bar"), "baz/bar should be ignored")
}
+
+// Validate the correct handling of leading slash
+func TestCompileIgnoreLines_HandleLeadingSlashPath(test *testing.T) {
+ writeFileToTestDir("test.gitignore", `
+/*.c
+`)
+ defer cleanupTestDir()
+
+ object, error := CompileIgnoreFile("./test_fixtures/test.gitignore")
+ assert.Nil(test, error, "error should be nil")
+ assert.NotNil(test, object, "object should not be nil")
+
+ assert.Equal(test, true, object.IgnoresPath("hello.c"), "hello.c should be ignored")
+ assert.Equal(test, false, object.IgnoresPath("foo/hello.c"), "foo/hello.c should not be ignored")
+}