ignored

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 8 Imported by: 0

README

ignored

ignored is a Go package designed to handle Gitignore-like ignore patterns at three levels:

  • Pattern level: Parsing and matching individual ignore rules.
  • Matcher level: Managing a collection of ignore patterns.
  • Repository Walker level: An fs.WalkDir wrapper that automatically applies ignore rules while traversing a directory.

Core Interfaces

Pattern

The Pattern interface handles individual ignore rules. Patterns are parsed from strings, supporting negation (e.g., !file.txt) and directory-specific rules.

Matcher

The Matcher interface manages a collection of patterns. It allows dynamic addition of patterns from strings or files (like .gitignore), providing efficient matching for paths.

RepoWalker

The RepoWalker provides a wrapper around fs.WalkDir, making it easy to traverse a filesystem while respecting ignore rules dynamically loaded from ignore files (e.g., .gitignore) in each directory.


Installation

go get github.com/Tahaa-Dev/ignored

Quick Examples

Using RepoWalker
import (
    "fmt"
    "io/fs"
    "github.com/Tahaa-Dev/ignored"
)

func main() {
    walker := ignored.NewRepoWalker("/path/to/project").SetIgnoreFileName(".dockerignore")
    
    err := walker.WalkRepo(func(path string, d fs.DirEntry, err error) error {
        if err != nil {
            return err
        }
        fmt.Println("Visiting:", path)
        return nil
    })
    
    if err != nil {
        // handle fs.WalkDir error
    }
    if walker.Err() != nil {
        // Handle accumulated errors
    }
}
Using Matcher
import (
    "fmt"
    "github.com/Tahaa-Dev/ignored"
)

func main() {
    matcher := ignored.NewMatcher("/root/project", "*.log", "node_modules/")
    
    if matcher.Match("/root/project/node_modules/pkg/main.js", false) {
        fmt.Println("Path is ignored")
    }
}

License

This project is licensed under the MIT License. See the LICENSE file for details.


Development

Documentation

Overview

Package ignored provides a way to handle gitignore and similar ignore files (e.g. dockerignore) at the pattern level, file level and repository level through 3 main interfaces:

## Pattern

The Pattern interface provides methods to handle ignore patterns individually which is parsed from a string via the ParsePattern function.

### Example

import (
	"fmt"
	"github.com/Tahaa-Dev/ignored"
)

func IsIgnored(pattern string, path string, isDir bool, rootDir string) bool {
	pat := ignored.ParsePattern(pattern)
	isIgnored, err := pat.Match(path, isDir, rootDir)
	if err != nil {
		fmt.Println("Error while matching path:", err.Error())
	}
}

## Matcher

The Matcher interface provides methods to handle multiple ignore patterns at once which is constructed via the NewMatcher function.

### Example

import "github.com/Tahaa-Dev/ignored"

var rootDir = "/home/myproject"
func IsIgnored(matcher ignored.Matcher, path string, isDir bool, ignorePath string) bool {
	if ignorePath != "" {
		matcher.ExtendFromFile(ignorePath)
	}
	return matcher.Match(path, isDir)
}

## RepoWalker

The RepoWalker interface provides an ignore file compliant wrapper for fs.WalkDir which is constructed via the NewRepoWalker function.

### Example

import (
	"fmt"
	"os"
	"github.com/Tahaa-Dev/ignored"
)

func PrintRepo(repoWalker ignored.RepoWalker) {
	repoWalker.WalkRepo(func(path string, d fs.DirEntry, err error) error {
		suffix := ""
		if d.IsDir() {
			suffix = "/"
		}
		fmt.Printf("%s%s\n", path, suffix)
	})
	if repoWalker.Err() != nil {
		fmt.Fprintf(os.Stderr, "Error while printing dir: %s\n", repoWalker.Err().Error())
	}
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalizePath

func NormalizePath(path string, rootDir string) (string, error)

Helper function for normalizing paths used by Pattern.Match() and Matcher.Match().

Types

type EmptyPatternErr

type EmptyPatternErr struct{}

func (*EmptyPatternErr) Error

func (*EmptyPatternErr) Error() string

type Matcher

type Matcher interface {
	// Matches path against [Pattern]s in the [Matcher].
	Match(path string, isDir bool) bool
	// Matches already normalized path against [Pattern]s in the [Matcher].
	MatchNormalized(path string, isDir bool) bool
	// Udates the root directory for the [Matcher].
	SetRootDir(rootDir string) Matcher
	// Appends new patterns from a slice of strings to the [Matcher].
	Extend(patterns ...string) Matcher
	// Appends new pre-parsed [Pattern]s to the [Matcher].
	ExtendFromPatterns(patterns ...Pattern) Matcher
	// Loads patterns from a file at the given path into the [Matcher].
	ExtendFromFile(path string) Matcher
	// Loads patterns from an [io.Reader] into the [Matcher].
	ExtendFromReader(reader io.Reader) Matcher

	// Returns the first accumulated error in the [Matcher].
	Err() error
	// Returns the number of patterns currently in the [Matcher].
	Len() int
	// contains filtered or unexported methods
}

Matcher provides methods to handle multiple ignore patterns at once. It is constructed via the NewMatcher function.

## Example:

matcher := ignored.NewMatcher("/home/user/project", "*.log", "node_modules/")
if matcher.Match("node_modules/pkg/main.js", false) {
	fmt.Println("Path is ignored")
}

// Dynamically add patterns
matcher.Extend("*.tmp")
matcher.ExtendFromFile("/home/user/project/.gitignore")

func NewMatcher

func NewMatcher(rootDir string, patterns ...string) Matcher

Function for constructing Matcher interfaces.

type Pattern

type Pattern interface {
	// Determines if the given path matches the pattern, relative to the rootDir.
	// The first bool is whether the raw pattern is a match or not.
	// The second one is whether if it's ignored or not considering negation (leading !).
	Match(path string, isDir bool, rootDir string) (isMatch bool, result bool)
	// Checks if the already-normalized path matches the pattern.
	// The first bool is whether the raw pattern is a match or not.
	// The second one is whether if it's ignored or not considering negation (leading !).
	MatchNormalized(path string, isDir bool) (isMatch bool, result bool)
	// Returns any error encountered during pattern parsing.
	Err() error
}

Pattern provides methods to handle ignore patterns individually. It is parsed from a string via the ParsePattern function.

Example:

pat := ignored.ParsePattern("*.log")
isIgnored, err := pat.Match("app.log", false, "/home/user/project")
if err != nil {
	// handle error
}
if isIgnored {
	fmt.Println("File is ignored")
}

func ParsePattern

func ParsePattern(pat string) Pattern

Function for constructing Pattern interfaces.

type RepoWalker

type RepoWalker interface {
	// Traverses the repository starting at the root, applying the [Matcher] to skip ignored files and directories.
	// Uses the provided [fs.WalkDirFunc].
	WalkRepo(fs.WalkDirFunc) error
	// Changes the name of the file used to detect ignore patterns (default is ".gitignore").
	SetIgnoreFileName(fileName string) RepoWalker
	// Returns any error that occurred during the repository traversal.
	Err() error
}

RepoWalker provides an ignore file compliant wrapper for fs.WalkDir. It is constructed via the NewRepoWalker function.

## Example:

walker := ignored.NewRepoWalker("/home/user/project")
walker.WalkRepo(func(path string, d fs.DirEntry, err error) error {
	if err != nil {
		return err
	}
	fmt.Println("Visiting:", path)
	return nil
})
if walker.Err() != nil {
	// handle error
}

func NewRepoWalker

func NewRepoWalker(root string, patterns ...string) RepoWalker

Function for constructing RepoWalker interfaces.

func NewRepoWalkerFS

func NewRepoWalkerFS(rootFS fs.FS, patterns ...string) RepoWalker

Function for constructing RepoWalker interfaces from an fs.FS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL