minimatch

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2026 License: BlueOak-1.0.0 Imports: 10 Imported by: 0

README

minimatch (Go)

ci

Idiomatic Go port of isaacs/minimatch: bash-style glob matching used across the npm ecosystem.

The TypeScript tree in ../minimatch (when present) is the behavioural specification. This package aims for observable parity (options, edge cases, ordering), not a line-by-line translation.

Status: v0.1.0 — usable library API with Node differential coverage (see CHANGELOG).

Install

go get github.com/benjaminnkem/minimatch-go@v0.1.0

Quick start

package main

import (
	"fmt"

	"github.com/benjaminnkem/minimatch-go"
)

func main() {
	ok, err := minimatch.Match("src/foo/bar.js", "**/*.js", minimatch.Options{})
	if err != nil {
		panic(err)
	}
	fmt.Println(ok) // true

	m, err := minimatch.NewMinimatch("*.{js,ts}", minimatch.Options{MatchBase: true})
	if err != nil {
		panic(err)
	}
	fmt.Println(m.Match("pkg/index.ts")) // true

	files, _ := minimatch.MatchList(
		[]string{"a.js", "b.txt", "c.js"},
		"*.js",
		minimatch.Options{},
	)
	fmt.Println(files) // [a.js c.js]
}

Main API

Function / type Purpose
Match(path, pattern, opts) One-shot match
NewMinimatch(pattern, opts) Compile once, match many
MatchList(files, pattern, opts) Filter a list (nonull via NoNull)
Filter(pattern, opts) Predicate for slices / manual loops
BraceExpand(pattern, opts) Bash brace expansion only
MakeRe(pattern, opts) Full-path regexp (prefer Match when possible)
Escape / Unescape Literal-safe glob text
NewDefaults(opts) Stack default options under per-call opts
ParseGlob / AST Segment AST (advanced)
Options

See Options in options.go. Highlights:

  • Dot — match leading . segments
  • NoCase — case-insensitive
  • NoGlobStar — treat ** as *
  • NoExt / NoBrace / NoNegate / NoComment
  • Partial — prefix match for directory walks
  • MatchBase — basename-only when pattern has no /
  • Platform — set PlatformWin32 for UNC/drive behaviour on any OS
  • OptimizationLevel0 / 1 (default) / ≥2
  • MaxGlobstarRecursion, MaxExtglobRecursion, BraceExpandMax — safety limits

Zero-value Options{} matches TypeScript {} for boolean flags.

Windows

Always prefer / in patterns. Backslashes in patterns are escapes unless WindowsPathsNoEscape is set.

opts := minimatch.Options{Platform: minimatch.PlatformWin32, NoCase: true}
ok, _ := minimatch.Match(`C:\Users\x\file.txt`, "C:/Users/**/*.txt", opts)

Path arguments may use \ on win32; they are normalized to / for comparison.

Testing

go test ./...
go test -bench=. -benchmem
go test -fuzz=FuzzMatchNoPanic -fuzztime=10s
Parity with Node

testdata/patterns_node.json is generated from the reference suite (patterns.js):

# from repo layout: minimatch/ (TS) next to minimatch-go/
cd ../minimatch && npm test   # builds dist
node ../minimatch-go/testdata/generate_patterns.mjs
cd ../minimatch-go && go test -run Differential -v

Random differential cases (requires Node + built reference):

go test -run FuzzDifferentialBatch -v

Layout

minimatch-go/
├── *.go                 # public API (package minimatch)
├── internal/
│   ├── brace/           # brace expansion
│   ├── scan/            # segment tokenizer
│   ├── class/           # character classes
│   └── ast/             # extglob AST + segment compile
├── testdata/            # Node oracles, fixtures
├── .github/workflows/   # CI
├── README.md
├── LICENSE.md
└── Makefile

Import only github.com/benjaminnkem/minimatch-go. The internal/ packages are implementation details.

Design notes

  • Matching uses segment-wise compare (literals, compiled segment patterns, **).
  • Segment regexps and MakeRe use regexp2 so lookarounds from the TS sources work (stdlib RE2 does not).
  • Pattern length is capped at 64KiB UTF-16 units (same as the reference).

Development

make check          # vet + test + differential
make bench
make fuzz
make fixtures       # regenerate Node oracle (needs ../minimatch)

License

Blue Oak Model License 1.0.0 — see LICENSE.md. Aligned with upstream isaacs/minimatch.

Documentation

Overview

Package minimatch is an idiomatic Go port of the JavaScript/TypeScript minimatch library: a bash-style glob matcher used widely in the npm ecosystem.

This package preserves the observable behaviour of the reference implementation at minimatch (TypeScript), including options semantics, edge cases, and ordering. It is not a mechanical file-by-file translation.

Package layout

minimatch-go/                      module github.com/benjaminnkem/minimatch-go
  *.go                             public API (package minimatch)
  internal/
    brace/                         bash brace expansion
    scan/                          path-segment lexer
    class/                         [character classes] + POSIX
    ast/                           extglob AST + segment regexp compile
  testdata/                        Node oracles and fixtures
  .github/workflows/               CI

Callers import only github.com/benjaminnkem/minimatch-go. Implementation packages under internal/ are not part of the compatibility surface.

The TypeScript tree under ../minimatch is the behavioural specification and is read-only for this port.

Reference

https://github.com/isaacs/minimatch

Index

Examples

Constants

View Source
const (
	// DefaultOptimizationLevel is applied when Options.OptimizationLevel is nil.
	//
	// TypeScript: const { optimizationLevel = 1 } = this.options
	// Explicit 0 is a valid, distinct level (no .. collapsing beyond adjacent **).
	DefaultOptimizationLevel = 1

	// DefaultMaxGlobstarRecursion is applied when Options.MaxGlobstarRecursion is nil.
	//
	// TypeScript: options.maxGlobstarRecursion ?? 200
	DefaultMaxGlobstarRecursion = 200

	// DefaultMaxExtglobRecursion is applied when Options.MaxExtglobRecursion is nil.
	//
	// TypeScript: options.maxExtglobRecursion ?? 2
	DefaultMaxExtglobRecursion = 2

	// DefaultBraceExpandMax is applied when Options.BraceExpandMax is nil.
	//
	// TypeScript passes options.braceExpandMax into brace-expansion; when
	// undefined, brace-expansion uses 100_000.
	DefaultBraceExpandMax = 100_000
)

Package-level default constants for Options fields whose TypeScript default is not the Go zero value (or where “unset” must differ from 0).

Boolean MinimatchOptions in TypeScript default to false when omitted. That maps directly to the Go zero value for bool fields on Options.

Numeric and tri-state fields use nil pointers for “omitted / undefined” so that an explicit 0 or false remains representable.

View Source
const (
	TokenText         = scan.TokenText
	TokenExtglobOpen  = scan.TokenExtglobOpen
	TokenPipe         = scan.TokenPipe
	TokenExtglobClose = scan.TokenExtglobClose
)

Token kind constants.

View Source
const (
	ExtglobNegate   = scan.ExtglobNegate
	ExtglobOptional = scan.ExtglobOptional
	ExtglobPlus     = scan.ExtglobPlus
	ExtglobStar     = scan.ExtglobStar
	ExtglobOne      = scan.ExtglobOne
)

Extglob type constants.

View Source
const ExpansionMax = brace.ExpansionMax

ExpansionMax is the default brace expansion cardinality cap.

View Source
const ExpansionMaxLength = brace.ExpansionMaxLength

ExpansionMaxLength caps total expansion character volume.

View Source
const MaxPatternLength = 1024 * 64

MaxPatternLength is the maximum allowed pattern length, measured in UTF-16 code units (the same unit as JavaScript's String.length). Patterns longer than this are rejected.

Matches the TypeScript constant MAX_PATTERN_LENGTH = 1024 * 64.

Variables

View Source
var (
	// ErrInvalidPattern is returned when a pattern is not a valid string.
	// In TypeScript this covers non-string values (null, numbers, objects).
	// The typed Go API accepts string, so call sites with a string typically
	// never see this; it remains for API parity and untyped adapters.
	// TypeScript message: "invalid pattern"
	ErrInvalidPattern = errors.New("invalid pattern")

	// ErrPatternTooLong is returned when a pattern exceeds MaxPatternLength
	// UTF-16 code units.
	// TypeScript message: "pattern is too long"
	ErrPatternTooLong = errors.New("pattern is too long")
)

Sentinel errors shared across the package.

Message strings match the TypeScript TypeError messages where the reference implementation throws, so behavioural tests can compare text.

View Source
var GlobStar = globStar{}

GlobStar is the singleton ** marker used in compiled pattern sets.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a *bool suitable for optional Options fields such as AllowWindowsEscape and WindowsNoMagicRoot.

func BraceExpand

func BraceExpand(pattern string, opts Options) ([]string, error)

BraceExpand performs bash-style brace expansion on pattern.

Corresponds to TypeScript minimatch.braceExpand.

Example
package main

import (
	"fmt"

	"github.com/benjaminnkem/minimatch-go"
)

func main() {
	out, err := minimatch.BraceExpand("file-{a,b}.txt", minimatch.Options{})
	if err != nil {
		panic(err)
	}
	fmt.Println(out)
}
Output:
[file-a.txt file-b.txt]

func Escape

func Escape(s string, opts EscapeOptions) string

Escape escapes all magic characters in a glob pattern so the result matches only the literal string.

Characters escaped by default: ? * ( ) [ ] and \ (unless WindowsPathsNoEscape). With MagicalBraces, { and } are also escaped.

+ @ ! are not escaped on their own; escaping parentheses is enough to prevent extglob interpretation. Escaping ! as [!] is intentionally avoided because [!]] is a valid class meaning "not ]".

In WindowsPathsNoEscape mode, magic characters are wrapped in [] because a character class containing only that character matches it literally, and \ is left alone as a path separator.

Slashes are never escaped.

Corresponds to TypeScript minimatch.escape / escape().

func Filter

func Filter(pattern string, opts Options) func(string) bool

Filter returns a predicate suitable for filtering path lists.

Corresponds to TypeScript minimatch.filter(pattern, options). Invalid patterns yield a predicate that always returns false.

func Int

func Int(v int) *int

Int returns a *int suitable for optional Options fields such as OptimizationLevel, BraceExpandMax, MaxGlobstarRecursion, and MaxExtglobRecursion.

func IsExtglobType

func IsExtglobType(c byte) bool

IsExtglobType reports whether c is an extglob type character.

func MakeRe

func MakeRe(pattern string, opts Options) (*regexp2.Regexp, bool, error)

MakeRe compiles pattern to a full-path regular expression. Corresponds to minimatch.makeRe(pattern, options).

func Match

func Match(p, pattern string, opts Options) (bool, error)

Match reports whether path p matches pattern under opts.

Corresponds to TypeScript minimatch(p, pattern, options).

Example
package main

import (
	"fmt"

	"github.com/benjaminnkem/minimatch-go"
)

func main() {
	ok, err := minimatch.Match("src/app/index.ts", "**/*.{js,ts}", minimatch.Options{})
	if err != nil {
		panic(err)
	}
	fmt.Println(ok)
}
Output:
true

func MatchList

func MatchList(list []string, pattern string, opts Options) ([]string, error)

MatchList filters list to paths matching pattern.

Corresponds to TypeScript minimatch.match(list, pattern, options). If nothing matches and Options.NoNull is set, returns []string{pattern}.

Example
package main

import (
	"fmt"

	"github.com/benjaminnkem/minimatch-go"
)

func main() {
	files, err := minimatch.MatchList(
		[]string{"a.js", "b.txt", "c.js"},
		"*.js",
		minimatch.Options{},
	)
	if err != nil {
		panic(err)
	}
	fmt.Println(files)
}
Output:
[a.js c.js]

func Unescape

func Unescape(s string, opts UnescapeOptions) string

Unescape reverses escaping produced by Escape.

In WindowsPathsNoEscape mode, only character-class escapes ([x]) are removed; backslash sequences are left intact.

Otherwise both [x] class escapes and \x backslash escapes are removed, with the restrictions below.

Slashes are never unescaped. In WindowsPathsNoEscape mode, backslashes are not unescaped either.

When MagicalBraces is false (explicit), escapes of { and } are not removed. When MagicalBraces is nil (zero-value options), braces are unescaped — matching TypeScript unescape()'s default of true.

Corresponds to TypeScript minimatch.unescape / unescape().

func ValidatePattern

func ValidatePattern(pattern string) error

ValidatePattern reports whether pattern is acceptable for minimatch.

Empty patterns are valid (they match only the empty path once matching exists). Patterns whose UTF-16 length is greater than MaxPatternLength return ErrPatternTooLong.

Length is measured in UTF-16 code units, not Go bytes or Unicode code points, so that the limit matches JavaScript's pattern.length check.

This corresponds to assertValidPattern in the TypeScript implementation, except that type rejection (ErrInvalidPattern) is a compile-time concern in Go when the caller already has a string.

ValidatePattern does not parse or match globs; it only enforces the shared size/type gate used by every public entry point in the reference.

Types

type AST

type AST = ast.AST

AST is the extglob syntax tree for a path segment.

func ParseGlob

func ParseGlob(pattern string, opts Options) *AST

ParseGlob parses a path-segment pattern into an AST.

func ParseTokens

func ParseTokens(src string, tokens []Token, opts Options) *AST

ParseTokens builds an AST from tokens previously produced by Scan.

type ASTPart

type ASTPart = ast.ASTPart

ASTPart is one entry in an AST node.

type Defaults

type Defaults struct {
	// contains filtered or unexported fields
}

Defaults holds a base Options bag applied under per-call options.

Corresponds to TypeScript minimatch.defaults(def). Boolean flags use OR-merge (true in either bag wins); pointer fields and Platform use non-nil/non-empty override wins. Call-site true flags always apply.

func NewDefaults

func NewDefaults(def Options) Defaults

NewDefaults returns a Defaults wrapper for def. Empty def behaves like the zero Options defaults.

func (Defaults) BraceExpand

func (d Defaults) BraceExpand(pattern string, opts Options) ([]string, error)

BraceExpand applies defaults then BraceExpand.

func (Defaults) Escape

func (d Defaults) Escape(s string, opts EscapeOptions) string

Escape applies defaults then Escape (windowsPathsNoEscape / magicalBraces).

func (Defaults) Filter

func (d Defaults) Filter(pattern string, opts Options) func(string) bool

Filter applies defaults then Filter.

func (Defaults) MakeRe

func (d Defaults) MakeRe(pattern string, opts Options) (*regexp2.Regexp, bool, error)

MakeRe applies defaults then MakeRe.

func (Defaults) Match

func (d Defaults) Match(p, pattern string, opts Options) (bool, error)

Match applies defaults then Match.

func (Defaults) MatchList

func (d Defaults) MatchList(list []string, pattern string, opts Options) ([]string, error)

MatchList applies defaults then MatchList.

func (Defaults) NewMinimatch

func (d Defaults) NewMinimatch(pattern string, opts Options) (*Minimatch, error)

NewMinimatch applies defaults then NewMinimatch.

func (Defaults) ParseGlob

func (d Defaults) ParseGlob(pattern string, opts Options) *AST

ParseGlob applies defaults then ParseGlob.

func (Defaults) Unescape

func (d Defaults) Unescape(s string, opts UnescapeOptions) string

Unescape applies defaults then Unescape.

type EscapeOptions

type EscapeOptions struct {
	// WindowsPathsNoEscape escapes magic characters by wrapping them in
	// character classes ([*]) instead of backslashes, and does not escape \.
	// TypeScript: windowsPathsNoEscape
	WindowsPathsNoEscape bool

	// MagicalBraces also escapes { and }.
	// TypeScript: magicalBraces (default false for escape)
	MagicalBraces bool
}

EscapeOptions is the subset of minimatch options that affect Escape.

The zero value matches TypeScript escape() defaults: windowsPathsNoEscape false, magicalBraces false.

func EscapeOptionsFrom

func EscapeOptionsFrom(o Options) EscapeOptions

EscapeOptionsFrom extracts EscapeOptions from a full Options value.

type ExtglobType

type ExtglobType = scan.ExtglobType

Re-export scan types for advanced callers.

type MMPattern

type MMPattern = ast.MMPattern

MMPattern is a compiled path-segment pattern (literal or regexp2).

type Minimatch

type Minimatch struct {
	// Options is the options bag used to build this pattern.
	Options Options
	// Pattern is the working pattern string (may have leading ! stripped
	// and \\ rewritten to / under WindowsPathsNoEscape).
	Pattern string

	// Negate is true when an odd number of leading ! were stripped.
	Negate bool
	// Comment is true when the pattern is a # comment (matches nothing).
	Comment bool
	// Empty is true when the pattern is the empty string (matches only "").
	Empty bool

	// Resolved flags / platform (mirrors TS instance fields).
	Nonegate                bool
	Partial                 bool
	NoCase                  bool
	PreserveMultipleSlashes bool
	WindowsPathsNoEscape    bool
	WindowsNoMagicRoot      bool
	IsWindows               bool
	Platform                Platform
	MaxGlobstarRecursion    int

	// GlobSet is brace-expanded unique alternatives (order preserved).
	GlobSet []string
	// GlobParts is each GlobSet entry slash-split and preprocessed.
	GlobParts [][]string
	// Set is compiled pattern rows (string | regexp | ** per segment).
	Set [][]PatternPart
	// contains filtered or unexported fields
}

Minimatch is a compiled glob pattern for path matching.

Corresponds to the TypeScript Minimatch class: validate, comment/empty, negate, brace expand, slashSplit, preprocess, and per-segment parse into Set.

func NewMinimatch

func NewMinimatch(pattern string, opts Options) (*Minimatch, error)

NewMinimatch validates pattern and fully compiles it for matching.

Corresponds to `new Minimatch(pattern, options)`.

Example
package main

import (
	"fmt"

	"github.com/benjaminnkem/minimatch-go"
)

func main() {
	m, err := minimatch.NewMinimatch("*.md", minimatch.Options{MatchBase: true})
	if err != nil {
		panic(err)
	}
	fmt.Println(m.Match("docs/README.md"))
	fmt.Println(m.HasMagic())
}
Output:
true
true

func (*Minimatch) HasMagic

func (m *Minimatch) HasMagic() bool

HasMagic reports whether the compiled pattern contains magic segments.

Corresponds to TypeScript Minimatch.hasMagic(). With MagicalBraces, multiple brace alternatives count as magic even if each alternative is a pure literal.

func (*Minimatch) LevelTwoFileOptimize

func (m *Minimatch) LevelTwoFileOptimize(parts []string) []string

LevelTwoFileOptimize optimizes a file path the way match() does under optimizationLevel >= 2 (TS levelTwoFileOptimize).

func (*Minimatch) MakeRe

func (m *Minimatch) MakeRe() (*regexp2.Regexp, bool)

MakeRe builds a single regular expression for the entire path pattern.

Corresponds to TypeScript Minimatch.makeRe() / minimatch.makeRe(). Returns (nil, false) when the pattern cannot form a useful regexp (empty set after compile), matching TypeScript's false return.

Prefer Match for correctness with optimizationLevel ≥ 2; MakeRe is a convenience for fnmatch-style full-string tests.

func (*Minimatch) Match

func (m *Minimatch) Match(f string) bool

Match reports whether path f matches this compiled pattern.

func (*Minimatch) MatchOne

func (m *Minimatch) MatchOne(file []string, pattern []PatternPart, partial bool) bool

MatchOne matches a split path against one compiled pattern row.

func (*Minimatch) MatchPartial

func (m *Minimatch) MatchPartial(f string, partial bool) bool

MatchPartial is Match with an explicit partial flag.

func (*Minimatch) Preprocess

func (m *Minimatch) Preprocess(globParts [][]string) [][]string

Preprocess applies noglobstar rewrite and optimization-level transforms. TypeScript Minimatch.preprocess.

func (*Minimatch) SlashSplit

func (m *Minimatch) SlashSplit(p string) []string

SlashSplit splits a path or pattern on / according to platform rules.

TypeScript Minimatch.slashSplit:

  • preserveMultipleSlashes: split on each /
  • win32 UNC //host…: preserve leading empty segments
  • else: coalesce runs of / via split on /+

type Options

type Options struct {
	// NoBrace disables brace expansion of {a,b} and {1..3} style sets.
	//
	// When false (default), brace expansion runs before other interpretation,
	// so patterns that look invalid before expansion can become valid after.
	// When true, the pattern is left unchanged by the brace-expand step.
	//
	// TypeScript: nobrace
	// Default: false
	NoBrace bool

	// NoComment disables treating a pattern that starts with '#' as a comment.
	//
	// When false (default), a leading '#' means the pattern matches nothing
	// (comment). When true, '#' is ordinary pattern text.
	//
	// TypeScript: nocomment
	// Default: false
	NoComment bool

	// NoNegate disables treating leading '!' characters as pattern negation.
	//
	// When false (default), each leading '!' toggles negation (so "!!" cancels).
	// When true, leading '!' is ordinary pattern text (useful when the pattern
	// should start with a negative extglob like "!(a|b)").
	//
	// TypeScript: nonegate
	// Default: false
	NoNegate bool

	// Debug enables verbose diagnostic logging during compile/match.
	//
	// In TypeScript this prints to stderr via console.error. The Go port will
	// honour this flag when matching is implemented; the flag itself carries
	// no behaviour in the Options model alone.
	//
	// TypeScript: debug
	// Default: false
	Debug bool

	// NoGlobStar disables multi-directory ** semantics.
	//
	// When false (default), a path segment that is exactly "**" is a globstar.
	// When true, "**" is treated like "*". Adjacent "**" collapsing and
	// globstar matching do not apply beyond that rewrite.
	//
	// TypeScript: noglobstar
	// Default: false
	NoGlobStar bool

	// NoExt disables extglob patterns such as +(a|b), *(a|b), ?(a|b),
	// @(a|b), and !(a|b).
	//
	// When true, those forms are not parsed as extglobs (they are ordinary
	// characters / other magic, depending on the rest of the pattern).
	//
	// TypeScript: noext
	// Default: false
	NoExt bool

	// NoNull changes list-filter behaviour when nothing matches.
	//
	// When used with the list Match API (TypeScript minimatch.match): if no
	// path matches and NoNull is true, the result is a one-element list
	// containing the pattern string itself; if false (default), the result
	// is an empty list. This is akin to bash nullglob being off when NoNull
	// is true (return the pattern), but escaped characters are not resolved.
	//
	// TypeScript: nonull
	// Default: false
	NoNull bool

	// WindowsPathsNoEscape treats '\' in patterns as a path separator only,
	// never as an escape character.
	//
	// When true, all '\' in the pattern are rewritten to '/' before further
	// processing. That makes it impossible to escape magic characters with
	// backslashes, but allows patterns built with Windows path.join-style
	// strings. Prefer forward slashes in patterns when possible.
	//
	// Also becomes effective when AllowWindowsEscape is explicitly false
	// (legacy TypeScript behaviour). See EffectiveWindowsPathsNoEscape.
	//
	// TypeScript: windowsPathsNoEscape
	// Default: false
	WindowsPathsNoEscape bool

	// AllowWindowsEscape is the deprecated inverse of WindowsPathsNoEscape.
	//
	// TypeScript only treats the exact value false as meaningful:
	// allowWindowsEscape === false forces windowsPathsNoEscape on.
	// true or undefined leave WindowsPathsNoEscape unchanged.
	//
	// Nil means undefined (default). Prefer WindowsPathsNoEscape in new code.
	//
	// TypeScript: allowWindowsEscape (deprecated)
	// Default: nil (undefined)
	AllowWindowsEscape *bool

	// Partial enables prefix matching for incomplete paths.
	//
	// When true, a path matches if the path segments present do not
	// contradict the pattern — useful while walking a tree before the full
	// path exists. Example (TypeScript semantics):
	//
	//	partial /a/b against /a/*/c/d → true (might become /a/b/c/d)
	//	partial /x/y/z against /a/**/z → false (x !== a)
	//
	// TypeScript: partial
	// Default: false
	Partial bool

	// Dot allows matching path segments that start with '.' even when the
	// pattern does not place a literal dot (or other explicit dot-matching
	// form) in that position.
	//
	// When false (default), patterns like "*" and "a/**/b" do not match
	// ".hidden" or "a/.d/b". When true, those matches are allowed subject
	// to the rest of the pattern. "." and ".." still have special cases in
	// the matcher (documented with matching, not here).
	//
	// TypeScript: dot
	// Default: false
	Dot bool

	// NoCase enables case-insensitive matching.
	//
	// When true, magic portions typically become case-insensitive (e.g.
	// regular expressions with the 'i' flag in TypeScript), and some
	// comparisons fold case. Interacts with NoCaseMagicOnly and
	// WindowsNoMagicRoot.
	//
	// TypeScript: nocase
	// Default: false
	NoCase bool

	// NoCaseMagicOnly, together with NoCase, limits case-insensitivity to
	// magic pattern parts only.
	//
	// When NoCase is true and NoCaseMagicOnly is true, literal string
	// segments stay case-sensitive while wildcards/classes use case-insensitive
	// rules. Has no effect when NoCase is false.
	//
	// TypeScript: nocaseMagicOnly
	// Default: false
	NoCaseMagicOnly bool

	// MagicalBraces controls whether brace expansion counts as “magic” for
	// HasMagic, and whether Escape/Unescape treat '{' and '}' as magic.
	//
	// When false (default), a pattern like "a{b,c}d" has HasMagic false if
	// the expanded alternatives have no other magic. When true, multiple
	// brace alternatives are treated as magic.
	//
	// Note: the free functions Escape and Unescape use their own option
	// structs; Unescape defaults magicalBraces to true even though this
	// field defaults to false on Options (TypeScript free-function defaults).
	//
	// TypeScript: magicalBraces
	// Default: false
	MagicalBraces bool

	// MatchBase matches a pattern that contains no '/' against the basenames
	// of paths that do contain slashes.
	//
	// Example: pattern "a?b" with MatchBase matches path "/xyz/123/acb" but
	// not "/xyz/acb/123".
	//
	// TypeScript: matchBase
	// Default: false
	MatchBase bool

	// FlipNegate changes the boolean result of negated patterns.
	//
	// Normally a negated pattern returns false on a hit (path is excluded).
	// With FlipNegate true, a hit returns true and a miss returns false —
	// as if the pattern were not negated for the purpose of the return value.
	//
	// TypeScript: flipNegate
	// Default: false
	FlipNegate bool

	// PreserveMultipleSlashes disables collapsing consecutive '/' characters
	// in patterns and paths.
	//
	// When false (default), "a///b" is treated like "a/b", except that a
	// leading "//" on Windows UNC forms is preserved specially. When true,
	// empty path segments from repeated slashes are kept.
	//
	// TypeScript: preserveMultipleSlashes
	// Default: false
	PreserveMultipleSlashes bool

	// OptimizationLevel selects how aggressively patterns are rewritten
	// before matching (TypeScript preprocess).
	//
	// Nil means DefaultOptimizationLevel (1). A non-nil pointer to 0
	// requests level 0 (explicit zero is not the same as unset).
	//
	//	0  — only collapse adjacent ** (when not noglobstar); keep . and ..
	//	1  — default; also cancel p/.. when p is not **, ., .., or empty
	//	≥2 — aggressive rewrites for filesystem walks (may diverge from
	//	     makeRe unless the path is optimized similarly)
	//
	// noglobstar always rewrites ** → * regardless of level. Adjacent **
	// collapsing always applies.
	//
	// TypeScript: optimizationLevel
	// Default: nil → 1
	OptimizationLevel *int

	// Platform selects OS personality for path rules (UNC, '\', drive letters).
	//
	// Empty means HostPlatform() (TypeScript process.platform). Only
	// PlatformWin32 ("win32") enables Windows-specific matching behaviour;
	// other values behave like POSIX for matching purposes.
	//
	// TypeScript: platform
	// Default: "" → HostPlatform()
	Platform Platform

	// WindowsNoMagicRoot keeps UNC/drive root segments as literal strings
	// under case-insensitive mode instead of case-insensitive magic.
	//
	// When nil, defaults to true if EffectivePlatform is win32 and NoCase
	// is true; otherwise false. When non-nil, that value is used exactly.
	//
	// TypeScript: windowsNoMagicRoot
	// Default: nil → (win32 && NoCase)
	WindowsNoMagicRoot *bool

	// BraceExpandMax caps how many strings brace expansion may produce.
	//
	// Nil means DefaultBraceExpandMax (100_000). Passed through to the
	// brace-expansion step when that subsystem exists.
	//
	// TypeScript: braceExpandMax
	// Default: nil → 100_000
	BraceExpandMax *int

	// MaxGlobstarRecursion caps how many non-adjacent ** body sections may
	// be walked recursively during matching.
	//
	// Nil means DefaultMaxGlobstarRecursion (200). If the limit is exceeded,
	// the reference treats the path as non-matching (intentional false
	// negative for security/performance).
	//
	// TypeScript: maxGlobstarRecursion
	// Default: nil → 200
	MaxGlobstarRecursion *int

	// MaxExtglobRecursion caps nested extglob parse depth (e.g. *(a|*(b|c))).
	//
	// Nil means DefaultMaxExtglobRecursion (2). When the limit is hit, nested
	// extglob syntax is not parsed further (effectively noext for that nest);
	// adoption/flattening of nestable forms can avoid hitting the limit.
	//
	// TypeScript: maxExtglobRecursion
	// Default: nil → 2
	MaxExtglobRecursion *int
}

Options controls glob compilation and matching behaviour.

It is the Go equivalent of TypeScript MinimatchOptions. Field names are idiomatic Go; each field documents its TypeScript key.

Options is pure configuration: reading or constructing it does not parse patterns, expand braces, or match paths. Later subsystems consume Options (and the Effective* helpers) when those behaviours are implemented.

Default behaviour (zero value)

var o Options  // and Options{}

matches TypeScript `{}` / omitted options for all flags:

NoBrace, NoComment, NoNegate, Debug, NoGlobStar, NoExt, NoNull,
WindowsPathsNoEscape, Partial, Dot, NoCase, NoCaseMagicOnly,
MagicalBraces, MatchBase, FlipNegate, PreserveMultipleSlashes
  → false

AllowWindowsEscape     → nil (undefined; does not force WindowsPathsNoEscape)
OptimizationLevel      → nil → EffectiveOptimizationLevel() == 1
Platform               → ""  → EffectivePlatform() == HostPlatform()
WindowsNoMagicRoot     → nil → true iff win32 && NoCase
BraceExpandMax         → nil → 100_000
MaxGlobstarRecursion   → nil → 200
MaxExtglobRecursion    → nil → 2

Use Bool and Int helpers to set pointer fields without awkward locals:

opts := Options{OptimizationLevel: Int(0), WindowsNoMagicRoot: Bool(false)}

Relation to Escape / Unescape

Escape and Unescape use small option structs (EscapeOptions, UnescapeOptions) because TypeScript applies different defaults for magicalBraces on those free functions (false vs true). EscapeOptionsFrom and UnescapeOptionsFrom project a full Options value into those structs.

func (Options) EffectiveBraceExpandMax

func (o Options) EffectiveBraceExpandMax() int

EffectiveBraceExpandMax returns the brace expansion cardinality cap.

TypeScript / brace-expansion: options.braceExpandMax ?? 100_000

func (Options) EffectiveIsWindows

func (o Options) EffectiveIsWindows() bool

EffectiveIsWindows reports whether EffectivePlatform is win32.

func (Options) EffectiveMaxExtglobRecursion

func (o Options) EffectiveMaxExtglobRecursion() int

EffectiveMaxExtglobRecursion returns the nested extglob depth limit.

TypeScript: options.maxExtglobRecursion ?? 2

func (Options) EffectiveMaxGlobstarRecursion

func (o Options) EffectiveMaxGlobstarRecursion() int

EffectiveMaxGlobstarRecursion returns the ** recursion limit.

TypeScript: options.maxGlobstarRecursion ?? 200

func (Options) EffectiveOptimizationLevel

func (o Options) EffectiveOptimizationLevel() int

EffectiveOptimizationLevel returns the optimization level, applying DefaultOptimizationLevel when OptimizationLevel is nil.

TypeScript: const { optimizationLevel = 1 } = this.options

func (Options) EffectivePlatform

func (o Options) EffectivePlatform() Platform

EffectivePlatform returns o.Platform, or HostPlatform() when Platform is empty (TypeScript: options.platform || process.platform).

func (Options) EffectiveWindowsNoMagicRoot

func (o Options) EffectiveWindowsNoMagicRoot() bool

EffectiveWindowsNoMagicRoot reports whether UNC/drive roots should remain non-magic under NoCase.

TypeScript:

windowsNoMagicRoot !== undefined
  ? windowsNoMagicRoot
  : !!(isWindows && nocase)

func (Options) EffectiveWindowsPathsNoEscape

func (o Options) EffectiveWindowsPathsNoEscape() bool

EffectiveWindowsPathsNoEscape reports whether '\' in patterns is a path separator (and not an escape).

True when WindowsPathsNoEscape is true, or when AllowWindowsEscape is explicitly false (TypeScript: !!windowsPathsNoEscape || allowWindowsEscape === false).

type ParseClassResult

type ParseClassResult = class.ParseClassResult

ParseClassResult is the outcome of ParseClass.

func ParseClass

func ParseClass(pattern string, position int) (ParseClassResult, error)

ParseClass parses a glob character class at position in pattern.

type PatternPart

type PatternPart struct {
	// IsGlobStar is true for **.
	IsGlobStar bool
	// Str is the literal string when matching exactly (also used for
	// windowsNoMagicRoot roots kept as strings).
	Str string
	// MM is the compiled segment pattern when magic.
	MM MMPattern
	// HasMM is true when MM is valid for matching (magic or forced RE).
	HasMM bool
	// Test is an optional fast-path predicate replacing MM.Match.
	Test func(string) bool
	// UFlag is true when the segment source needs Unicode properties.
	UFlag bool
}

PatternPart is one compiled path segment (TypeScript ParseReturnFiltered).

Exactly one of:

  • IsGlobStar
  • literal Str (IsRE false and Test nil) for exact string match
  • MM + optional Test for magic match

type Platform

type Platform string

Platform identifies the operating system personality that controls Windows-specific path behaviour (UNC paths, backslash handling, drive letters, windowsNoMagicRoot defaults).

Values match Node.js process.platform strings from the TypeScript API, not necessarily Go's runtime.GOOS (in particular Windows is "win32").

const (
	PlatformAIX     Platform = "aix"
	PlatformAndroid Platform = "android"
	PlatformDarwin  Platform = "darwin"
	PlatformFreeBSD Platform = "freebsd"
	PlatformHaiku   Platform = "haiku"
	PlatformLinux   Platform = "linux"
	PlatformOpenBSD Platform = "openbsd"
	PlatformSunOS   Platform = "sunos"
	PlatformWin32   Platform = "win32"
	PlatformCygwin  Platform = "cygwin"
	PlatformNetBSD  Platform = "netbsd"
)

Platform constants corresponding to the TypeScript Platform union.

func HostPlatform

func HostPlatform() Platform

HostPlatform returns the Platform value for the running operating system.

Go's runtime.GOOS uses "windows"; the TypeScript API uses "win32". This function maps that difference so Windows-specific behaviour aligns with the reference implementation. Other GOOS values are returned as Platform(GOOS) when they match a Node platform string; unknown systems are returned as their GOOS string without special handling (only win32 changes matching semantics in the reference).

func (Platform) IsWindows

func (p Platform) IsWindows() bool

IsWindows reports whether p is the Windows platform (Node "win32").

func (Platform) PathSep

func (p Platform) PathSep() Sep

PathSep returns the path separator associated with p. Non-Windows platforms use SepPOSIX.

type RegExpSource

type RegExpSource = ast.RegExpSource

RegExpSource is the result of AST.ToRegExpSource.

type Sep

type Sep string

Sep is a path separator character used when reporting the active separator for the default platform (TypeScript minimatch.sep).

const (
	// SepPOSIX is the forward slash used on non-Windows platforms.
	SepPOSIX Sep = "/"
	// SepWindows is the backslash used when the platform is win32.
	SepWindows Sep = `\`
)

Path separator constants.

func HostSep

func HostSep() Sep

HostSep is the path separator for the host platform (TypeScript minimatch.sep).

type Token

type Token = scan.Token

Re-export scan types for advanced callers.

func Scan

func Scan(segment string, opts Options) []Token

Scan tokenizes a single path-segment pattern string.

type TokenKind

type TokenKind = scan.TokenKind

Re-export scan types for advanced callers.

type UnescapeOptions

type UnescapeOptions struct {
	// WindowsPathsNoEscape removes only []-style escapes, not backslash
	// escapes, because \ is a path separator in that mode.
	// TypeScript: windowsPathsNoEscape
	WindowsPathsNoEscape bool

	// MagicalBraces controls whether brace escapes ({ }) are unescaped.
	// When nil, braces are unescaped (TypeScript default true for unescape).
	// When non-nil, the pointed-to value is used.
	// TypeScript: magicalBraces (default true for unescape)
	MagicalBraces *bool
}

UnescapeOptions is the subset of minimatch options that affect Unescape.

The zero value matches TypeScript unescape() defaults: windowsPathsNoEscape false, magicalBraces true (note: true, unlike Escape).

func UnescapeOptionsFrom

func UnescapeOptionsFrom(o Options) UnescapeOptions

UnescapeOptionsFrom extracts UnescapeOptions from a full Options value.

MagicalBraces is taken as an explicit bool from o (including false), matching Object.assign when the property is present on the options object. For TypeScript-style free-function defaults (magicalBraces undefined → true), use the zero value UnescapeOptions{} instead.

Directories

Path Synopsis
internal
ast

Jump to

Keyboard shortcuts

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