gofd

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2026 License: MIT Imports: 11 Imported by: 0

README

go-fd

A pure-Go port of fd — a simple, fast and user-friendly alternative to find. It provides both a CLI tool (fd) that mirrors the original's interface and a Go SDK for programmatic use.

Go License

Features

  • Intuitive syntaxfd PATTERN instead of find -iname '*PATTERN*'.
  • Regex (default) and glob matching (-g/--glob).
  • Fast, parallel directory traversal using goroutines.
  • Smart case — case-insensitive unless the pattern has an uppercase char.
  • Respects ignore files.gitignore, .ignore, .fdignore, global and custom ignore files, with nested-directory support.
  • Hidden-file handling, exclusion globs (-E), and directory pruning.
  • Rich filters — by type (-t), extension (-e), size (-S), modification time (--changed-within/--changed-before) and owner (-o, unix).
  • Command execution — run a command per result (-x) or batched (-X).
  • Output control — colors (LS_COLORS), --format templates, --print0, hyperlinks, custom path separators, depth and result limits.
  • NPM distribution — install via npm/yarn for Node.js projects.
  • Pure Go SDK — embed fd-style search in your own programs.

Installation

From source
git clone https://github.com/startvibecoding/go-fd.git
cd go-fd
make build          # produces ./bin/fd
Via go install
go install github.com/startvibecoding/go-fd/cmd/fd@latest
As a Go library
go get github.com/startvibecoding/go-fd@latest

Then import the module root. The import path contains go-fd, but the package name is gofd:

import gofd "github.com/startvibecoding/go-fd"
Via the install script
curl -fsSL https://raw.githubusercontent.com/startvibecoding/go-fd/main/install.sh | bash
# Install to a custom directory:
curl -fsSL https://raw.githubusercontent.com/startvibecoding/go-fd/main/install.sh | bash -s -- -d ~/.local/bin
# Uninstall:
curl -fsSL https://raw.githubusercontent.com/startvibecoding/go-fd/main/install.sh | bash -s -- --uninstall
Via npm

The npm package ships a small launcher plus per-platform binary packages (optionalDependencies), so you only download the binary for your platform.

npm install -g @startvibecoding/go-fd-installer
# Binary available as `fd`
Pre-built binaries

Download a .tar.gz (Linux/macOS/FreeBSD) or .zip (Windows) from the GitHub Releases page.

Supported platforms

go-fd is pure Go and builds for a broad OS/architecture matrix. Pre-built binaries and npm packages are published for:

OS Architectures
Linux (glibc) amd64, arm64, arm (v7), 386, loong64, riscv64, ppc64le, s390x
Linux (musl, static) amd64, arm64
macOS amd64 (Intel), arm64 (Apple Silicon)
Windows amd64, arm64, 386
FreeBSD amd64, arm64

The source additionally compiles for other Go targets (NetBSD, OpenBSD, DragonFly, illumos/Solaris, Android, and more) — run make build-<os> or set GOOS/GOARCH directly.

CLI usage

# Find entries matching a regex (filename only, by default)
fd netfl

# Match all files with a given extension
fd -e go

# Glob search
fd -g '*.txt'

# Search hidden + ignored files
fd -u pattern

# Filter by type and size, in a specific path
fd -t f -S +1m '\.log$' /var/log

# Execute a command per result
fd -e jpg -x convert {} {.}.png

# Batch execution
fd -e rs -X wc -l

# Custom output template
fd -e go --format '{//} -> {/.}'

Run fd --help for the full option list.

SDK usage

The module root exposes a friendly API in package gofd.

package main

import (
	"context"
	"fmt"

	gofd "github.com/startvibecoding/go-fd"
)

func main() {
	// Collect all matching paths.
	paths, err := gofd.Find(context.Background(), gofd.Options{
		Pattern: `\.go$`,
		Paths:   []string{"."},
		Hidden:  false,
	})
	if err != nil {
		panic(err)
	}
	for _, p := range paths {
		fmt.Println(p)
	}

	// Or stream results as they are discovered.
	results, errs, err := gofd.Stream(context.Background(), gofd.Options{
		Pattern: "main",
		Glob:    false,
		Paths:   []string{"."},
	})
	if err != nil {
		panic(err)
	}
	for r := range results {
		fmt.Println("found:", r.Path)
	}
	for range errs {
		// non-fatal traversal errors
	}
}
gofd.Options

The Options struct exposes the same knobs as the CLI: pattern interpretation (Glob, FixedStrings, Exact), case handling (CaseSensitive, IgnoreCase), ignore handling (Hidden, NoIgnore, Unrestricted, ...), traversal (MaxDepth, MinDepth, FollowLinks, Prune, Threads), filters (Types, Extensions, Sizes, ChangedWithin, ChangedBefore, Owner, Exclude) and output (NullSeparator, Format, MaxResults, Color).

For lower-level control, the github.com/startvibecoding/go-fd/pkg/finder package lets you build a finder.Config directly and call finder.New(cfg).

Go module compatibility

The module path is:

github.com/startvibecoding/go-fd

It has no external Go dependencies and declares Go 1.21 as its minimum version. Other Go projects can depend on it with go get github.com/startvibecoding/go-fd@latest or a specific tagged version.

When publishing Git tags for Go consumers, use semantic module tags that match the module path. Because the path does not include a major-version suffix like /v2, publish library-compatible tags as v0.x.y or v1.x.y. The CLI can still report the upstream fd compatibility version, such as 10.4.2-go, through fd --version.

Before pushing a release tag:

gofmt -l .
go vet ./...
go test ./...
go list ./...

Project layout

cmd/fd/            CLI entry point and argument parser
pkg/finder/        Core engine: config, parallel walk, filtering, output, SDK
pkg/glob/          Glob -> regex translation
pkg/ignore/        gitignore-style pattern matching
pkg/filter/        Size, time and owner filters
pkg/format/        Placeholder templates ({}, {/}, {//}, {.}, {/.})
pkg/exec/          Command execution (-x / -X)
fd.go              High-level SDK (package gofd)
tests/             Integration tests

Testing

make test     # go test ./...
make vet      # go vet ./...

License

Licensed under the MIT License.

Documentation

Overview

Package gofd is a pure-Go port of the `fd` file finder. It exposes a friendly SDK for embedding fd-style search in Go programs, while cmd/fd provides a CLI compatible with the original tool.

Typical SDK usage:

import gofd "github.com/startvibecoding/go-fd"

results, err := gofd.Find(context.Background(), gofd.Options{
    Pattern: "\\.go$",
    Paths:   []string{"."},
})

Index

Examples

Constants

View Source
const (
	ExitSuccess      = finder.ExitSuccess
	ExitGeneralError = finder.ExitGeneralError
)

Process exit codes.

Variables

This section is empty.

Functions

func Compile

func Compile(opts Options) (*finder.Finder, []string, error)

Compile validates the options, builds the finder and resolves search paths.

func Find

func Find(ctx context.Context, opts Options) ([]string, error)

Find runs a search and returns matching paths sorted lexicographically.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"sort"

	gofd "github.com/startvibecoding/go-fd"
)

func main() {
	dir, err := os.MkdirTemp("", "gofd-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	for _, name := range []string{"main.go", "README.md", "internal/util.go"} {
		path := filepath.Join(dir, filepath.FromSlash(name))
		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
			panic(err)
		}
		if err := os.WriteFile(path, []byte(""), 0o644); err != nil {
			panic(err)
		}
	}

	paths, err := gofd.Find(context.Background(), gofd.Options{
		Pattern: `\.go$`,
		Paths:   []string{dir},
	})
	if err != nil {
		panic(err)
	}

	var rels []string
	for _, path := range paths {
		rel, err := filepath.Rel(dir, path)
		if err != nil {
			panic(err)
		}
		rels = append(rels, filepath.ToSlash(rel))
	}
	sort.Strings(rels)
	for _, rel := range rels {
		fmt.Println(rel)
	}

}
Output:
internal/util.go
main.go

func Stream

func Stream(ctx context.Context, opts Options) (<-chan Result, <-chan error, error)

Stream runs a search and streams results over a channel.

Example
package main

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

	gofd "github.com/startvibecoding/go-fd"
)

func main() {
	dir, err := os.MkdirTemp("", "gofd-example-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(dir)

	for _, name := range []string{"main.go", "util.go"} {
		if err := os.WriteFile(filepath.Join(dir, name), []byte(""), 0o644); err != nil {
			panic(err)
		}
	}

	results, errs, err := gofd.Stream(context.Background(), gofd.Options{
		Pattern: `\.go$`,
		Paths:   []string{dir},
	})
	if err != nil {
		panic(err)
	}

	count := 0
	for range results {
		count++
	}
	for err := range errs {
		if err != nil {
			panic(err)
		}
	}
	fmt.Println(count)

}
Output:
2

func ValidateSearchPaths added in v0.0.4

func ValidateSearchPaths(opts Options) ([]string, []string, error)

ValidateSearchPaths resolves valid search roots and reports invalid ones without printing anything. It is primarily useful for callers that want to preserve CLI-style diagnostics while keeping SDK operations silent.

Types

type ExitCode

type ExitCode = finder.ExitCode

ExitCode re-exports finder.ExitCode for SDK/CLI consumers.

type Options

type Options struct {
	// Pattern is the primary search pattern. Empty matches everything.
	Pattern string
	// Exprs are additional patterns that must all match (fd's --and).
	Exprs []string
	// Paths are the search roots. Defaults to the current directory.
	Paths []string

	// Pattern interpretation.
	Glob         bool // treat patterns as globs
	FixedStrings bool // treat patterns as literal substrings
	Exact        bool // match the whole filename literally

	// Case handling. By default smart-case is used.
	CaseSensitive bool
	IgnoreCase    bool

	// Path matching.
	FullPath     bool // match against the full path, not just the file name
	AbsolutePath bool // emit absolute paths

	// Ignore handling.
	Hidden         bool // include hidden files
	NoIgnore       bool // disable all ignore files
	NoIgnoreVcs    bool // disable .gitignore only
	NoIgnoreParent bool // disable ignore files in parent directories
	NoGlobalIgnore bool // disable the global ignore file
	NoRequireGit   bool // respect gitignore even outside a git repo
	Unrestricted   bool // alias for NoIgnore + Hidden

	// Traversal.
	FollowLinks   bool
	OneFileSystem bool
	MaxDepth      int // 0 = unlimited
	MinDepth      int // 0 = none
	ExactDepth    int // 0 = unset; sets both min and max
	Prune         bool
	Threads       int // 0 = auto

	// Filters.
	Types         []string // f,d,l,x,e,s,p,c,b (or long names)
	Extensions    []string
	Exclude       []string
	Sizes         []string // e.g. "+1m", "-500k"
	ChangedWithin string
	ChangedBefore string
	Owner         string // [user|uid][:group|gid]
	IgnoreFiles   []string
	IgnoreContain []string

	// Output.
	NullSeparator  bool
	PathSeparator  string
	MaxResults     int // 0 = unlimited
	Format         string
	StripCwdPrefix *bool // nil = auto

	// Color: "auto", "always", "never".
	Color     string
	Hyperlink string // "auto", "always", "never"

	// Command execution (mutually exclusive with Format/output).
	Exec      []string // -x command template (terminated logically by caller)
	ExecBatch []string // -X command template
	BatchSize int

	ShowErrors bool
	Quiet      bool

	// ListDetails emulates --list-details (ls -l style listing).
	ListDetails bool
}

Options is the high-level, user-facing configuration for a search. Sensible fd defaults (smart case, respecting ignore files, skipping hidden entries) are applied automatically.

type Result

type Result = finder.Result

Result re-exports finder.Result for SDK consumers.

Directories

Path Synopsis
cmd
fd command
Command fd is a Go port of the `fd` file finder.
Command fd is a Go port of the `fd` file finder.
pkg
exec
Package exec implements fd's command execution feature (-x/--exec and -X/--exec-batch), including placeholder substitution and batching.
Package exec implements fd's command execution feature (-x/--exec and -X/--exec-batch), including placeholder substitution and batching.
filter
Package filter implements the result filters used by fd: size, modification time and (on unix) ownership constraints.
Package filter implements the result filters used by fd: size, modification time and (on unix) ownership constraints.
finder
Package finder is the core engine of go-fd.
Package finder is the core engine of go-fd.
format
Package format implements fd's format/exec placeholder templates, supporting the tokens {}, {/}, {//}, {.}, {/.} and literal brace escaping ({{ }}).
Package format implements fd's format/exec placeholder templates, supporting the tokens {}, {/}, {//}, {.}, {/.} and literal brace escaping ({{ }}).
glob
Package glob translates shell-style glob patterns into Go regular expressions.
Package glob translates shell-style glob patterns into Go regular expressions.
ignore
Package ignore implements gitignore-style pattern matching used by fd to honor .gitignore, .ignore, .fdignore and custom ignore files.
Package ignore implements gitignore-style pattern matching used by fd to honor .gitignore, .ignore, .fdignore and custom ignore files.

Jump to

Keyboard shortcuts

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