Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: look for gitignore file until the git root #200

Merged
merged 1 commit into from
Aug 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading