Skip to content

Commit

Permalink
fix: look for gitignore file until the git root
Browse files Browse the repository at this point in the history
  • Loading branch information
nikaro committed Aug 2, 2024
1 parent 2cdff15 commit 745a890
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions path_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package yamlfmt

import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
Expand Down Expand Up @@ -162,7 +164,47 @@ func (c *DoublestarCollector) CollectPaths() ([]string, error) {
return pathsToFormat, nil
}

func findGitIgnorePath(gitignorePath string) (string, error) {
// if path is absolute, check if exists and return
if filepath.IsAbs(gitignorePath) {
_, err := os.Stat(gitignorePath)
return gitignorePath, err
}

// if path is relative, search for it until the git root
dir, err := os.Getwd()
if err != nil {
return gitignorePath, fmt.Errorf("cannot get current working directory: %w", err)
}
for {
// check if gitignore is there
gitIgnore := filepath.Join(dir, gitignorePath)
if _, err := os.Stat(gitIgnore); err == nil {
return gitIgnore, nil
}

// check if we are at the git root directory
gitRoot := filepath.Join(dir, ".git")
if _, err := os.Stat(gitRoot); err == nil {
return gitignorePath, errors.New("gitignore not found")
}

// check if we are at the root of the filesystem
parent := filepath.Dir(dir)
if parent == dir {
return gitignorePath, errors.New("no git repository found")
}

// level up
dir = parent
}
}

func ExcludeWithGitignore(gitignorePath string, paths []string) ([]string, error) {
gitignorePath, err := findGitIgnorePath(gitignorePath)
if err != nil {
return nil, err
}
logger.Debug(logger.DebugCodePaths, "excluding paths with gitignore: %s", gitignorePath)
ignorer, err := ignore.CompileIgnoreFile(gitignorePath)
if err != nil {
Expand Down

0 comments on commit 745a890

Please sign in to comment.