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

Hide files excluded by .gitignore #32

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
56 changes: 36 additions & 20 deletions cmd/codeowners/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"

Expand Down Expand Up @@ -55,25 +56,27 @@ func main() {
defer out.Flush()

for _, startPath := range paths {
// godirwalk only accepts directories, so we need to handle files separately
if !isDir(startPath) {
if err := printFileOwners(out, ruleset, startPath, ownerFilters, showUnowned); err != nil {
fmt.Fprintf(os.Stderr, "error: %v", err)
os.Exit(1)
}
continue
}
files := gitFiles(startPath)

err = filepath.WalkDir(startPath, func(path string, d os.DirEntry, err error) error {
if path == ".git" {
return filepath.SkipDir
if d.IsDir() {
if path == ".git" {
return filepath.SkipDir
}

// Don't show code owners for directories.
return nil
}

// Only show code owners for files, not directories
if !d.IsDir() {
return printFileOwners(out, ruleset, path, ownerFilters, showUnowned)
if files != nil {
// Skip displaying code owners for files that are not managed by git,
// e.g. untracked files or files excluded by .gitignore.
if _, ok := files[path]; !ok {
return nil
}
}
return nil

return printFileOwners(out, ruleset, path, ownerFilters, showUnowned)
})

if err != nil {
Expand Down Expand Up @@ -126,11 +129,24 @@ func loadCodeowners(path string) (codeowners.Ruleset, error) {
return codeowners.LoadFile(path)
}

// isDir checks if there's a directory at the path specified.
func isDir(path string) bool {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return false
// gitFiles returns a map of files in the git repository at the given path.
// Notably, this omits files that have been excluded by .gitignore,
// .git/info/exclude and system-wide gitignore. See
// https://git-scm.com/docs/gitignore for more details.
//
// Returns nil if anything goes wrong, such as the path not being a git repo or
// git not being installed.
func gitFiles(path string) map[string]struct{} {
cmd := exec.Command("git", "ls-files", "-z", "--", path)
out, err := cmd.Output()
if err != nil {
return nil
}

files := make(map[string]struct{})
for _, file := range strings.Split(string(out), "\x00") {
files[file] = struct{}{}
}
return info.IsDir()

return files
}