diff --git a/README.md b/README.md index 4533a89..abc3af1 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ including `dmlfmt` (an opinionated deterministic code formatter). ### Via `go install` -With Go 1.23+ installed: +With Go 1.27+ installed: ```bash # Install the dmlfmt code formatter diff --git a/cmd/dmlfmt/cmdline.go b/cmd/dmlfmt/cmdline.go index 6e5ffa1..80c312a 100644 --- a/cmd/dmlfmt/cmdline.go +++ b/cmd/dmlfmt/cmdline.go @@ -31,6 +31,9 @@ const ( ExitCodeOK = 0 ExitCodeWouldReformat = 1 ExitCodeInternalError = 123 + + // MaxFileSize defines the maximum permitted file size in bytes for disk files (50 MiB). + MaxFileSize int64 = 50 << 20 ) // ColorMode specifies the coloring behavior for terminal outputs. diff --git a/cmd/dmlfmt/collector.go b/cmd/dmlfmt/collector.go deleted file mode 100644 index 2c0c769..0000000 --- a/cmd/dmlfmt/collector.go +++ /dev/null @@ -1,286 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -// Copyright (C) 2026 Sergei Timoshchenko - -package main - -import ( - "fmt" - iofs "io/fs" - "os" - "path/filepath" - "regexp" - "slices" - "strings" - - "github.com/timoschenko/dmltools/pkg/fs" -) - -// IgnoreCallback is called when a file or directory is ignored due to exclusion/inclusion filters. -type IgnoreCallback func(path string, isDir bool, filterName string) - -// FileCollector handles file discovery, recursive directory traversal, -// and filtering based on include, exclude, extend-exclude, and force-exclude regular expressions. -type FileCollector struct { - include *regexp.Regexp - exclude *regexp.Regexp - extendExclude *regexp.Regexp - forceExclude *regexp.Regexp - onIgnore IgnoreCallback -} - -// SetOnIgnore sets the callback invoked when a file or directory is skipped. -func (fc *FileCollector) SetOnIgnore(cb IgnoreCallback) { - fc.onIgnore = cb -} - -// NewFileCollector compiles regular expressions from the CLI configuration. -func NewFileCollector(cfg *CLIConfig) (*FileCollector, error) { - // TODO: AI slop - fc := &FileCollector{} - var err error - - if cfg.Include != "" { - fc.include, err = regexp.Compile(cfg.Include) - if err != nil { - return nil, fmt.Errorf( - "invalid regular expression for --include: %w", - err, - ) - } - } - if cfg.Exclude != "" { - fc.exclude, err = regexp.Compile(cfg.Exclude) - if err != nil { - return nil, fmt.Errorf( - "invalid regular expression for --exclude: %w", - err, - ) - } - } - if cfg.ExtendExclude != "" { - fc.extendExclude, err = regexp.Compile(cfg.ExtendExclude) - if err != nil { - return nil, fmt.Errorf( - "invalid regular expression for --extend-exclude: %w", - err, - ) - } - } - if cfg.ForceExclude != "" { - fc.forceExclude, err = regexp.Compile(cfg.ForceExclude) - if err != nil { - return nil, fmt.Errorf( - "invalid regular expression for --force-exclude: %w", - err, - ) - } - } - return fc, nil -} - -// IsForceExcluded reports whether a file or directory matches the --force-exclude regex. -func (fc *FileCollector) IsForceExcluded(path string) bool { - // TODO: AI slop - if fc.forceExclude == nil { - return false - } - normFile := fs.NormalizePath(path, false) - if fc.forceExclude.MatchString(normFile) { - return true - } - normDir := fs.NormalizePath(path, true) - if fc.forceExclude.MatchString(normDir) { - return true - } - if !filepath.IsAbs(path) { - if abs, err := filepath.Abs(path); err == nil { - if fc.forceExclude.MatchString(fs.NormalizePath(abs, false)) { - return true - } - if fc.forceExclude.MatchString(fs.NormalizePath(abs, true)) { - return true - } - } - } - return false -} - -func (fc *FileCollector) matchExcludeFilter(normPath string) string { - if fc.forceExclude != nil && fc.forceExclude.MatchString(normPath) { - return "--force-exclude" - } - if fc.exclude != nil && fc.exclude.MatchString(normPath) { - return "--exclude" - } - if fc.extendExclude != nil && fc.extendExclude.MatchString(normPath) { - return "--extend-exclude" - } - return "" -} - -func (fc *FileCollector) pathExcludeFilter( - relToRoot, fullPath string, - isDir bool, -) string { - normRel := fs.NormalizePath(relToRoot, isDir) - if f := fc.matchExcludeFilter(normRel); f != "" { - return f - } - normFull := fs.NormalizePath(fullPath, isDir) - if f := fc.matchExcludeFilter(normFull); f != "" { - return f - } - if !filepath.IsAbs(fullPath) { - if abs, err := filepath.Abs(fullPath); err == nil { - normAbs := fs.NormalizePath(abs, isDir) - if f := fc.matchExcludeFilter(normAbs); f != "" { - return f - } - } - } - return "" -} - -func (fc *FileCollector) isPathIncluded(relToRoot, fullPath string) bool { - // TODO: AI slop - if fc.include == nil { - return true - } - normRel := fs.NormalizePath(relToRoot, false) - if fc.include.MatchString(normRel) { - return true - } - normFull := fs.NormalizePath(fullPath, false) - if fc.include.MatchString(normFull) { - return true - } - if !filepath.IsAbs(fullPath) { - if abs, err := filepath.Abs(fullPath); err == nil { - if fc.include.MatchString(fs.NormalizePath(abs, false)) { - return true - } - } - } - return false -} - -// Collect discovers, filters, deduplicates, and sorts file paths specified by sources. -func (fc *FileCollector) Collect(sources []string) ([]string, error) { - // TODO: AI slop - seen := make(map[string]bool) - var files []string - - for _, src := range sources { - if fc.IsForceExcluded(src) { - if fc.onIgnore != nil { - isDir := false - if info, err := os.Stat(src); err == nil && info.IsDir() { - isDir = true - } - cleanSrc := filepath.Clean(src) - if isDir || strings.HasSuffix(cleanSrc, ".dml") { - fc.onIgnore(cleanSrc, isDir, "--force-exclude") - } - } - continue - } - - info, err := os.Stat(src) - if err != nil { - return nil, fmt.Errorf("reading file %s: %w", src, err) - } - - if info.IsDir() { - cleanSrc := filepath.Clean(src) - filter := fc.pathExcludeFilter(src, src, true) - if filter != "" { - if fc.onIgnore != nil { - fc.onIgnore(cleanSrc, true, filter) - } - continue - } - - err := filepath.WalkDir( - src, - func(path string, d iofs.DirEntry, walkErr error) error { - if walkErr != nil { - return fmt.Errorf( - "reading file %s: %w", - path, - walkErr, - ) - } - - rel, err := filepath.Rel(src, path) - if err != nil { - rel = path - } - - cleanPath := filepath.Clean(path) - - if d.IsDir() { - if path == src { - return nil - } - filter := fc.pathExcludeFilter(rel, path, true) - if filter != "" { - if fc.onIgnore != nil { - fc.onIgnore(cleanPath, true, filter) - } - return filepath.SkipDir - } - return nil - } - - if d.Type()&iofs.ModeSymlink != 0 { - targetInfo, err := os.Stat(path) - if err != nil { - // Broken symlink; skip - return nil - } - if targetInfo.IsDir() { - // Do not traverse into directory symlinks - return nil - } - } - - isDml := strings.HasSuffix(cleanPath, ".dml") - filter := fc.pathExcludeFilter(rel, path, false) - if filter != "" { - if isDml && fc.onIgnore != nil { - fc.onIgnore(cleanPath, false, filter) - } - return nil - } - - if !fc.isPathIncluded(rel, path) { - if isDml && fc.onIgnore != nil { - fc.onIgnore(cleanPath, false, "--include") - } - return nil - } - - if !seen[cleanPath] { - seen[cleanPath] = true - files = append(files, cleanPath) - } - return nil - }, - ) - if err != nil { - return nil, err - } - } else { - // Explicit file argument: bypasses --include, --exclude, and --extend-exclude. - // Only --force-exclude applies. - cleanPath := filepath.Clean(src) - if !seen[cleanPath] { - seen[cleanPath] = true - files = append(files, cleanPath) - } - } - } - - slices.Sort(files) - return files, nil -} diff --git a/cmd/dmlfmt/collector_test.go b/cmd/dmlfmt/collector_test.go index ee7e715..7504bf8 100644 --- a/cmd/dmlfmt/collector_test.go +++ b/cmd/dmlfmt/collector_test.go @@ -9,16 +9,42 @@ import ( "slices" "strings" "testing" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" ) +func newTestFinder(cfg *CLIConfig) (lookup.Finder, error) { + return newFinderFromConfig(cfg) +} + func createTestTree(t *testing.T, baseDir string, files []string) { t.Helper() + withContent := make(map[string]string, len(files)) for _, f := range files { + withContent[f] = "content" + } + createTestTreeWithContent(t, baseDir, withContent) +} + +func createTestTreeWithContent( + t *testing.T, + baseDir string, + files map[string]string, +) { + t.Helper() + for f, content := range files { + if strings.HasSuffix(f, "/") { + dirPath := filepath.Join(baseDir, filepath.FromSlash(f)) + if err := os.MkdirAll(dirPath, 0750); err != nil { + t.Fatalf("failed to create dir %s: %v", f, err) + } + continue + } fullPath := filepath.Join(baseDir, filepath.FromSlash(f)) if err := os.MkdirAll(filepath.Dir(fullPath), 0750); err != nil { t.Fatalf("failed to create dir for %s: %v", f, err) } - if err := os.WriteFile(fullPath, []byte("content"), 0600); err != nil { + if err := os.WriteFile(fullPath, []byte(content), 0600); err != nil { t.Fatalf("failed to write file %s: %v", f, err) } } @@ -40,12 +66,12 @@ func TestCollector_Defaults(t *testing.T) { Include: DefaultIncludePattern, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { - t.Fatalf("unexpected error creating collector: %v", err) + t.Fatalf("unexpected error creating finder: %v", err) } - files, err := collector.Collect([]string{tmpDir}) + files, err := finder.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected collect error: %v", err) } @@ -74,12 +100,12 @@ func TestCollector_CustomInclude(t *testing.T) { Include: `\.dml14$`, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } - files, err := collector.Collect([]string{tmpDir}) + files, err := finder.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -93,12 +119,12 @@ func TestCollector_CustomInclude(t *testing.T) { Include: "", Exclude: DefaultExcludePattern, } - collectorEmpty, err := NewFileCollector(cfgEmpty) + finderEmpty, err := newTestFinder(cfgEmpty) if err != nil { t.Fatalf("unexpected error: %v", err) } - filesEmpty, err := collectorEmpty.Collect([]string{tmpDir}) + filesEmpty, err := finderEmpty.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -124,12 +150,12 @@ func TestCollector_CustomExclude(t *testing.T) { Include: DefaultIncludePattern, Exclude: `/skip/`, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } - files, err := collector.Collect([]string{tmpDir}) + files, err := finder.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -159,12 +185,12 @@ func TestCollector_ExtendExclude(t *testing.T) { Exclude: DefaultExcludePattern, ExtendExclude: `/custom/`, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } - files, err := collector.Collect([]string{tmpDir}) + files, err := finder.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -190,13 +216,13 @@ func TestCollector_ForceExclude(t *testing.T) { Exclude: DefaultExcludePattern, ForceExclude: `(skip_gen|_ignored)`, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } // Test 1: Recursive directory search - files, err := collector.Collect([]string{tmpDir}) + files, err := finder.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -212,7 +238,7 @@ func TestCollector_ForceExclude(t *testing.T) { // Test 2: Explicitly passed files (force-exclude skips even explicit files) keepFile := filepath.Join(tmpDir, "keep.dml") skipFile := filepath.Join(tmpDir, "skip_gen.dml") - explicitFiles, err := collector.Collect([]string{keepFile, skipFile}) + explicitFiles, err := finder.Collect([]string{keepFile, skipFile}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -232,13 +258,13 @@ func TestCollector_ExplicitFilesBypassExcludeAndInclude(t *testing.T) { Include: DefaultIncludePattern, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } target := filepath.Join(tmpDir, "venv", "test.txt") - files, err := collector.Collect([]string{target}) + files, err := finder.Collect([]string{target}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -263,7 +289,7 @@ func TestCollector_DeduplicationAndSorting(t *testing.T) { Include: DefaultIncludePattern, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -272,7 +298,7 @@ func TestCollector_DeduplicationAndSorting(t *testing.T) { fileB := filepath.Join(tmpDir, "b.dml") // Pass redundant directory and explicit files out of order - files, err := collector.Collect([]string{fileB, tmpDir, fileA}) + files, err := finder.Collect([]string{fileB, tmpDir, fileA}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -296,7 +322,7 @@ func TestCollector_InvalidRegex(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - _, err := NewFileCollector(tc.cfg) + _, err := newTestFinder(tc.cfg) if err == nil { t.Fatalf("expected error for %s, got nil", tc.name) } @@ -315,13 +341,13 @@ func TestCollector_NonExistentPath(t *testing.T) { Include: DefaultIncludePattern, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } missing := filepath.Join(t.TempDir(), "does_not_exist.dml") - _, err = collector.Collect([]string{missing}) + _, err = finder.Collect([]string{missing}) if err == nil { t.Fatalf("expected error for non-existent path, got nil") } @@ -334,21 +360,21 @@ func TestCollector_IsForceExcluded(t *testing.T) { cfg := &CLIConfig{ ForceExclude: `generated/.*\.dml$`, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } - if !collector.IsForceExcluded("path/to/generated/foo.dml") { + if !finder.Filter().IsForceExcluded("path/to/generated/foo.dml") { t.Errorf("expected path to be force-excluded") } - if collector.IsForceExcluded("path/to/normal/foo.dml") { + if finder.Filter().IsForceExcluded("path/to/normal/foo.dml") { t.Errorf("expected normal path not to be force-excluded") } // When force-exclude is not set - nilCollector, _ := NewFileCollector(&CLIConfig{}) - if nilCollector.IsForceExcluded("any/file.dml") { + nilFinder, _ := newTestFinder(&CLIConfig{}) + if nilFinder.Filter().IsForceExcluded("any/file.dml") { t.Errorf("expected false when force-exclude is not set") } } @@ -367,12 +393,12 @@ func TestCollector_AnchoredIncludeAndExclude(t *testing.T) { Include: `^src/.*`, Exclude: DefaultExcludePattern, } - collectorInc, err := NewFileCollector(cfgInclude) + finderInc, err := newTestFinder(cfgInclude) if err != nil { - t.Fatalf("unexpected error creating collector: %v", err) + t.Fatalf("unexpected error creating finder: %v", err) } - filesInc, err := collectorInc.Collect([]string{tmpDir}) + filesInc, err := finderInc.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected collect error: %v", err) } @@ -390,12 +416,12 @@ func TestCollector_AnchoredIncludeAndExclude(t *testing.T) { Include: DefaultIncludePattern, Exclude: `^test/`, } - collectorExc, err := NewFileCollector(cfgExclude) + finderExc, err := newTestFinder(cfgExclude) if err != nil { - t.Fatalf("unexpected error creating collector: %v", err) + t.Fatalf("unexpected error creating finder: %v", err) } - filesExc, err := collectorExc.Collect([]string{tmpDir}) + filesExc, err := finderExc.Collect([]string{tmpDir}) if err != nil { t.Fatalf("unexpected collect error: %v", err) } @@ -425,12 +451,12 @@ func TestCollector_RelativeSourceDefaultExclusions(t *testing.T) { Include: DefaultIncludePattern, Exclude: DefaultExcludePattern, } - collector, err := NewFileCollector(cfg) + finder, err := newTestFinder(cfg) if err != nil { t.Fatalf("unexpected error: %v", err) } - files, err := collector.Collect([]string{"."}) + files, err := finder.Collect([]string{"."}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -444,3 +470,473 @@ func TestCollector_RelativeSourceDefaultExclusions(t *testing.T) { t.Fatalf("expected %v, got %v", expected, files) } } + +func TestCollector_GitIgnore_Basic(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": strings.Join([]string{ + "# comment should be ignored", + "exact_skip.dml", + "*_gen.dml", + "**/*.bak.dml", + "ignored_dir/", + "/root_only.dml", + }, "\n") + "\n", + "keep.dml": "content", + "exact_skip.dml": "content", + "dev_gen.dml": "content", + "top.bak.dml": "content", + "root_only.dml": "content", + "sub/keep_sub.dml": "content", + "sub/nested_gen.dml": "content", + "sub/deep/inner.bak.dml": "content", + "sub/root_only.dml": "content", + "ignored_dir/skipped.dml": "content", + "sub/ignored_dir/nested.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "keep.dml"), + filepath.Join(tmpDir, "sub", "keep_sub.dml"), + filepath.Join(tmpDir, "sub", "root_only.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } +} + +func TestCollector_IgnoreFile(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": strings.Join([]string{ + "*.gen.dml", + "override_dir/", + }, "\n") + "\n", + ".ignore": strings.Join([]string{ + "ignore_only.dml", + "temp_ignore_dir/", + "!keep.gen.dml", + "!override_dir/", + }, "\n") + "\n", + "normal.dml": "content", + "ignore_only.dml": "content", + "skip.gen.dml": "content", + "keep.gen.dml": "content", + "temp_ignore_dir/a.dml": "content", + "override_dir/rescued.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "keep.gen.dml"), + filepath.Join(tmpDir, "normal.dml"), + filepath.Join(tmpDir, "override_dir", "rescued.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } +} + +func TestCollector_NestedGitIgnore_AndNegation(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": "parent_skip_*.dml\n", + "sub/.gitignore": strings.Join([]string{ + "/local_only.dml", + "!parent_skip_kept.dml", + }, "\n") + "\n", + "sub/.ignore": strings.Join([]string{ + "sub_ignored.dml", + "nested_glob/**", + "!nested_glob/allow.dml", + }, "\n") + "\n", + "local_only.dml": "content", + "parent_skip_root.dml": "content", + "sub/ok.dml": "content", + "sub/local_only.dml": "content", + "sub/parent_skip_drop.dml": "content", + "sub/parent_skip_kept.dml": "content", + "sub/sub_ignored.dml": "content", + "sub/deep/local_only.dml": "content", + "sub/nested_glob/skip.dml": "content", + "sub/nested_glob/allow.dml": "content", + "sub/nested_glob/dir/x.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "local_only.dml"), + filepath.Join(tmpDir, "sub", "deep", "local_only.dml"), + filepath.Join(tmpDir, "sub", "nested_glob", "allow.dml"), + filepath.Join(tmpDir, "sub", "ok.dml"), + filepath.Join(tmpDir, "sub", "parent_skip_kept.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } +} + +func TestCollector_GitIgnore_OverriddenByCustomExclude(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": "git_skip.dml\n", + ".ignore": "ignore_skip.dml\n", + "keep.dml": "content", + "git_skip.dml": "content", + "ignore_skip.dml": "content", + "custom/skip.dml": "content", + "venv/lib.dml": "content", + }) + + t.Run("custom exclude value disables ignore files", func(t *testing.T) { + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: `/(\.git|custom)/`, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "git_skip.dml"), + filepath.Join(tmpDir, "ignore_skip.dml"), + filepath.Join(tmpDir, "keep.dml"), + filepath.Join(tmpDir, "venv", "lib.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } + }) + + t.Run( + "explicit default exclude flag disables ignore files", + func(t *testing.T) { + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + ExplicitFlags: []string{"exclude"}, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "custom", "skip.dml"), + filepath.Join(tmpDir, "git_skip.dml"), + filepath.Join(tmpDir, "ignore_skip.dml"), + filepath.Join(tmpDir, "keep.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } + }, + ) + + t.Run("empty exclude disables ignore files", func(t *testing.T) { + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: "", + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(tmpDir, "custom", "skip.dml"), + filepath.Join(tmpDir, "git_skip.dml"), + filepath.Join(tmpDir, "ignore_skip.dml"), + filepath.Join(tmpDir, "keep.dml"), + filepath.Join(tmpDir, "venv", "lib.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } + }) +} + +func TestCollector_GitIgnore_CombinedWithExtendAndForceExclude(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": "git_skip.dml\n", + ".ignore": "ignore_skip.dml\n", + "keep.dml": "content", + "git_skip.dml": "content", + "ignore_skip.dml": "content", + "forced_git.dml": "content", + "extra_dir/skip.dml": "content", + "venv/lib.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + ExtendExclude: `/extra_dir/`, + ForceExclude: `forced_git\.dml$`, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Recursive collection honors default excludes, --extend-exclude, --force-exclude, + // .gitignore, and .ignore. + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + expected := []string{ + filepath.Join(tmpDir, "keep.dml"), + } + if !slices.Equal(files, expected) { + t.Fatalf("recursive collect expected %v, got %v", expected, files) + } + + // Explicit file arguments bypass .gitignore/.ignore unless matched by --force-exclude. + gitSkipFile := filepath.Join(tmpDir, "git_skip.dml") + ignoreSkipFile := filepath.Join(tmpDir, "ignore_skip.dml") + forcedFile := filepath.Join(tmpDir, "forced_git.dml") + explicitFiles, err := finder.Collect([]string{ + gitSkipFile, + ignoreSkipFile, + forcedFile, + }) + if err != nil { + t.Fatalf("explicit collect error: %v", err) + } + expectedExplicit := []string{gitSkipFile, ignoreSkipFile} + slices.Sort(expectedExplicit) + if !slices.Equal(explicitFiles, expectedExplicit) { + t.Fatalf( + "explicit collect expected %v, got %v", + expectedExplicit, + explicitFiles, + ) + } +} + +func TestCollector_GitIgnore_VCSBoundary(t *testing.T) { + tmpDir := t.TempDir() + outerDir := filepath.Join(tmpDir, "outer") + repoDir := filepath.Join(outerDir, "repo") + + createTestTreeWithContent(t, outerDir, map[string]string{ + ".gitignore": "outer_ignored.dml\n", + ".ignore": "outer_dir/\n", + "repo/.git/": "", + "repo/.gitignore": "repo_ignored.dml\n", + "repo/main.dml": "content", + "repo/outer_ignored.dml": "content", + "repo/outer_dir/keep.dml": "content", + "repo/repo_ignored.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + files, err := finder.Collect([]string{repoDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expected := []string{ + filepath.Join(repoDir, "main.dml"), + filepath.Join(repoDir, "outer_dir", "keep.dml"), + filepath.Join(repoDir, "outer_ignored.dml"), + } + slices.Sort(expected) + if !slices.Equal(files, expected) { + t.Fatalf("expected %v, got %v", expected, files) + } +} + +func TestCollector_GitIgnore_OnIgnoreCallback(t *testing.T) { + tmpDir := t.TempDir() + createTestTreeWithContent(t, tmpDir, map[string]string{ + ".git/": "", + ".gitignore": "git_skip.dml\ngit_dir/\n", + ".ignore": "dotignore_skip.dml\ndotignore_dir/\n", + "keep.dml": "content", + "git_skip.dml": "content", + "git_dir/a.dml": "content", + "dotignore_skip.dml": "content", + "dotignore_dir/b.dml": "content", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + type ignoreEvent struct { + path string + isDir bool + filter string + } + var events []ignoreEvent + finder.SetOnIgnore(func(path string, isDir bool, filterName string) { + events = append(events, ignoreEvent{ + path: path, + isDir: isDir, + filter: filterName, + }) + }) + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + expectedFiles := []string{filepath.Join(tmpDir, "keep.dml")} + if !slices.Equal(files, expectedFiles) { + t.Fatalf("expected %v, got %v", expectedFiles, files) + } + + wantEvents := []ignoreEvent{ + { + path: filepath.Join(tmpDir, "git_skip.dml"), + isDir: false, + filter: lookup.FileGitIgnore, + }, + { + path: filepath.Join(tmpDir, "git_dir"), + isDir: true, + filter: lookup.FileGitIgnore, + }, + { + path: filepath.Join(tmpDir, "dotignore_skip.dml"), + isDir: false, + filter: lookup.FileIgnore, + }, + { + path: filepath.Join(tmpDir, "dotignore_dir"), + isDir: true, + filter: lookup.FileIgnore, + }, + } + for _, want := range wantEvents { + if !slices.Contains(events, want) { + t.Errorf("missing ignore event %+v in %+v", want, events) + } + } +} + +func TestCollector_MaxFileSize_50MiB(t *testing.T) { + tmpDir := t.TempDir() + + gitIgnorePath := filepath.Join(tmpDir, ".gitignore") + f, err := os.Create(filepath.Clean(gitIgnorePath)) + if err != nil { + t.Fatalf("failed to create .gitignore: %v", err) + } + if _, err := f.WriteString("skip.dml\n"); err != nil { + _ = f.Close() + t.Fatalf("failed to write rule to .gitignore: %v", err) + } + if err := f.Truncate(2 << 20); err != nil { + _ = f.Close() + t.Fatalf("failed to truncate .gitignore to 2 MiB: %v", err) + } + _ = f.Close() + + createTestTree(t, tmpDir, []string{ + "keep.dml", + "skip.dml", + }) + + cfg := &CLIConfig{ + Include: DefaultIncludePattern, + Exclude: DefaultExcludePattern, + } + finder, err := newTestFinder(cfg) + if err != nil { + t.Fatalf("failed to create test finder: %v", err) + } + + files, err := finder.Collect([]string{tmpDir}) + if err != nil { + t.Fatalf("unexpected collect error: %v", err) + } + + expectedFiles := []string{filepath.Join(tmpDir, "keep.dml")} + if !slices.Equal(files, expectedFiles) { + t.Fatalf("expected %v, got %v", expectedFiles, files) + } +} diff --git a/cmd/dmlfmt/dmlfmt.go b/cmd/dmlfmt/dmlfmt.go index 5520385..df476da 100644 --- a/cmd/dmlfmt/dmlfmt.go +++ b/cmd/dmlfmt/dmlfmt.go @@ -15,6 +15,7 @@ import ( "slices" "github.com/timoschenko/dmltools/pkg/dmlex" + "github.com/timoschenko/dmltools/pkg/fs/lookup" "github.com/timoschenko/dmltools/pkg/fs/stream" "github.com/timoschenko/dmltools/pkg/printer" @@ -141,7 +142,7 @@ func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int { ) } - collector, err := NewFileCollector(cfg) + finder, err := newFinderFromConfig(cfg) if err != nil { ui.PrintError("Error: %v", err) return ExitCodeInternalError @@ -149,7 +150,7 @@ func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int { if len(cfg.Sources) == 1 && cfg.Sources[0] == "-" { if cfg.StdinFilename != "" && - collector.IsForceExcluded(cfg.StdinFilename) { + finder.Filter().IsForceExcluded(cfg.StdinFilename) { if !cfg.Check { if stdin == nil { stdin = os.Stdin @@ -174,7 +175,25 @@ func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return ExitCodeInternalError } - return runPipeline(cfg, collector, ui, stats) + return runPipeline(cfg, finder, ui, stats) +} + +func newFinderFromConfig(cfg *CLIConfig) (lookup.Finder, error) { + opts := []lookup.Option{ + lookup.WithInclude(cfg.Include), + lookup.WithExclude(cfg.Exclude), + lookup.WithExtendExclude(cfg.ExtendExclude), + lookup.WithForceExclude(cfg.ForceExclude), + lookup.WithMaxFileSize(MaxFileSize), + } + if !slices.Contains(cfg.ExplicitFlags, "exclude") && + cfg.Exclude == DefaultExcludePattern { + opts = append( + opts, + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.FileIgnore), + ) + } + return lookup.NewFinder(opts...) } func formatCode( diff --git a/cmd/dmlfmt/dmlfmt_test.go b/cmd/dmlfmt/dmlfmt_test.go index 1842020..d27010f 100644 --- a/cmd/dmlfmt/dmlfmt_test.go +++ b/cmd/dmlfmt/dmlfmt_test.go @@ -2661,6 +2661,155 @@ func TestRun_Dml12_CheckStdin_Errors(t *testing.T) { } } +func TestRun_OversizedFile_Ignored(t *testing.T) { + t.Parallel() + + tmpDir := t.TempDir() + filePath := filepath.Join(tmpDir, "huge.dml") + f, err := os.Create(filepath.Clean(filePath)) + if err != nil { + t.Fatalf("failed to create huge file: %v", err) + } + if err := f.Truncate(51 << 20); err != nil { + _ = f.Close() + t.Fatalf("failed to truncate huge file: %v", err) + } + _ = f.Close() + + var stdout, stderr bytes.Buffer + code := run([]string{filePath}, &stdout, &stderr) + if code != ExitCodeInternalError { + t.Fatalf( + "expected ExitCodeInternalError (123), got %d (stderr: %s)", + code, + stderr.String(), + ) + } + expectedMsg := fmt.Sprintf( + "ignored %s (file size exceeds 50 MiB limit)\n1 file failed to reformat.\n", + filePath, + ) + if stdout.String() != expectedMsg { + t.Errorf("expected stdout %q, got %q", expectedMsg, stdout.String()) + } + if stderr.Len() != 0 { + t.Errorf("expected empty stderr, got %q", stderr.String()) + } +} + +func TestRun_OversizedFile_CheckMode(t *testing.T) { + t.Parallel() + + tmpDir := t.TempDir() + filePath := filepath.Join(tmpDir, "huge.dml") + f, err := os.Create(filepath.Clean(filePath)) + if err != nil { + t.Fatalf("failed to create huge file: %v", err) + } + if err := f.Truncate(51 << 20); err != nil { + _ = f.Close() + t.Fatalf("failed to truncate huge file: %v", err) + } + _ = f.Close() + + var stdout, stderr bytes.Buffer + code := run([]string{"--check", filePath}, &stdout, &stderr) + if code != ExitCodeInternalError { + t.Fatalf( + "expected ExitCodeInternalError (123), got %d (stderr: %s)", + code, + stderr.String(), + ) + } + expectedMsg := fmt.Sprintf( + "ignored %s (file size exceeds 50 MiB limit)\n1 file would fail to reformat.\n", + filePath, + ) + if stdout.String() != expectedMsg { + t.Errorf("expected stdout %q, got %q", expectedMsg, stdout.String()) + } + if stderr.Len() != 0 { + t.Errorf("expected empty stderr, got %q", stderr.String()) + } +} + +func TestRun_OversizedFile_MixedWithValid(t *testing.T) { + t.Parallel() + + tmpDir := t.TempDir() + hugePath := filepath.Join(tmpDir, "huge.dml") + f, err := os.Create(filepath.Clean(hugePath)) + if err != nil { + t.Fatalf("failed to create huge file: %v", err) + } + if err := f.Truncate(51 << 20); err != nil { + _ = f.Close() + t.Fatalf("failed to truncate huge file: %v", err) + } + _ = f.Close() + + validPath := filepath.Join(tmpDir, "valid.dml") + validContent := []byte("dml 1.4 ;\n\ndevice dev ;\n") + if err := os.WriteFile(validPath, validContent, 0600); err != nil { + t.Fatalf("failed to write valid file: %v", err) + } + + var stdout, stderr bytes.Buffer + code := run([]string{tmpDir}, &stdout, &stderr) + if code != ExitCodeInternalError { + t.Fatalf( + "expected ExitCodeInternalError (123), got %d (stderr: %s)", + code, + stderr.String(), + ) + } + outStr := stdout.String() + expectedIgnored := fmt.Sprintf( + "ignored %s (file size exceeds 50 MiB limit)\n", + hugePath, + ) + if !strings.Contains(outStr, expectedIgnored) { + t.Errorf( + "expected stdout to contain %q, got %q", + expectedIgnored, + outStr, + ) + } + expectedReformatted := fmt.Sprintf( + "reformatted %s\n", + validPath, + ) + if !strings.Contains(outStr, expectedReformatted) { + t.Errorf( + "expected stdout to contain %q, got %q", + expectedReformatted, + outStr, + ) + } + if !strings.Contains( + outStr, + "1 file reformatted, 1 file failed to reformat.\n", + ) { + t.Errorf("expected summary line in stdout, got %q", outStr) + } + if stderr.Len() != 0 { + t.Errorf("expected empty stderr, got %q", stderr.String()) + } + + afterValid, err := os.ReadFile(filepath.Clean(validPath)) + if err != nil { + t.Fatalf("failed to read valid file: %v", err) + } + expectedValid := "dml 1.4;\n\ndevice dev;\n" + if string(afterValid) != expectedValid { + t.Errorf( + "expected valid file reformatted to %q, got %q", + expectedValid, + string(afterValid), + ) + } +} + func TestRun_Quiet_Files(t *testing.T) { t.Parallel() @@ -3840,4 +3989,100 @@ func TestVerboseMode(t *testing.T) { ) } }) + + t.Run("GitIgnoreAndIgnoreFile_Verbose", func(t *testing.T) { + tmpDir := t.TempDir() + _ = os.Mkdir(filepath.Join(tmpDir, ".git"), 0750) + _ = os.WriteFile( + filepath.Join(tmpDir, ".gitignore"), + []byte("git_skip.dml\ngit_ignored_dir/\nnotes.txt\n"), + 0600, + ) + _ = os.WriteFile( + filepath.Join(tmpDir, ".ignore"), + []byte("dotignore_skip.dml\ndotignore_dir/\n"), + 0600, + ) + + keepPath := filepath.Join(tmpDir, "keep.dml") + gitSkipPath := filepath.Join(tmpDir, "git_skip.dml") + gitDir := filepath.Join(tmpDir, "git_ignored_dir") + dotIgnoreSkipPath := filepath.Join(tmpDir, "dotignore_skip.dml") + dotIgnoreDir := filepath.Join(tmpDir, "dotignore_dir") + notesPath := filepath.Join(tmpDir, "notes.txt") + + _ = os.Mkdir(gitDir, 0750) + _ = os.Mkdir(dotIgnoreDir, 0750) + _ = os.WriteFile(keepPath, []byte("dml 1.4;\ndevice keep;\n"), 0600) + _ = os.WriteFile( + gitSkipPath, + []byte("dml 1.4;\ndevice gskip;\n"), + 0600, + ) + _ = os.WriteFile( + filepath.Join(gitDir, "inner.dml"), + []byte("dml 1.4;\ndevice gdir;\n"), + 0600, + ) + _ = os.WriteFile( + dotIgnoreSkipPath, + []byte("dml 1.4;\ndevice dskip;\n"), + 0600, + ) + _ = os.WriteFile( + filepath.Join(dotIgnoreDir, "inner.dml"), + []byte("dml 1.4;\ndevice ddir;\n"), + 0600, + ) + _ = os.WriteFile(notesPath, []byte("ignored text"), 0600) + + var stdout, stderr bytes.Buffer + args := []string{"-v", "--no-color", tmpDir} + code := run(args, &stdout, &stderr) + if code != ExitCodeOK { + t.Fatalf( + "expected ExitCodeOK (0), got %d (stderr: %s)", + code, + stderr.String(), + ) + } + + outStr := stdout.String() + expectedMsgs := []string{ + fmt.Sprintf("Processing %s...\n", keepPath), + fmt.Sprintf( + "%s ignored: matches the .gitignore file content\n", + gitSkipPath, + ), + fmt.Sprintf( + "%s directory ignored: matches the .gitignore file content\n", + gitDir, + ), + fmt.Sprintf( + "%s ignored: matches the .ignore file content\n", + dotIgnoreSkipPath, + ), + fmt.Sprintf( + "%s directory ignored: matches the .ignore file content\n", + dotIgnoreDir, + ), + fmt.Sprintf("%s already well formatted, good job.\n", keepPath), + } + for _, want := range expectedMsgs { + if !strings.Contains(outStr, want) { + t.Errorf( + "expected stdout to contain %q, got:\n%s", + want, + outStr, + ) + } + } + + if strings.Contains(outStr, "notes.txt") { + t.Errorf( + "non-DML file notes.txt should not appear in verbose output, got:\n%s", + outStr, + ) + } + }) } diff --git a/cmd/dmlfmt/pipeline.go b/cmd/dmlfmt/pipeline.go index 3a4ee7e..741440b 100644 --- a/cmd/dmlfmt/pipeline.go +++ b/cmd/dmlfmt/pipeline.go @@ -6,17 +6,19 @@ package main import ( "bufio" "bytes" + "errors" "fmt" "io" - "math" "os" "path/filepath" "runtime" + "strings" "sync" "time" "github.com/timoschenko/dmltools/pkg/dmlex" "github.com/timoschenko/dmltools/pkg/fs" + "github.com/timoschenko/dmltools/pkg/fs/lookup" "github.com/timoschenko/dmltools/pkg/fs/stream" "github.com/timoschenko/dmltools/pkg/printer" @@ -272,6 +274,9 @@ func processFormattingJob( } } +// ErrFileTooLarge indicates a file exceeds the MaxFileSize limit. +var ErrFileTooLarge = errors.New("file size exceeds 50 MiB limit") + // readInputJob opens a file, reads its contents into a HashingStream, and closes // the file handle before returning. func readInputJob(path string, stats StatsCollector) (InputJob, error) { @@ -294,12 +299,8 @@ func readInputJob(path string, stats StatsCollector) (InputJob, error) { err, ) } - if info.Size() >= math.MaxInt { - return InputJob{}, fmt.Errorf( - "file %s exceeds maximum supported size (%d bytes)", - path, - info.Size(), - ) + if info.Size() > MaxFileSize { + return InputJob{}, ErrFileTooLarge } size := int(info.Size()) @@ -324,20 +325,20 @@ func readInputJob(path string, stats StatsCollector) (InputJob, error) { // and parallel processing (-W workers). func runPipeline( cfg *CLIConfig, - collector *FileCollector, + finder lookup.Finder, ui *UI, stats StatsCollector, ) int { - // TODO: AI Slop - if cfg.Verbose { - collector.SetOnIgnore(func(path string, isDir bool, filterName string) { - ui.IgnoredFilter(path, isDir, filterName) + finder.SetOnIgnore(func(path string, isDir bool, filterName string) { + if isDir || strings.HasSuffix(path, ".dml") { + ui.IgnoredFilter(path, isDir, filterName) + } }) } startTime := time.Now() - paths, err := collector.Collect(cfg.Sources) + paths, err := finder.Collect(cfg.Sources) stats.RecordWalkIo(time.Since(startTime)) if err != nil { ui.PrintError("Error: %v", err) @@ -400,6 +401,15 @@ func runPipeline( } job, readErr := readInputJob(path, stats) if readErr != nil { + if errors.Is(readErr, ErrFileTooLarge) { + ui.IgnoredReason( + path, + readErr.Error(), + ) + hasErrors = true + report.IncrementFailed() + continue + } ui.PrintError("Error: %v", readErr) hasErrors = true report.IncrementFailed() diff --git a/cmd/dmlfmt/ui.go b/cmd/dmlfmt/ui.go index 5ded56a..ddce60d 100644 --- a/cmd/dmlfmt/ui.go +++ b/cmd/dmlfmt/ui.go @@ -11,6 +11,7 @@ import ( "sync" "github.com/timoschenko/dmltools/pkg/dmlex" + "github.com/timoschenko/dmltools/pkg/fs/lookup" ) // ANSI color escape codes @@ -235,18 +236,26 @@ func (u *UI) WouldReformat(filename string) { // Ignored writes an ignored-file notice to stdout. func (u *UI) Ignored(filename, version string) { + if version != "" { + version = "dml " + version + } + u.IgnoredReason(filename, version) +} + +// IgnoredReason writes an ignored notice with a reason to stdout. +func (u *UI) IgnoredReason(filename, reason string) { wr := u.out var msg string - if version != "" { + if reason != "" { if wr.IsColorEnabled() { msg = fmt.Sprintf( - "%s %s (dml %s)\n", + "%s %s (%s)\n", ansiBoldYellow+"ignored"+ansiReset, ansiBold+filename+ansiReset, - version, + reason, ) } else { - msg = fmt.Sprintf("ignored %s (dml %s)\n", filename, version) + msg = fmt.Sprintf("ignored %s (%s)\n", filename, reason) } } else { if wr.IsColorEnabled() { @@ -291,17 +300,23 @@ func (u *UI) Processing(path string) { // IgnoredFilter writes a filtered-out file or directory notice to stdout. func (u *UI) IgnoredFilter(path string, isDir bool, filterName string) { + reason := "regular expression" + if filterName == lookup.FileGitIgnore || filterName == lookup.FileIgnore { + reason = "file content" + } if isDir { u.Verbose( - "%s directory ignored: matches the %s regular expression\n", + "%s directory ignored: matches the %s %s\n", path, filterName, + reason, ) } else { u.Verbose( - "%s ignored: matches the %s regular expression\n", + "%s ignored: matches the %s %s\n", path, filterName, + reason, ) } } diff --git a/cmd/dmlfmt/ui_test.go b/cmd/dmlfmt/ui_test.go index 503b5d0..29dd2db 100644 --- a/cmd/dmlfmt/ui_test.go +++ b/cmd/dmlfmt/ui_test.go @@ -102,6 +102,18 @@ func TestUIRouting(t *testing.T) { out.Reset() err.Reset() + // IgnoredReason -> out + ui.IgnoredReason("test.dml", "file size exceeds 50 MiB limit") + if out.Len() == 0 || err.Len() != 0 { + t.Errorf( + "IgnoredReason should write to out only, got out=%q, err=%q", + out.String(), + err.String(), + ) + } + out.Reset() + err.Reset() + // SyntaxError -> err ui.SyntaxError("test.dml", 1, 2, "bad") if err.Len() == 0 || out.Len() != 0 { @@ -190,6 +202,27 @@ func TestUIUncoloredOutput(t *testing.T) { } out.Reset() + ui.IgnoredReason("dev.dml", "file size exceeds 50 MiB limit") + if out.String() != "ignored dev.dml (file size exceeds 50 MiB limit)\n" || + err.Len() != 0 { + t.Errorf( + "unexpected output: out=%q err=%q", + out.String(), + err.String(), + ) + } + out.Reset() + + ui.IgnoredReason("dev.dml", "") + if out.String() != "ignored dev.dml\n" || err.Len() != 0 { + t.Errorf( + "unexpected output: out=%q err=%q", + out.String(), + err.String(), + ) + } + out.Reset() + ui.SyntaxError("dev.dml", 5, 10, "mismatched token") if err.String() != "dev.dml:5 column 10: Syntax error - mismatched token\n" { t.Errorf("unexpected output: %q", err.String()) @@ -262,6 +295,34 @@ func TestUIColoredOutput(t *testing.T) { } out.Reset() + ui.IgnoredReason("dev.dml", "file size exceeds 50 MiB limit") + outStr = out.String() + if !strings.Contains(outStr, ansiBoldYellow) || + !strings.Contains(outStr, "ignored") || + !strings.Contains(outStr, "(file size exceeds 50 MiB limit)") || + !strings.Contains(outStr, ansiReset) { + t.Errorf("expected colored ignored reason message, got %q", outStr) + } + if err.Len() != 0 { + t.Errorf("expected err to be empty, got %q", err.String()) + } + out.Reset() + + ui.IgnoredReason("dev.dml", "") + outStr = out.String() + if !strings.Contains(outStr, ansiBoldYellow) || + !strings.Contains(outStr, "ignored") || + !strings.Contains(outStr, ansiReset) { + t.Errorf( + "expected colored ignored empty reason message, got %q", + outStr, + ) + } + if err.Len() != 0 { + t.Errorf("expected err to be empty, got %q", err.String()) + } + out.Reset() + ui.SyntaxError("dev.dml", 1, 2, "error msg") errStr := err.String() if !strings.Contains(errStr, ansiBoldRed) || diff --git a/pkg/fs/lookup/cache.go b/pkg/fs/lookup/cache.go new file mode 100644 index 0000000..17e6304 --- /dev/null +++ b/pkg/fs/lookup/cache.go @@ -0,0 +1,897 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "errors" + "fmt" + iofs "io/fs" + "math" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "time" +) + +// Cache manages stat-fingerprint-validated filesystem metadata, directory +// boundary resolution, and candidate file security checks. +type Cache interface { + ResolveStart(startPath string) ( + startDir string, + absStart string, + isFile bool, + startMeta FileMeta, + err error, + ) + ResolveDirChain( + startDir string, + startMeta FileMeta, + ) ([]string, BoundaryInfo, FileMeta, error) + ResolveBoundary(startPath string) (BoundaryInfo, error) + DirEntries(dir string) ([]iofs.DirEntry, error) + ProbeCandidate( + dir string, + name string, + candidatePath string, + evalBoundaryRoot string, + startMeta FileMeta, + ) (DiscoveredFile, bool, error) + EvalBoundaryRoot(boundaryRoot string) string + Stat(path string) (FileMeta, error) + Lstat(path string) (FileMeta, error) + Abs(path string) (string, error) + HandleSkip(path string, reason SkipReason, detail error) error + Invalidate(path string) + Reset() + Stats() CacheStats +} + +type vcsMarkerState struct { + marker string + exists bool + meta FileMeta +} + +type fileCacheEntry struct { + validatedAt time.Time + exists bool + lstatMeta FileMeta + isSymlink bool + resolvedPath string + targetMeta FileMeta + boundaryRoot string + discovered DiscoveredFile + skipReason SkipReason + hasSkip bool + skipErr error +} + +type dirCacheEntry struct { + meta FileMeta + vcsProbed bool + isVCSRoot bool + vcsPath string + markers []vcsMarkerState + validatedAt time.Time + dirEntries []iofs.DirEntry + dirEntriesCached bool + dirEntriesAt time.Time + files map[string]fileCacheEntry +} + +type securityCache struct { + fsys FileSystem + clock Clock + vcsMarkers []string + stopAtVCSRoot bool + stopAtMount bool + verifyOwnership bool + allowSymlinks bool + allowSymlinkEsc bool + ceilingDirs map[string]struct{} + maxDepth int + maxFileSize int64 + cacheTTL time.Duration + strictSecurity bool + onSkip SkipCallback + + mu sync.RWMutex + dirs map[string]*dirCacheEntry + dirHits atomic.Uint64 + dirMisses atomic.Uint64 + fileHits atomic.Uint64 + fileMisses atomic.Uint64 + invalidations atomic.Uint64 +} + +// NewCache creates a standalone [Cache] instance configured with the given options. +func NewCache(opts ...Option) Cache { + cfg := defaultConfig() + for _, opt := range opts { + if opt != nil { + opt(&cfg) + } + } + return newCacheFromConfig(&cfg) +} + +func newCacheFromConfig(cfg *config) *securityCache { + ceilings := make(map[string]struct{}, len(cfg.ceilingDirs)*2) + for _, dir := range cfg.ceilingDirs { + if dir == "" { + continue + } + absDir, absErr := cfg.fsys.Abs(dir) + if absErr != nil { + absDir = filepath.Clean(dir) + } else { + absDir = filepath.Clean(absDir) + } + ceilings[absDir] = struct{}{} + if evalDir, evalErr := cfg.fsys.EvalSymlinks(absDir); evalErr == nil { + ceilings[filepath.Clean(evalDir)] = struct{}{} + } + } + + return &securityCache{ + fsys: cfg.fsys, + clock: cfg.clock, + vcsMarkers: cfg.vcsMarkers, + stopAtVCSRoot: cfg.stopAtVCSRoot, + stopAtMount: cfg.stopAtMountPoint, + verifyOwnership: cfg.verifyOwnership, + allowSymlinks: cfg.allowSymlinks, + allowSymlinkEsc: cfg.allowSymlinkEsc, + ceilingDirs: ceilings, + maxDepth: cfg.maxDepth, + maxFileSize: cfg.maxFileSize, + cacheTTL: cfg.cacheTTL, + strictSecurity: cfg.strictSecurity, + onSkip: cfg.onSkip, + dirs: make(map[string]*dirCacheEntry), + } +} + +func (c *securityCache) Stat(path string) (FileMeta, error) { + return c.fsys.Stat(path) +} + +func (c *securityCache) Lstat(path string) (FileMeta, error) { + return c.fsys.Lstat(path) +} + +func (c *securityCache) Abs(path string) (string, error) { + return c.fsys.Abs(path) +} + +func (c *securityCache) Stats() CacheStats { + return CacheStats{ + DirHits: c.dirHits.Load(), + DirMisses: c.dirMisses.Load(), + FileHits: c.fileHits.Load(), + FileMisses: c.fileMisses.Load(), + Invalidations: c.invalidations.Load(), + } +} + +func (c *securityCache) Reset() { + c.mu.Lock() + clear(c.dirs) + c.mu.Unlock() + c.invalidations.Add(1) +} + +func (c *securityCache) Invalidate(path string) { + if path == "" { + return + } + absPath, err := c.fsys.Abs(path) + if err != nil { + absPath = filepath.Clean(path) + } else { + absPath = filepath.Clean(absPath) + } + targets := []string{absPath} + if evalPath, evalErr := c.fsys.EvalSymlinks(absPath); evalErr == nil { + cleanEval := filepath.Clean(evalPath) + if cleanEval != absPath { + targets = append(targets, cleanEval) + } + } + + var removed uint64 + c.mu.Lock() + for dir := range c.dirs { + if matchesAnyInvalidationTarget(dir, targets) { + delete(c.dirs, dir) + removed++ + } + } + c.mu.Unlock() + + if removed > 0 { + c.invalidations.Add(removed) + } +} + +func matchesAnyInvalidationTarget(dir string, targets []string) bool { + sep := string(filepath.Separator) + for _, target := range targets { + parentDir := filepath.Dir(target) + prefix := target + sep + if dir == target || dir == parentDir || + strings.HasPrefix(dir, prefix) { + return true + } + } + return false +} + +func (c *securityCache) ResolveBoundary( + startPath string, +) (BoundaryInfo, error) { + startDir, _, _, startMeta, err := c.ResolveStart(startPath) + if err != nil { + return BoundaryInfo{}, err + } + _, boundary, _, err := c.ResolveDirChain(startDir, startMeta) + if err != nil { + return BoundaryInfo{}, err + } + return boundary, nil +} + +func (c *securityCache) ResolveStart( + startPath string, +) (string, string, bool, FileMeta, error) { + if startPath == "" { + startPath = "." + } + absPath, err := c.fsys.Abs(startPath) + if err != nil { + return "", "", false, FileMeta{}, err + } + absPath = filepath.Clean(absPath) + + meta, err := c.fsys.Stat(absPath) + if err == nil { + if meta.Mode.IsDir() { + return absPath, absPath, false, meta, nil + } + startDir := filepath.Dir(absPath) + dirMeta, dirErr := c.fsys.Stat(startDir) + if dirErr != nil { + return "", "", false, FileMeta{}, dirErr + } + return startDir, absPath, true, dirMeta, nil + } + + lmeta, lerr := c.fsys.Lstat(absPath) + if lerr != nil { + return "", "", false, FileMeta{}, err + } + if lmeta.Mode.IsDir() { + return absPath, absPath, false, lmeta, nil + } + startDir := filepath.Dir(absPath) + dirMeta, dirErr := c.fsys.Stat(startDir) + if dirErr != nil { + return "", "", false, FileMeta{}, dirErr + } + return startDir, absPath, true, dirMeta, nil +} + +func (c *securityCache) ResolveDirChain( + startDir string, + startMeta FileMeta, +) ([]string, BoundaryInfo, FileMeta, error) { + dirs := make([]string, 0, 8) + currentDir := startDir + depth := 0 + euid := c.fsys.Geteuid() + + curMeta, isVCS, vcsPath, err := c.getOrRefreshDir(currentDir) + if err != nil { + return nil, BoundaryInfo{}, FileMeta{}, err + } + startMeta = curMeta + + for { + dirs = append(dirs, currentDir) + + if c.isCeiling(currentDir) { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryCeiling, + }, startMeta, nil + } + if c.stopAtVCSRoot && isVCS { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryVCSRoot, + VCSPath: vcsPath, + }, startMeta, nil + } + if depth >= c.maxDepth { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryMaxDepth, + }, startMeta, nil + } + + parentDir := filepath.Dir(currentDir) + if parentDir == currentDir { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryFilesystemRoot, + }, startMeta, nil + } + + parentMeta, parentIsVCS, parentVCSPath, parentErr := c.getOrRefreshDir( + parentDir, + ) + if parentErr != nil { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryOwnership, + }, startMeta, nil + } + + if c.stopAtMount && startMeta.HasDevice && parentMeta.HasDevice && + parentMeta.DeviceID != startMeta.DeviceID { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryMountPoint, + }, startMeta, nil + } + + if c.verifyOwnership && startMeta.HasUID && parentMeta.HasUID { + if !isTrustedOwner(parentMeta.UID, startMeta.UID, euid) { + return dirs, BoundaryInfo{ + RootDir: currentDir, + Reason: BoundaryOwnership, + }, startMeta, nil + } + } + + currentDir = parentDir + isVCS = parentIsVCS + vcsPath = parentVCSPath + depth++ + } +} + +func isTrustedOwner(parentUID, startUID uint32, euid int) bool { + if parentUID == startUID || parentUID == 0 { + return true + } + if euid >= 0 && int64(euid) <= math.MaxUint32 { + // #nosec G115 -- guarded against negative and > MaxUint32 + return parentUID == uint32(euid) + } + return false +} + +func (c *securityCache) isCeiling(dir string) bool { + if len(c.ceilingDirs) == 0 { + return false + } + if _, ok := c.ceilingDirs[dir]; ok { + return true + } + if evalDir, err := c.fsys.EvalSymlinks(dir); err == nil { + _, ok := c.ceilingDirs[filepath.Clean(evalDir)] + return ok + } + return false +} + +func (c *securityCache) getOrRefreshDir( + dir string, +) (FileMeta, bool, string, error) { + now := c.clock.Now() + + c.mu.RLock() + entry, ok := c.dirs[dir] + if ok && entry.vcsProbed && c.cacheTTL > 0 && + now.Sub(entry.validatedAt) < c.cacheTTL { + meta := entry.meta + isVCS := entry.isVCSRoot + vcsPath := entry.vcsPath + c.mu.RUnlock() + c.dirHits.Add(1) + return meta, isVCS, vcsPath, nil + } + var cachedMeta FileMeta + var cachedVCSProbed bool + var cachedMarkers []vcsMarkerState + var cachedVCS bool + var cachedVCSPath string + if ok { + cachedMeta = entry.meta + cachedVCSProbed = entry.vcsProbed + cachedMarkers = slices.Clone(entry.markers) + cachedVCS = entry.isVCSRoot + cachedVCSPath = entry.vcsPath + } + c.mu.RUnlock() + + curMeta, err := c.fsys.Stat(dir) + if err != nil { + if ok { + c.mu.Lock() + if cur, exists := c.dirs[dir]; exists && cur == entry { + delete(c.dirs, dir) + c.invalidations.Add(1) + } + c.mu.Unlock() + } + return FileMeta{}, false, "", err + } + + if ok && cachedMeta.sameFingerprint(curMeta) { + if cachedVCSProbed && c.markersUnchanged(dir, cachedMarkers) { + c.mu.Lock() + if cur, exists := c.dirs[dir]; exists && cur == entry { + cur.validatedAt = now + } + c.mu.Unlock() + c.dirHits.Add(1) + return cachedMeta, cachedVCS, cachedVCSPath, nil + } + if !cachedVCSProbed { + isVCS, vcsPath, markers := c.probeVCSMarkers(dir) + c.mu.Lock() + if cur, exists := c.dirs[dir]; exists && cur == entry { + cur.vcsProbed = true + cur.isVCSRoot = isVCS + cur.vcsPath = vcsPath + cur.markers = markers + cur.validatedAt = now + } + c.mu.Unlock() + c.dirHits.Add(1) + return cachedMeta, isVCS, vcsPath, nil + } + } + + if ok { + c.invalidations.Add(1) + } + c.dirMisses.Add(1) + + isVCS, vcsPath, markers := c.probeVCSMarkers(dir) + newEntry := &dirCacheEntry{ + meta: curMeta, + vcsProbed: true, + isVCSRoot: isVCS, + vcsPath: vcsPath, + markers: markers, + validatedAt: now, + files: make(map[string]fileCacheEntry), + } + + c.mu.Lock() + c.dirs[dir] = newEntry + c.mu.Unlock() + + return curMeta, isVCS, vcsPath, nil +} + +func (c *securityCache) ensureDirEntry(dir string) { + now := c.clock.Now() + curMeta, err := c.fsys.Stat(dir) + if err != nil { + return + } + + c.mu.Lock() + defer c.mu.Unlock() + if cur, exists := c.dirs[dir]; exists { + if cur.meta.sameFingerprint(curMeta) { + cur.validatedAt = now + return + } + c.invalidations.Add(1) + } + c.dirMisses.Add(1) + c.dirs[dir] = &dirCacheEntry{ + meta: curMeta, + validatedAt: now, + files: make(map[string]fileCacheEntry), + } +} + +func (c *securityCache) probeVCSMarkers( + dir string, +) (bool, string, []vcsMarkerState) { + if !c.stopAtVCSRoot || len(c.vcsMarkers) == 0 { + return false, "", nil + } + states := make([]vcsMarkerState, 0, len(c.vcsMarkers)) + isVCS := false + vcsPath := "" + + for _, marker := range c.vcsMarkers { + p := filepath.Join(dir, marker) + lmeta, err := c.fsys.Lstat(p) + if err != nil { + states = append(states, vcsMarkerState{ + marker: marker, + exists: false, + }) + continue + } + states = append(states, vcsMarkerState{ + marker: marker, + exists: true, + meta: lmeta, + }) + if isVCS { + continue + } + if lmeta.Mode.IsDir() || lmeta.Mode.IsRegular() { + isVCS = true + vcsPath = p + continue + } + if lmeta.Mode&iofs.ModeSymlink != 0 { + if smeta, serr := c.fsys.Stat(p); serr == nil && + (smeta.Mode.IsDir() || smeta.Mode.IsRegular()) { + isVCS = true + vcsPath = p + } + } + } + + return isVCS, vcsPath, states +} + +func (c *securityCache) markersUnchanged( + dir string, + states []vcsMarkerState, +) bool { + if !c.stopAtVCSRoot { + return len(states) == 0 + } + if len(states) != len(c.vcsMarkers) { + return false + } + for _, st := range states { + p := filepath.Join(dir, st.marker) + lmeta, err := c.fsys.Lstat(p) + if err != nil { + if st.exists { + return false + } + continue + } + if !st.exists || !st.meta.sameFingerprint(lmeta) { + return false + } + } + return true +} + +func (c *securityCache) DirEntries(dir string) ([]iofs.DirEntry, error) { + now := c.clock.Now() + cacheKey := filepath.Clean(dir) + if absDir, err := c.fsys.Abs(dir); err == nil { + cacheKey = filepath.Clean(absDir) + } + + c.mu.RLock() + entry, ok := c.dirs[cacheKey] + if ok && entry.dirEntriesCached && c.cacheTTL > 0 && + now.Sub(entry.dirEntriesAt) < c.cacheTTL { + entries := slices.Clone(entry.dirEntries) + c.mu.RUnlock() + c.dirHits.Add(1) + return entries, nil + } + c.mu.RUnlock() + + if !ok { + c.ensureDirEntry(cacheKey) + } + + dirEntries, err := c.fsys.ReadDir(dir) + if err != nil { + return nil, err + } + entries := slices.Clone(dirEntries) + slices.SortFunc(entries, func(a, b iofs.DirEntry) int { + return strings.Compare(a.Name(), b.Name()) + }) + + c.mu.Lock() + if cur, exists := c.dirs[cacheKey]; exists { + cur.dirEntries = slices.Clone(entries) + cur.dirEntriesCached = true + cur.dirEntriesAt = now + } + c.mu.Unlock() + + return entries, nil +} + +func (c *securityCache) ProbeCandidate( + dir string, + name string, + candidatePath string, + evalBoundaryRoot string, + startMeta FileMeta, +) (DiscoveredFile, bool, error) { + now := c.clock.Now() + + c.mu.RLock() + dirEntry, dirOK := c.dirs[dir] + var fentry fileCacheEntry + var fOK bool + if dirOK { + fentry, fOK = dirEntry.files[name] + } + c.mu.RUnlock() + + if fOK && c.cacheTTL > 0 && now.Sub(fentry.validatedAt) < c.cacheTTL && + fentry.boundaryRoot == evalBoundaryRoot { + c.fileHits.Add(1) + return c.resultFromCacheEntry(candidatePath, fentry) + } + + lmeta, err := c.fsys.Lstat(candidatePath) + if err != nil { + if os.IsNotExist(err) || errors.Is(err, iofs.ErrNotExist) { + if fOK && !fentry.exists { + c.fileHits.Add(1) + c.storeFileCache(dir, dirEntry, name, fileCacheEntry{ + validatedAt: now, + exists: false, + boundaryRoot: evalBoundaryRoot, + }) + return DiscoveredFile{}, false, nil + } + if fOK && fentry.exists { + c.invalidations.Add(1) + } + c.fileMisses.Add(1) + c.storeFileCache(dir, dirEntry, name, fileCacheEntry{ + validatedAt: now, + exists: false, + boundaryRoot: evalBoundaryRoot, + }) + return DiscoveredFile{}, false, nil + } + + if fOK && fentry.exists { + c.invalidations.Add(1) + } + c.fileMisses.Add(1) + return DiscoveredFile{}, false, c.HandleSkip( + candidatePath, + SkipPermissionDenied, + err, + ) + } + + if fOK && fentry.exists && fentry.boundaryRoot == evalBoundaryRoot && + fentry.lstatMeta.sameFingerprint(lmeta) { + if !fentry.isSymlink { + c.fileHits.Add(1) + fentry.validatedAt = now + c.storeFileCache(dir, dirEntry, name, fentry) + return c.resultFromCacheEntry(candidatePath, fentry) + } + if resolved, rerr := c.fsys.EvalSymlinks(candidatePath); rerr == nil { + resolved = filepath.Clean(resolved) + if resolved == fentry.resolvedPath { + if smeta, serr := c.fsys.Stat(resolved); serr == nil && + fentry.targetMeta.sameFingerprint(smeta) { + c.fileHits.Add(1) + fentry.validatedAt = now + c.storeFileCache(dir, dirEntry, name, fentry) + return c.resultFromCacheEntry(candidatePath, fentry) + } + } + } + } + + if fOK { + c.invalidations.Add(1) + } + c.fileMisses.Add(1) + + newEntry := c.evaluateCandidate( + dir, + name, + candidatePath, + lmeta, + evalBoundaryRoot, + startMeta, + now, + ) + c.storeFileCache(dir, dirEntry, name, newEntry) + return c.resultFromCacheEntry(candidatePath, newEntry) +} + +func (c *securityCache) storeFileCache( + dir string, + expectedDir *dirCacheEntry, + name string, + entry fileCacheEntry, +) { + c.mu.Lock() + cur, ok := c.dirs[dir] + if ok && (expectedDir == nil || cur == expectedDir) { + if cur.files == nil { + cur.files = make(map[string]fileCacheEntry) + } + cur.files[name] = entry + } + c.mu.Unlock() +} + +func (c *securityCache) resultFromCacheEntry( + candidatePath string, + entry fileCacheEntry, +) (DiscoveredFile, bool, error) { + if !entry.exists { + return DiscoveredFile{}, false, nil + } + if entry.hasSkip { + return DiscoveredFile{}, false, c.HandleSkip( + candidatePath, + entry.skipReason, + entry.skipErr, + ) + } + return entry.discovered, true, nil +} + +func (c *securityCache) evaluateCandidate( + dir string, + name string, + candidatePath string, + lmeta FileMeta, + evalBoundaryRoot string, + startMeta FileMeta, + now time.Time, +) fileCacheEntry { + base := fileCacheEntry{ + validatedAt: now, + exists: true, + lstatMeta: lmeta, + boundaryRoot: evalBoundaryRoot, + } + + isSymlink := lmeta.Mode&iofs.ModeSymlink != 0 + base.isSymlink = isSymlink + + targetMeta := lmeta + resolvedPath := candidatePath + + if isSymlink { + if !c.allowSymlinks { + base.hasSkip = true + base.skipReason = SkipSymlinkDisabled + return base + } + resolved, err := c.fsys.EvalSymlinks(candidatePath) + if err != nil { + base.hasSkip = true + base.skipReason = SkipBrokenSymlink + base.skipErr = err + return base + } + resolvedPath = filepath.Clean(resolved) + base.resolvedPath = resolvedPath + + smeta, err := c.fsys.Stat(resolvedPath) + if err != nil { + base.hasSkip = true + base.skipReason = SkipBrokenSymlink + base.skipErr = err + return base + } + targetMeta = smeta + base.targetMeta = smeta + + if c.stopAtMount && startMeta.HasDevice && smeta.HasDevice && + smeta.DeviceID != startMeta.DeviceID { + base.hasSkip = true + base.skipReason = SkipSymlinkCrossDevice + base.skipErr = fmt.Errorf( + "symlink target %s crosses device boundary (%d != %d)", + resolvedPath, + smeta.DeviceID, + startMeta.DeviceID, + ) + return base + } + + if !c.allowSymlinkEsc && + !isWithinBoundary(evalBoundaryRoot, resolvedPath) { + base.hasSkip = true + base.skipReason = SkipSymlinkEscape + base.skipErr = fmt.Errorf( + "symlink target %s escapes boundary %s", + resolvedPath, + evalBoundaryRoot, + ) + return base + } + } + + if !targetMeta.Mode.IsRegular() { + base.hasSkip = true + base.skipReason = SkipNotRegular + base.skipErr = fmt.Errorf("mode %v is not regular", targetMeta.Mode) + return base + } + + if c.maxFileSize > 0 && targetMeta.Size > c.maxFileSize { + base.hasSkip = true + base.skipReason = SkipFileTooLarge + base.skipErr = fmt.Errorf( + "size %d exceeds limit %d", + targetMeta.Size, + c.maxFileSize, + ) + return base + } + + base.discovered = DiscoveredFile{ + Path: candidatePath, + ResolvedPath: resolvedPath, + Dir: dir, + Name: name, + Size: targetMeta.Size, + ModTime: targetMeta.ModTime, + Mode: targetMeta.Mode, + IsSymlink: isSymlink, + Meta: targetMeta, + } + return base +} + +func (c *securityCache) EvalBoundaryRoot(boundaryRoot string) string { + if evalRoot, err := c.fsys.EvalSymlinks(boundaryRoot); err == nil { + return filepath.Clean(evalRoot) + } + return filepath.Clean(boundaryRoot) +} + +func isWithinBoundary(boundaryRoot, target string) bool { + cleanRoot := filepath.Clean(boundaryRoot) + cleanTarget := filepath.Clean(target) + rel, err := filepath.Rel(cleanRoot, cleanTarget) + if err != nil { + return false + } + if filepath.IsAbs(rel) || rel == ".." { + return false + } + return !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +func (c *securityCache) HandleSkip( + path string, + reason SkipReason, + detail error, +) error { + if c.onSkip != nil { + c.onSkip(path, reason, detail) + } + if c.strictSecurity && reason != SkipExcluded { + return &SecurityError{ + Path: path, + Reason: reason, + Err: detail, + } + } + return nil +} diff --git a/pkg/fs/lookup/doc.go b/pkg/fs/lookup/doc.go new file mode 100644 index 0000000..c02aa25 --- /dev/null +++ b/pkg/fs/lookup/doc.go @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +// Package lookup provides multipurpose file discovery, hierarchical +// configuration lookup, recursive source collection, path filtering, and +// stat-validated security caching. +// +// # SOLID Architecture +// +// Responsibilities are decomposed into focused interfaces: +// +// - [Cache]: Manages stat-fingerprint-validated filesystem metadata, directory +// boundary resolution (VCS roots like .git/.hg, mount-point boundaries, +// directory UID ownership checks, ceiling directories, and max depth), and +// candidate file security validation (regular-file checks, size limits, +// and symlink containment). +// - [Filter]: Evaluates path inclusion and exclusion rules (--include, +// --exclude, --extend-exclude, --force-exclude) normalized via +// [fs.NormalizePath]. +// - [IgnoreMatcher]: Parses, caches, and evaluates hierarchical ignore rule +// files (.gitignore, .ignore) with standard glob, directory, and negation +// semantics. +// - [Finder]: Composes [Cache], [Filter], and [IgnoreMatcher] to support both +// upward configuration discovery ([Finder.FindChain], [Finder.FindNearest]) +// and downward recursive source collection ([Finder.Collect]). +// +// # Usage Example +// +// finder, err := lookup.NewFinder( +// lookup.WithInclude(`\.dml$`), +// lookup.WithExclude(fs.DefaultExcludePattern), +// ) +// if err != nil { +// log.Fatalf("init lookup finder: %v", err) +// } +// +// sources, err := finder.Collect([]string{"."}) +// if err != nil { +// log.Fatalf("collect sources: %v", err) +// } +// configs, err := finder.FindChain( +// "path/to/device.dml", +// lookup.FileEditorConfig, +// lookup.FileGitIgnore, +// ) +package lookup diff --git a/pkg/fs/lookup/filter.go b/pkg/fs/lookup/filter.go new file mode 100644 index 0000000..33a9b77 --- /dev/null +++ b/pkg/fs/lookup/filter.go @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "fmt" + "path/filepath" + "regexp" + + "github.com/timoschenko/dmltools/pkg/fs" +) + +// Filter evaluates path inclusion and exclusion rules. +type Filter interface { + IsForceExcluded(path string) bool + MatchExclude(relToRoot, fullPath string, isDir bool) string + IsIncluded(relToRoot, fullPath string) bool + HasInclude() bool +} + +type regexFilter struct { + fsys FileSystem + include *regexp.Regexp + exclude *regexp.Regexp + extendExclude *regexp.Regexp + forceExclude *regexp.Regexp +} + +// NewFilter creates a standalone [Filter] compiled from regular-expression options. +func NewFilter(opts ...Option) (Filter, error) { + cfg := defaultConfig() + for _, opt := range opts { + if opt != nil { + opt(&cfg) + } + } + return newFilterFromConfig(&cfg) +} + +func newFilterFromConfig(cfg *config) (*regexFilter, error) { + var err error + var incRe, excRe, extRe, forceRe *regexp.Regexp + + if cfg.includePattern != "" { + incRe, err = regexp.Compile(cfg.includePattern) + if err != nil { + return nil, fmt.Errorf( + "invalid regular expression for %s: %w", + FilterInclude, + err, + ) + } + } + if cfg.excludePattern != "" { + excRe, err = regexp.Compile(cfg.excludePattern) + if err != nil { + return nil, fmt.Errorf( + "invalid regular expression for %s: %w", + FilterExclude, + err, + ) + } + } + if cfg.extendExcludePattern != "" { + extRe, err = regexp.Compile(cfg.extendExcludePattern) + if err != nil { + return nil, fmt.Errorf( + "invalid regular expression for %s: %w", + FilterExtendExclude, + err, + ) + } + } + if cfg.forceExcludePattern != "" { + forceRe, err = regexp.Compile(cfg.forceExcludePattern) + if err != nil { + return nil, fmt.Errorf( + "invalid regular expression for %s: %w", + FilterForceExclude, + err, + ) + } + } + + return ®exFilter{ + fsys: cfg.fsys, + include: incRe, + exclude: excRe, + extendExclude: extRe, + forceExclude: forceRe, + }, nil +} + +func (f *regexFilter) HasInclude() bool { + return f.include != nil +} + +func (f *regexFilter) IsForceExcluded(path string) bool { + if f.forceExclude == nil { + return false + } + normFile := fs.NormalizePath(path, false) + if f.forceExclude.MatchString(normFile) { + return true + } + normDir := fs.NormalizePath(path, true) + if f.forceExclude.MatchString(normDir) { + return true + } + if !filepath.IsAbs(path) { + if abs, err := f.fsys.Abs(path); err == nil { + if f.forceExclude.MatchString(fs.NormalizePath(abs, false)) { + return true + } + if f.forceExclude.MatchString(fs.NormalizePath(abs, true)) { + return true + } + } + } + return false +} + +func (f *regexFilter) matchExcludeFilter(normPath string) string { + if f.forceExclude != nil && f.forceExclude.MatchString(normPath) { + return FilterForceExclude + } + if f.exclude != nil && f.exclude.MatchString(normPath) { + return FilterExclude + } + if f.extendExclude != nil && f.extendExclude.MatchString(normPath) { + return FilterExtendExclude + } + return "" +} + +func (f *regexFilter) MatchExclude( + relToRoot, fullPath string, + isDir bool, +) string { + normRel := fs.NormalizePath(relToRoot, isDir) + if name := f.matchExcludeFilter(normRel); name != "" { + return name + } + normFull := fs.NormalizePath(fullPath, isDir) + if name := f.matchExcludeFilter(normFull); name != "" { + return name + } + if !filepath.IsAbs(fullPath) { + if abs, err := f.fsys.Abs(fullPath); err == nil { + normAbs := fs.NormalizePath(abs, isDir) + if name := f.matchExcludeFilter(normAbs); name != "" { + return name + } + } + } + return "" +} + +func (f *regexFilter) IsIncluded(relToRoot, fullPath string) bool { + if f.include == nil { + return true + } + normRel := fs.NormalizePath(relToRoot, false) + if f.include.MatchString(normRel) { + return true + } + normFull := fs.NormalizePath(fullPath, false) + if f.include.MatchString(normFull) { + return true + } + if !filepath.IsAbs(fullPath) { + if abs, err := f.fsys.Abs(fullPath); err == nil { + if f.include.MatchString(fs.NormalizePath(abs, false)) { + return true + } + } + } + return false +} diff --git a/pkg/fs/lookup/finder.go b/pkg/fs/lookup/finder.go new file mode 100644 index 0000000..d11da0e --- /dev/null +++ b/pkg/fs/lookup/finder.go @@ -0,0 +1,617 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "fmt" + iofs "io/fs" + "path/filepath" + "slices" + "sync" +) + +// Finder combines [Cache] and [Filter] to perform upward configuration +// discovery and downward recursive source collection. +type Finder interface { + // FindChain walks upward from startPath to the effective boundary and + // returns all matching files ordered Root-to-Leaf (outermost first, + // nearest to startPath last). Within the same directory, matches follow + // the order of names (or lexical order when matching via Include regex). + FindChain(startPath string, names ...string) ([]DiscoveredFile, error) + + // FindNearest walks upward from startPath to the effective boundary and + // returns the closest matching file to startPath. + FindNearest( + startPath string, + names ...string, + ) (DiscoveredFile, bool, error) + + // Collect discovers, filters, deduplicates, and lexically sorts file paths + // from the provided source files and directories. + Collect(sources []string) ([]string, error) + + // SetOnIgnore registers the callback invoked when Collect skips a path + // due to inclusion or exclusion filters. + SetOnIgnore(cb IgnoreCallback) + + // Cache returns the underlying [Cache] instance. + Cache() Cache + + // Filter returns the underlying [Filter] instance. + Filter() Filter +} + +type fileFinder struct { + cache Cache + filter Filter + ignoreMatcher IgnoreMatcher + ignoreFiles []string + mu sync.RWMutex + onIgnore IgnoreCallback +} + +// NewFinder constructs a [Finder] using injected [WithCache], [WithFilter], or +// [WithIgnoreMatcher] instances, or creating defaults from the provided options. +func NewFinder(opts ...Option) (Finder, error) { + cfg := defaultConfig() + for _, opt := range opts { + if opt != nil { + opt(&cfg) + } + } + + f := cfg.filter + if f == nil { + rf, err := newFilterFromConfig(&cfg) + if err != nil { + return nil, err + } + f = rf + } + + c := cfg.cache + if c == nil { + c = newCacheFromConfig(&cfg) + } + + im := cfg.ignoreMatcher + if im == nil && len(cfg.ignoreFiles) > 0 { + im = newIgnoreMatcherFromConfig(&cfg) + } + + return &fileFinder{ + cache: c, + filter: f, + ignoreMatcher: im, + ignoreFiles: slices.Clone(cfg.ignoreFiles), + onIgnore: cfg.onIgnore, + }, nil +} + +func (f *fileFinder) Cache() Cache { + return f.cache +} + +func (f *fileFinder) Filter() Filter { + return f.filter +} + +func (f *fileFinder) SetOnIgnore(cb IgnoreCallback) { + f.mu.Lock() + f.onIgnore = cb + f.mu.Unlock() +} + +func (f *fileFinder) notifyIgnore(path string, isDir bool, filterName string) { + f.mu.RLock() + cb := f.onIgnore + f.mu.RUnlock() + if cb != nil { + cb(path, isDir, filterName) + } +} + +func (f *fileFinder) FindChain( + startPath string, + names ...string, +) ([]DiscoveredFile, error) { + startDir, absStart, isFile, startMeta, err := f.cache.ResolveStart( + startPath, + ) + if err != nil { + return nil, err + } + + if isFile { + if flt := f.filter.MatchExclude( + startPath, + absStart, + false, + ); flt != "" { + _ = f.cache.HandleSkip( + absStart, + SkipExcluded, + fmt.Errorf("matched %s", flt), + ) + return nil, nil + } + } + + dirs, boundary, resolvedMeta, err := f.cache.ResolveDirChain( + startDir, + startMeta, + ) + if err != nil { + return nil, err + } + + evalBoundaryRoot := f.cache.EvalBoundaryRoot(boundary.RootDir) + var results []DiscoveredFile + + for _, dir := range slices.Backward(dirs) { + found, skipErr := f.probeDir( + dir, + boundary.RootDir, + evalBoundaryRoot, + resolvedMeta, + names, + false, + ) + if skipErr != nil { + return nil, skipErr + } + results = append(results, found...) + } + + return results, nil +} + +func (f *fileFinder) FindNearest( + startPath string, + names ...string, +) (DiscoveredFile, bool, error) { + startDir, absStart, isFile, startMeta, err := f.cache.ResolveStart( + startPath, + ) + if err != nil { + return DiscoveredFile{}, false, err + } + + if isFile { + if flt := f.filter.MatchExclude( + startPath, + absStart, + false, + ); flt != "" { + _ = f.cache.HandleSkip( + absStart, + SkipExcluded, + fmt.Errorf("matched %s", flt), + ) + return DiscoveredFile{}, false, nil + } + } + + dirs, boundary, resolvedMeta, err := f.cache.ResolveDirChain( + startDir, + startMeta, + ) + if err != nil { + return DiscoveredFile{}, false, err + } + + evalBoundaryRoot := f.cache.EvalBoundaryRoot(boundary.RootDir) + + for _, dir := range dirs { + found, skipErr := f.probeDir( + dir, + boundary.RootDir, + evalBoundaryRoot, + resolvedMeta, + names, + true, + ) + if skipErr != nil { + return DiscoveredFile{}, false, skipErr + } + if len(found) > 0 { + return found[0], true, nil + } + } + + return DiscoveredFile{}, false, nil +} + +type collectContext struct { + rootSrc string + boundaryRoot string + evalBoundaryRoot string + startMeta FileMeta + seen map[string]bool + files *[]string +} + +func (f *fileFinder) ignoreEnabled() bool { + return f.ignoreMatcher != nil && len(f.ignoreFiles) > 0 +} + +func (f *fileFinder) Collect(sources []string) ([]string, error) { + seen := make(map[string]bool) + var files []string + + for _, src := range sources { + if f.filter.IsForceExcluded(src) { + isDir := false + if info, err := f.cache.Stat(src); err == nil && + info.Mode.IsDir() { + isDir = true + } + f.notifyIgnore(filepath.Clean(src), isDir, FilterForceExclude) + continue + } + + info, err := f.cache.Stat(src) + if err != nil { + return nil, fmt.Errorf("reading file %s: %w", src, err) + } + + if info.Mode.IsDir() { + cleanSrc := filepath.Clean(src) + if flt := f.filter.MatchExclude(src, src, true); flt != "" { + f.notifyIgnore(cleanSrc, true, flt) + continue + } + + ctx := &collectContext{ + rootSrc: src, + seen: seen, + files: &files, + } + var stack []IgnoreRuleSet + absSrc := cleanSrc + if abs, absErr := f.cache.Abs(src); absErr == nil { + absSrc = filepath.Clean(abs) + } + + if f.ignoreEnabled() { + initStack, bRoot, evalBRoot, sMeta, startDir, initErr := f.initCollectIgnoreStack( + src, + ) + if initErr != nil { + return nil, initErr + } + stack = initStack + ctx.boundaryRoot = bRoot + ctx.evalBoundaryRoot = evalBRoot + ctx.startMeta = sMeta + absSrc = startDir + if len(stack) > 0 { + if igName := f.ignoreMatcher.Match( + stack, + absSrc, + true, + ); igName != "" { + f.notifyIgnore(cleanSrc, true, igName) + continue + } + } + } + + if err := f.walkCollectDir( + ctx, + src, + absSrc, + stack, + false, + ); err != nil { + return nil, err + } + } else { + cleanPath := filepath.Clean(src) + if !seen[cleanPath] { + seen[cleanPath] = true + files = append(files, cleanPath) + } + } + } + + slices.Sort(files) + return files, nil +} + +func (f *fileFinder) initCollectIgnoreStack( + src string, +) ([]IgnoreRuleSet, string, string, FileMeta, string, error) { + startDir, _, _, startMeta, err := f.cache.ResolveStart(src) + if err != nil { + return nil, "", "", FileMeta{}, "", err + } + + dirs, boundary, resolvedMeta, err := f.cache.ResolveDirChain( + startDir, + startMeta, + ) + if err != nil { + return nil, "", "", FileMeta{}, "", err + } + + evalBoundaryRoot := f.cache.EvalBoundaryRoot(boundary.RootDir) + var stack []IgnoreRuleSet + for _, dir := range slices.Backward(dirs) { + loaded, loadErr := f.loadDirIgnoreRules( + dir, + boundary.RootDir, + evalBoundaryRoot, + resolvedMeta, + ) + if loadErr != nil { + return nil, "", "", FileMeta{}, "", loadErr + } + stack = append(stack, loaded...) + } + + return stack, boundary.RootDir, evalBoundaryRoot, resolvedMeta, startDir, nil +} + +func (f *fileFinder) loadDirIgnoreRules( + dir string, + boundaryRoot string, + evalBoundaryRoot string, + startMeta FileMeta, +) ([]IgnoreRuleSet, error) { + found, skipErr := f.probeDir( + dir, + boundaryRoot, + evalBoundaryRoot, + startMeta, + f.ignoreFiles, + false, + ) + if skipErr != nil { + return nil, skipErr + } + if len(found) == 0 { + return nil, nil + } + + rules := make([]IgnoreRuleSet, 0, len(found)) + for _, df := range found { + rs, loadErr := f.ignoreMatcher.LoadFile(df) + if loadErr != nil { + return nil, fmt.Errorf( + "reading ignore file %s: %w", + df.Path, + loadErr, + ) + } + rules = append(rules, rs) + } + return rules, nil +} + +func dirHasAnyCandidate(entries []iofs.DirEntry, names []string) bool { + for _, de := range entries { + if slices.Contains(names, de.Name()) { + return true + } + } + return false +} + +func (f *fileFinder) walkCollectDir( + ctx *collectContext, + currDir string, + absCurrDir string, + stack []IgnoreRuleSet, + probeSelf bool, +) error { + entries, err := f.cache.DirEntries(currDir) + if err != nil { + return fmt.Errorf("reading file %s: %w", currDir, err) + } + + activeStack := stack + if probeSelf && f.ignoreEnabled() && + dirHasAnyCandidate(entries, f.ignoreFiles) { + loaded, loadErr := f.loadDirIgnoreRules( + absCurrDir, + ctx.boundaryRoot, + ctx.evalBoundaryRoot, + ctx.startMeta, + ) + if loadErr != nil { + return loadErr + } + if len(loaded) > 0 { + activeStack = append(slices.Clone(stack), loaded...) + } + } + + for _, d := range entries { + path := filepath.Join(currDir, d.Name()) + absPath := filepath.Join(absCurrDir, d.Name()) + rel, relErr := filepath.Rel(ctx.rootSrc, path) + if relErr != nil { + rel = path + } + cleanPath := filepath.Clean(path) + + if d.IsDir() { + if flt := f.filter.MatchExclude(rel, path, true); flt != "" { + f.notifyIgnore(cleanPath, true, flt) + continue + } + if f.ignoreMatcher != nil && len(activeStack) > 0 { + if igName := f.ignoreMatcher.Match( + activeStack, + absPath, + true, + ); igName != "" { + f.notifyIgnore(cleanPath, true, igName) + continue + } + } + if err := f.walkCollectDir( + ctx, + path, + absPath, + activeStack, + true, + ); err != nil { + return err + } + continue + } + + if d.Type()&iofs.ModeSymlink != 0 { + targetInfo, statErr := f.cache.Stat(path) + if statErr != nil || targetInfo.Mode.IsDir() { + continue + } + } + + if flt := f.filter.MatchExclude(rel, path, false); flt != "" { + f.notifyIgnore(cleanPath, false, flt) + continue + } + + if f.ignoreMatcher != nil && len(activeStack) > 0 { + if igName := f.ignoreMatcher.Match( + activeStack, + absPath, + false, + ); igName != "" { + f.notifyIgnore(cleanPath, false, igName) + continue + } + } + + if !f.filter.IsIncluded(rel, path) { + f.notifyIgnore(cleanPath, false, FilterInclude) + continue + } + + if !ctx.seen[cleanPath] { + ctx.seen[cleanPath] = true + *ctx.files = append(*ctx.files, cleanPath) + } + } + + return nil +} + +func (f *fileFinder) probeDir( + dir string, + boundaryRoot string, + evalBoundaryRoot string, + startMeta FileMeta, + names []string, + stopOnFirst bool, +) ([]DiscoveredFile, error) { + relDir := relPathForFilter(boundaryRoot, dir) + if flt := f.filter.MatchExclude(relDir, dir, true); flt != "" { + _ = f.cache.HandleSkip( + dir, + SkipExcluded, + fmt.Errorf("matched %s", flt), + ) + return nil, nil + } + + candidates, err := f.candidatesForDir(dir, boundaryRoot, names) + if err != nil { + return nil, err + } + + var results []DiscoveredFile + for _, name := range candidates { + if name == "" { + continue + } + candidatePath := filepath.Join(dir, name) + relFile := relPathForFilter(boundaryRoot, candidatePath) + if flt := f.filter.MatchExclude( + relFile, + candidatePath, + false, + ); flt != "" { + _ = f.cache.HandleSkip( + candidatePath, + SkipExcluded, + fmt.Errorf("matched %s", flt), + ) + continue + } + + df, ok, skipErr := f.cache.ProbeCandidate( + dir, + name, + candidatePath, + evalBoundaryRoot, + startMeta, + ) + if skipErr != nil { + return nil, skipErr + } + if ok { + results = append(results, df) + if stopOnFirst { + return results, nil + } + } + } + return results, nil +} + +func (f *fileFinder) candidatesForDir( + dir string, + boundaryRoot string, + names []string, +) ([]string, error) { + if len(names) > 0 { + out := make([]string, 0, len(names)) + seen := make(map[string]struct{}, len(names)) + for _, n := range names { + if n == "" { + continue + } + if _, ok := seen[n]; ok { + continue + } + seen[n] = struct{}{} + out = append(out, n) + } + return out, nil + } + if !f.filter.HasInclude() { + return nil, nil + } + + entries, err := f.cache.DirEntries(dir) + if err != nil { + return nil, f.cache.HandleSkip(dir, SkipPermissionDenied, err) + } + + var matched []string + for _, de := range entries { + if de.IsDir() { + continue + } + full := filepath.Join(dir, de.Name()) + rel := relPathForFilter(boundaryRoot, full) + if f.filter.IsIncluded(rel, full) { + matched = append(matched, de.Name()) + } + } + return matched, nil +} + +func relPathForFilter(boundaryRoot, fullPath string) string { + if rel, err := filepath.Rel(boundaryRoot, fullPath); err == nil { + if rel != "." { + return rel + } + } + return fullPath +} diff --git a/pkg/fs/lookup/fs.go b/pkg/fs/lookup/fs.go new file mode 100644 index 0000000..9d766c6 --- /dev/null +++ b/pkg/fs/lookup/fs.go @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + iofs "io/fs" + "os" + "path/filepath" + "time" +) + +// Clock supplies the current time for cache TTL evaluation. +type Clock interface { + Now() time.Time +} + +type realClock struct{} + +func (realClock) Now() time.Time { + return time.Now() +} + +// FileMeta captures portable and platform-specific filesystem metadata used for +// security boundary checks and cache fingerprint validation. +type FileMeta struct { + Name string + Size int64 + Mode iofs.FileMode + ModTime time.Time + DeviceID uint64 + Inode uint64 + UID uint32 + HasDevice bool + HasInode bool + HasUID bool +} + +func (m FileMeta) sameFingerprint(other FileMeta) bool { + if m.Mode != other.Mode || m.Size != other.Size || + !m.ModTime.Equal(other.ModTime) { + return false + } + if m.HasDevice != other.HasDevice || + (m.HasDevice && m.DeviceID != other.DeviceID) { + return false + } + if m.HasInode != other.HasInode || + (m.HasInode && m.Inode != other.Inode) { + return false + } + if m.HasUID != other.HasUID || (m.HasUID && m.UID != other.UID) { + return false + } + return true +} + +// FileSystem abstracts OS filesystem operations so boundary, mount-point, +// ownership, and cache behavior can be tested deterministically across OSes. +type FileSystem interface { + Stat(path string) (FileMeta, error) + Lstat(path string) (FileMeta, error) + ReadDir(path string) ([]iofs.DirEntry, error) + ReadFile(path string) ([]byte, error) + EvalSymlinks(path string) (string, error) + Abs(path string) (string, error) + Geteuid() int +} + +type osFileSystem struct{} + +// NewOSFileSystem returns the default [FileSystem] backed by the OS. +func NewOSFileSystem() FileSystem { + return osFileSystem{} +} + +func (osFileSystem) Stat(path string) (FileMeta, error) { + info, err := os.Stat(path) + if err != nil { + return FileMeta{}, err + } + return fileInfoToMeta(path, info), nil +} + +func (osFileSystem) Lstat(path string) (FileMeta, error) { + info, err := os.Lstat(path) + if err != nil { + return FileMeta{}, err + } + return fileInfoToMeta(path, info), nil +} + +func (osFileSystem) ReadDir(path string) ([]iofs.DirEntry, error) { + return os.ReadDir(path) +} + +func (osFileSystem) ReadFile(path string) ([]byte, error) { + //nolint:gosec // callers validate candidate paths via Cache security guards + return os.ReadFile(filepath.Clean(path)) +} + +func (osFileSystem) EvalSymlinks(path string) (string, error) { + return filepath.EvalSymlinks(path) +} + +func (osFileSystem) Abs(path string) (string, error) { + return filepath.Abs(path) +} + +func (osFileSystem) Geteuid() int { + return osGeteuid() +} + +func fileInfoToMeta(path string, info os.FileInfo) FileMeta { + meta := FileMeta{ + Name: info.Name(), + Size: info.Size(), + Mode: info.Mode(), + ModTime: info.ModTime(), + } + fillSysMeta(path, info, &meta) + return meta +} diff --git a/pkg/fs/lookup/ignore.go b/pkg/fs/lookup/ignore.go new file mode 100644 index 0000000..c160e4b --- /dev/null +++ b/pkg/fs/lookup/ignore.go @@ -0,0 +1,463 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "bytes" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" +) + +// IgnoreRuleSet holds the compiled ignore patterns parsed from a single ignore +// file (such as .gitignore or .ignore). +type IgnoreRuleSet struct { + BaseDir string + SourceName string + rules []ignoreRule +} + +// IgnoreMatcher parses, caches, and evaluates hierarchical ignore rule files +// (such as .gitignore and .ignore). +type IgnoreMatcher interface { + LoadFile(df DiscoveredFile) (IgnoreRuleSet, error) + Match(stack []IgnoreRuleSet, fullPath string, isDir bool) string +} + +type ignoreRule struct { + regex *regexp.Regexp + negate bool + dirOnly bool +} + +type cachedRuleSet struct { + meta FileMeta + resolvedPath string + baseDir string + sourceName string + ruleSet IgnoreRuleSet +} + +type gitignoreMatcher struct { + fsys FileSystem + mu sync.RWMutex + cache map[string]cachedRuleSet +} + +// NewIgnoreMatcher creates a standalone [IgnoreMatcher] with stat-validated +// rule caching. +func NewIgnoreMatcher(opts ...Option) IgnoreMatcher { + cfg := defaultConfig() + for _, opt := range opts { + if opt != nil { + opt(&cfg) + } + } + return newIgnoreMatcherFromConfig(&cfg) +} + +func newIgnoreMatcherFromConfig(cfg *config) *gitignoreMatcher { + return &gitignoreMatcher{ + fsys: cfg.fsys, + cache: make(map[string]cachedRuleSet), + } +} + +func (m *gitignoreMatcher) LoadFile( + df DiscoveredFile, +) (IgnoreRuleSet, error) { + readPath := df.Path + if readPath == "" { + readPath = df.ResolvedPath + } + cacheKey := filepath.Clean(readPath) + + sourceName := df.Name + if sourceName == "" { + sourceName = filepath.Base(readPath) + } + baseDir := df.Dir + if baseDir == "" { + baseDir = filepath.Dir(readPath) + } + baseDir = filepath.Clean(baseDir) + + meta, err := m.resolveFileMeta(readPath, df) + if err != nil { + return IgnoreRuleSet{}, err + } + + m.mu.RLock() + entry, ok := m.cache[cacheKey] + m.mu.RUnlock() + if ok && entry.resolvedPath == df.ResolvedPath && + entry.baseDir == baseDir && + entry.sourceName == sourceName && + entry.meta.sameFingerprint(meta) { + return entry.ruleSet, nil + } + + data, err := m.fsys.ReadFile(readPath) + if err != nil { + return IgnoreRuleSet{}, err + } + + rs := IgnoreRuleSet{ + BaseDir: baseDir, + SourceName: sourceName, + rules: parseIgnoreRules(data), + } + + m.mu.Lock() + m.cache[cacheKey] = cachedRuleSet{ + meta: meta, + resolvedPath: df.ResolvedPath, + baseDir: baseDir, + sourceName: sourceName, + ruleSet: rs, + } + m.mu.Unlock() + + return rs, nil +} + +func (m *gitignoreMatcher) resolveFileMeta( + readPath string, + df DiscoveredFile, +) (FileMeta, error) { + if df.Meta.Mode != 0 { + return df.Meta, nil + } + if df.Mode != 0 || !df.ModTime.IsZero() || df.Size != 0 { + return FileMeta{ + Name: df.Name, + Size: df.Size, + Mode: df.Mode, + ModTime: df.ModTime, + }, nil + } + return m.fsys.Stat(readPath) +} + +func (m *gitignoreMatcher) Match( + stack []IgnoreRuleSet, + fullPath string, + isDir bool, +) string { + if len(stack) == 0 { + return "" + } + + cleanFull := filepath.Clean(fullPath) + for _, ancDir := range ancestorDirsUnderStack(stack, cleanFull) { + if src := matchSinglePath(stack, ancDir, true); src != "" { + return src + } + } + + return matchSinglePath(stack, cleanFull, isDir) +} + +func ancestorDirsUnderStack( + stack []IgnoreRuleSet, + cleanFull string, +) []string { + var ancestors []string + for dir := filepath.Dir(cleanFull); dir != "" && + dir != "." && + dir != filepath.Dir(dir); dir = filepath.Dir(dir) { + underAny := false + for _, rs := range stack { + if len(rs.rules) == 0 { + continue + } + if _, ok := relUnderBaseDir(rs.BaseDir, dir); ok { + underAny = true + break + } + } + if !underAny { + break + } + ancestors = append(ancestors, dir) + } + slices.Reverse(ancestors) + return ancestors +} + +func matchSinglePath( + stack []IgnoreRuleSet, + cleanFull string, + isDir bool, +) string { + ignored := false + matchedSource := "" + + var lastBase string + var lastRel string + var lastValid bool + + for _, rs := range stack { + if len(rs.rules) == 0 { + continue + } + var slashRel string + var valid bool + if rs.BaseDir == lastBase { + slashRel = lastRel + valid = lastValid + } else { + slashRel, valid = relUnderBaseDir(rs.BaseDir, cleanFull) + lastBase = rs.BaseDir + lastRel = slashRel + lastValid = valid + } + if !valid { + continue + } + + for _, r := range rs.rules { + if r.dirOnly && !isDir { + continue + } + if r.regex.MatchString(slashRel) { + ignored = !r.negate + if ignored { + matchedSource = rs.SourceName + } else { + matchedSource = "" + } + } + } + } + + return matchedSource +} + +func relUnderBaseDir(baseDir, fullPath string) (string, bool) { + rel, err := filepath.Rel(baseDir, fullPath) + if err != nil { + return "", false + } + if rel == "." || rel == ".." || + strings.HasPrefix(rel, ".."+string(filepath.Separator)) || + filepath.IsAbs(rel) { + return "", false + } + return filepath.ToSlash(rel), true +} + +func parseIgnoreRules(data []byte) []ignoreRule { + var rules []ignoreRule + for line := range bytes.SplitSeq(data, []byte("\n")) { + rule, ok := parseIgnoreLine(string(line)) + if ok { + rules = append(rules, rule) + } + } + return rules +} + +func parseIgnoreLine(raw string) (ignoreRule, bool) { + line := strings.TrimSuffix(raw, "\r") + if line == "" || line[0] == '#' { + return ignoreRule{}, false + } + + line = trimUnescapedTrailingSpaces(line) + if line == "" { + return ignoreRule{}, false + } + + negate := false + if line[0] == '!' { + negate = true + line = line[1:] + if line == "" { + return ignoreRule{}, false + } + } + + dirOnly := false + if strings.HasSuffix(line, "/") { + dirOnly = true + line = strings.TrimRight(line, "/") + if line == "" { + return ignoreRule{}, false + } + } + + anchored := false + if strings.Contains(line, "/") { + anchored = true + line = strings.TrimPrefix(line, "/") + if line == "" { + return ignoreRule{}, false + } + } + + re, err := compileGitignoreGlob(line, anchored) + if err != nil { + return ignoreRule{}, false + } + + return ignoreRule{ + regex: re, + negate: negate, + dirOnly: dirOnly, + }, true +} + +func trimUnescapedTrailingSpaces(s string) string { + end := len(s) + for end > 0 && s[end-1] == ' ' { + backslashes := 0 + for i := end - 2; i >= 0 && s[i] == '\\'; i-- { + backslashes++ + } + if backslashes%2 == 1 { + break + } + end-- + } + return s[:end] +} + +func compileGitignoreGlob( + pat string, + anchored bool, +) (*regexp.Regexp, error) { + var b strings.Builder + if !anchored { + b.WriteString("^(?:[^/]+/)*") + } else { + b.WriteByte('^') + } + + if pat == "**" { + b.WriteString(".*$") + return regexp.Compile(b.String()) + } + + i := 0 + for i < len(pat) { + switch { + case pat[i] == '\\': + if i+1 < len(pat) { + b.WriteString(regexp.QuoteMeta(string(pat[i+1]))) + i += 2 + } else { + b.WriteString(`\\`) + i++ + } + case i == 0 && strings.HasPrefix(pat[i:], "**/"): + b.WriteString("(?:[^/]+/)*") + i += 3 + for strings.HasPrefix(pat[i:], "**/") { + i += 3 + } + case strings.HasPrefix(pat[i:], "/**/"): + b.WriteString("/(?:[^/]+/)*") + i += 4 + for strings.HasPrefix(pat[i:], "**/") { + i += 3 + } + case pat[i:] == "/**": + b.WriteString("/.*") + i += 3 + case pat[i] == '*': + for i+1 < len(pat) && pat[i+1] == '*' { + i++ + } + b.WriteString("[^/]*") + i++ + case pat[i] == '?': + b.WriteString("[^/]") + i++ + case pat[i] == '[': + cls, next, ok := translateCharClass(pat, i) + if ok { + b.WriteString(cls) + i = next + } else { + b.WriteString(`\[`) + i++ + } + default: + b.WriteString(regexp.QuoteMeta(string(pat[i]))) + i++ + } + } + + b.WriteByte('$') + return regexp.Compile(b.String()) +} + +func translateCharClass(pat string, start int) (string, int, bool) { + i := start + 1 + if i >= len(pat) { + return "", start, false + } + + var body strings.Builder + negate := false + if pat[i] == '!' || pat[i] == '^' { + negate = true + i++ + } + + if i < len(pat) && pat[i] == ']' { + body.WriteString(`\]`) + i++ + } + + for i < len(pat) { + ch := pat[i] + if ch == '/' { + return "", start, false + } + if ch == '\\' && i+1 < len(pat) { + if pat[i+1] == '/' { + return "", start, false + } + body.WriteByte('\\') + body.WriteByte(pat[i+1]) + i += 2 + continue + } + if ch == ']' { + if body.Len() == 0 { + return "", start, false + } + if negate { + return "[^/" + body.String() + "]", i + 1, true + } + return "[" + body.String() + "]", i + 1, true + } + if ch == '[' { + body.WriteString(`\[`) + } else { + body.WriteByte(ch) + } + i++ + } + + return "", start, false +} + +func normalizeIgnoreFileNames(names []string) []string { + if len(names) == 0 { + return nil + } + out := make([]string, 0, len(names)) + for _, n := range names { + if n == "" || slices.Contains(out, n) { + continue + } + out = append(out, n) + } + return out +} diff --git a/pkg/fs/lookup/lookup_test.go b/pkg/fs/lookup/lookup_test.go new file mode 100644 index 0000000..96d5230 --- /dev/null +++ b/pkg/fs/lookup/lookup_test.go @@ -0,0 +1,1630 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "errors" + iofs "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" +) + +type mockClock struct { + mu sync.Mutex + now time.Time +} + +func newMockClock(t time.Time) *mockClock { + return &mockClock{now: t} +} + +func (m *mockClock) Now() time.Time { + m.mu.Lock() + defer m.mu.Unlock() + return m.now +} + +func (m *mockClock) Advance(d time.Duration) { + m.mu.Lock() + defer m.mu.Unlock() + m.now = m.now.Add(d) +} + +type mockNode struct { + meta FileMeta + symlinkTo string + content []byte + statErr error + lstatErr error + readDirErr error + readFileErr error + evalOverride string +} + +type mockDirEntry struct { + name string + mode iofs.FileMode + meta FileMeta +} + +func (e mockDirEntry) Name() string { return e.name } +func (e mockDirEntry) IsDir() bool { return e.mode.IsDir() } +func (e mockDirEntry) Type() iofs.FileMode { return e.mode.Type() } + +func (e mockDirEntry) Info() (iofs.FileInfo, error) { return mockFileInfo{meta: e.meta}, nil } + +type mockFileInfo struct { + meta FileMeta +} + +func (i mockFileInfo) Name() string { return i.meta.Name } +func (i mockFileInfo) Size() int64 { return i.meta.Size } +func (i mockFileInfo) Mode() iofs.FileMode { return i.meta.Mode } +func (i mockFileInfo) ModTime() time.Time { return i.meta.ModTime } +func (i mockFileInfo) IsDir() bool { return i.meta.Mode.IsDir() } +func (i mockFileInfo) Sys() any { return nil } + +type mockFS struct { + mu sync.Mutex + cwd string + euid int + nodes map[string]*mockNode + statCalls map[string]int + readFileCalls map[string]int +} + +func newMockFS(cwd string, euid int) *mockFS { + return &mockFS{ + cwd: filepath.Clean(cwd), + euid: euid, + nodes: make(map[string]*mockNode), + statCalls: make(map[string]int), + readFileCalls: make(map[string]int), + } +} + +func (m *mockFS) setDir( + path string, + dev uint64, + uid uint32, + mtime time.Time, +) { + m.mu.Lock() + defer m.mu.Unlock() + clean := filepath.Clean(path) + m.nodes[clean] = &mockNode{ + meta: FileMeta{ + Name: filepath.Base(clean), + Mode: iofs.ModeDir | 0755, + ModTime: mtime, + DeviceID: dev, + Inode: uint64(len(m.nodes) + 1), + UID: uid, + HasDevice: true, + HasInode: true, + HasUID: true, + }, + } +} + +func (m *mockFS) setFile( + path string, + mode iofs.FileMode, + size int64, + dev uint64, + uid uint32, + mtime time.Time, +) { + m.mu.Lock() + defer m.mu.Unlock() + clean := filepath.Clean(path) + m.nodes[clean] = &mockNode{ + meta: FileMeta{ + Name: filepath.Base(clean), + Mode: mode, + Size: size, + ModTime: mtime, + DeviceID: dev, + Inode: uint64(len(m.nodes) + 1), + UID: uid, + HasDevice: true, + HasInode: true, + HasUID: true, + }, + } +} + +func (m *mockFS) setFileWithContent( + path string, + content []byte, + dev uint64, + uid uint32, + mtime time.Time, +) { + m.mu.Lock() + defer m.mu.Unlock() + clean := filepath.Clean(path) + m.nodes[clean] = &mockNode{ + meta: FileMeta{ + Name: filepath.Base(clean), + Mode: 0644, + Size: int64(len(content)), + ModTime: mtime, + DeviceID: dev, + Inode: uint64(len(m.nodes) + 1), + UID: uid, + HasDevice: true, + HasInode: true, + HasUID: true, + }, + content: slices.Clone(content), + } +} + +func (m *mockFS) setSymlink( + path string, + target string, + dev uint64, + uid uint32, + mtime time.Time, +) { + m.mu.Lock() + defer m.mu.Unlock() + clean := filepath.Clean(path) + m.nodes[clean] = &mockNode{ + meta: FileMeta{ + Name: filepath.Base(clean), + Mode: iofs.ModeSymlink | 0777, + ModTime: mtime, + DeviceID: dev, + Inode: uint64(len(m.nodes) + 1), + UID: uid, + HasDevice: true, + HasInode: true, + HasUID: true, + }, + symlinkTo: filepath.Clean(target), + } +} + +func (m *mockFS) deleteNode(path string) { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.nodes, filepath.Clean(path)) +} + +func (m *mockFS) setStatErr(path string, err error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := filepath.Clean(path) + if n, ok := m.nodes[clean]; ok { + n.statErr = err + n.lstatErr = err + } else { + m.nodes[clean] = &mockNode{ + statErr: err, + lstatErr: err, + } + } +} + +func (m *mockFS) totalStatCalls() int { + m.mu.Lock() + defer m.mu.Unlock() + total := 0 + for _, c := range m.statCalls { + total += c + } + return total +} + +func (m *mockFS) resetStatCalls() { + m.mu.Lock() + defer m.mu.Unlock() + clear(m.statCalls) +} + +func (m *mockFS) totalReadFileCalls() int { + m.mu.Lock() + defer m.mu.Unlock() + total := 0 + for _, c := range m.readFileCalls { + total += c + } + return total +} + +func (m *mockFS) absLocked(path string) string { + if filepath.IsAbs(path) { + return filepath.Clean(path) + } + return filepath.Clean(filepath.Join(m.cwd, path)) +} + +func (m *mockFS) Stat(path string) (FileMeta, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + m.statCalls[clean]++ + for range 8 { + n, ok := m.nodes[clean] + if !ok { + return FileMeta{}, os.ErrNotExist + } + if n.statErr != nil { + return FileMeta{}, n.statErr + } + if n.symlinkTo == "" { + return n.meta, nil + } + clean = n.symlinkTo + } + return FileMeta{}, errors.New("too many levels of symbolic links") +} + +func (m *mockFS) Lstat(path string) (FileMeta, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + m.statCalls[clean]++ + n, ok := m.nodes[clean] + if !ok { + return FileMeta{}, os.ErrNotExist + } + if n.lstatErr != nil { + return FileMeta{}, n.lstatErr + } + return n.meta, nil +} + +func (m *mockFS) ReadDir(path string) ([]iofs.DirEntry, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + n, ok := m.nodes[clean] + if !ok { + return nil, os.ErrNotExist + } + if n.readDirErr != nil { + return nil, n.readDirErr + } + prefix := clean + string(filepath.Separator) + var entries []iofs.DirEntry + for p, node := range m.nodes { + if !strings.HasPrefix(p, prefix) { + continue + } + rest := strings.TrimPrefix(p, prefix) + if rest == "" || strings.Contains(rest, string(filepath.Separator)) { + continue + } + entries = append(entries, mockDirEntry{ + name: rest, + mode: node.meta.Mode, + meta: node.meta, + }) + } + return entries, nil +} + +func (m *mockFS) ReadFile(path string) ([]byte, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + m.readFileCalls[clean]++ + for range 8 { + n, ok := m.nodes[clean] + if !ok { + return nil, os.ErrNotExist + } + if n.readFileErr != nil { + return nil, n.readFileErr + } + if n.symlinkTo == "" { + if n.meta.Mode.IsDir() { + return nil, errors.New("is a directory") + } + return slices.Clone(n.content), nil + } + clean = n.symlinkTo + } + return nil, errors.New("too many levels of symbolic links") +} + +func (m *mockFS) EvalSymlinks(path string) (string, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + for range 8 { + n, ok := m.nodes[clean] + if !ok { + return "", os.ErrNotExist + } + if n.evalOverride != "" { + return n.evalOverride, nil + } + if n.symlinkTo == "" { + return clean, nil + } + clean = n.symlinkTo + } + return "", errors.New("too many levels of symbolic links") +} + +func (m *mockFS) Abs(path string) (string, error) { + if filepath.IsAbs(path) { + return filepath.Clean(path), nil + } + return filepath.Clean(filepath.Join(m.cwd, path)), nil +} + +func (m *mockFS) Geteuid() int { + return m.euid +} + +func buildMockRepo(baseTime time.Time) *mockFS { + m := newMockFS("/repo/sub/deep", 1000) + m.setDir("/", 1, 0, baseTime) + m.setDir("/outside", 1, 1000, baseTime) + m.setDir("/repo", 1, 1000, baseTime) + m.setDir("/repo/.git", 1, 1000, baseTime) + m.setDir("/repo/sub", 1, 1000, baseTime) + m.setDir("/repo/sub/deep", 1, 1000, baseTime) + return m +} + +func TestSOLIDCompositionAndInjection(t *testing.T) { + now := time.Unix(1700000000, 0) + m := buildMockRepo(now) + m.setFile("/repo/.editorconfig", 0644, 20, 1, 1000, now) + m.setFile("/repo/sub/main.dml", 0644, 30, 1, 1000, now) + + cache := NewCache(WithFileSystem(m)) + filter, err := NewFilter( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithExclude(`/\.git/`), + ) + if err != nil { + t.Fatalf("NewFilter failed: %v", err) + } + if !filter.HasInclude() { + t.Fatal("expected filter.HasInclude() to be true") + } + + finder1, err := NewFinder(WithCache(cache), WithFilter(filter)) + if err != nil { + t.Fatalf("NewFinder 1 failed: %v", err) + } + finder2, err := NewFinder(WithCache(cache), WithFilter(filter)) + if err != nil { + t.Fatalf("NewFinder 2 failed: %v", err) + } + + if finder1.Cache() != cache || finder1.Filter() != filter { + t.Fatal("expected finder1 to expose injected Cache and Filter") + } + + collected, err := finder1.Collect([]string{"/repo"}) + if err != nil { + t.Fatalf("Collect failed: %v", err) + } + if len(collected) != 1 || + collected[0] != filepath.Clean("/repo/sub/main.dml") { + t.Fatalf("unexpected collected files: %v", collected) + } + + // finder2 shares the same Cache instance as finder1. + chain, err := finder2.FindChain("/repo/sub/main.dml", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if len(chain) != 1 || + chain[0].Path != filepath.Clean("/repo/.editorconfig") { + t.Fatalf("unexpected chain: %+v", chain) + } + if cache.Stats().DirHits == 0 { + t.Errorf("expected shared cache hits between finder1 and finder2") + } +} + +func TestFindChainAndFindNearest_OrderingAndNames(t *testing.T) { + now := time.Unix(1700000000, 0) + m := buildMockRepo(now) + m.setFile("/outside/.editorconfig", 0644, 10, 1, 1000, now) + m.setFile("/repo/.editorconfig", 0644, 20, 1, 1000, now) + m.setFile("/repo/.gitignore", 0644, 15, 1, 1000, now) + m.setFile("/repo/sub/.editorconfig", 0644, 25, 1, 1000, now) + m.setFile("/repo/sub/deep/main.dml", 0644, 40, 1, 1000, now) + + finder, err := NewFinder(WithFileSystem(m)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + chain, err := finder.FindChain( + "/repo/sub/deep/main.dml", + FileEditorConfig, + FileGitIgnore, + ) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + wantPaths := []string{ + filepath.Clean("/repo/.editorconfig"), + filepath.Clean("/repo/.gitignore"), + filepath.Clean("/repo/sub/.editorconfig"), + } + if len(chain) != len(wantPaths) { + t.Fatalf( + "got %d files (%v), want %d", + len(chain), + chain, + len(wantPaths), + ) + } + for i, want := range wantPaths { + if chain[i].Path != want { + t.Errorf("chain[%d].Path = %q, want %q", i, chain[i].Path, want) + } + } + + nearest, found, err := finder.FindNearest( + "/repo/sub/deep", + FileEditorConfig, + FileGitIgnore, + ) + if err != nil { + t.Fatalf("FindNearest failed: %v", err) + } + if !found { + t.Fatal("expected FindNearest to find a file") + } + if nearest.Path != filepath.Clean("/repo/sub/.editorconfig") { + t.Errorf( + "nearest.Path = %q, want /repo/sub/.editorconfig", + nearest.Path, + ) + } +} + +func TestFinderCollect(t *testing.T) { + now := time.Unix(1700000000, 0) + m := newMockFS("/ws", 1000) + m.setDir("/", 1, 0, now) + m.setDir("/ws", 1, 1000, now) + m.setDir("/ws/.git", 1, 1000, now) + m.setFile("/ws/.git/hook.dml", 0644, 5, 1, 1000, now) + m.setDir("/ws/venv", 1, 1000, now) + m.setFile("/ws/venv/lib.dml", 0644, 5, 1, 1000, now) + m.setDir("/ws/sub", 1, 1000, now) + m.setFile("/ws/sub/a.dml", 0644, 5, 1, 1000, now) + m.setFile("/ws/sub/b.txt", 0644, 5, 1, 1000, now) + m.setFile("/ws/sub/skip_gen.dml", 0644, 5, 1, 1000, now) + m.setFile("/ws/root.dml", 0644, 5, 1, 1000, now) + m.setSymlink("/ws/dirlink", "/ws/sub", 1, 1000, now) + m.setSymlink("/ws/broken.dml", "/ws/missing.dml", 1, 1000, now) + + type ignoredEvent struct { + path string + isDir bool + filter string + } + var ignored []ignoredEvent + + finder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithExclude(`/(\.git|venv)/`), + WithForceExclude(`skip_gen`), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + finder.SetOnIgnore(func(path string, isDir bool, filterName string) { + ignored = append(ignored, ignoredEvent{path, isDir, filterName}) + }) + + files, err := finder.Collect([]string{ + "/ws/root.dml", + "/ws", + "/ws/venv/lib.dml", + "/ws/sub/skip_gen.dml", + }) + if err != nil { + t.Fatalf("Collect failed: %v", err) + } + + // /ws/venv/lib.dml passed explicitly bypasses --exclude, while skip_gen.dml + // is skipped by --force-exclude. Directory symlink and broken symlink are skipped. + want := []string{ + filepath.Clean("/ws/root.dml"), + filepath.Clean("/ws/sub/a.dml"), + filepath.Clean("/ws/venv/lib.dml"), + } + if !slices.Equal(files, want) { + t.Fatalf("got %v, want %v", files, want) + } + + if !slices.Contains(ignored, ignoredEvent{ + path: filepath.Clean("/ws/sub/b.txt"), + isDir: false, + filter: FilterInclude, + }) { + t.Errorf( + "expected b.txt to trigger %s ignore event, got %+v", + FilterInclude, + ignored, + ) + } + if !slices.Contains(ignored, ignoredEvent{ + path: filepath.Clean("/ws/venv"), + isDir: true, + filter: FilterExclude, + }) { + t.Errorf( + "expected venv dir to trigger %s ignore event, got %+v", + FilterExclude, + ignored, + ) + } + + if _, err := finder.Collect([]string{"/ws/nonexistent.dml"}); err == nil { + t.Fatal("expected error for non-existent source") + } + + m.mu.Lock() + subGitProbes := m.statCalls[filepath.Clean("/ws/sub/.git")] + subHgProbes := m.statCalls[filepath.Clean("/ws/sub/.hg")] + m.mu.Unlock() + if subGitProbes != 0 || subHgProbes != 0 { + t.Errorf( + "expected no VCS marker probes on subdirectory during Collect, got .git=%d .hg=%d", + subGitProbes, + subHgProbes, + ) + } +} + +func TestVCSBoundaries(t *testing.T) { + now := time.Unix(1700000000, 0) + + t.Run("git worktree regular file", func(t *testing.T) { + m := newMockFS("/outer/worktree/sub", 1000) + m.setDir("/", 1, 0, now) + m.setDir("/outer", 1, 1000, now) + m.setDir("/outer/.git", 1, 1000, now) + m.setFile("/outer/.editorconfig", 0644, 10, 1, 1000, now) + m.setDir("/outer/worktree", 1, 1000, now) + m.setFile("/outer/worktree/.git", 0644, 32, 1, 1000, now) + m.setFile("/outer/worktree/.editorconfig", 0644, 12, 1, 1000, now) + m.setDir("/outer/worktree/sub", 1, 1000, now) + + finder, err := NewFinder(WithFileSystem(m)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + b, err := finder.Cache().ResolveBoundary("/outer/worktree/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != BoundaryVCSRoot || + b.RootDir != filepath.Clean("/outer/worktree") { + t.Fatalf("unexpected boundary: %+v", b) + } + + chain, err := finder.FindChain("/outer/worktree/sub", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if len(chain) != 1 || + chain[0].Path != filepath.Clean("/outer/worktree/.editorconfig") { + t.Fatalf("unexpected chain: %+v", chain) + } + }) + + t.Run("hg directory and custom markers", func(t *testing.T) { + m := newMockFS("/proj/src", 1000) + m.setDir("/", 1, 0, now) + m.setDir("/proj", 1, 1000, now) + m.setDir("/proj/.hg", 1, 1000, now) + m.setDir("/proj/src", 1, 1000, now) + m.setDir("/proj/src/.jj", 1, 1000, now) + + c1 := NewCache(WithFileSystem(m)) + b, err := c1.ResolveBoundary("/proj/src") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != BoundaryVCSRoot || b.RootDir != filepath.Clean("/proj") { + t.Fatalf("expected /proj vcs boundary, got %+v", b) + } + + c2 := NewCache(WithFileSystem(m), WithVCSMarkers(".jj")) + cb, err := c2.ResolveBoundary("/proj/src") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if cb.Reason != BoundaryVCSRoot || + cb.RootDir != filepath.Clean("/proj/src") { + t.Fatalf("expected /proj/src .jj boundary, got %+v", cb) + } + }) + + t.Run("disable VCS root stop", func(t *testing.T) { + m := buildMockRepo(now) + c := NewCache(WithFileSystem(m), WithStopAtVCSRoot(false)) + b, err := c.ResolveBoundary("/repo/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != BoundaryFilesystemRoot { + t.Fatalf("expected BoundaryFilesystemRoot, got %+v", b) + } + }) +} + +func TestMountOwnershipCeilingAndDepthBoundaries(t *testing.T) { + now := time.Unix(1700000000, 0) + + t.Run("mount point boundary", func(t *testing.T) { + m := newMockFS("/mnt/usb/proj/sub", 1000) + m.setDir("/", 1, 1000, now) + m.setDir("/mnt", 1, 1000, now) + m.setDir("/mnt/usb", 42, 1000, now) + m.setDir("/mnt/usb/proj", 42, 1000, now) + m.setDir("/mnt/usb/proj/sub", 42, 1000, now) + + c := NewCache(WithFileSystem(m)) + b, err := c.ResolveBoundary("/mnt/usb/proj/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != BoundaryMountPoint || + b.RootDir != filepath.Clean("/mnt/usb") { + t.Fatalf("expected BoundaryMountPoint at /mnt/usb, got %+v", b) + } + + noMount := NewCache(WithFileSystem(m), WithStopAtMountPoint(false)) + b2, err := noMount.ResolveBoundary("/mnt/usb/proj/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b2.Reason != BoundaryFilesystemRoot { + t.Fatalf("expected BoundaryFilesystemRoot, got %+v", b2) + } + }) + + t.Run("ownership boundary", func(t *testing.T) { + m := newMockFS("/shared/otheruser/myproj", 1000) + m.setDir("/", 1, 0, now) + m.setDir("/shared", 1, 0, now) + m.setDir("/shared/otheruser", 1, 2000, now) + m.setDir("/shared/otheruser/myproj", 1, 1000, now) + + c := NewCache(WithFileSystem(m)) + b, err := c.ResolveBoundary("/shared/otheruser/myproj") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != BoundaryOwnership || + b.RootDir != filepath.Clean("/shared/otheruser/myproj") { + t.Fatalf("expected BoundaryOwnership, got %+v", b) + } + + noOwn := NewCache(WithFileSystem(m), WithVerifyOwnership(false)) + b2, err := noOwn.ResolveBoundary("/shared/otheruser/myproj") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b2.Reason != BoundaryFilesystemRoot { + t.Fatalf("expected BoundaryFilesystemRoot, got %+v", b2) + } + }) + + t.Run("ceiling dir and max depth", func(t *testing.T) { + m := buildMockRepo(now) + ceilCache := NewCache(WithFileSystem(m), WithCeilingDirs("/repo/sub")) + cb, err := ceilCache.ResolveBoundary("/repo/sub/deep") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if cb.Reason != BoundaryCeiling || + cb.RootDir != filepath.Clean("/repo/sub") { + t.Fatalf("expected BoundaryCeiling at /repo/sub, got %+v", cb) + } + + depthCache := NewCache(WithFileSystem(m), WithMaxDepth(0)) + db, err := depthCache.ResolveBoundary("/repo/sub/deep") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if db.Reason != BoundaryMaxDepth || + db.RootDir != filepath.Clean("/repo/sub/deep") { + t.Fatalf("expected BoundaryMaxDepth at deep, got %+v", db) + } + }) +} + +func TestSecurityGuardsAndStrictMode(t *testing.T) { + now := time.Unix(1700000000, 0) + + cases := []struct { + name string + setup func(m *mockFS) string + opts []Option + wantReason SkipReason + }{ + { + name: "directory instead of regular file", + setup: func(m *mockFS) string { + m.setDir("/repo/.editorconfig", 1, 1000, now) + return "/repo/.editorconfig" + }, + wantReason: SkipNotRegular, + }, + { + name: "fifo named pipe", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setFile(p, iofs.ModeNamedPipe|0644, 0, 1, 1000, now) + return p + }, + wantReason: SkipNotRegular, + }, + { + name: "unix socket", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setFile(p, iofs.ModeSocket|0644, 0, 1, 1000, now) + return p + }, + wantReason: SkipNotRegular, + }, + { + name: "device node", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setFile(p, iofs.ModeDevice|0644, 0, 1, 1000, now) + return p + }, + wantReason: SkipNotRegular, + }, + { + name: "oversized file", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setFile(p, 0644, 2048, 1, 1000, now) + return p + }, + opts: []Option{WithMaxFileSize(1024)}, + wantReason: SkipFileTooLarge, + }, + { + name: "symlinks disabled", + setup: func(m *mockFS) string { + m.setFile("/repo/shared.cfg", 0644, 16, 1, 1000, now) + p := "/repo/.editorconfig" + m.setSymlink(p, "/repo/shared.cfg", 1, 1000, now) + return p + }, + opts: []Option{WithAllowSymlinks(false)}, + wantReason: SkipSymlinkDisabled, + }, + { + name: "broken symlink", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setSymlink(p, "/repo/missing.cfg", 1, 1000, now) + return p + }, + wantReason: SkipBrokenSymlink, + }, + { + name: "symlink escaping boundary", + setup: func(m *mockFS) string { + m.setFile("/outside/secret.cfg", 0644, 16, 1, 1000, now) + p := "/repo/.editorconfig" + m.setSymlink(p, "/outside/secret.cfg", 1, 1000, now) + return p + }, + wantReason: SkipSymlinkEscape, + }, + { + name: "symlink crossing mount device", + setup: func(m *mockFS) string { + m.setFile("/repo/other.cfg", 0644, 16, 99, 1000, now) + p := "/repo/.editorconfig" + m.setSymlink(p, "/repo/other.cfg", 1, 1000, now) + return p + }, + wantReason: SkipSymlinkCrossDevice, + }, + { + name: "permission denied", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setStatErr(p, iofs.ErrPermission) + return p + }, + wantReason: SkipPermissionDenied, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := buildMockRepo(now) + target := tc.setup(m) + + var skips []SkipReason + opts := append([]Option{}, tc.opts...) + opts = append( + opts, + WithFileSystem(m), + WithOnSkip(func(p string, r SkipReason, _ error) { + if p == filepath.Clean(target) { + skips = append(skips, r) + } + }), + ) + + finder, err := NewFinder(opts...) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + got, err := finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil { + t.Fatalf("non-strict mode returned error: %v", err) + } + if len(got) != 0 { + t.Fatalf("expected 0 files, got %+v", got) + } + if len(skips) != 1 || skips[0] != tc.wantReason { + t.Fatalf("skips = %v, want [%v]", skips, tc.wantReason) + } + + strictOpts := append([]Option{}, tc.opts...) + strictOpts = append( + strictOpts, + WithFileSystem(m), + WithStrictSecurity(true), + ) + strictFinder, err := NewFinder(strictOpts...) + if err != nil { + t.Fatalf("NewFinder strict failed: %v", err) + } + _, err = strictFinder.FindChain("/repo/sub", FileEditorConfig) + var secErr *SecurityError + if !errors.As(err, &secErr) { + t.Fatalf("expected *SecurityError, got %v", err) + } + if secErr.Reason != tc.wantReason { + t.Errorf( + "secErr.Reason = %v, want %v", + secErr.Reason, + tc.wantReason, + ) + } + if secErr.Error() == "" { + t.Error("expected non-empty Error() string") + } + }) + } +} + +func TestValidSymlinkAndEscapeOverride(t *testing.T) { + now := time.Unix(1700000000, 0) + m := buildMockRepo(now) + m.setFile("/repo/shared/editorconfig", 0644, 42, 1, 1000, now) + m.setDir("/repo/shared", 1, 1000, now) + m.setSymlink( + "/repo/sub/.editorconfig", + "/repo/shared/editorconfig", + 1, + 1000, + now, + ) + m.setFile("/outside/global.cfg", 0644, 12, 1, 1000, now) + m.setSymlink("/repo/.editorconfig", "/outside/global.cfg", 1, 1000, now) + + finder, err := NewFinder(WithFileSystem(m)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + files, err := finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if len(files) != 1 { + t.Fatalf("expected 1 valid in-repo symlink, got %+v", files) + } + if !files[0].IsSymlink || + files[0].ResolvedPath != filepath.Clean("/repo/shared/editorconfig") { + t.Errorf("unexpected symlink metadata: %+v", files[0]) + } + + allowEsc, err := NewFinder( + WithFileSystem(m), + WithAllowSymlinkEscape(true), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + escFiles, err := allowEsc.FindChain("/repo/sub", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if len(escFiles) != 2 { + t.Fatalf("expected 2 files with escape allowed, got %d", len(escFiles)) + } +} + +func TestRegexFiltersAndIncludeDiscovery(t *testing.T) { + now := time.Unix(1700000000, 0) + + t.Run("invalid regex errors", func(t *testing.T) { + bad := []struct { + opt Option + flag string + }{ + {WithInclude("["), FilterInclude}, + {WithExclude("["), FilterExclude}, + {WithExtendExclude("["), FilterExtendExclude}, + {WithForceExclude("["), FilterForceExclude}, + } + for _, tc := range bad { + _, err := NewFilter(tc.opt) + if err == nil || !strings.Contains(err.Error(), tc.flag) || + !strings.Contains(err.Error(), "invalid regular expression") { + t.Errorf("unexpected error for %s: %v", tc.flag, err) + } + } + }) + + t.Run("filter matching methods", func(t *testing.T) { + m := buildMockRepo(now) + flt, err := NewFilter( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithExclude(`/venv/`), + WithExtendExclude(`/custom/`), + WithForceExclude(`generated/.*\.dml$`), + ) + if err != nil { + t.Fatalf("NewFilter failed: %v", err) + } + + if !flt.IsForceExcluded("src/generated/foo.dml") { + t.Error("expected generated/foo.dml to be force-excluded") + } + if flt.IsForceExcluded("src/normal/foo.dml") { + t.Error("expected normal/foo.dml not to be force-excluded") + } + + if got := flt.MatchExclude( + "a/generated/x.dml", + "a/generated/x.dml", + false, + ); got != FilterForceExclude { + t.Errorf("got %q, want %q", got, FilterForceExclude) + } + if got := flt.MatchExclude( + "venv/x.dml", + "/repo/venv/x.dml", + false, + ); got != FilterExclude { + t.Errorf("got %q, want %q", got, FilterExclude) + } + if got := flt.MatchExclude( + "custom/x.dml", + "/repo/custom/x.dml", + false, + ); got != FilterExtendExclude { + t.Errorf("got %q, want %q", got, FilterExtendExclude) + } + + if !flt.IsIncluded("sub/a.dml", "/repo/sub/a.dml") { + t.Error("expected .dml file to be included") + } + if flt.IsIncluded("sub/a.txt", "/repo/sub/a.txt") { + t.Error("expected .txt file not to be included") + } + }) + + t.Run("filters in FindChain and Include fallback", func(t *testing.T) { + m := buildMockRepo(now) + m.setDir("/repo/venv", 1, 1000, now) + m.setFile("/repo/venv/.editorconfig", 0644, 10, 1, 1000, now) + m.setFile("/repo/.editorconfig", 0644, 10, 1, 1000, now) + m.setFile("/repo/sub/a.cfg", 0644, 10, 1, 1000, now) + m.setFile("/repo/sub/b.cfg", 0644, 10, 1, 1000, now) + m.setFile("/repo/sub/skip.cfg", 0644, 10, 1, 1000, now) + m.setFile("/repo/sub/other.txt", 0644, 10, 1, 1000, now) + + var skipped []string + finder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.cfg$`), + WithExclude(`/venv/`), + WithExtendExclude(`skip\.cfg$`), + WithStrictSecurity(true), + WithOnSkip(func(path string, reason SkipReason, _ error) { + if reason == SkipExcluded { + skipped = append(skipped, path) + } + }), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + chain, err := finder.FindChain("/repo/venv", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if len(chain) != 1 || + chain[0].Path != filepath.Clean("/repo/.editorconfig") { + t.Fatalf("expected only /repo/.editorconfig, got %+v", chain) + } + if !slices.Contains(skipped, filepath.Clean("/repo/venv")) { + t.Errorf("expected /repo/venv to be reported as SkipExcluded") + } + + incFiles, err := finder.FindChain("/repo/sub/deep") + if err != nil { + t.Fatalf("FindChain with Include failed: %v", err) + } + if len(incFiles) != 2 || + incFiles[0].Name != "a.cfg" || + incFiles[1].Name != "b.cfg" { + t.Fatalf("unexpected Include discovery results: %+v", incFiles) + } + + m.setFile("/repo/venv/test.dml", 0644, 5, 1, 1000, now) + res, found, err := finder.FindNearest( + "/repo/venv/test.dml", + FileEditorConfig, + ) + if err != nil || found || res.Path != "" { + t.Fatalf( + "expected excluded start file to return empty, got (%+v, %v, %v)", + res, + found, + err, + ) + } + }) +} + +func TestCachingMutationsTTLAndConcurrency(t *testing.T) { + t0 := time.Unix(1700000000, 0) + clk := newMockClock(t0) + + t.Run("real-time stat validation detects FS mutations", func(t *testing.T) { + m := buildMockRepo(t0) + finder, err := NewFinder(WithFileSystem(m), WithClock(clk)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + files, err := finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 0 { + t.Fatalf("expected 0 files, got %v, %v", files, err) + } + st1 := finder.Cache().Stats() + if st1.DirMisses == 0 || st1.FileMisses == 0 || st1.DirHits != 0 { + t.Fatalf( + "expected initial misses and 0 dir hits, got %+v", + st1, + ) + } + + _, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil { + t.Fatalf("FindChain failed: %v", err) + } + st2 := finder.Cache().Stats() + if st2.DirHits <= st1.DirHits || st2.FileHits <= st1.FileHits { + t.Fatalf( + "expected dir/file hits, got before=%+v after=%+v", + st1, + st2, + ) + } + + t1 := t0.Add(time.Second) + m.setFile("/repo/.editorconfig", 0644, 12, 1, 1000, t1) + files, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 1 || files[0].Size != 12 { + t.Fatalf( + "expected newly created file size 12, got %+v, %v", + files, + err, + ) + } + + m.setFile("/repo/.editorconfig", 0644, 99, 1, 1000, t1.Add(time.Second)) + files, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 1 || files[0].Size != 99 { + t.Fatalf("expected updated file size 99, got %+v, %v", files, err) + } + + m.setFile("/repo/target.cfg", 0644, 7, 1, 1000, t1) + m.setSymlink("/repo/.editorconfig", "/repo/target.cfg", 1, 1000, t1) + files, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 1 || !files[0].IsSymlink || + files[0].Size != 7 { + t.Fatalf("expected symlink size 7, got %+v, %v", files, err) + } + m.setFile("/repo/target.cfg", 0644, 33, 1, 1000, t1.Add(2*time.Second)) + files, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 1 || files[0].Size != 33 { + t.Fatalf( + "expected updated symlink target size 33, got %+v, %v", + files, + err, + ) + } + + m.deleteNode("/repo/.editorconfig") + files, err = finder.FindChain("/repo/sub", FileEditorConfig) + if err != nil || len(files) != 0 { + t.Fatalf("expected deleted file gone, got %+v, %v", files, err) + } + + m.setDir("/repo/sub/.git", 1, 1000, t1) + b, err := finder.Cache().ResolveBoundary("/repo/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.RootDir != filepath.Clean("/repo/sub") { + t.Fatalf("expected new .git boundary at /repo/sub, got %+v", b) + } + }) + + t.Run( + "TTL cache avoids syscalls and explicit Invalidate/Reset", + func(t *testing.T) { + m := buildMockRepo(t0) + m.setFile("/repo/.editorconfig", 0644, 10, 1, 1000, t0) + finder, err := NewFinder( + WithFileSystem(m), + WithClock(clk), + WithCacheTTL(5*time.Second), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + if _, err := finder.FindChain( + "/repo/sub", + FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain failed: %v", err) + } + m.resetStatCalls() + + clk.Advance(2 * time.Second) + if _, err := finder.FindChain( + "/repo/sub", + FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain failed: %v", err) + } + if calls := m.totalStatCalls(); calls != 1 { + t.Errorf("expected 1 start stat call within TTL, got %d", calls) + } + + finder.Cache().Invalidate("/repo/.editorconfig") + if finder.Cache().Stats().Invalidations == 0 { + t.Error("expected Invalidations > 0 after Invalidate") + } + if _, err := finder.FindChain( + "/repo/sub", + FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain failed: %v", err) + } + + clk.Advance(10 * time.Second) + finder.Cache().Reset() + if _, err := finder.FindChain( + "/repo/sub", + FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain after Reset failed: %v", err) + } + }, + ) + + t.Run("concurrent access", func(t *testing.T) { + m := buildMockRepo(t0) + m.setFile("/repo/.editorconfig", 0644, 10, 1, 1000, t0) + m.setFile("/repo/sub/.gitignore", 0644, 15, 1, 1000, t0) + m.setFile("/repo/sub/deep/a.dml", 0644, 10, 1, 1000, t0) + + finder, err := NewFinder( + WithFileSystem(m), + WithClock(clk), + WithInclude(`\.dml$`), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + var wg sync.WaitGroup + for i := range 16 { + wg.Add(1) + go func(id int) { + defer wg.Done() + for j := range 25 { + _, _ = finder.FindChain( + "/repo/sub/deep", + FileEditorConfig, + FileGitIgnore, + ) + _, _, _ = finder.FindNearest( + "/repo/sub/deep", + FileEditorConfig, + ) + _, _ = finder.Collect([]string{"/repo"}) + _, _ = finder.Cache().ResolveBoundary("/repo/sub/deep") + if (id+j)%7 == 0 { + finder.Cache().Invalidate("/repo/sub") + } + if (id+j)%13 == 0 { + finder.Cache().Reset() + } + _ = finder.Cache().Stats() + } + }(i) + } + wg.Wait() + }) +} + +func TestEnumsAndErrorFormatting(t *testing.T) { + reasons := []BoundaryReason{ + BoundaryNone, + BoundaryFilesystemRoot, + BoundaryVCSRoot, + BoundaryMountPoint, + BoundaryOwnership, + BoundaryCeiling, + BoundaryMaxDepth, + BoundaryReason(99), + } + for _, r := range reasons { + if r.String() == "" { + t.Errorf("empty String for BoundaryReason %d", r) + } + } + + skips := []SkipReason{ + SkipNotRegular, + SkipFileTooLarge, + SkipSymlinkDisabled, + SkipBrokenSymlink, + SkipSymlinkEscape, + SkipSymlinkCrossDevice, + SkipPermissionDenied, + SkipExcluded, + SkipReason(99), + } + for _, s := range skips { + if s.String() == "" { + t.Errorf("empty String for SkipReason %d", s) + } + } + + inner := errors.New("boom") + se := &SecurityError{Path: "/a", Reason: SkipNotRegular, Err: inner} + if !errors.Is(se, inner) { + t.Error("SecurityError.Unwrap did not match inner error") + } + if !strings.Contains(se.Error(), "boom") { + t.Errorf("unexpected Error(): %q", se.Error()) + } + seNoErr := &SecurityError{Path: "/a", Reason: SkipNotRegular} + if seNoErr.Error() == "" { + t.Error("expected non-empty Error() without inner err") + } +} + +func TestIgnoreMatcher_PatternsAndCaching(t *testing.T) { + t0 := time.Unix(1700000000, 0) + + t.Run("glob patterns escapes comments and CRLF", func(t *testing.T) { + m := buildMockRepo(t0) + rules := strings.Join([]string{ + "# comment", + " ", + `\!bang.dml`, + `\#hash.dml`, + "trail.dml ", + `esc\ .dml`, + "file[12].dml", + "only[!1].dml", + "[]a].dml", + "unclosed[.dml", + "char?.dml", + "**/deep.dml", + "a/**/b.dml", + "a**b.dml", + "box/**", + "!box/keep.dml", + "ignored_dir/", + "!ignored_dir/cannot_rescue.dml", + "rescued_dir/", + "!rescued_dir/", + "rescued_dir/drop.dml", + "!rescued_dir/keep.dml", + }, "\r\n") + "\r\n" + + m.setFileWithContent("/repo/.gitignore", []byte(rules), 1, 1000, t0) + matcher := NewIgnoreMatcher(WithFileSystem(m)) + + rs, err := matcher.LoadFile(DiscoveredFile{ + Path: "/repo/.gitignore", + Dir: "/repo", + Name: FileGitIgnore, + }) + if err != nil { + t.Fatalf("LoadFile failed: %v", err) + } + stack := []IgnoreRuleSet{rs} + + shouldIgnore := []string{ + "/repo/!bang.dml", + "/repo/#hash.dml", + "/repo/trail.dml", + "/repo/esc .dml", + "/repo/file1.dml", + "/repo/file2.dml", + "/repo/only2.dml", + "/repo/].dml", + "/repo/a.dml", + "/repo/sub/].dml", + "/repo/unclosed[.dml", + "/repo/charx.dml", + "/repo/deep.dml", + "/repo/sub/deep.dml", + "/repo/a/b.dml", + "/repo/a/x/y/b.dml", + "/repo/axxxyb.dml", + "/repo/box/drop.dml", + "/repo/box/sub/nested.dml", + "/repo/ignored_dir/file.dml", + "/repo/ignored_dir/sub/nested.dml", + "/repo/ignored_dir/cannot_rescue.dml", + "/repo/rescued_dir/drop.dml", + } + for _, p := range shouldIgnore { + if got := matcher.Match(stack, p, false); got != FileGitIgnore { + t.Errorf("Match(%q) = %q, want %q", p, got, FileGitIgnore) + } + } + + shouldNotIgnore := []string{ + "/repo/# comment", + "/repo/ ", + "/repo/trail.dml ", + "/repo/file3.dml", + "/repo/only1.dml", + "/repo/]a.dml", + "/repo/only/.dml", + "/repo/charab.dml", + "/repo/sub/a/x/b.dml", + "/repo/a/sub/b.dml.extra", + "/repo/ax/yb.dml", + "/repo/box", + "/repo/box/keep.dml", + "/repo/rescued_dir/keep.dml", + } + for _, p := range shouldNotIgnore { + if got := matcher.Match(stack, p, false); got != "" { + t.Errorf("Match(%q) = %q, want empty", p, got) + } + } + }) + + t.Run("cache hit and invalidation on file mutation", func(t *testing.T) { + m := buildMockRepo(t0) + m.setFileWithContent( + "/repo/.gitignore", + []byte("skip.dml\n"), + 1, + 1000, + t0, + ) + m.setFileWithContent("/repo/skip.dml", []byte("x"), 1, 1000, t0) + m.setFileWithContent("/repo/keep.dml", []byte("x"), 1, 1000, t0) + + finder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithIgnoreFiles(FileGitIgnore, FileIgnore), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + files, err := finder.Collect([]string{"/repo"}) + if err != nil { + t.Fatalf("Collect 1 failed: %v", err) + } + if len(files) != 1 || files[0] != filepath.Clean("/repo/keep.dml") { + t.Fatalf("Collect 1 got %v, want [/repo/keep.dml]", files) + } + if calls := m.totalReadFileCalls(); calls != 1 { + t.Fatalf("expected 1 ReadFile call on cold cache, got %d", calls) + } + + // Second Collect without FS changes should reuse cached IgnoreRuleSet. + files2, err := finder.Collect([]string{"/repo"}) + if err != nil { + t.Fatalf("Collect 2 failed: %v", err) + } + if !slices.Equal(files2, files) { + t.Fatalf("Collect 2 got %v, want %v", files2, files) + } + if calls := m.totalReadFileCalls(); calls != 1 { + t.Fatalf("expected cached ReadFile count=1, got %d", calls) + } + + // Modify .gitignore mtime/size -> invalidates cache and re-parses. + t1 := t0.Add(time.Second) + m.setFileWithContent( + "/repo/.gitignore", + []byte("keep.dml\n"), + 1, + 1000, + t1, + ) + files3, err := finder.Collect([]string{"/repo"}) + if err != nil { + t.Fatalf("Collect 3 failed: %v", err) + } + if len(files3) != 1 || files3[0] != filepath.Clean("/repo/skip.dml") { + t.Fatalf("Collect 3 got %v, want [/repo/skip.dml]", files3) + } + if calls := m.totalReadFileCalls(); calls != 2 { + t.Fatalf("expected ReadFile count=2 after mutation, got %d", calls) + } + }) + + t.Run("strict security and relative source in Collect", func(t *testing.T) { + m := buildMockRepo(t0) + m.setFileWithContent( + "/repo/sub/.gitignore", + []byte("skip.dml\n"), + 1, + 1000, + t0, + ) + m.setFileWithContent( + "/repo/sub/.ignore", + []byte("!skip.dml\n"), + 1, + 1000, + t0, + ) + m.setFileWithContent("/repo/sub/skip.dml", []byte("x"), 1, 1000, t0) + m.setFileWithContent( + "/repo/sub/deep/main.dml", + []byte("x"), + 1, + 1000, + t0, + ) + m.cwd = "/repo" + + matcher := NewIgnoreMatcher(WithFileSystem(m)) + finder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithIgnoreMatcher(matcher), + WithIgnoreFiles(FileGitIgnore, FileIgnore), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + files, err := finder.Collect([]string{"."}) + if err != nil { + t.Fatalf("Collect('.') failed: %v", err) + } + want := []string{ + filepath.Join("sub", "deep", "main.dml"), + filepath.Join("sub", "skip.dml"), + } + slices.Sort(want) + if !slices.Equal(files, want) { + t.Fatalf("Collect('.') got %v, want %v", files, want) + } + + // FIFO as .gitignore in strict mode must surface *SecurityError during Collect. + m.setFile( + "/repo/sub/deep/.gitignore", + iofs.ModeNamedPipe|0644, + 0, + 1, + 1000, + t0, + ) + strictFinder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithStrictSecurity(true), + WithIgnoreFiles(FileGitIgnore), + ) + if err != nil { + t.Fatalf("NewFinder strict failed: %v", err) + } + _, err = strictFinder.Collect([]string{"/repo"}) + var secErr *SecurityError + if !errors.As(err, &secErr) || secErr.Reason != SkipNotRegular { + t.Fatalf("expected SkipNotRegular SecurityError, got %v", err) + } + }) + + t.Run("collect starting inside ignored directory", func(t *testing.T) { + m := buildMockRepo(t0) + m.setDir("/repo/ignored_dir", 1, 1000, t0) + m.setFileWithContent( + "/repo/.gitignore", + []byte("ignored_dir/\n"), + 1, + 1000, + t0, + ) + m.setFileWithContent( + "/repo/ignored_dir/main.dml", + []byte("x"), + 1, + 1000, + t0, + ) + + type ignoreEvent struct { + path string + isDir bool + filter string + } + var events []ignoreEvent + + finder, err := NewFinder( + WithFileSystem(m), + WithInclude(`\.dml$`), + WithIgnoreFiles(FileGitIgnore, FileIgnore), + WithOnIgnore(func(path string, isDir bool, filterName string) { + events = append(events, ignoreEvent{path, isDir, filterName}) + }), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + files, err := finder.Collect([]string{"/repo/ignored_dir"}) + if err != nil { + t.Fatalf("Collect failed: %v", err) + } + if len(files) != 0 { + t.Fatalf("expected no files from ignored_dir, got %v", files) + } + wantEvent := ignoreEvent{ + path: filepath.Clean("/repo/ignored_dir"), + isDir: true, + filter: FileGitIgnore, + } + if !slices.Contains(events, wantEvent) { + t.Fatalf("expected ignore event %+v, got %+v", wantEvent, events) + } + }) +} diff --git a/pkg/fs/lookup/options.go b/pkg/fs/lookup/options.go new file mode 100644 index 0000000..5609719 --- /dev/null +++ b/pkg/fs/lookup/options.go @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import "time" + +type config struct { + cache Cache + filter Filter + ignoreMatcher IgnoreMatcher + + includePattern string + excludePattern string + extendExcludePattern string + forceExcludePattern string + ignoreFiles []string + + vcsMarkers []string + stopAtVCSRoot bool + stopAtMountPoint bool + verifyOwnership bool + allowSymlinks bool + allowSymlinkEsc bool + ceilingDirs []string + maxDepth int + maxFileSize int64 + cacheTTL time.Duration + strictSecurity bool + onSkip SkipCallback + onIgnore IgnoreCallback + fsys FileSystem + clock Clock +} + +func defaultConfig() config { + return config{ + vcsMarkers: []string{VCSMarkerGit, VCSMarkerHg}, + stopAtVCSRoot: true, + stopAtMountPoint: true, + verifyOwnership: true, + allowSymlinks: true, + allowSymlinkEsc: false, + maxDepth: DefaultMaxDepth, + maxFileSize: DefaultMaxFileSize, + fsys: NewOSFileSystem(), + clock: realClock{}, + } +} + +// Option configures a [Cache], [Filter], or [Finder] instance. +type Option func(*config) + +// WithCache injects an existing [Cache] into [NewFinder]. +func WithCache(cache Cache) Option { + return func(c *config) { + c.cache = cache + } +} + +// WithFilter injects an existing [Filter] into [NewFinder]. +func WithFilter(filter Filter) Option { + return func(c *config) { + c.filter = filter + } +} + +// WithIgnoreMatcher injects an existing [IgnoreMatcher] into [NewFinder]. +func WithIgnoreMatcher(matcher IgnoreMatcher) Option { + return func(c *config) { + c.ignoreMatcher = matcher + } +} + +// WithIgnoreFiles configures hierarchical ignore filenames (such as +// [FileGitIgnore] and [FileIgnore]) evaluated during [Finder.Collect]. +// Within each directory, files are evaluated in the order specified. +func WithIgnoreFiles(names ...string) Option { + return func(c *config) { + c.ignoreFiles = normalizeIgnoreFileNames(names) + } +} + +// WithInclude sets the regular expression matching paths to include. +func WithInclude(pattern string) Option { + return func(c *config) { + c.includePattern = pattern + } +} + +// WithExclude sets the regular expression matching paths to exclude. +func WithExclude(pattern string) Option { + return func(c *config) { + c.excludePattern = pattern + } +} + +// WithExtendExclude sets an additional regular expression matching paths to exclude. +func WithExtendExclude(pattern string) Option { + return func(c *config) { + c.extendExcludePattern = pattern + } +} + +// WithForceExclude sets the regular expression matching paths to forcibly exclude. +func WithForceExclude(pattern string) Option { + return func(c *config) { + c.forceExcludePattern = pattern + } +} + +// WithVCSMarkers overrides the VCS root marker names (default: .git, .hg). +func WithVCSMarkers(markers ...string) Option { + return func(c *config) { + filtered := make([]string, 0, len(markers)) + for _, m := range markers { + if m != "" { + filtered = append(filtered, m) + } + } + c.vcsMarkers = filtered + } +} + +// WithStopAtVCSRoot controls whether upward traversal stops at VCS roots. +func WithStopAtVCSRoot(enabled bool) Option { + return func(c *config) { + c.stopAtVCSRoot = enabled + } +} + +// WithStopAtMountPoint controls whether upward traversal stops at mount boundaries. +func WithStopAtMountPoint(enabled bool) Option { + return func(c *config) { + c.stopAtMountPoint = enabled + } +} + +// WithVerifyOwnership controls whether upward traversal verifies directory UIDs. +func WithVerifyOwnership(enabled bool) Option { + return func(c *config) { + c.verifyOwnership = enabled + } +} + +// WithAllowSymlinks controls whether symlinked utility files are followed. +func WithAllowSymlinks(allow bool) Option { + return func(c *config) { + c.allowSymlinks = allow + } +} + +// WithAllowSymlinkEscape controls whether symlinks may resolve outside the boundary root. +func WithAllowSymlinkEscape(allow bool) Option { + return func(c *config) { + c.allowSymlinkEsc = allow + } +} + +// WithCeilingDirs configures directory paths where upward traversal must stop. +func WithCeilingDirs(dirs ...string) Option { + return func(c *config) { + c.ceilingDirs = append([]string(nil), dirs...) + } +} + +// WithMaxDepth sets the maximum number of parent directories to ascend. +func WithMaxDepth(depth int) Option { + return func(c *config) { + if depth >= 0 { + c.maxDepth = depth + } + } +} + +// WithMaxFileSize sets the maximum permitted size in bytes for candidate files. +// Non-positive values disable the size limit. +func WithMaxFileSize(maxBytes int64) Option { + return func(c *config) { + c.maxFileSize = maxBytes + } +} + +// WithCacheTTL sets a cache validity window during which repeated probes skip +// re-statting the filesystem. Zero forces stat-fingerprint validation on every call. +func WithCacheTTL(ttl time.Duration) Option { + return func(c *config) { + if ttl >= 0 { + c.cacheTTL = ttl + } + } +} + +// WithStrictSecurity causes security check failures on candidate files to +// return a [*SecurityError] instead of skipping the file. +func WithStrictSecurity(strict bool) Option { + return func(c *config) { + c.strictSecurity = strict + } +} + +// WithOnSkip registers a callback notified whenever a candidate is skipped. +func WithOnSkip(cb SkipCallback) Option { + return func(c *config) { + c.onSkip = cb + } +} + +// WithOnIgnore registers a callback notified when [Finder.Collect] ignores a path. +func WithOnIgnore(cb IgnoreCallback) Option { + return func(c *config) { + c.onIgnore = cb + } +} + +// WithFileSystem overrides the backing [FileSystem] (useful for tests). +func WithFileSystem(fsys FileSystem) Option { + return func(c *config) { + if fsys != nil { + c.fsys = fsys + } + } +} + +// WithClock overrides the [Clock] used for cache TTL evaluation. +func WithClock(clock Clock) Option { + return func(c *config) { + if clock != nil { + c.clock = clock + } + } +} diff --git a/pkg/fs/lookup/sys_other.go b/pkg/fs/lookup/sys_other.go new file mode 100644 index 0000000..17e06d6 --- /dev/null +++ b/pkg/fs/lookup/sys_other.go @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +//go:build !unix && !windows + +package lookup + +import "os" + +func fillSysMeta(_ string, _ os.FileInfo, _ *FileMeta) {} + +func osGeteuid() int { + return -1 +} diff --git a/pkg/fs/lookup/sys_unix.go b/pkg/fs/lookup/sys_unix.go new file mode 100644 index 0000000..adbaf86 --- /dev/null +++ b/pkg/fs/lookup/sys_unix.go @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +//go:build unix + +package lookup + +import ( + "os" + "syscall" +) + +func fillSysMeta(_ string, info os.FileInfo, meta *FileMeta) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || st == nil { + return + } + // #nosec G115 -- st.Dev on Darwin is int32; preserve raw bit pattern as ID + //nolint:unconvert // st.Dev is int32 on Darwin and uint64 on Linux + meta.DeviceID = uint64(st.Dev) + meta.Inode = st.Ino + meta.UID = st.Uid + meta.HasDevice = true + meta.HasInode = true + meta.HasUID = true +} + +func osGeteuid() int { + return os.Geteuid() +} diff --git a/pkg/fs/lookup/sys_windows.go b/pkg/fs/lookup/sys_windows.go new file mode 100644 index 0000000..3b752b2 --- /dev/null +++ b/pkg/fs/lookup/sys_windows.go @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +//go:build windows + +package lookup + +import ( + "hash/fnv" + "os" + "path/filepath" + "strings" +) + +func fillSysMeta(path string, _ os.FileInfo, meta *FileMeta) { + vol := filepath.VolumeName(filepath.Clean(path)) + if vol == "" { + return + } + h := fnv.New64a() + _, _ = h.Write([]byte(strings.ToUpper(vol))) + meta.DeviceID = h.Sum64() + meta.HasDevice = true +} + +func osGeteuid() int { + return -1 +} diff --git a/pkg/fs/lookup/types.go b/pkg/fs/lookup/types.go new file mode 100644 index 0000000..8dcde73 --- /dev/null +++ b/pkg/fs/lookup/types.go @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "fmt" + iofs "io/fs" + "time" +) + +const ( + // FileGitIgnore is the standard Git ignore rules filename. + FileGitIgnore = ".gitignore" + // FileIgnore is the generic ignore rules filename used by search/lint tools. + FileIgnore = ".ignore" + // FileEditorConfig is the EditorConfig formatting configuration filename. + FileEditorConfig = ".editorconfig" + + // VCSMarkerGit is the Git repository/worktree marker name. + VCSMarkerGit = ".git" + // VCSMarkerHg is the Mercurial repository marker name. + VCSMarkerHg = ".hg" + + // FilterForceExclude is the filter name returned for force-exclude matches. + FilterForceExclude = "--force-exclude" + // FilterExclude is the filter name returned for exclude matches. + FilterExclude = "--exclude" + // FilterExtendExclude is the filter name returned for extend-exclude matches. + FilterExtendExclude = "--extend-exclude" + // FilterInclude is the filter name used when reporting include filter skips. + FilterInclude = "--include" + + // DefaultMaxDepth is the default maximum upward directory traversal depth. + DefaultMaxDepth = 64 + // DefaultMaxFileSize is the default maximum allowed utility file size (1 MiB). + DefaultMaxFileSize int64 = 1 << 20 +) + +// BoundaryReason identifies why upward directory traversal stopped. +type BoundaryReason int + +const ( + // BoundaryNone indicates no boundary was determined. + BoundaryNone BoundaryReason = iota + // BoundaryFilesystemRoot indicates traversal reached the filesystem root. + BoundaryFilesystemRoot + // BoundaryVCSRoot indicates traversal stopped at a VCS repository root. + BoundaryVCSRoot + // BoundaryMountPoint indicates the parent directory resides on a different mount/device. + BoundaryMountPoint + // BoundaryOwnership indicates the parent directory has an untrusted owner UID. + BoundaryOwnership + // BoundaryCeiling indicates traversal reached a configured ceiling directory. + BoundaryCeiling + // BoundaryMaxDepth indicates traversal reached the configured max depth limit. + BoundaryMaxDepth +) + +// String returns a human-readable description of the boundary reason. +func (r BoundaryReason) String() string { + switch r { + case BoundaryNone: + return "none" + case BoundaryFilesystemRoot: + return "filesystem-root" + case BoundaryVCSRoot: + return "vcs-root" + case BoundaryMountPoint: + return "mount-point" + case BoundaryOwnership: + return "ownership" + case BoundaryCeiling: + return "ceiling" + case BoundaryMaxDepth: + return "max-depth" + default: + return fmt.Sprintf("unknown(%d)", int(r)) + } +} + +// BoundaryInfo describes the outermost directory permitted for a lookup. +type BoundaryInfo struct { + RootDir string + Reason BoundaryReason + VCSPath string +} + +// SkipReason classifies why a candidate directory or utility file was skipped. +type SkipReason int + +const ( + // SkipNotRegular indicates a candidate path is not a regular file (e.g. FIFO, socket, directory). + SkipNotRegular SkipReason = iota + 1 + // SkipFileTooLarge indicates a candidate file exceeds the configured MaxFileSize. + SkipFileTooLarge + // SkipSymlinkDisabled indicates symlinks are disallowed by configuration. + SkipSymlinkDisabled + // SkipBrokenSymlink indicates a symlink target does not exist or cannot be resolved. + SkipBrokenSymlink + // SkipSymlinkEscape indicates a symlink resolves outside the active boundary root. + SkipSymlinkEscape + // SkipSymlinkCrossDevice indicates a symlink resolves onto a different mount/device. + SkipSymlinkCrossDevice + // SkipPermissionDenied indicates a filesystem permission or stat error occurred. + SkipPermissionDenied + // SkipExcluded indicates a path matched exclude, extend-exclude, or force-exclude filters. + SkipExcluded +) + +// String returns a human-readable label for the skip reason. +func (r SkipReason) String() string { + switch r { + case SkipNotRegular: + return "not-regular-file" + case SkipFileTooLarge: + return "file-too-large" + case SkipSymlinkDisabled: + return "symlink-disabled" + case SkipBrokenSymlink: + return "broken-symlink" + case SkipSymlinkEscape: + return "symlink-escape" + case SkipSymlinkCrossDevice: + return "symlink-cross-device" + case SkipPermissionDenied: + return "permission-denied" + case SkipExcluded: + return "excluded" + default: + return fmt.Sprintf("unknown(%d)", int(r)) + } +} + +// SkipCallback is invoked whenever a candidate file or directory is rejected +// by a security guard or path exclusion filter during upward discovery. +type SkipCallback func(path string, reason SkipReason, detail error) + +// IgnoreCallback is invoked during recursive collection when a file or +// directory is ignored due to inclusion or exclusion filters. +type IgnoreCallback func(path string, isDir bool, filterName string) + +// SecurityError is returned by discovery methods when StrictSecurity is +// enabled and a candidate file violates a security check. +type SecurityError struct { + Path string + Reason SkipReason + Err error +} + +// Error implements the error interface. +func (e *SecurityError) Error() string { + if e.Err != nil { + return fmt.Sprintf( + "lookup security check failed (%s) for %s: %v", + e.Reason, + e.Path, + e.Err, + ) + } + return fmt.Sprintf( + "lookup security check failed (%s) for %s", + e.Reason, + e.Path, + ) +} + +// Unwrap returns the underlying error associated with this security failure. +func (e *SecurityError) Unwrap() error { + return e.Err +} + +// DiscoveredFile holds the resolved path and validated metadata for a file. +type DiscoveredFile struct { + Path string + ResolvedPath string + Dir string + Name string + Size int64 + ModTime time.Time + Mode iofs.FileMode + IsSymlink bool + Meta FileMeta +} + +// CacheStats reports cache hit, miss, and invalidation counters. +type CacheStats struct { + DirHits uint64 + DirMisses uint64 + FileHits uint64 + FileMisses uint64 + Invalidations uint64 +} diff --git a/test/doc_test.go b/test/doc_test.go index c313772..8374c8f 100644 --- a/test/doc_test.go +++ b/test/doc_test.go @@ -98,6 +98,7 @@ func TestGoDocCommand(t *testing.T) { pkgs := []string{ "./pkg/dmlex", "./pkg/fs", + "./pkg/fs/lookup", "./pkg/fs/stream", "./pkg/printer", "./pkg/printer/dml_defaults", diff --git a/test/fs/lookup_test.go b/test/fs/lookup_test.go new file mode 100644 index 0000000..c633fbf --- /dev/null +++ b/test/fs/lookup_test.go @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_fs + +import ( + "errors" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/timoschenko/dmltools/pkg/fs" + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +func writeTestFile(t *testing.T, path string, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0750); err != nil { + t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) + } + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func TestLookup_RealRepoHierarchyCollectAndMutations(t *testing.T) { + tmpDir := t.TempDir() + + outerRepo := filepath.Join(tmpDir, "outer") + innerRepo := filepath.Join(outerRepo, "inner") + subDir := filepath.Join(innerRepo, "pkg", "dev") + targetFile := filepath.Join(subDir, "device.dml") + + if err := os.MkdirAll(filepath.Join(outerRepo, ".git"), 0750); err != nil { + t.Fatalf("mkdir outer .git: %v", err) + } + if err := os.MkdirAll(filepath.Join(innerRepo, ".git"), 0750); err != nil { + t.Fatalf("mkdir inner .git: %v", err) + } + writeTestFile(t, filepath.Join(outerRepo, ".editorconfig"), "root = true\n") + writeTestFile(t, filepath.Join(innerRepo, ".editorconfig"), "indent = 4\n") + writeTestFile(t, filepath.Join(innerRepo, ".gitignore"), "*.bak.dml\n") + writeTestFile( + t, + filepath.Join(innerRepo, "pkg", ".ignore"), + "generated/\n", + ) + writeTestFile(t, targetFile, "dml 1.4;\ndevice dev;\n") + writeTestFile(t, filepath.Join(innerRepo, "skip.bak.dml"), "dml 1.4;\n") + writeTestFile( + t, + filepath.Join(innerRepo, "pkg", "generated", "gen.dml"), + "dml 1.4;\n", + ) + writeTestFile(t, filepath.Join(innerRepo, "venv", "skip.dml"), "dml 1.4;\n") + + finder, err := lookup.NewFinder( + lookup.WithInclude(`\.dml$`), + lookup.WithExclude(fs.DefaultExcludePattern), + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.FileIgnore), + ) + if err != nil { + t.Fatalf("lookup.NewFinder: %v", err) + } + + collected, err := finder.Collect([]string{innerRepo}) + if err != nil { + t.Fatalf("Collect: %v", err) + } + if !slices.Equal(collected, []string{targetFile}) { + t.Fatalf("Collect got %v, want [%s]", collected, targetFile) + } + + boundary, err := finder.Cache().ResolveBoundary(targetFile) + if err != nil { + t.Fatalf("ResolveBoundary: %v", err) + } + if boundary.Reason != lookup.BoundaryVCSRoot || + boundary.RootDir != innerRepo { + t.Fatalf("expected innerRepo VCS boundary, got %+v", boundary) + } + + chain, err := finder.FindChain( + targetFile, + lookup.FileEditorConfig, + lookup.FileGitIgnore, + lookup.FileIgnore, + ) + if err != nil { + t.Fatalf("FindChain: %v", err) + } + + wantPaths := []string{ + filepath.Join(innerRepo, lookup.FileEditorConfig), + filepath.Join(innerRepo, lookup.FileGitIgnore), + filepath.Join(innerRepo, "pkg", lookup.FileIgnore), + } + gotPaths := make([]string, len(chain)) + for i, f := range chain { + gotPaths[i] = f.Path + } + if !slices.Equal(gotPaths, wantPaths) { + t.Fatalf("got paths %v, want %v", gotPaths, wantPaths) + } + + // Mutate local filesystem: add a deeper .editorconfig, edit existing, delete .ignore. + deepEditorCfg := filepath.Join(subDir, lookup.FileEditorConfig) + writeTestFile(t, deepEditorCfg, "indent = 2\n") + writeTestFile( + t, + filepath.Join(innerRepo, lookup.FileEditorConfig), + "indent = 8\n# updated\n", + ) + if err := os.Remove( + filepath.Join(innerRepo, "pkg", lookup.FileIgnore), + ); err != nil { + t.Fatalf("remove .ignore: %v", err) + } + + nearest, found, err := finder.FindNearest( + targetFile, + lookup.FileEditorConfig, + ) + if err != nil { + t.Fatalf("FindNearest after mutation: %v", err) + } + if !found || nearest.Path != deepEditorCfg { + t.Fatalf( + "expected nearest %s, got (%+v, %v)", + deepEditorCfg, + nearest, + found, + ) + } + + chainAfter, err := finder.FindChain( + targetFile, + lookup.FileEditorConfig, + lookup.FileIgnore, + ) + if err != nil { + t.Fatalf("FindChain after mutation: %v", err) + } + if len(chainAfter) != 2 || + chainAfter[0].Size != int64(len("indent = 8\n# updated\n")) || + chainAfter[1].Path != deepEditorCfg { + t.Fatalf("unexpected chain after mutation: %+v", chainAfter) + } +} + +func TestLookup_RealSymlinksAndRelativePaths(t *testing.T) { + tmpDir := t.TempDir() + repo := filepath.Join(tmpDir, "repo") + sub := filepath.Join(repo, "sub") + outsideFile := filepath.Join(tmpDir, "outside.cfg") + inRepoTarget := filepath.Join(repo, "shared.cfg") + + if err := os.MkdirAll(filepath.Join(repo, ".git"), 0750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + if err := os.MkdirAll(sub, 0750); err != nil { + t.Fatalf("mkdir sub: %v", err) + } + writeTestFile(t, outsideFile, "secret=1\n") + writeTestFile(t, inRepoTarget, "safe=1\n") + + if err := os.Symlink( + outsideFile, + filepath.Join(repo, lookup.FileEditorConfig), + ); err != nil { + t.Fatalf("symlink outside: %v", err) + } + if err := os.Symlink( + inRepoTarget, + filepath.Join(sub, lookup.FileEditorConfig), + ); err != nil { + t.Fatalf("symlink inside: %v", err) + } + if err := os.Symlink( + filepath.Join(repo, "missing.cfg"), + filepath.Join(sub, lookup.FileIgnore), + ); err != nil { + t.Fatalf("symlink broken: %v", err) + } + + var skips []lookup.SkipReason + finder, err := lookup.NewFinder( + lookup.WithOnSkip(func(_ string, r lookup.SkipReason, _ error) { + skips = append(skips, r) + }), + ) + if err != nil { + t.Fatalf("lookup.NewFinder: %v", err) + } + + t.Chdir(sub) + + files, err := finder.FindChain( + ".", + lookup.FileEditorConfig, + lookup.FileIgnore, + ) + if err != nil { + t.Fatalf("FindChain: %v", err) + } + if len(files) != 1 { + t.Fatalf("expected 1 safe file, got %+v", files) + } + evalTarget, err := filepath.EvalSymlinks(inRepoTarget) + if err != nil { + t.Fatalf("EvalSymlinks: %v", err) + } + if !files[0].IsSymlink || files[0].ResolvedPath != evalTarget { + t.Errorf( + "unexpected symlink result: %+v (want %s)", + files[0], + evalTarget, + ) + } + if !slices.Contains(skips, lookup.SkipSymlinkEscape) || + !slices.Contains(skips, lookup.SkipBrokenSymlink) { + t.Errorf("expected escape and broken symlink skips, got %v", skips) + } + + strictFinder, err := lookup.NewFinder(lookup.WithStrictSecurity(true)) + if err != nil { + t.Fatalf("NewFinder strict: %v", err) + } + _, err = strictFinder.FindChain(".", lookup.FileEditorConfig) + var secErr *lookup.SecurityError + if !errors.As(err, &secErr) || + secErr.Reason != lookup.SkipSymlinkEscape { + t.Fatalf("expected SkipSymlinkEscape SecurityError, got %v", err) + } +} diff --git a/test/fs/lookup_unix_test.go b/test/fs/lookup_unix_test.go new file mode 100644 index 0000000..e229ce3 --- /dev/null +++ b/test/fs/lookup_unix_test.go @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +//go:build unix + +package test_fs + +import ( + "errors" + "os" + "path/filepath" + "syscall" + "testing" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +func TestLookup_UnixRejectsFIFO(t *testing.T) { + tmpDir := t.TempDir() + repo := filepath.Join(tmpDir, "repo") + if err := os.MkdirAll(filepath.Join(repo, ".git"), 0750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + + fifoPath := filepath.Join(repo, lookup.FileEditorConfig) + if err := syscall.Mkfifo(fifoPath, 0600); err != nil { + t.Fatalf("mkfifo: %v", err) + } + + finder, err := lookup.NewFinder(lookup.WithStrictSecurity(true)) + if err != nil { + t.Fatalf("lookup.NewFinder: %v", err) + } + + _, err = finder.FindChain(repo, lookup.FileEditorConfig) + var secErr *lookup.SecurityError + if !errors.As(err, &secErr) || + secErr.Reason != lookup.SkipNotRegular { + t.Fatalf("expected SkipNotRegular SecurityError for FIFO, got %v", err) + } +}