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

Add ability to compile a pattern #99

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

lukemassa
Copy link
Contributor

@lukemassa lukemassa commented Jan 23, 2025

What

Add ability to compile a Pattern once and use it for subsequent matches.

Note this is currently a naive implementation that just calls the existing Match(), I wanted to firstly gauge interest of the maintainers to see if this is a feature worth implementing, and also to discuss what the various exported identifiers should be.

Why

ValidatePattern(), allows the user to inspect whether there is an error before saving the pattern for later. This goes a step further, and removes the error from the analogous Match() function, since it cannot fail once compiled, making it a bit cleaner to use.

Additionally, presumably a compiled pattern could be made to be more efficient, though I haven't dug into the implementation there yet. My naive implementation is very slightly better than Match(), since it makes use of the existing MatchUnvalidated, which skips some validation and therefore saves time.

I modeled the methods and signatures after regexp in go's standard library (quoted in part here):

func MatchString(pattern string, s string) (matched bool, err error)
type Regexp struct{ ... }
    func Compile(expr string) (*Regexp, error)
    func MustCompile(str string) *Regexp
    func (re *Regexp) Match(s string) bool

https://pkg.go.dev/regexp

Usage

    pattern, err := doublestar.Compile("foo/*")
    if err != nil {
        log.Fatal(err)
    }
    if pattern.Match("foo/bar") {
        fmt.Println("Pattern matches foo/bar")
    }
    if pattern.Match("bar/foo") {
        fmt.Println("Pattern matches bar/foo")
    }
    
    // Prints "Pattern matches foo/bar"

Testing

The compiled version is run through the same suite of tests as the normal version, which also serves to make sure they are in lock-step.

References

Closes: #85

@lukemassa lukemassa marked this pull request as ready for review January 24, 2025 19:32
@lukemassa lukemassa force-pushed the add_compiled_pattern_matcher branch 2 times, most recently from 45146b6 to 15cbf42 Compare January 25, 2025 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature request: add functionality to compile globs
1 participant