fsglob

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2025 License: MIT Imports: 9 Imported by: 1

README

fsglob

Go Reference Go Report Card MIT License

fsglob is a Go package for finding file paths that match glob patterns. It operates by walking a filesystem and is designed to be cross-platform and extensible.

Features

  • Standard Glob Patterns: Supports common glob syntax for flexible matching.
  • Cross-Platform Path Handling: Automatically handles both Windows (\) and Unix (/) path separators in patterns.
  • Extensible Filesystem: Can operate on any filesystem that implements the provided filesystem.Filesystem interface, making it suitable for testing with mocks or for use with virtual filesystems.

Installation

go get github.com/your-username/fsglob

Quick Start

The main function in this package is fsglob.GetFiles(). It takes a pattern and returns a slice of all matching file and directory paths.

package main

import (
	"fmt"
	"log"

	"github.com/your-username/fsglob"
)

func main() {
	// Example 1: Find all Go files recursively from the current directory.
	goFiles, err := fsglob.GetFiles("**/*.go")
	if err != nil {
		log.Fatalf("Failed to find Go files: %v", err)
	}

	fmt.Println("Found Go files:")
	for _, file := range goFiles {
		fmt.Println(file)
	}

	// Example 2: Find all Markdown or text files in a 'docs' directory.
	docFiles, err := fsglob.GetFiles("docs/*.{md,txt}")
	if err != nil {
		log.Fatalf("Failed to find doc files: %v", err)
	}

	fmt.Println("\nFound documentation files:")
	for _, file := range docFiles {
		fmt.Println(file)
	}
}

Pattern Matching Details

fsglob supports the following pattern syntax:

Pattern Description Example
* Matches any sequence of characters, except for path separators (/ or \). *.log
? Matches any single character. file?.txt
** Matches zero or more directories, files, and subdirectories recursively. reports/**/*.xml
[] Matches any single character within the brackets. Can be a set or a range. [abc].go, [0-9].txt
{} Matches any of the comma-separated patterns within the braces. image.{jpg,png,gif}

Advanced Usage: Custom Filesystem

For testing or working with virtual filesystems (e.g., in-memory, TAR files), you can use fsglob.NewGlob() to create a globber instance that operates on a custom filesystem.

Your custom filesystem must implement the filesystem.Filesystem interface, which is exposed by github.com/your-username/fsglob/filesystem.

package main

import (
	"fmt"
	"log"

	"github.com/your-username/fsglob"
	"github.com/your-username/fsglob/filesystem"
)

// InMemoryFS is a simple in-memory implementation of filesystem.Filesystem.
// (This is a conceptual example; a full implementation is required).
type InMemoryFS struct {
    // ... fields to store files and directories in memory
}

// Implement the methods of the filesystem.Filesystem interface for InMemoryFS...
func (fs *InMemoryFS) Stat(name string) (fs.FileInfo, error) { /* ... */ }
func (fs *InMemoryFS) ReadDir(name string) ([]fs.DirEntry, error) { /* ... */ }
func (fs *InMemoryFS) Getwd() (string, error) { /* ... */ }
func (fs *InMemoryFS) Abs(path string) (string, error) { /* ... */ }
// ... other methods

func main() {
	// 1. Create an instance of your custom filesystem.
	memFS := &InMemoryFS{}
	// ... code to populate memFS with files and directories ...

	// 2. Create a new Glob instance with the custom filesystem.
	g := fsglob.NewGlob("/**/*.log", memFS)

	// 3. Use the Expand() method to find matches.
	matches, err := g.Expand()
	if err != nil {
		log.Fatalf("Error during glob expansion: %v", err)
	}

	fmt.Println("Log files found in the in-memory filesystem:")
	for _, match := range matches {
		fmt.Println(match)
	}
}

License

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetFiles

func GetFiles(pattern string) ([]string, error)

GetFiles is the public entry point for globbing.

Types

type Glob

type Glob struct {
	OriginalPattern string
	IgnoreCase      bool
	FS              filesystem.Filesystem
	// contains filtered or unexported fields
}

Glob is the main globbing engine. It holds the original pattern and configuration for a globbing operation.

An instance is created with NewGlob, which allows for advanced configuration, such as setting a custom filesystem or enabling case-insensitive matching.

func NewGlob

func NewGlob(pattern string, fs filesystem.Filesystem, opts ...GlobOption) *Glob

NewGlob creates and returns a new Glob engine for the given pattern. It uses the provided filesystem `fs` for all file operations. If `fs` is nil, it defaults to the host operating system's filesystem.

Functional options (GlobOption) can be provided to customize the globber's behavior, such as enabling case-insensitive matching with WithIgnoreCase.

func (*Glob) Expand

func (g *Glob) Expand() ([]string, error)

Expand executes the glob pattern and returns all matching file paths. It is the primary method for retrieving results from a configured Glob instance. The function returns an empty, non-nil slice if no matches are found.

func (*Glob) ExpandNames deprecated

func (g *Glob) ExpandNames() ([]string, error)

ExpandNames executes the glob pattern and returns all matching file paths.

Deprecated: This function is an alias for Expand. Please use Expand instead.

func (*Glob) String

func (g *Glob) String() string

String returns the original, unmodified pattern that was used to create the Glob instance.

type GlobOption

type GlobOption func(*Glob)

A GlobOption configures a Glob instance. It's a functional option type used with NewGlob.

func WithIgnoreCase

func WithIgnoreCase(v bool) GlobOption

WithIgnoreCase returns a GlobOption that sets the globber to perform case-insensitive matching. On Windows, literal (non-wildcard) path segments are case-insensitive by default. This option forces wildcards and all other patterns to also ignore case.

type RegexOrString

type RegexOrString struct {
	// CompiledRegex is the compiled regular expression if the pattern segment contains wildcards.
	CompiledRegex *regexp.Regexp
	// IsRegex indicates if CompiledRegex is used for matching.
	IsRegex bool
	// LiteralPattern is the original glob pattern segment if it's treated as a literal.
	LiteralPattern string
	// IgnoreCase indicates if matching should be case-insensitive for literal patterns.
	IgnoreCase bool
	// OriginalRegexPattern stores the regex string pattern before compilation (for debugging or special checks).
	OriginalRegexPattern string
}

RegexOrString is a helper struct that holds either a compiled regular expression or a literal string for efficient pattern matching. It is used internally to optimize matching by avoiding regex compilation for simple patterns.

func (*RegexOrString) IsMatch

func (ros *RegexOrString) IsMatch(input string) bool

IsMatch checks if the input string matches this RegexOrString. For regex patterns, it uses the compiled regex. For literal patterns, it performs a string comparison, respecting IgnoreCase.

Directories

Path Synopsis
Package filesystem provides abstractions for filesystem operations to enable easier testing and mocking of file system interactions.
Package filesystem provides abstractions for filesystem operations to enable easier testing and mocking of file system interactions.

Jump to

Keyboard shortcuts

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