Skip to content

Commit d804d8d

Browse files
authored
Merge pull request #77 from codecrafters-io/andy/fix-gitignore
Fix issue of gitignore matching parent dir when it shouldn't
2 parents 81f24b4 + 8360e9e commit d804d8d

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

internal/utils/git_ignore.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ func NewGitIgnore(baseDir string) GitIgnore {
2727
}
2828

2929
func (i GitIgnore) SkipFile(path string) (bool, error) {
30+
path = strings.TrimPrefix(path, i.baseDir)
31+
path = strings.TrimPrefix(path, "/")
32+
3033
// Never skip the .git directory or files inside it, even if matched by .gitignore patterns.
3134
if path == ".git" ||
3235
strings.HasPrefix(path, ".git/") ||

internal/utils/git_ignore_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,27 @@ func TestGitIgnore(t *testing.T) {
6969
})
7070
}
7171
})
72+
73+
t.Run("match only paths within baseDir, not its parent directories", func(t *testing.T) {
74+
backup := setupGlobalGitIgnore(t, "var/\nignore.txt\n")
75+
defer func() {
76+
if backup.originalPath == "" {
77+
unsetGlobalGitIgnoreConfig(t)
78+
}
79+
backup.Restore(t)
80+
}()
81+
82+
baseDir := filepath.Join(t.TempDir(), "var", "home", "user", "repo")
83+
err := os.MkdirAll(baseDir, 0755)
84+
assert.NoError(t, err)
85+
writeFile(t, filepath.Join(baseDir, "not-ignore.txt"), "not-ignore")
86+
writeFile(t, filepath.Join(baseDir, "ignore.txt"), "ignore")
87+
88+
gitIgnore := NewGitIgnore(baseDir)
89+
90+
assertFileNotSkipped(t, &gitIgnore, filepath.Join(baseDir, "not-ignore.txt"))
91+
assertFileSkipped(t, &gitIgnore, filepath.Join(baseDir, "ignore.txt"))
92+
})
7293
}
7394

7495
func assertFileSkipped(t *testing.T, gitIgnore *GitIgnore, path string) {

0 commit comments

Comments
 (0)