go gitignore

golang gitignore recursive walk

package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	ignore "github.com/sabhiram/go-gitignore"
)

func main() {
	// recursive iteration over `os.Args[1]` path
	filepath.Walk(os.Args[1], func(path string, info os.FileInfo, err error) error {
		if err != nil {
			log.Println(err)
		}

		// path == "/Users/mac/Desktop/demo/obj/Debug/net6.0/logging.AssemblyInfo.cs"
		// info.Name() == "logging.AssemblyInfo.cs"

		// inner, walk up till root or found gitignore
		var gitignore *ignore.GitIgnore
		parent := path
		for {
			gitignore, _ = ignore.CompileIgnoreFile(filepath.Join(parent, ".gitignore"))
			if gitignore != nil {
				// gitignore found, breaking loop
				break
			}
			if parent == filepath.Dir(parent) {
				// we are at root and there is no more parents, breaking loop
				break
			} else {
				parent = filepath.Dir(parent)
			}
		}

		ignored := false
		if gitignore != nil {
			ignored = gitignore.MatchesPath(path)
		} else {
		}
		fmt.Printf("%v %s\n", ignored, path)
		return nil
	})
}

can be used as:

go run main.go /Users/mac/github.com/mac2000/notes/

was discovered for trufflehog