diff --git a/cmd/dmlfmt/cmdline.go b/cmd/dmlfmt/cmdline.go index 80c312a..36eb068 100644 --- a/cmd/dmlfmt/cmdline.go +++ b/cmd/dmlfmt/cmdline.go @@ -88,33 +88,44 @@ type CLIConfig struct { // CodeSet indicates whether -c or --code was explicitly provided CodeSet bool + + Device string + DeviceSet bool + FollowAllImport bool + IncludeSet bool + + DmlcFlags []string + DmlcIncludeDirs []string + DmlcFlagsErr string } var implementedFlags = map[string]bool{ - "W": true, - "c": true, - "check": true, - "code": true, - "color": true, - "exclude": true, - "extend-exclude": true, - "fast": true, - "force-exclude": true, - "h": true, - "help": true, - "include": true, - "l": true, - "line-length": true, - "nerd-stats": true, - "no-color": true, - "q": true, - "quiet": true, - "safe": true, - "stdin-filename": true, - "v": true, - "verbose": true, - "version": true, - "workers": true, + "W": true, + "c": true, + "check": true, + "code": true, + "color": true, + "device": true, + "exclude": true, + "extend-exclude": true, + "fast": true, + "follow-all-import": true, + "force-exclude": true, + "h": true, + "help": true, + "include": true, + "l": true, + "line-length": true, + "nerd-stats": true, + "no-color": true, + "q": true, + "quiet": true, + "safe": true, + "stdin-filename": true, + "v": true, + "verbose": true, + "version": true, + "workers": true, } func isFlagImplemented(flagName string) bool { @@ -173,6 +184,10 @@ func printUsage(w io.Writer) { Options: -c, --code TEXT Format the code passed in as a string. + --device FILE Format device DML and imported files + (pass dmlc flags after '--'). + --follow-all-import Fail if an imported file is missing + (requires --device). -l, --line-length INTEGER How many characters per line to allow. [default: %d] --check Don't write the files back, just return the @@ -449,15 +464,47 @@ func parseArgs(args []string, stderr io.Writer) (*CLIConfig, error) { "", "Write memory profile to file.", ) + fs.StringVar( + &cfg.Device, + "device", + "", + "Format device DML file and its imported files.", + ) + fs.BoolVar( + &cfg.FollowAllImport, + "follow-all-import", + false, + "Fail if an imported file cannot be found (requires --device).", + ) - if err := fs.Parse(args); err != nil { + dashIdx := -1 + for i, arg := range args { + if arg == "--" { + dashIdx = i + break + } + } + + parseTarget := args + var afterDash []string + if dashIdx >= 0 { + parseTarget = args[:dashIdx] + afterDash = args[dashIdx+1:] + } + + if err := fs.Parse(parseTarget); err != nil { return nil, err } fs.Visit(func(f *flag.Flag) { cfg.ExplicitFlags = append(cfg.ExplicitFlags, f.Name) - if f.Name == "c" || f.Name == "code" { + switch f.Name { + case "c", "code": cfg.CodeSet = true + case "device": + cfg.DeviceSet = true + case "include": + cfg.IncludeSet = true } }) @@ -499,7 +546,7 @@ func parseArgs(args []string, stderr io.Writer) (*CLIConfig, error) { // Fast / safe toggles: track ordering so the last specified flag wins. lastSafeIdx := -1 lastFastIdx := -1 - for i, arg := range args { + for i, arg := range parseTarget { switch arg { case "--safe", "-safe": lastSafeIdx = i @@ -522,7 +569,7 @@ func parseArgs(args []string, stderr io.Writer) (*CLIConfig, error) { // Color toggles: track ordering so the last specified flag wins. lastColorIdx := -1 lastNoColorIdx := -1 - for i, arg := range args { + for i, arg := range parseTarget { switch arg { case "--color", "-color": lastColorIdx = i @@ -550,5 +597,14 @@ func parseArgs(args []string, stderr io.Writer) (*CLIConfig, error) { cfg.Sources = append(cfg.Sources, fs.Args()...) + if cfg.DeviceSet { + if len(afterDash) > 0 { + cfg.DmlcFlags = afterDash + cfg.DmlcIncludeDirs, cfg.DmlcFlagsErr = parseDmlcFlags(afterDash) + } + } else if dashIdx >= 0 { + cfg.Sources = append(cfg.Sources, afterDash...) + } + return cfg, nil } diff --git a/cmd/dmlfmt/device.go b/cmd/dmlfmt/device.go new file mode 100644 index 0000000..0eee1a4 --- /dev/null +++ b/cmd/dmlfmt/device.go @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package main + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + + "github.com/antlr4-go/antlr/v4" + "github.com/timoschenko/dmltools/pkg/dmlex" + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +const implicitBuiltinsImport = "dml-builtins.dml" + +var dmlcValueFlags = map[string]bool{ + "-D": true, + "-P": true, + "--dep": true, + "--dep-target": true, + "--warn": true, + "--nowarn": true, + "--simics-api": true, + "--max-errors": true, + "--no-compat": true, + "--breaking-change": true, + "--split-c-file": true, +} + +// ImportRef describes an import statement location and target string. +type ImportRef struct { + Name string + Line int + Column int +} + +func nextDmlcArg( + tail []string, + flagName string, + requireNonEmpty bool, +) (string, string) { + if len(tail) == 0 { + if requireNonEmpty { + return "", fmt.Sprintf( + "flag '%s' requires a directory argument", + flagName, + ) + } + return "", fmt.Sprintf("flag '%s' requires an argument", flagName) + } + val := tail[0] + if requireNonEmpty && val == "" { + return "", fmt.Sprintf( + "flag '%s' requires a directory argument", + flagName, + ) + } + return val, "" +} + +// parseDmlcFlags extracts include directories from dmlc flags after '--' +// and rejects unexpected positional arguments. +func parseDmlcFlags(args []string) ([]string, string) { + var includeDirs []string + + for i := 0; i < len(args); i++ { + arg := args[i] + + switch { + case arg == "-I" || arg == "--include-dir": + val, errMsg := nextDmlcArg(args[i+1:], arg, true) + if errMsg != "" { + return nil, errMsg + } + i++ + includeDirs = append(includeDirs, val) + case strings.HasPrefix(arg, "-I="): + val := arg[len("-I="):] + if val == "" { + return nil, "flag '-I=' requires a directory argument" + } + includeDirs = append(includeDirs, val) + case strings.HasPrefix(arg, "-I") && len(arg) > 2: + includeDirs = append(includeDirs, arg[2:]) + case strings.HasPrefix(arg, "--include-dir="): + val := arg[len("--include-dir="):] + if val == "" { + return nil, "flag '--include-dir=' requires a directory argument" + } + includeDirs = append(includeDirs, val) + case dmlcValueFlags[arg]: + if _, errMsg := nextDmlcArg(args[i+1:], arg, false); errMsg != "" { + return nil, errMsg + } + i++ + case strings.HasPrefix(arg, "-") && arg != "-": + // Ignore other dmlc flags. + default: + return nil, fmt.Sprintf( + "unexpected argument '%s' after '--' in device mode", + arg, + ) + } + } + + return includeDirs, "" +} + +// extractDmlFileMeta inspects a parsed DML AST for a device declaration tag +// and all top-level import statements (including inside #if / #else). +func extractDmlFileMeta( + tree antlr.ParseTree, +) (bool, int, int, []ImportRef) { + dmlCtx, ok := tree.(dmlex.IDmlContext) + if !ok || dmlCtx == nil { + return false, 0, 0, nil + } + + codeCtx := dmlCtx.DmlCode() + if codeCtx == nil { + return false, 0, 0, nil + } + + var ( + hasDevice bool + devLine int + devCol int + ) + if devTag := codeCtx.DeviceTag(); devTag != nil { + hasDevice = true + if tok := devTag.GetStart(); tok != nil { + devLine = tok.GetLine() + devCol = tok.GetColumn() + } + } + + var imports []ImportRef + collectImportsFromStatements(codeCtx.DeviceStatements(), &imports) + + return hasDevice, devLine, devCol, imports +} + +func collectImportsFromStatements( + stmts dmlex.IDeviceStatementsContext, + out *[]ImportRef, +) { + if stmts == nil { + return + } + for _, stmt := range stmts.AllDeviceStatement() { + if stmt == nil { + continue + } + if imp := stmt.ImportStatement(); imp != nil { + if ref, ok := extractImportRef(imp); ok { + *out = append(*out, ref) + } + } + if ifCtx := stmt.ToplevelIf(); ifCtx != nil { + collectImportsFromToplevelIf(ifCtx, out) + } + } +} + +func collectImportsFromToplevelIf( + ifCtx dmlex.IToplevelIfContext, + out *[]ImportRef, +) { + if ifCtx == nil { + return + } + if ifStmt := ifCtx.ToplevelIfStatement(); ifStmt != nil { + collectImportsFromStatements(ifStmt.DeviceStatements(), out) + } + if elseStmt := ifCtx.ToplevelElseStatement(); elseStmt != nil { + collectImportsFromStatements(elseStmt.DeviceStatements(), out) + collectImportsFromToplevelIf(elseStmt.ToplevelIf(), out) + } +} + +func extractImportRef(imp dmlex.IImportStatementContext) (ImportRef, bool) { + lit := imp.STRING_LITERAL() + if lit == nil { + return ImportRef{}, false + } + raw := lit.GetText() + if raw == "" { + return ImportRef{}, false + } + var line, col int + if sym := lit.GetSymbol(); sym != nil { + line = sym.GetLine() + col = sym.GetColumn() + } + return ImportRef{ + Name: unquoteDmlString(raw), + Line: line, + Column: col, + }, true +} + +func unquoteDmlString(raw string) string { + if unquoted, err := strconv.Unquote(raw); err == nil { + return unquoted + } + if len(raw) >= 2 && raw[0] == '"' && raw[len(raw)-1] == '"' { + return raw[1 : len(raw)-1] + } + return raw +} + +// deviceImportResolver resolves imports and enforces workspace boundaries +// and ignore/exclude/include filters in --device mode. +type deviceImportResolver struct { + cache lookup.Cache + finder lookup.Finder + ui *UI + includeSet bool + verbose bool + rootDisplayPath string + deviceDir string + boundaryRoot string + includeDirs []string + visited map[string]struct{} +} + +func newDeviceImportResolver( + cfg *CLIConfig, + finder lookup.Finder, + ui *UI, +) (*deviceImportResolver, error) { + cache := finder.Cache() + displayDevice := filepath.Clean(cfg.Device) + absDevice, err := cache.Abs(displayDevice) + if err != nil { + return nil, fmt.Errorf("resolving device file %s: %w", cfg.Device, err) + } + + meta, err := cache.Stat(absDevice) + if err != nil { + return nil, fmt.Errorf("reading device file %s: %w", cfg.Device, err) + } + if meta.Mode.IsDir() { + return nil, fmt.Errorf( + "device path %s is a directory, expected a DML file", + cfg.Device, + ) + } + + boundary, err := cache.ResolveBoundary(absDevice) + if err != nil { + return nil, fmt.Errorf( + "resolving workspace boundary for %s: %w", + cfg.Device, + err, + ) + } + + includeDirs := make([]string, 0, len(cfg.DmlcIncludeDirs)) + for _, dir := range cfg.DmlcIncludeDirs { + includeDirs = append(includeDirs, filepath.Clean(dir)) + } + + return &deviceImportResolver{ + cache: cache, + finder: finder, + ui: ui, + includeSet: cfg.IncludeSet, + verbose: cfg.Verbose, + rootDisplayPath: displayDevice, + deviceDir: filepath.Dir(displayDevice), + boundaryRoot: cache.EvalBoundaryRoot(boundary.RootDir), + includeDirs: includeDirs, + visited: make(map[string]struct{}), + }, nil +} + +func (r *deviceImportResolver) initialPaths() []string { + if !r.shouldFormatAndFollow(r.rootDisplayPath, true) { + return nil + } + return []string{r.rootDisplayPath} +} + +func (r *deviceImportResolver) shouldFormatAndFollow( + targetPath string, + isRoot bool, +) bool { + displayPath := filepath.Clean(targetPath) + absPath, err := r.cache.Abs(displayPath) + if err != nil { + return false + } + evalPath := r.canonicalizePath(absPath) + + if _, seen := r.visited[evalPath]; seen { + return false + } + r.visited[evalPath] = struct{}{} + + if isRoot { + if r.finder.Filter().IsForceExcluded(displayPath) || + (evalPath != absPath && + r.finder.Filter().IsForceExcluded(evalPath)) { + if r.verbose { + r.ui.IgnoredFilter( + displayPath, + false, + lookup.FilterForceExclude, + ) + } + return false + } + return true + } + + inBoundary := r.cache.IsWithinBoundary(r.boundaryRoot, absPath) + if !inBoundary { + if !r.includeSet { + if r.verbose { + r.ui.Verbose( + "%s ignored: outside workspace boundary\n", + displayPath, + ) + } + return false + } + if !r.isOutsideIncluded(absPath, evalPath, displayPath) { + if r.verbose { + r.ui.Verbose( + "%s ignored: outside workspace boundary and does not match --include\n", + displayPath, + ) + } + return false + } + } + + if filterName := r.matchExcludeWithAncestors( + absPath, + evalPath, + displayPath, + ); filterName != "" { + if r.verbose { + r.ui.IgnoredFilter(displayPath, false, filterName) + } + return false + } + + if ignoreFile, err := r.finder.MatchIgnore(absPath); err == nil && + ignoreFile != "" { + if r.verbose { + r.ui.IgnoredFilter(displayPath, false, ignoreFile) + } + return false + } + + return true +} + +func (r *deviceImportResolver) canonicalizePath(absPath string) string { + if resolved, err := filepath.EvalSymlinks(absPath); err == nil { + return filepath.Clean(resolved) + } + return filepath.Clean(absPath) +} + +func (r *deviceImportResolver) relUnderBoundary( + evalPath string, +) (string, bool) { + rel, err := filepath.Rel(r.boundaryRoot, evalPath) + if err != nil { + return "", false + } + if rel == "." || rel == ".." || + strings.HasPrefix(rel, ".."+string(filepath.Separator)) || + filepath.IsAbs(rel) { + return "", false + } + return rel, true +} + +func (r *deviceImportResolver) matchExcludeWithAncestors( + absPath, evalPath, displayPath string, +) string { + filter := r.finder.Filter() + rel, underBoundary := r.relUnderBoundary(evalPath) + if underBoundary { + parts := strings.Split(filepath.ToSlash(rel), "/") + for i := range len(parts) - 1 { + subRel := strings.Join(parts[:i+1], "/") + subFull := filepath.Join(r.boundaryRoot, filepath.FromSlash(subRel)) + if name := filter.MatchExclude(subRel, subFull, true); name != "" { + return name + } + } + return filter.MatchExclude(rel, displayPath, false) + } + + if name := filter.MatchExclude(displayPath, absPath, false); name != "" { + return name + } + if evalPath != absPath { + return filter.MatchExclude(evalPath, evalPath, false) + } + return "" +} + +func (r *deviceImportResolver) isOutsideIncluded( + absPath, evalPath, displayPath string, +) bool { + filter := r.finder.Filter() + if filter.IsIncluded(displayPath, absPath) { + return true + } + if evalPath != absPath && filter.IsIncluded(evalPath, evalPath) { + return true + } + return false +} + +func (r *deviceImportResolver) resolveImportPath( + importingPath, impName string, +) (string, bool) { + importingDir := filepath.Dir(filepath.Clean(importingPath)) + nativeImp := filepath.FromSlash(impName) + + if strings.HasPrefix(impName, "./") { + candidate := filepath.Join(importingDir, nativeImp) + if r.isRegularFile(candidate) { + return candidate, true + } + return "", false + } + + if strings.HasPrefix(impName, "../") { + candidate := filepath.Join(importingDir, nativeImp) + if r.isRegularFile(candidate) { + return candidate, true + } + } + + searchDirs := make([]string, 0, len(r.includeDirs)+2) + searchDirs = append(searchDirs, r.includeDirs...) + searchDirs = append(searchDirs, r.deviceDir, importingDir) + + for _, dir := range searchDirs { + verCandidate := filepath.Join(dir, dmlex.SupportedDmlVersion, nativeImp) + if r.isRegularFile(verCandidate) { + return verCandidate, true + } + directCandidate := filepath.Join(dir, nativeImp) + if r.isRegularFile(directCandidate) { + return directCandidate, true + } + } + + return "", false +} + +func (r *deviceImportResolver) isRegularFile(path string) bool { + meta, err := r.cache.Stat(filepath.Clean(path)) + return err == nil && meta.Mode.IsRegular() +} + +func handleDeviceJobResult( + job *OutputJob, + resolver *deviceImportResolver, + cfg *CLIConfig, + ui *UI, + paths *[]string, +) bool { + isRoot := job.Path == resolver.rootDisplayPath + if isRoot && !job.HasDeviceTag { + ui.SyntaxError( + job.Path, + 1, + 0, + "EDEVICE: missing device declaration", + ) + return true + } + if !isRoot && job.HasDeviceTag { + ui.SyntaxError( + job.Path, + job.DeviceLine, + job.DeviceColumn, + "EDEVIMP: cannot import a device file", + ) + return true + } + + if isRoot { + if resolved, ok := resolver.resolveImportPath( + job.Path, + implicitBuiltinsImport, + ); ok && resolver.shouldFormatAndFollow(resolved, false) { + *paths = append(*paths, resolved) + } + } + + importFailed := false + for _, imp := range job.Imports { + resolved, ok := resolver.resolveImportPath(job.Path, imp.Name) + if !ok { + if cfg.FollowAllImport { + ui.SyntaxError( + job.Path, + imp.Line, + imp.Column, + fmt.Sprintf( + "EIMPORT: cannot find file to import: %s", + imp.Name, + ), + ) + importFailed = true + } else if cfg.Verbose { + ui.Verbose( + "%s:%d: imported file not found, skipping: %s\n", + job.Path, + imp.Line, + imp.Name, + ) + } + continue + } + if resolver.shouldFormatAndFollow(resolved, false) { + *paths = append(*paths, resolved) + } + } + + return importFailed +} diff --git a/cmd/dmlfmt/device_test.go b/cmd/dmlfmt/device_test.go new file mode 100644 index 0000000..dada894 --- /dev/null +++ b/cmd/dmlfmt/device_test.go @@ -0,0 +1,644 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package main + +import ( + "bytes" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +func writeTestDmlFile(t *testing.T, path, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil { + t.Fatalf("mkdir %s: %v", filepath.Dir(path), err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func readTestDmlFile(t *testing.T, path string) string { + t.Helper() + //nolint:gosec // test helper reads controlled temp path + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(data) +} + +func runDmlfmtTest( + t *testing.T, + args ...string, +) (int, string, string) { + t.Helper() + var stdout, stderr bytes.Buffer + code := runWithIO(args, strings.NewReader(""), &stdout, &stderr) + return code, stdout.String(), stderr.String() +} + +func TestParseDmlcFlags(t *testing.T) { + dirs, errMsg := parseDmlcFlags([]string{ + "-I", "inc1", + "-Iinc2", + "-I=inc3", + "--include-dir=inc4", + "--include-dir", "inc5", + "-D", "FOO=1", + "-DBAR", + "-P", "header.h", + "--dep", "out.d", + "--dep-target", "out.o", + "--warn", "WUNUSED", + "--nowarn", "WEXPERIMENTAL", + "--simics-api", "6", + "--max-errors", "10", + "--no-compat", "dml12_int", + "--breaking-change", "bc", + "--split-c-file", "2", + "--mindeps", + "-g", + "--werror", + }) + if errMsg != "" { + t.Fatalf("unexpected error: %s", errMsg) + } + want := []string{"inc1", "inc2", "inc3", "inc4", "inc5"} + if !slices.Equal(dirs, want) { + t.Fatalf("got dirs %v, want %v", dirs, want) + } + + errCases := [][]string{ + {"-I"}, + {"-I="}, + {"--include-dir"}, + {"--include-dir="}, + {"-D"}, + {"--simics-api"}, + {"bare.dml"}, + {"-"}, + {"-I", "inc", "extra.dml"}, + } + for _, tc := range errCases { + if _, msg := parseDmlcFlags(tc); msg == "" { + t.Errorf("parseDmlcFlags(%v) expected error, got empty", tc) + } + } +} + +func TestDeviceCLIValidation(t *testing.T) { + dir := t.TempDir() + devFile := filepath.Join(dir, "dev.dml") + writeTestDmlFile(t, devFile, "dml 1.4;\ndevice dev;\n") + + cases := []struct { + name string + args []string + wantCode int + wantErr string + }{ + { + name: "device_with_src", + args: []string{"--device", devFile, devFile}, + wantCode: ExitCodeInternalError, + wantErr: "'SRC' and 'device'", + }, + { + name: "device_with_stdin_dash", + args: []string{"--device", devFile, "-"}, + wantCode: ExitCodeInternalError, + wantErr: "'SRC' and 'device'", + }, + { + name: "device_with_code", + args: []string{"--device", devFile, "-c", "dml 1.4;"}, + wantCode: ExitCodeInternalError, + wantErr: "'device' and 'code'", + }, + { + name: "device_empty", + args: []string{"--device", ""}, + wantCode: ExitCodeInternalError, + wantErr: "'--device' requires a DML file path", + }, + { + name: "device_missing_file", + args: []string{"--device", filepath.Join(dir, "nope.dml")}, + wantCode: ExitCodeInternalError, + wantErr: "nope.dml", + }, + { + name: "device_is_dir", + args: []string{"--device", dir}, + wantCode: ExitCodeInternalError, + wantErr: "is a directory", + }, + { + name: "follow_all_import_without_device", + args: []string{"--follow-all-import", devFile}, + wantCode: ExitCodeInternalError, + wantErr: "'--follow-all-import' requires '--device'", + }, + { + name: "positional_after_double_dash", + args: []string{"--device", devFile, "--", "extra.dml"}, + wantCode: ExitCodeInternalError, + wantErr: "unexpected argument 'extra.dml'", + }, + { + name: "dmlc_flag_without_double_dash", + args: []string{"--device", devFile, "-I", dir}, + wantCode: ExitCodeInternalError, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + code, _, stderr := runDmlfmtTest(t, tc.args...) + if code != tc.wantCode { + t.Fatalf( + "got exit code %d, want %d; stderr=%q", + code, + tc.wantCode, + stderr, + ) + } + if tc.wantErr != "" && !strings.Contains(stderr, tc.wantErr) { + t.Fatalf( + "stderr %q does not contain %q", + stderr, + tc.wantErr, + ) + } + }) + } +} + +func TestDeviceMode_FollowImportsAndSearchOrder(t *testing.T) { + ws := t.TempDir() + if err := os.MkdirAll(filepath.Join(ws, ".git"), 0o750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + + inc1 := filepath.Join(ws, "inc1") + inc2 := filepath.Join(ws, "inc2") + devDir := filepath.Join(ws, "devices", "mydev") + + unfmt := func(body string) string { + return "dml 1.4;\nconstant x = 1;\n" + body + } + + devPath := filepath.Join(devDir, "dev.dml") + writeTestDmlFile( + t, + devPath, + "dml 1.4;\n"+ + "device mydev;\n"+ + "constant x = 1;\n"+ + "import \"from_inc.dml\";\n"+ + "import \"prefer_ver.dml\";\n"+ + "import \"sub/child.dml\";\n", + ) + + // Implicit dml-builtins.dml inside inc1/1.4 + builtinsPath := filepath.Join(inc1, "1.4", "dml-builtins.dml") + writeTestDmlFile(t, builtinsPath, unfmt("")) + + // inc1 vs inc2 precedence + inc1File := filepath.Join(inc1, "from_inc.dml") + inc2Shadow := filepath.Join(inc2, "from_inc.dml") + writeTestDmlFile(t, inc1File, unfmt("")) + writeTestDmlFile(t, inc2Shadow, unfmt("")) + + // 1.4/ subdir vs direct subdir inside inc1 + verPreferred := filepath.Join(inc1, "1.4", "prefer_ver.dml") + directShadow := filepath.Join(inc1, "prefer_ver.dml") + writeTestDmlFile(t, verPreferred, unfmt("")) + writeTestDmlFile(t, directShadow, unfmt("")) + + // ./ and ../ relative import checks from sub/child.dml + childPath := filepath.Join(devDir, "sub", "child.dml") + writeTestDmlFile(t, childPath, unfmt( + "import \"./sibling.dml\";\n"+ + "import \"../parent_rel.dml\";\n"+ + "import \"../fallback_inc.dml\";\n", + )) + + siblingPath := filepath.Join(devDir, "sub", "sibling.dml") + writeTestDmlFile(t, siblingPath, unfmt("")) + // Should NOT be resolved via ./ from inc1 + incSiblingShadow := filepath.Join(inc1, "sibling.dml") + writeTestDmlFile(t, incSiblingShadow, unfmt("")) + + parentRelPath := filepath.Join(devDir, "parent_rel.dml") + writeTestDmlFile(t, parentRelPath, unfmt("")) + + // ../fallback_inc.dml doesn't exist in devDir, falls back to inc1/1.4 + fallbackIncPath := filepath.Join(inc1, "1.4", "../fallback_inc.dml") + // filepath.Join cleans .., so place at inc1/fallback_inc.dml and also + // place one at inc1/other_fallback.dml referenced via fallback.dml. + _ = fallbackIncPath + fallbackInInc1 := filepath.Join(inc1, "fallback_inc.dml") + writeTestDmlFile(t, fallbackInInc1, unfmt("")) + + // Wait: `../fallback_inc.dml` against `inc1/1.4/` cleans to + // `inc1/fallback_inc.dml` cleanly! Let's also verify `check` mode first. + checkCode, checkOut, checkErr := runDmlfmtTest( + t, + "--check", + "--device", devPath, + "--", "-I", inc1, "-I"+inc2, "-D", "SIMICS=6", + ) + if checkCode != ExitCodeWouldReformat { + t.Fatalf( + "--check got %d, want %d; out=%q err=%q", + checkCode, + ExitCodeWouldReformat, + checkOut, + checkErr, + ) + } + + code, stdout, stderr := runDmlfmtTest( + t, + "--device", devPath, + "--", "-I", inc1, "-I="+inc2, + ) + if code != ExitCodeOK { + t.Fatalf("got code %d; stdout=%q stderr=%q", code, stdout, stderr) + } + + shouldBeFormatted := []string{ + devPath, + builtinsPath, + inc1File, + verPreferred, + childPath, + siblingPath, + parentRelPath, + fallbackInInc1, + } + for _, p := range shouldBeFormatted { + got := readTestDmlFile(t, p) + if strings.Contains(got, " ") { + t.Errorf("expected %s to be formatted, got:\n%s", p, got) + } + } + + shouldStayUnformatted := []string{ + inc2Shadow, + directShadow, + incSiblingShadow, + } + for _, p := range shouldStayUnformatted { + got := readTestDmlFile(t, p) + if !strings.Contains(got, "constant x = 1;") { + t.Errorf("expected %s NOT to be formatted, got:\n%s", p, got) + } + } +} + +func TestDeviceMode_DotSlashStrictRelative(t *testing.T) { + ws := t.TempDir() + if err := os.MkdirAll(filepath.Join(ws, ".git"), 0o750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + + inc := filepath.Join(ws, "inc") + devPath := filepath.Join(ws, "dev.dml") + writeTestDmlFile( + t, + devPath, + "dml 1.4;\ndevice dev;\nimport \"./in_inc_only.dml\";\n", + ) + writeTestDmlFile( + t, + filepath.Join(inc, "in_inc_only.dml"), + "dml 1.4;\nconstant x = 1;\n", + ) + + // Without --follow-all-import: ./ must NOT match file in -I inc. + code, _, _ := runDmlfmtTest( + t, + "--follow-all-import", + "--device", devPath, + "--", "-I", inc, + ) + if code != ExitCodeInternalError { + t.Fatalf("expected EIMPORT for ./ matching only -I dir, got %d", code) + } +} + +func TestDeviceMode_TopLevelIfElse(t *testing.T) { + ws := t.TempDir() + if err := os.MkdirAll(filepath.Join(ws, ".git"), 0o750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + + devPath := filepath.Join(ws, "dev.dml") + writeTestDmlFile( + t, + devPath, + "dml 1.4;\n"+ + "device dev;\n"+ + "#if (true) {\n"+ + " import \"if_branch.dml\";\n"+ + "} #else #if (false) {\n"+ + " import \"elif_branch.dml\";\n"+ + "} #else {\n"+ + " import \"else_branch.dml\";\n"+ + "}\n", + ) + + branches := []string{ + filepath.Join(ws, "if_branch.dml"), + filepath.Join(ws, "elif_branch.dml"), + filepath.Join(ws, "else_branch.dml"), + } + for _, p := range branches { + writeTestDmlFile(t, p, "dml 1.4;\nconstant b = 2;\n") + } + + code, stdout, stderr := runDmlfmtTest(t, "--device", devPath) + if code != ExitCodeOK { + t.Fatalf("got code %d; stdout=%q stderr=%q", code, stdout, stderr) + } + + for _, p := range branches { + if got := readTestDmlFile(t, p); strings.Contains(got, " ") { + t.Errorf("branch file %s was not formatted:\n%s", p, got) + } + } +} + +func TestDeviceMode_SemanticAndImportErrors(t *testing.T) { + t.Run("EDEVICE_missing_device_tag", func(t *testing.T) { + ws := t.TempDir() + devPath := filepath.Join(ws, "dev.dml") + orig := "dml 1.4;\nconstant x = 1;\n" + writeTestDmlFile(t, devPath, orig) + + code, _, stderr := runDmlfmtTest(t, "--device", devPath) + if code != ExitCodeInternalError { + t.Fatalf("got %d, want %d; stderr=%q", code, ExitCodeInternalError, + stderr) + } + if !strings.Contains(stderr, "EDEVICE") { + t.Fatalf("expected EDEVICE in stderr, got %q", stderr) + } + if got := readTestDmlFile(t, devPath); got != orig { + t.Fatalf("root file with EDEVICE should not be modified") + } + }) + + t.Run("EDEVIMP_imported_device_file", func(t *testing.T) { + ws := t.TempDir() + devPath := filepath.Join(ws, "dev.dml") + impPath := filepath.Join(ws, "imp.dml") + impOrig := "dml 1.4;\ndevice subdev;\n" + writeTestDmlFile( + t, + devPath, + "dml 1.4;\ndevice dev;\nimport \"imp.dml\";\n", + ) + writeTestDmlFile(t, impPath, impOrig) + + code, _, stderr := runDmlfmtTest(t, "--device", devPath) + if code != ExitCodeInternalError { + t.Fatalf("got %d, want %d; stderr=%q", code, ExitCodeInternalError, + stderr) + } + if !strings.Contains(stderr, "EDEVIMP") { + t.Fatalf("expected EDEVIMP in stderr, got %q", stderr) + } + if got := readTestDmlFile(t, impPath); got != impOrig { + t.Fatalf("imported file with EDEVIMP should not be modified") + } + }) + + t.Run("unresolved_import_default_vs_follow_all", func(t *testing.T) { + ws := t.TempDir() + devPath := filepath.Join(ws, "dev.dml") + presentPath := filepath.Join(ws, "present.dml") + writeTestDmlFile( + t, + devPath, + "dml 1.4;\ndevice dev;\n"+ + "import \"missing.dml\";\n"+ + "import \"present.dml\";\n", + ) + writeTestDmlFile(t, presentPath, "dml 1.4;\nconstant p = 1;\n") + + // Default mode skips missing import and formats present.dml. + code, stdout, stderr := runDmlfmtTest(t, "-v", "--device", devPath) + if code != ExitCodeOK { + t.Fatalf("default mode got %d; out=%q err=%q", code, stdout, stderr) + } + if !strings.Contains( + stdout, + "imported file not found, skipping: missing.dml", + ) { + t.Fatalf("expected verbose skip message, got:\n%s", stdout) + } + if got := readTestDmlFile( + t, + presentPath, + ); strings.Contains( + got, + " ", + ) { + t.Fatalf("present.dml should be formatted") + } + + // With --follow-all-import: reports EIMPORT and exits 123. + code, _, stderr = runDmlfmtTest( + t, + "--follow-all-import", + "--device", devPath, + ) + if code != ExitCodeInternalError { + t.Fatalf("--follow-all-import got %d, want %d; stderr=%q", + code, ExitCodeInternalError, stderr) + } + if !strings.Contains(stderr, "EIMPORT") || + !strings.Contains( + stderr, + "cannot find file to import: missing.dml", + ) { + t.Fatalf("expected EIMPORT error in stderr, got %q", stderr) + } + }) +} + +func TestDeviceMode_WorkspaceBoundaryAndInclude(t *testing.T) { + base := t.TempDir() + ws := filepath.Join(base, "repo") + ext := filepath.Join(base, "external") + if err := os.MkdirAll(filepath.Join(ws, ".git"), 0o750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + + devPath := filepath.Join(ws, "dev.dml") + internalPath := filepath.Join(ws, "internal.dml") + extAPath := filepath.Join(ext, "ext_a.dml") + extBPath := filepath.Join(ext, "ext_b.dml") + extBouncePath := filepath.Join(ws, "bounced.dml") + + unfmt := "dml 1.4;\nconstant x = 1;\n" + writeTestDmlFile( + t, + devPath, + "dml 1.4;\n"+ + "device dev;\n"+ + "import \"internal.dml\";\n"+ + "import \"ext_a.dml\";\n", + ) + writeTestDmlFile(t, internalPath, unfmt) + writeTestDmlFile( + t, + extAPath, + "dml 1.4;\nconstant a = 1;\n"+ + "import \"ext_b.dml\";\n"+ + "import \"bounced.dml\";\n", + ) + writeTestDmlFile(t, extBPath, unfmt) + writeTestDmlFile(t, extBouncePath, unfmt) + + // 1. Default without --include: external files and bounced transitive + // imports are skipped immediately. + code, stdout, stderr := runDmlfmtTest( + t, + "-v", + "--device", devPath, + "--", "-I", ext, "-I", ws, + ) + if code != ExitCodeOK { + t.Fatalf("got %d; stdout=%q stderr=%q", code, stdout, stderr) + } + if strings.Contains(readTestDmlFile(t, internalPath), " ") { + t.Errorf("internal.dml inside workspace should be formatted") + } + for _, p := range []string{extAPath, extBPath, extBouncePath} { + if !strings.Contains(readTestDmlFile(t, p), " ") { + t.Errorf("%s should NOT be formatted without --include", p) + } + } + + // 2. With --include matching external files (using non-matching pattern for + // internal.dml to verify workspace files still format even with --include). + writeTestDmlFile(t, internalPath, unfmt) + extPattern := regexp.QuoteMeta("ext_") + code, stdout, stderr = runDmlfmtTest( + t, + "--device", devPath, + "--include", extPattern, + "--", "-I", ext, "-I", ws, + ) + if code != ExitCodeOK { + t.Fatalf("with --include got %d; out=%q err=%q", code, stdout, stderr) + } + for _, p := range []string{ + internalPath, + extAPath, + extBPath, + extBouncePath, + } { + if strings.Contains(readTestDmlFile(t, p), " ") { + t.Errorf("%s should be formatted with --include %q", p, extPattern) + } + } +} + +func TestDeviceMode_FiltersAndCycles(t *testing.T) { + ws := t.TempDir() + if err := os.MkdirAll(filepath.Join(ws, ".git"), 0o750); err != nil { + t.Fatalf("mkdir .git: %v", err) + } + writeTestDmlFile(t, filepath.Join(ws, ".gitignore"), "gen/\nignored.dml\n") + + devPath := filepath.Join(ws, "dev.dml") + aPath := filepath.Join(ws, "a.dml") + bPath := filepath.Join(ws, "b.dml") + genPath := filepath.Join(ws, "gen", "g.dml") + ignoredPath := filepath.Join(ws, "ignored.dml") + + writeTestDmlFile( + t, + devPath, + "dml 1.4;\ndevice dev;\n"+ + "import \"a.dml\";\n"+ + "import \"gen/g.dml\";\n"+ + "import \"ignored.dml\";\n", + ) + writeTestDmlFile( + t, + aPath, + "dml 1.4;\nconstant a = 1;\nimport \"b.dml\";\n", + ) + writeTestDmlFile( + t, + bPath, + "dml 1.4;\nconstant b = 2;\nimport \"a.dml\";\n", + ) + writeTestDmlFile(t, genPath, "dml 1.4;\nconstant g = 3;\n") + writeTestDmlFile(t, ignoredPath, "dml 1.4;\nconstant i = 4;\n") + + code, stdout, stderr := runDmlfmtTest( + t, + "--follow-all-import", + "--device", devPath, + ) + if code != ExitCodeOK { + t.Fatalf("got %d; stdout=%q stderr=%q", code, stdout, stderr) + } + if strings.Contains(readTestDmlFile(t, aPath), " ") || + strings.Contains(readTestDmlFile(t, bPath), " ") { + t.Errorf("cyclic files a.dml and b.dml should be formatted") + } + if !strings.Contains(readTestDmlFile(t, genPath), " ") { + t.Errorf("gitignored dir file %s should NOT be formatted", genPath) + } + if !strings.Contains(readTestDmlFile(t, ignoredPath), " ") { + t.Errorf("gitignored file %s should NOT be formatted", ignoredPath) + } + + // --force-exclude on root device file skips everything cleanly. + code, stdout, stderr = runDmlfmtTest( + t, + "--force-exclude", `dev\.dml$`, + "--device", devPath, + ) + if code != ExitCodeOK { + t.Fatalf("force-exclude got %d; out=%q err=%q", code, stdout, stderr) + } + if !strings.Contains(stdout, "No DML files are present") { + t.Fatalf("expected no-files message on stdout, got %q", stdout) + } + + // --exclude skips imported files matching pattern without disabling + // explicit non-excluded files. + excludedImp := filepath.Join(ws, "excluded_imp.dml") + writeTestDmlFile( + t, + devPath, + "dml 1.4;\ndevice dev;\nimport \"excluded_imp.dml\";\n", + ) + writeTestDmlFile(t, excludedImp, "dml 1.4;\nconstant e = 1;\n") + code, stdout, stderr = runDmlfmtTest( + t, + "--exclude", `excluded_imp\.dml$`, + "--device", devPath, + ) + if code != ExitCodeOK { + t.Fatalf("--exclude got %d; out=%q err=%q", code, stdout, stderr) + } + if !strings.Contains(readTestDmlFile(t, excludedImp), " ") { + t.Errorf("excluded_imp.dml should NOT be formatted under --exclude") + } +} diff --git a/cmd/dmlfmt/dmlfmt.go b/cmd/dmlfmt/dmlfmt.go index df476da..d46c010 100644 --- a/cmd/dmlfmt/dmlfmt.go +++ b/cmd/dmlfmt/dmlfmt.go @@ -88,13 +88,50 @@ func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return ExitCodeInternalError } + if cfg.DmlcFlagsErr != "" { + ui.PrintError("Error: %s", cfg.DmlcFlagsErr) + return ExitCodeInternalError + } + + if cfg.FollowAllImport && !cfg.DeviceSet { + ui.PrintError( + "Error: '--follow-all-import' requires '--device'.", + ) + ui.PrintErrorUsage() + return ExitCodeInternalError + } + + if cfg.DeviceSet { + if cfg.Device == "" { + ui.PrintError( + "Error: '--device' requires a DML file path.", + ) + ui.PrintErrorUsage() + return ExitCodeInternalError + } + if cfg.CodeSet { + ui.PrintError( + "'device' and 'code' cannot be passed simultaneously.", + ) + ui.PrintErrorUsage() + return ExitCodeInternalError + } + if len(cfg.Sources) > 0 { + ui.PrintError( + "'SRC' and 'device' cannot be passed simultaneously.", + ) + ui.PrintErrorUsage() + return ExitCodeInternalError + } + } + if cfg.CodeSet && len(cfg.Sources) > 0 { ui.PrintError("'SRC' and 'code' cannot be passed simultaneously.") ui.PrintErrorUsage() return ExitCodeInternalError } - if !cfg.CodeSet && len(cfg.Sources) == 0 { + if !cfg.CodeSet && !cfg.DeviceSet && len(cfg.Sources) == 0 { ui.PrintNoSourcesError() return ExitCodeInternalError } diff --git a/cmd/dmlfmt/pipeline.go b/cmd/dmlfmt/pipeline.go index 741440b..2ad9633 100644 --- a/cmd/dmlfmt/pipeline.go +++ b/cmd/dmlfmt/pipeline.go @@ -57,6 +57,10 @@ type OutputJob struct { WouldReformat bool Ignored bool IgnoreReason string + HasDeviceTag bool + DeviceLine int + DeviceColumn int + Imports []ImportRef } // parseDmlStream parses input into a DmlFile and AST tree using an ErrorListener configured for path. @@ -264,6 +268,8 @@ func processFormattingJob( } } + hasDevice, devLine, devCol, imports := extractDmlFileMeta(tree) + return OutputJob{ Path: job.Path, OrigMode: job.OrigMode, @@ -271,6 +277,10 @@ func processFormattingJob( OutputHash: outputHash, OutputBuffer: outBuf.Bytes(), WouldReformat: wouldReformat, + HasDeviceTag: hasDevice, + DeviceLine: devLine, + DeviceColumn: devCol, + Imports: imports, } } @@ -337,12 +347,28 @@ func runPipeline( }) } + var ( + paths []string + resolver *deviceImportResolver + ) startTime := time.Now() - paths, err := finder.Collect(cfg.Sources) - stats.RecordWalkIo(time.Since(startTime)) - if err != nil { - ui.PrintError("Error: %v", err) - return ExitCodeInternalError + if cfg.DeviceSet { + var err error + resolver, err = newDeviceImportResolver(cfg, finder, ui) + stats.RecordWalkIo(time.Since(startTime)) + if err != nil { + ui.PrintError("Error: %v", err) + return ExitCodeInternalError + } + paths = resolver.initialPaths() + } else { + var err error + paths, err = finder.Collect(cfg.Sources) + stats.RecordWalkIo(time.Since(startTime)) + if err != nil { + ui.PrintError("Error: %v", err) + return ExitCodeInternalError + } } if len(paths) == 0 { ui.PrintNoFiles() @@ -388,6 +414,7 @@ func runPipeline( pathIdx int nextJob InputJob hasPending bool + inFlight int processClosed bool ) writeOut := writeChan @@ -419,7 +446,8 @@ func runPipeline( hasPending = true } - if !hasPending && pathIdx == len(paths) && !processClosed { + if !hasPending && pathIdx == len(paths) && inFlight == 0 && + !processClosed { close(processChan) processClosed = true } @@ -435,6 +463,7 @@ func runPipeline( writeOut = nil continue } + inFlight-- if job.SyntaxErrors { hasErrors = true report.IncrementFailed() @@ -453,6 +482,12 @@ func runPipeline( } continue } + if cfg.DeviceSet && + handleDeviceJobResult(&job, resolver, cfg, ui, &paths) { + hasErrors = true + report.IncrementFailed() + continue + } if !job.WouldReformat { if cfg.Verbose { ui.Unchanged(job.Path) @@ -475,6 +510,7 @@ func runPipeline( } report.IncrementReformatted() case processIn <- nextJob: + inFlight++ hasPending = false nextJob = InputJob{} } diff --git a/pkg/fs/lookup/boundary.go b/pkg/fs/lookup/boundary.go new file mode 100644 index 0000000..0bc15f0 --- /dev/null +++ b/pkg/fs/lookup/boundary.go @@ -0,0 +1,341 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + iofs "io/fs" + "math" + "path/filepath" + "strings" +) + +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() + + snap, ttlHit, ok := c.store.lookupDir(dir, now) + if ok && ttlHit { + return snap.meta, snap.isVCSRoot, snap.vcsPath, nil + } + + curMeta, err := c.fsys.Stat(dir) + if err != nil { + if ok { + c.store.evictDir(dir, snap.entry) + } + return FileMeta{}, false, "", err + } + + if ok && snap.meta.sameFingerprint(curMeta) { + if snap.vcsProbed && c.markersUnchanged(dir, snap.markers) { + c.store.touchDir(dir, snap.entry, now) + return snap.meta, snap.isVCSRoot, snap.vcsPath, nil + } + if !snap.vcsProbed { + isVCS, vcsPath, markers := c.probeVCSMarkers(dir) + c.store.updateDirVCS(dir, snap.entry, isVCS, vcsPath, markers, now) + return snap.meta, isVCS, vcsPath, nil + } + } + + isVCS, vcsPath, markers := c.probeVCSMarkers(dir) + c.store.saveNewDir(dir, curMeta, isVCS, vcsPath, markers, now, ok) + return curMeta, isVCS, vcsPath, nil +} + +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) EvalBoundaryRoot(boundaryRoot string) string { + if evalRoot, err := c.fsys.EvalSymlinks(boundaryRoot); err == nil { + return filepath.Clean(evalRoot) + } + return filepath.Clean(boundaryRoot) +} + +func (c *securityCache) absClean(path string) string { + if abs, err := c.fsys.Abs(path); err == nil { + return filepath.Clean(abs) + } + return filepath.Clean(path) +} + +func (c *securityCache) IsWithinBoundary( + boundaryRoot string, + targetPath string, +) bool { + if boundaryRoot == "" || targetPath == "" { + return false + } + absBoundary := c.absClean(boundaryRoot) + evalBoundary := c.EvalBoundaryRoot(absBoundary) + absTarget := c.absClean(targetPath) + + if evalTarget, err := c.fsys.EvalSymlinks(absTarget); err == nil { + cleanEval := filepath.Clean(evalTarget) + if isWithinBoundary(evalBoundary, cleanEval) { + return true + } + if !c.allowSymlinkEsc { + return false + } + } else if evalDir, dirErr := c.fsys.EvalSymlinks( + filepath.Dir(absTarget), + ); dirErr == nil { + cand := filepath.Join( + filepath.Clean(evalDir), + filepath.Base(absTarget), + ) + if isWithinBoundary(evalBoundary, cand) { + return true + } + if !c.allowSymlinkEsc { + return false + } + } + + return isWithinBoundary(absBoundary, absTarget) || + isWithinBoundary(evalBoundary, absTarget) +} + +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)) +} diff --git a/pkg/fs/lookup/cache.go b/pkg/fs/lookup/cache.go index 17e6304..4f548ba 100644 --- a/pkg/fs/lookup/cache.go +++ b/pkg/fs/lookup/cache.go @@ -7,13 +7,10 @@ import ( "errors" "fmt" iofs "io/fs" - "math" "os" "path/filepath" "slices" "strings" - "sync" - "sync/atomic" "time" ) @@ -41,6 +38,7 @@ type Cache interface { startMeta FileMeta, ) (DiscoveredFile, bool, error) EvalBoundaryRoot(boundaryRoot string) string + IsWithinBoundary(boundaryRoot, targetPath string) bool Stat(path string) (FileMeta, error) Lstat(path string) (FileMeta, error) Abs(path string) (string, error) @@ -50,39 +48,6 @@ type Cache interface { 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 @@ -95,17 +60,10 @@ type securityCache struct { 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 + store *dirStore } // NewCache creates a standalone [Cache] instance configured with the given options. @@ -116,10 +74,10 @@ func NewCache(opts ...Option) Cache { opt(&cfg) } } - return newCacheFromConfig(&cfg) + return newCacheFromConfig(&cfg.cacheCfg) } -func newCacheFromConfig(cfg *config) *securityCache { +func newCacheFromConfig(cfg *cacheConfig) *securityCache { ceilings := make(map[string]struct{}, len(cfg.ceilingDirs)*2) for _, dir := range cfg.ceilingDirs { if dir == "" { @@ -149,10 +107,9 @@ func newCacheFromConfig(cfg *config) *securityCache { ceilingDirs: ceilings, maxDepth: cfg.maxDepth, maxFileSize: cfg.maxFileSize, - cacheTTL: cfg.cacheTTL, strictSecurity: cfg.strictSecurity, onSkip: cfg.onSkip, - dirs: make(map[string]*dirCacheEntry), + store: newDirStore(cfg.cacheTTL), } } @@ -169,20 +126,11 @@ func (c *securityCache) Abs(path string) (string, error) { } 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(), - } + return c.store.stats() } func (c *securityCache) Reset() { - c.mu.Lock() - clear(c.dirs) - c.mu.Unlock() - c.invalidations.Add(1) + c.store.reset() } func (c *securityCache) Invalidate(path string) { @@ -202,379 +150,7 @@ func (c *securityCache) Invalidate(path string) { 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 + c.store.invalidateTargets(targets) } func (c *securityCache) DirEntries(dir string) ([]iofs.DirEntry, error) { @@ -584,18 +160,12 @@ func (c *securityCache) DirEntries(dir string) ([]iofs.DirEntry, error) { 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) + if entries, ttlHit, ok := c.store.lookupDirEntries( + cacheKey, + now, + ); ok && ttlHit { return entries, nil - } - c.mu.RUnlock() - - if !ok { + } else if !ok { c.ensureDirEntry(cacheKey) } @@ -608,17 +178,19 @@ func (c *securityCache) DirEntries(dir string) ([]iofs.DirEntry, error) { 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() - + c.store.saveDirEntries(cacheKey, entries, now) return entries, nil } +func (c *securityCache) ensureDirEntry(dir string) { + now := c.clock.Now() + curMeta, err := c.fsys.Stat(dir) + if err != nil { + return + } + c.store.ensureDirEntry(dir, curMeta, now) +} + func (c *securityCache) ProbeCandidate( dir string, name string, @@ -628,18 +200,12 @@ func (c *securityCache) ProbeCandidate( ) (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() + dirEntry, fentry, fOK := c.store.lookupFile(dir, name) - if fOK && c.cacheTTL > 0 && now.Sub(fentry.validatedAt) < c.cacheTTL && + if fOK && c.store.cacheTTL > 0 && + now.Sub(fentry.validatedAt) < c.store.cacheTTL && fentry.boundaryRoot == evalBoundaryRoot { - c.fileHits.Add(1) + c.store.recordFileHit() return c.resultFromCacheEntry(candidatePath, fentry) } @@ -647,19 +213,16 @@ func (c *securityCache) ProbeCandidate( 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{ + c.store.recordFileHit() + c.store.storeFile(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{ + c.store.recordFileMiss(fOK && fentry.exists) + c.store.storeFile(dir, dirEntry, name, fileCacheEntry{ validatedAt: now, exists: false, boundaryRoot: evalBoundaryRoot, @@ -667,10 +230,7 @@ func (c *securityCache) ProbeCandidate( return DiscoveredFile{}, false, nil } - if fOK && fentry.exists { - c.invalidations.Add(1) - } - c.fileMisses.Add(1) + c.store.recordFileMiss(fOK && fentry.exists) return DiscoveredFile{}, false, c.HandleSkip( candidatePath, SkipPermissionDenied, @@ -681,9 +241,9 @@ func (c *securityCache) ProbeCandidate( if fOK && fentry.exists && fentry.boundaryRoot == evalBoundaryRoot && fentry.lstatMeta.sameFingerprint(lmeta) { if !fentry.isSymlink { - c.fileHits.Add(1) + c.store.recordFileHit() fentry.validatedAt = now - c.storeFileCache(dir, dirEntry, name, fentry) + c.store.storeFile(dir, dirEntry, name, fentry) return c.resultFromCacheEntry(candidatePath, fentry) } if resolved, rerr := c.fsys.EvalSymlinks(candidatePath); rerr == nil { @@ -691,19 +251,16 @@ func (c *securityCache) ProbeCandidate( if resolved == fentry.resolvedPath { if smeta, serr := c.fsys.Stat(resolved); serr == nil && fentry.targetMeta.sameFingerprint(smeta) { - c.fileHits.Add(1) + c.store.recordFileHit() fentry.validatedAt = now - c.storeFileCache(dir, dirEntry, name, fentry) + c.store.storeFile(dir, dirEntry, name, fentry) return c.resultFromCacheEntry(candidatePath, fentry) } } } } - if fOK { - c.invalidations.Add(1) - } - c.fileMisses.Add(1) + c.store.recordFileMiss(fOK) newEntry := c.evaluateCandidate( dir, @@ -714,27 +271,10 @@ func (c *securityCache) ProbeCandidate( startMeta, now, ) - c.storeFileCache(dir, dirEntry, name, newEntry) + c.store.storeFile(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, @@ -858,26 +398,6 @@ func (c *securityCache) evaluateCandidate( 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, diff --git a/pkg/fs/lookup/cache_store.go b/pkg/fs/lookup/cache_store.go new file mode 100644 index 0000000..0f41f1f --- /dev/null +++ b/pkg/fs/lookup/cache_store.go @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + iofs "io/fs" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "time" +) + +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 dirSnapshot struct { + entry *dirCacheEntry + meta FileMeta + vcsProbed bool + isVCSRoot bool + vcsPath string + markers []vcsMarkerState +} + +type dirStore struct { + cacheTTL time.Duration + mu sync.RWMutex + dirs map[string]*dirCacheEntry + dirHits atomic.Uint64 + dirMisses atomic.Uint64 + fileHits atomic.Uint64 + fileMisses atomic.Uint64 + invalidations atomic.Uint64 +} + +func newDirStore(cacheTTL time.Duration) *dirStore { + return &dirStore{ + cacheTTL: cacheTTL, + dirs: make(map[string]*dirCacheEntry), + } +} + +func (s *dirStore) stats() CacheStats { + return CacheStats{ + DirHits: s.dirHits.Load(), + DirMisses: s.dirMisses.Load(), + FileHits: s.fileHits.Load(), + FileMisses: s.fileMisses.Load(), + Invalidations: s.invalidations.Load(), + } +} + +func (s *dirStore) reset() { + s.mu.Lock() + clear(s.dirs) + s.mu.Unlock() + s.invalidations.Add(1) +} + +func (s *dirStore) invalidateTargets(targets []string) { + var removed uint64 + s.mu.Lock() + for dir := range s.dirs { + if matchesAnyInvalidationTarget(dir, targets) { + delete(s.dirs, dir) + removed++ + } + } + s.mu.Unlock() + + if removed > 0 { + s.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 (s *dirStore) lookupDir( + dir string, + now time.Time, +) (dirSnapshot, bool, bool) { + s.mu.RLock() + entry, ok := s.dirs[dir] + if !ok { + s.mu.RUnlock() + return dirSnapshot{}, false, false + } + snap := dirSnapshot{ + entry: entry, + meta: entry.meta, + vcsProbed: entry.vcsProbed, + isVCSRoot: entry.isVCSRoot, + vcsPath: entry.vcsPath, + markers: slices.Clone(entry.markers), + } + if entry.vcsProbed && s.cacheTTL > 0 && + now.Sub(entry.validatedAt) < s.cacheTTL { + s.mu.RUnlock() + s.dirHits.Add(1) + return snap, true, true + } + s.mu.RUnlock() + return snap, false, true +} + +func (s *dirStore) touchDir( + dir string, + expected *dirCacheEntry, + now time.Time, +) { + s.mu.Lock() + if cur, exists := s.dirs[dir]; exists && cur == expected { + cur.validatedAt = now + } + s.mu.Unlock() + s.dirHits.Add(1) +} + +func (s *dirStore) updateDirVCS( + dir string, + expected *dirCacheEntry, + isVCS bool, + vcsPath string, + markers []vcsMarkerState, + now time.Time, +) { + s.mu.Lock() + if cur, exists := s.dirs[dir]; exists && cur == expected { + cur.vcsProbed = true + cur.isVCSRoot = isVCS + cur.vcsPath = vcsPath + cur.markers = markers + cur.validatedAt = now + } + s.mu.Unlock() + s.dirHits.Add(1) +} + +func (s *dirStore) evictDir(dir string, expected *dirCacheEntry) { + s.mu.Lock() + if cur, exists := s.dirs[dir]; exists && cur == expected { + delete(s.dirs, dir) + s.invalidations.Add(1) + } + s.mu.Unlock() +} + +func (s *dirStore) saveNewDir( + dir string, + meta FileMeta, + isVCS bool, + vcsPath string, + markers []vcsMarkerState, + now time.Time, + hadPrevious bool, +) { + if hadPrevious { + s.invalidations.Add(1) + } + s.dirMisses.Add(1) + newEntry := &dirCacheEntry{ + meta: meta, + vcsProbed: true, + isVCSRoot: isVCS, + vcsPath: vcsPath, + markers: markers, + validatedAt: now, + files: make(map[string]fileCacheEntry), + } + s.mu.Lock() + s.dirs[dir] = newEntry + s.mu.Unlock() +} + +func (s *dirStore) ensureDirEntry( + dir string, + curMeta FileMeta, + now time.Time, +) { + s.mu.Lock() + defer s.mu.Unlock() + if cur, exists := s.dirs[dir]; exists { + if cur.meta.sameFingerprint(curMeta) { + cur.validatedAt = now + return + } + s.invalidations.Add(1) + } + s.dirMisses.Add(1) + s.dirs[dir] = &dirCacheEntry{ + meta: curMeta, + validatedAt: now, + files: make(map[string]fileCacheEntry), + } +} + +func (s *dirStore) lookupDirEntries( + cacheKey string, + now time.Time, +) ([]iofs.DirEntry, bool, bool) { + s.mu.RLock() + entry, ok := s.dirs[cacheKey] + if ok && entry.dirEntriesCached && s.cacheTTL > 0 && + now.Sub(entry.dirEntriesAt) < s.cacheTTL { + entries := slices.Clone(entry.dirEntries) + s.mu.RUnlock() + s.dirHits.Add(1) + return entries, true, true + } + s.mu.RUnlock() + return nil, false, ok +} + +func (s *dirStore) saveDirEntries( + cacheKey string, + entries []iofs.DirEntry, + now time.Time, +) { + s.mu.Lock() + if cur, exists := s.dirs[cacheKey]; exists { + cur.dirEntries = slices.Clone(entries) + cur.dirEntriesCached = true + cur.dirEntriesAt = now + } + s.mu.Unlock() +} + +func (s *dirStore) lookupFile( + dir, name string, +) (*dirCacheEntry, fileCacheEntry, bool) { + s.mu.RLock() + dirEntry, dirOK := s.dirs[dir] + var fentry fileCacheEntry + var fOK bool + if dirOK { + fentry, fOK = dirEntry.files[name] + } + s.mu.RUnlock() + return dirEntry, fentry, fOK +} + +func (s *dirStore) storeFile( + dir string, + expectedDir *dirCacheEntry, + name string, + entry fileCacheEntry, +) { + s.mu.Lock() + cur, ok := s.dirs[dir] + if ok && (expectedDir == nil || cur == expectedDir) { + if cur.files == nil { + cur.files = make(map[string]fileCacheEntry) + } + cur.files[name] = entry + } + s.mu.Unlock() +} + +func (s *dirStore) recordFileHit() { + s.fileHits.Add(1) +} + +func (s *dirStore) recordFileMiss(invalidated bool) { + if invalidated { + s.invalidations.Add(1) + } + s.fileMisses.Add(1) +} diff --git a/pkg/fs/lookup/cache_store_test.go b/pkg/fs/lookup/cache_store_test.go new file mode 100644 index 0000000..4c4aab9 --- /dev/null +++ b/pkg/fs/lookup/cache_store_test.go @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "path/filepath" + "testing" + "time" +) + +func TestDirStore_BasicsAndStats(t *testing.T) { + store := newDirStore(100 * time.Millisecond) + + initialStats := store.stats() + if initialStats != (CacheStats{}) { + t.Fatalf("expected zero stats, got %+v", initialStats) + } + + t0 := time.Unix(1000, 0) + meta := FileMeta{Name: "dir", Mode: 0755} + store.saveNewDir("/repo", meta, true, "/repo/.git", nil, t0, false) + + stats := store.stats() + if stats.DirMisses != 1 { + t.Errorf("expected 1 DirMiss, got %d", stats.DirMisses) + } + + snap, ttlHit, ok := store.lookupDir("/repo", t0.Add(50*time.Millisecond)) + if !ok || !ttlHit { + t.Fatalf("expected TTL hit, got ok=%v, ttlHit=%v", ok, ttlHit) + } + if snap.meta.Name != "dir" || !snap.isVCSRoot || + snap.vcsPath != "/repo/.git" { + t.Errorf("unexpected snapshot: %+v", snap) + } + + stats = store.stats() + if stats.DirHits != 1 { + t.Errorf("expected 1 DirHit, got %d", stats.DirHits) + } + + // After TTL expires: + _, ttlHit, ok = store.lookupDir("/repo", t0.Add(200*time.Millisecond)) + if !ok || ttlHit { + t.Errorf("expected expired TTL hit, got ok=%v, ttlHit=%v", ok, ttlHit) + } + + store.touchDir("/repo", snap.entry, t0.Add(250*time.Millisecond)) + stats = store.stats() + if stats.DirHits != 2 { + t.Errorf("expected 2 DirHits after touchDir, got %d", stats.DirHits) + } + + store.updateDirVCS( + "/repo", + snap.entry, + false, + "", + nil, + t0.Add(260*time.Millisecond), + ) + stats = store.stats() + if stats.DirHits != 3 { + t.Errorf("expected 3 DirHits after updateDirVCS, got %d", stats.DirHits) + } + + store.reset() + stats = store.stats() + if stats.Invalidations != 1 { + t.Errorf( + "expected 1 invalidation after reset, got %d", + stats.Invalidations, + ) + } + + _, _, ok = store.lookupDir("/repo", t0.Add(300*time.Millisecond)) + if ok { + t.Error("expected dir to be evicted after reset") + } +} + +func TestDirStore_InvalidateTargets(t *testing.T) { + store := newDirStore(0) + t0 := time.Unix(1000, 0) + m := FileMeta{Mode: 0755} + + store.saveNewDir(filepath.Clean("/repo"), m, false, "", nil, t0, false) + store.saveNewDir(filepath.Clean("/repo/sub"), m, false, "", nil, t0, false) + store.saveNewDir( + filepath.Clean("/repo/sub/deep"), + m, + false, + "", + nil, + t0, + false, + ) + store.saveNewDir(filepath.Clean("/other"), m, false, "", nil, t0, false) + + // Invalidate /repo/sub/deep -> affects /repo/sub/deep and its parent /repo/sub + store.invalidateTargets([]string{filepath.Clean("/repo/sub/deep")}) + + _, _, okDeep := store.lookupDir(filepath.Clean("/repo/sub/deep"), t0) + _, _, okSub := store.lookupDir(filepath.Clean("/repo/sub"), t0) + _, _, okRepo := store.lookupDir(filepath.Clean("/repo"), t0) + _, _, okOther := store.lookupDir(filepath.Clean("/other"), t0) + + if okDeep || okSub { + t.Errorf( + "expected deep and sub to be evicted: okDeep=%v, okSub=%v", + okDeep, + okSub, + ) + } + if !okRepo || !okOther { + t.Errorf( + "expected repo and other to remain: okRepo=%v, okOther=%v", + okRepo, + okOther, + ) + } +} + +func TestDirStore_FileCacheAndCounters(t *testing.T) { + store := newDirStore(100 * time.Millisecond) + t0 := time.Unix(1000, 0) + + store.saveNewDir("/repo", FileMeta{Mode: 0755}, false, "", nil, t0, false) + dirEntry, _, ok := store.lookupFile("/repo", "file.txt") + if ok || dirEntry == nil { + t.Fatalf( + "expected no file, but dirEntry present: ok=%v, dirEntry=%v", + ok, + dirEntry, + ) + } + + fe := fileCacheEntry{ + validatedAt: t0, + exists: true, + discovered: DiscoveredFile{Path: "/repo/file.txt", Name: "file.txt"}, + } + store.storeFile("/repo", dirEntry, "file.txt", fe) + + _, gotFE, ok := store.lookupFile("/repo", "file.txt") + if !ok || gotFE.discovered.Path != "/repo/file.txt" { + t.Fatalf("expected file to be found, got ok=%v, fe=%+v", ok, gotFE) + } + + store.recordFileHit() + store.recordFileMiss(true) + stats := store.stats() + if stats.FileHits != 1 || stats.FileMisses != 1 || + stats.Invalidations != 1 { + t.Errorf("unexpected file stats: %+v", stats) + } +} diff --git a/pkg/fs/lookup/collect.go b/pkg/fs/lookup/collect.go new file mode 100644 index 0000000..8835756 --- /dev/null +++ b/pkg/fs/lookup/collect.go @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "fmt" + iofs "io/fs" + "path/filepath" + "slices" +) + +type collectContext struct { + rootSrc string + boundaryRoot string + evalBoundaryRoot string + startMeta FileMeta + seen map[string]bool + files *[]string +} + +type ignoreStackInfo struct { + stack []IgnoreRuleSet + boundaryRoot string + evalBoundaryRoot string + startMeta FileMeta + startDir string + absStart string + isFile bool +} + +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() { + igInfo, initErr := f.initCollectIgnoreStack(src) + if initErr != nil { + return nil, initErr + } + stack = igInfo.stack + ctx.boundaryRoot = igInfo.boundaryRoot + ctx.evalBoundaryRoot = igInfo.evalBoundaryRoot + ctx.startMeta = igInfo.startMeta + absSrc = igInfo.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) MatchIgnore(path string) (string, error) { + if !f.ignoreEnabled() { + return "", nil + } + info, err := f.initCollectIgnoreStack(path) + if err != nil { + return "", err + } + if len(info.stack) == 0 { + return "", nil + } + return f.ignoreMatcher.Match( + info.stack, + info.absStart, + !info.isFile, + ), nil +} + +func (f *fileFinder) initCollectIgnoreStack( + src string, +) (ignoreStackInfo, error) { + startDir, absStart, isFile, startMeta, err := f.cache.ResolveStart(src) + if err != nil { + return ignoreStackInfo{}, err + } + + dirs, boundary, resolvedMeta, err := f.cache.ResolveDirChain( + startDir, + startMeta, + ) + if err != nil { + return ignoreStackInfo{}, 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 ignoreStackInfo{}, loadErr + } + stack = append(stack, loaded...) + } + + return ignoreStackInfo{ + stack: stack, + boundaryRoot: boundary.RootDir, + evalBoundaryRoot: evalBoundaryRoot, + startMeta: resolvedMeta, + startDir: startDir, + absStart: absStart, + isFile: isFile, + }, 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 +} diff --git a/pkg/fs/lookup/filter.go b/pkg/fs/lookup/filter.go index 33a9b77..68fdb7d 100644 --- a/pkg/fs/lookup/filter.go +++ b/pkg/fs/lookup/filter.go @@ -35,10 +35,10 @@ func NewFilter(opts ...Option) (Filter, error) { opt(&cfg) } } - return newFilterFromConfig(&cfg) + return newFilterFromConfig(&cfg.filterCfg) } -func newFilterFromConfig(cfg *config) (*regexFilter, error) { +func newFilterFromConfig(cfg *filterConfig) (*regexFilter, error) { var err error var incRe, excRe, extRe, forceRe *regexp.Regexp diff --git a/pkg/fs/lookup/finder.go b/pkg/fs/lookup/finder.go index d11da0e..1927a53 100644 --- a/pkg/fs/lookup/finder.go +++ b/pkg/fs/lookup/finder.go @@ -5,7 +5,6 @@ package lookup import ( "fmt" - iofs "io/fs" "path/filepath" "slices" "sync" @@ -31,6 +30,11 @@ type Finder interface { // from the provided source files and directories. Collect(sources []string) ([]string, error) + // MatchIgnore evaluates configured ignore files (.gitignore, .ignore) for + // path within its resolved boundary, returning the matching ignore file + // name or an empty string if not ignored. + MatchIgnore(path string) (string, error) + // SetOnIgnore registers the callback invoked when Collect skips a path // due to inclusion or exclusion filters. SetOnIgnore(cb IgnoreCallback) @@ -63,7 +67,7 @@ func NewFinder(opts ...Option) (Finder, error) { f := cfg.filter if f == nil { - rf, err := newFilterFromConfig(&cfg) + rf, err := newFilterFromConfig(&cfg.filterCfg) if err != nil { return nil, err } @@ -72,12 +76,12 @@ func NewFinder(opts ...Option) (Finder, error) { c := cfg.cache if c == nil { - c = newCacheFromConfig(&cfg) + c = newCacheFromConfig(&cfg.cacheCfg) } im := cfg.ignoreMatcher if im == nil && len(cfg.ignoreFiles) > 0 { - im = newIgnoreMatcherFromConfig(&cfg) + im = newIgnoreMatcher(cfg.cacheCfg.fsys) } return &fileFinder{ @@ -223,284 +227,6 @@ func (f *fileFinder) FindNearest( 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, diff --git a/pkg/fs/lookup/ignore.go b/pkg/fs/lookup/ignore.go index c160e4b..d11cf35 100644 --- a/pkg/fs/lookup/ignore.go +++ b/pkg/fs/lookup/ignore.go @@ -4,9 +4,7 @@ package lookup import ( - "bytes" "path/filepath" - "regexp" "slices" "strings" "sync" @@ -27,12 +25,6 @@ type IgnoreMatcher interface { 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 @@ -56,12 +48,12 @@ func NewIgnoreMatcher(opts ...Option) IgnoreMatcher { opt(&cfg) } } - return newIgnoreMatcherFromConfig(&cfg) + return newIgnoreMatcher(cfg.cacheCfg.fsys) } -func newIgnoreMatcherFromConfig(cfg *config) *gitignoreMatcher { +func newIgnoreMatcher(fsys FileSystem) *gitignoreMatcher { return &gitignoreMatcher{ - fsys: cfg.fsys, + fsys: fsys, cache: make(map[string]cachedRuleSet), } } @@ -249,215 +241,3 @@ func relUnderBaseDir(baseDir, fullPath string) (string, bool) { } 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/ignore_parser.go b/pkg/fs/lookup/ignore_parser.go new file mode 100644 index 0000000..adb1062 --- /dev/null +++ b/pkg/fs/lookup/ignore_parser.go @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "bytes" + "regexp" + "slices" + "strings" +) + +type ignoreRule struct { + regex *regexp.Regexp + negate bool + dirOnly bool +} + +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/ignore_parser_test.go b/pkg/fs/lookup/ignore_parser_test.go new file mode 100644 index 0000000..1ba905c --- /dev/null +++ b/pkg/fs/lookup/ignore_parser_test.go @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package lookup + +import ( + "slices" + "testing" +) + +func TestParseIgnoreLine(t *testing.T) { + tests := []struct { + name string + raw string + wantOK bool + wantNeg bool + wantDir bool + wantAnchor bool + }{ + {"empty", "", false, false, false, false}, + {"comment", "# just a comment", false, false, false, false}, + {"spaces only", " \r", false, false, false, false}, + {"simple file", "foo.txt", true, false, false, false}, + {"negated file", "!foo.txt", true, true, false, false}, + {"dir only", "build/", true, false, true, false}, + {"negated dir only", "!build/", true, true, true, false}, + {"anchored path", "pkg/foo.txt", true, false, false, false}, + {"leading slash anchored", "/root.txt", true, false, false, false}, + {"escaped space", `hello\ world.txt `, true, false, false, false}, + {"trailing slash only", "/", false, false, false, false}, + {"negation only", "!", false, false, false, false}, + {"escaped hash", `\#hash.dml`, true, false, false, false}, + {"escaped exclamation", `\!bang.dml`, true, false, false, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rule, ok := parseIgnoreLine(tt.raw) + if ok != tt.wantOK { + t.Fatalf( + "parseIgnoreLine(%q) ok = %v, want %v", + tt.raw, + ok, + tt.wantOK, + ) + } + if !ok { + return + } + if rule.negate != tt.wantNeg { + t.Errorf("rule.negate = %v, want %v", rule.negate, tt.wantNeg) + } + if rule.dirOnly != tt.wantDir { + t.Errorf("rule.dirOnly = %v, want %v", rule.dirOnly, tt.wantDir) + } + if rule.regex == nil { + t.Error("rule.regex should not be nil") + } + }) + } +} + +func TestParseIgnoreRules(t *testing.T) { + data := []byte("# comment\nfoo.dml\n\n!bar.dml\nbuild/\n") + rules := parseIgnoreRules(data) + if len(rules) != 3 { + t.Fatalf("expected 3 rules, got %d", len(rules)) + } + if rules[0].negate || rules[0].dirOnly { + t.Errorf("rule[0] unexpected flags: %+v", rules[0]) + } + if !rules[1].negate || rules[1].dirOnly { + t.Errorf("rule[1] unexpected flags: %+v", rules[1]) + } + if rules[2].negate || !rules[2].dirOnly { + t.Errorf("rule[2] unexpected flags: %+v", rules[2]) + } +} + +func TestTrimUnescapedTrailingSpaces(t *testing.T) { + tests := []struct { + input string + want string + }{ + {"abc ", "abc"}, + {`abc\ `, `abc\ `}, + {`abc\\ `, `abc\\`}, + {`abc\\\ `, `abc\\\ `}, + {"abc", "abc"}, + {" ", ""}, + } + for _, tt := range tests { + got := trimUnescapedTrailingSpaces(tt.input) + if got != tt.want { + t.Errorf( + "trimUnescapedTrailingSpaces(%q) = %q, want %q", + tt.input, + got, + tt.want, + ) + } + } +} + +func TestCompileGitignoreGlob_Patterns(t *testing.T) { + tests := []struct { + pattern string + anchored bool + match []string + noMatch []string + }{ + { + pattern: "**", + anchored: false, + match: []string{"a", "a/b", "a/b/c"}, + noMatch: nil, + }, + { + pattern: "*.txt", + anchored: false, + match: []string{"file.txt", "a/b/c.txt"}, + noMatch: []string{"file.txt2", "file.log"}, + }, + { + pattern: "foo/*.txt", + anchored: true, + match: []string{"foo/a.txt"}, + noMatch: []string{"bar/foo/a.txt", "foo/sub/a.txt"}, + }, + { + pattern: "**/build", + anchored: true, + match: []string{"build", "a/build", "a/b/build"}, + noMatch: []string{"builder", "a/build/nested"}, + }, + { + pattern: "a/**/b", + anchored: true, + match: []string{"a/b", "a/x/b", "a/x/y/b"}, + noMatch: []string{"a/b/c", "x/a/b"}, + }, + { + pattern: "file[12].dml", + anchored: false, + match: []string{"file1.dml", "file2.dml", "sub/file1.dml"}, + noMatch: []string{"file3.dml", "file.dml"}, + }, + { + pattern: "only[!1].dml", + anchored: false, + match: []string{"only2.dml", "only3.dml"}, + noMatch: []string{"only1.dml"}, + }, + { + pattern: "char?.dml", + anchored: false, + match: []string{"chara.dml", "char1.dml"}, + noMatch: []string{"charab.dml", "char/.dml"}, + }, + { + pattern: `esc\ .dml`, + anchored: false, + match: []string{"esc .dml"}, + noMatch: []string{"esc.dml", "esc .dml"}, + }, + { + pattern: `box/**`, + anchored: true, + match: []string{"box/a", "box/a/b"}, + noMatch: []string{"box", "boxer"}, + }, + } + + for _, tt := range tests { + t.Run(tt.pattern, func(t *testing.T) { + re, err := compileGitignoreGlob(tt.pattern, tt.anchored) + if err != nil { + t.Fatalf("compileGitignoreGlob(%q) failed: %v", tt.pattern, err) + } + for _, m := range tt.match { + if !re.MatchString(m) { + t.Errorf("pattern %q should match %q", tt.pattern, m) + } + } + for _, nm := range tt.noMatch { + if re.MatchString(nm) { + t.Errorf("pattern %q should NOT match %q", tt.pattern, nm) + } + } + }) + } +} + +func TestNormalizeIgnoreFileNames(t *testing.T) { + input := []string{".gitignore", "", ".ignore", ".gitignore", ".custom"} + got := normalizeIgnoreFileNames(input) + want := []string{".gitignore", ".ignore", ".custom"} + if !slices.Equal(got, want) { + t.Errorf("normalizeIgnoreFileNames got %v, want %v", got, want) + } + + if normalizeIgnoreFileNames(nil) != nil { + t.Error("expected nil for empty slice") + } +} diff --git a/pkg/fs/lookup/lookup_test.go b/pkg/fs/lookup/lookup_test.go deleted file mode 100644 index 96d5230..0000000 --- a/pkg/fs/lookup/lookup_test.go +++ /dev/null @@ -1,1630 +0,0 @@ -// 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 index 5609719..36bef5a 100644 --- a/pkg/fs/lookup/options.go +++ b/pkg/fs/lookup/options.go @@ -5,17 +5,17 @@ package lookup import "time" -type config struct { - cache Cache - filter Filter - ignoreMatcher IgnoreMatcher - +type filterConfig struct { + fsys FileSystem includePattern string excludePattern string extendExcludePattern string forceExcludePattern string - ignoreFiles []string +} +type cacheConfig struct { + fsys FileSystem + clock Clock vcsMarkers []string stopAtVCSRoot bool stopAtMountPoint bool @@ -28,23 +28,39 @@ type config struct { cacheTTL time.Duration strictSecurity bool onSkip SkipCallback - onIgnore IgnoreCallback - fsys FileSystem - clock Clock +} + +type config struct { + cache Cache + filter Filter + ignoreMatcher IgnoreMatcher + + filterCfg filterConfig + cacheCfg cacheConfig + + ignoreFiles []string + onIgnore IgnoreCallback } func defaultConfig() config { + fsys := NewOSFileSystem() + clock := realClock{} return config{ - vcsMarkers: []string{VCSMarkerGit, VCSMarkerHg}, - stopAtVCSRoot: true, - stopAtMountPoint: true, - verifyOwnership: true, - allowSymlinks: true, - allowSymlinkEsc: false, - maxDepth: DefaultMaxDepth, - maxFileSize: DefaultMaxFileSize, - fsys: NewOSFileSystem(), - clock: realClock{}, + filterCfg: filterConfig{ + fsys: fsys, + }, + cacheCfg: cacheConfig{ + fsys: fsys, + clock: clock, + vcsMarkers: []string{VCSMarkerGit, VCSMarkerHg}, + stopAtVCSRoot: true, + stopAtMountPoint: true, + verifyOwnership: true, + allowSymlinks: true, + allowSymlinkEsc: false, + maxDepth: DefaultMaxDepth, + maxFileSize: DefaultMaxFileSize, + }, } } @@ -84,28 +100,28 @@ func WithIgnoreFiles(names ...string) Option { // WithInclude sets the regular expression matching paths to include. func WithInclude(pattern string) Option { return func(c *config) { - c.includePattern = pattern + c.filterCfg.includePattern = pattern } } // WithExclude sets the regular expression matching paths to exclude. func WithExclude(pattern string) Option { return func(c *config) { - c.excludePattern = pattern + c.filterCfg.excludePattern = pattern } } // WithExtendExclude sets an additional regular expression matching paths to exclude. func WithExtendExclude(pattern string) Option { return func(c *config) { - c.extendExcludePattern = pattern + c.filterCfg.extendExcludePattern = pattern } } // WithForceExclude sets the regular expression matching paths to forcibly exclude. func WithForceExclude(pattern string) Option { return func(c *config) { - c.forceExcludePattern = pattern + c.filterCfg.forceExcludePattern = pattern } } @@ -118,49 +134,49 @@ func WithVCSMarkers(markers ...string) Option { filtered = append(filtered, m) } } - c.vcsMarkers = filtered + c.cacheCfg.vcsMarkers = filtered } } // WithStopAtVCSRoot controls whether upward traversal stops at VCS roots. func WithStopAtVCSRoot(enabled bool) Option { return func(c *config) { - c.stopAtVCSRoot = enabled + c.cacheCfg.stopAtVCSRoot = enabled } } // WithStopAtMountPoint controls whether upward traversal stops at mount boundaries. func WithStopAtMountPoint(enabled bool) Option { return func(c *config) { - c.stopAtMountPoint = enabled + c.cacheCfg.stopAtMountPoint = enabled } } // WithVerifyOwnership controls whether upward traversal verifies directory UIDs. func WithVerifyOwnership(enabled bool) Option { return func(c *config) { - c.verifyOwnership = enabled + c.cacheCfg.verifyOwnership = enabled } } // WithAllowSymlinks controls whether symlinked utility files are followed. func WithAllowSymlinks(allow bool) Option { return func(c *config) { - c.allowSymlinks = allow + c.cacheCfg.allowSymlinks = allow } } // WithAllowSymlinkEscape controls whether symlinks may resolve outside the boundary root. func WithAllowSymlinkEscape(allow bool) Option { return func(c *config) { - c.allowSymlinkEsc = allow + c.cacheCfg.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...) + c.cacheCfg.ceilingDirs = append([]string(nil), dirs...) } } @@ -168,7 +184,7 @@ func WithCeilingDirs(dirs ...string) Option { func WithMaxDepth(depth int) Option { return func(c *config) { if depth >= 0 { - c.maxDepth = depth + c.cacheCfg.maxDepth = depth } } } @@ -177,7 +193,7 @@ func WithMaxDepth(depth int) Option { // Non-positive values disable the size limit. func WithMaxFileSize(maxBytes int64) Option { return func(c *config) { - c.maxFileSize = maxBytes + c.cacheCfg.maxFileSize = maxBytes } } @@ -186,7 +202,7 @@ func WithMaxFileSize(maxBytes int64) Option { func WithCacheTTL(ttl time.Duration) Option { return func(c *config) { if ttl >= 0 { - c.cacheTTL = ttl + c.cacheCfg.cacheTTL = ttl } } } @@ -195,14 +211,14 @@ func WithCacheTTL(ttl time.Duration) Option { // return a [*SecurityError] instead of skipping the file. func WithStrictSecurity(strict bool) Option { return func(c *config) { - c.strictSecurity = strict + c.cacheCfg.strictSecurity = strict } } // WithOnSkip registers a callback notified whenever a candidate is skipped. func WithOnSkip(cb SkipCallback) Option { return func(c *config) { - c.onSkip = cb + c.cacheCfg.onSkip = cb } } @@ -217,7 +233,8 @@ func WithOnIgnore(cb IgnoreCallback) Option { func WithFileSystem(fsys FileSystem) Option { return func(c *config) { if fsys != nil { - c.fsys = fsys + c.filterCfg.fsys = fsys + c.cacheCfg.fsys = fsys } } } @@ -226,7 +243,7 @@ func WithFileSystem(fsys FileSystem) Option { func WithClock(clock Clock) Option { return func(c *config) { if clock != nil { - c.clock = clock + c.cacheCfg.clock = clock } } } diff --git a/test/fs/lookup/cache_test.go b/test/fs/lookup/cache_test.go new file mode 100644 index 0000000..a691137 --- /dev/null +++ b/test/fs/lookup/cache_test.go @@ -0,0 +1,722 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_lookup + +import ( + "errors" + iofs "io/fs" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +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 := lookup.NewFinder(lookup.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 != lookup.BoundaryVCSRoot || + b.RootDir != filepath.Clean("/outer/worktree") { + t.Fatalf("unexpected boundary: %+v", b) + } + + chain, err := finder.FindChain( + "/outer/worktree/sub", + lookup.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 := lookup.NewCache(lookup.WithFileSystem(m)) + b, err := c1.ResolveBoundary("/proj/src") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != lookup.BoundaryVCSRoot || + b.RootDir != filepath.Clean("/proj") { + t.Fatalf("expected /proj vcs boundary, got %+v", b) + } + + c2 := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithVCSMarkers(".jj"), + ) + cb, err := c2.ResolveBoundary("/proj/src") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if cb.Reason != lookup.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 := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithStopAtVCSRoot(false), + ) + b, err := c.ResolveBoundary("/repo/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != lookup.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 := lookup.NewCache(lookup.WithFileSystem(m)) + b, err := c.ResolveBoundary("/mnt/usb/proj/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != lookup.BoundaryMountPoint || + b.RootDir != filepath.Clean("/mnt/usb") { + t.Fatalf("expected BoundaryMountPoint at /mnt/usb, got %+v", b) + } + + noMount := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithStopAtMountPoint(false), + ) + b2, err := noMount.ResolveBoundary("/mnt/usb/proj/sub") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b2.Reason != lookup.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 := lookup.NewCache(lookup.WithFileSystem(m)) + b, err := c.ResolveBoundary("/shared/otheruser/myproj") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b.Reason != lookup.BoundaryOwnership || + b.RootDir != filepath.Clean("/shared/otheruser/myproj") { + t.Fatalf("expected BoundaryOwnership, got %+v", b) + } + + noOwn := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithVerifyOwnership(false), + ) + b2, err := noOwn.ResolveBoundary("/shared/otheruser/myproj") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if b2.Reason != lookup.BoundaryFilesystemRoot { + t.Fatalf("expected BoundaryFilesystemRoot, got %+v", b2) + } + }) + + t.Run("ceiling dir and max depth", func(t *testing.T) { + m := buildMockRepo(now) + ceilCache := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithCeilingDirs("/repo/sub"), + ) + cb, err := ceilCache.ResolveBoundary("/repo/sub/deep") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if cb.Reason != lookup.BoundaryCeiling || + cb.RootDir != filepath.Clean("/repo/sub") { + t.Fatalf("expected BoundaryCeiling at /repo/sub, got %+v", cb) + } + + depthCache := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithMaxDepth(0), + ) + db, err := depthCache.ResolveBoundary("/repo/sub/deep") + if err != nil { + t.Fatalf("ResolveBoundary failed: %v", err) + } + if db.Reason != lookup.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 []lookup.Option + wantReason lookup.SkipReason + }{ + { + name: "directory instead of regular file", + setup: func(m *mockFS) string { + m.setDir("/repo/.editorconfig", 1, 1000, now) + return "/repo/.editorconfig" + }, + wantReason: lookup.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: lookup.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: lookup.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: lookup.SkipNotRegular, + }, + { + name: "oversized file", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setFile(p, 0644, 2048, 1, 1000, now) + return p + }, + opts: []lookup.Option{lookup.WithMaxFileSize(1024)}, + wantReason: lookup.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: []lookup.Option{lookup.WithAllowSymlinks(false)}, + wantReason: lookup.SkipSymlinkDisabled, + }, + { + name: "broken symlink", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setSymlink(p, "/repo/missing.cfg", 1, 1000, now) + return p + }, + wantReason: lookup.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: lookup.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: lookup.SkipSymlinkCrossDevice, + }, + { + name: "permission denied", + setup: func(m *mockFS) string { + p := "/repo/.editorconfig" + m.setStatErr(p, iofs.ErrPermission) + return p + }, + wantReason: lookup.SkipPermissionDenied, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := buildMockRepo(now) + target := tc.setup(m) + + var skips []lookup.SkipReason + opts := append([]lookup.Option{}, tc.opts...) + opts = append( + opts, + lookup.WithFileSystem(m), + lookup.WithOnSkip(func(p string, r lookup.SkipReason, _ error) { + if p == filepath.Clean(target) { + skips = append(skips, r) + } + }), + ) + + finder, err := lookup.NewFinder(opts...) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + got, err := finder.FindChain("/repo/sub", lookup.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([]lookup.Option{}, tc.opts...) + strictOpts = append( + strictOpts, + lookup.WithFileSystem(m), + lookup.WithStrictSecurity(true), + ) + strictFinder, err := lookup.NewFinder(strictOpts...) + if err != nil { + t.Fatalf("NewFinder strict failed: %v", err) + } + _, err = strictFinder.FindChain( + "/repo/sub", + lookup.FileEditorConfig, + ) + var secErr *lookup.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 := lookup.NewFinder(lookup.WithFileSystem(m)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + files, err := finder.FindChain("/repo/sub", lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithAllowSymlinkEscape(true), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + escFiles, err := allowEsc.FindChain("/repo/sub", lookup.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 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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithClock(clk), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + files, err := finder.FindChain("/repo/sub", lookup.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", lookup.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", lookup.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", lookup.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", lookup.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", lookup.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", lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithClock(clk), + lookup.WithCacheTTL(5*time.Second), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + if _, err := finder.FindChain( + "/repo/sub", + lookup.FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain failed: %v", err) + } + m.resetStatCalls() + + clk.Advance(2 * time.Second) + if _, err := finder.FindChain( + "/repo/sub", + lookup.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", + lookup.FileEditorConfig, + ); err != nil { + t.Fatalf("FindChain failed: %v", err) + } + + clk.Advance(10 * time.Second) + finder.Cache().Reset() + if _, err := finder.FindChain( + "/repo/sub", + lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithClock(clk), + lookup.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", + lookup.FileEditorConfig, + lookup.FileGitIgnore, + ) + _, _, _ = finder.FindNearest( + "/repo/sub/deep", + lookup.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 := []lookup.BoundaryReason{ + lookup.BoundaryNone, + lookup.BoundaryFilesystemRoot, + lookup.BoundaryVCSRoot, + lookup.BoundaryMountPoint, + lookup.BoundaryOwnership, + lookup.BoundaryCeiling, + lookup.BoundaryMaxDepth, + lookup.BoundaryReason(99), + } + for _, r := range reasons { + if r.String() == "" { + t.Errorf("empty String for BoundaryReason %d", r) + } + } + + skips := []lookup.SkipReason{ + lookup.SkipNotRegular, + lookup.SkipFileTooLarge, + lookup.SkipSymlinkDisabled, + lookup.SkipBrokenSymlink, + lookup.SkipSymlinkEscape, + lookup.SkipSymlinkCrossDevice, + lookup.SkipPermissionDenied, + lookup.SkipExcluded, + lookup.SkipReason(99), + } + for _, s := range skips { + if s.String() == "" { + t.Errorf("empty String for SkipReason %d", s) + } + } + + inner := errors.New("boom") + se := &lookup.SecurityError{ + Path: "/a", + Reason: lookup.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 := &lookup.SecurityError{ + Path: "/a", + Reason: lookup.SkipNotRegular, + } + if seNoErr.Error() == "" { + t.Error("expected non-empty Error() without inner err") + } +} + +func TestCacheIsWithinBoundary(t *testing.T) { + t0 := time.Unix(1700000000, 0) + m := buildMockRepo(t0) + m.setFile("/repo/sub/deep/main.dml", 0644, 10, 1, 1000, t0) + m.setFile("/outside/ext.dml", 0644, 10, 1, 1000, t0) + m.setSymlink("/repo/sub/escape.dml", "/outside/ext.dml", 1, 1000, t0) + m.setSymlink( + "/repo/sub/internal.dml", + "/repo/sub/deep/main.dml", + 1, + 1000, + t0, + ) + + c := lookup.NewCache(lookup.WithFileSystem(m)) + if !c.IsWithinBoundary("/repo", "/repo/sub/deep/main.dml") { + t.Error("expected main.dml to be within /repo boundary") + } + if !c.IsWithinBoundary("/repo", "main.dml") { + t.Error( + "expected relative main.dml (cwd=/repo/sub/deep) to be within /repo", + ) + } + if c.IsWithinBoundary("/repo", "/outside/ext.dml") { + t.Error("expected /outside/ext.dml to be outside /repo boundary") + } + if c.IsWithinBoundary("/repo", "/repo/sub/escape.dml") { + t.Error("expected escaping symlink to be outside /repo boundary") + } + if !c.IsWithinBoundary("/repo", "/repo/sub/internal.dml") { + t.Error("expected internal symlink to be within /repo boundary") + } + if c.IsWithinBoundary("", "/repo/sub/deep/main.dml") || + c.IsWithinBoundary("/repo", "") { + t.Error("expected empty boundary or target to return false") + } + + cEsc := lookup.NewCache( + lookup.WithFileSystem(m), + lookup.WithAllowSymlinkEscape(true), + ) + if !cEsc.IsWithinBoundary("/repo", "/repo/sub/escape.dml") { + t.Error("expected escaping symlink allowed when allowSymlinkEsc=true") + } +} diff --git a/test/fs/lookup/filter_test.go b/test/fs/lookup/filter_test.go new file mode 100644 index 0000000..19ab3bb --- /dev/null +++ b/test/fs/lookup/filter_test.go @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_lookup + +import ( + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +func TestRegexFiltersAndIncludeDiscovery(t *testing.T) { + now := time.Unix(1700000000, 0) + + t.Run("invalid regex errors", func(t *testing.T) { + bad := []struct { + opt lookup.Option + flag string + }{ + {lookup.WithInclude("["), lookup.FilterInclude}, + {lookup.WithExclude("["), lookup.FilterExclude}, + {lookup.WithExtendExclude("["), lookup.FilterExtendExclude}, + {lookup.WithForceExclude("["), lookup.FilterForceExclude}, + } + for _, tc := range bad { + _, err := lookup.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 := lookup.NewFilter( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithExclude(`/venv/`), + lookup.WithExtendExclude(`/custom/`), + lookup.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 != lookup.FilterForceExclude { + t.Errorf("got %q, want %q", got, lookup.FilterForceExclude) + } + if got := flt.MatchExclude( + "venv/x.dml", + "/repo/venv/x.dml", + false, + ); got != lookup.FilterExclude { + t.Errorf("got %q, want %q", got, lookup.FilterExclude) + } + if got := flt.MatchExclude( + "custom/x.dml", + "/repo/custom/x.dml", + false, + ); got != lookup.FilterExtendExclude { + t.Errorf("got %q, want %q", got, lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.cfg$`), + lookup.WithExclude(`/venv/`), + lookup.WithExtendExclude(`skip\.cfg$`), + lookup.WithStrictSecurity(true), + lookup.WithOnSkip( + func(path string, reason lookup.SkipReason, _ error) { + if reason == lookup.SkipExcluded { + skipped = append(skipped, path) + } + }, + ), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + chain, err := finder.FindChain( + "/repo/venv", + lookup.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", + lookup.FileEditorConfig, + ) + if err != nil || found || res.Path != "" { + t.Fatalf( + "expected excluded start file to return empty, got (%+v, %v, %v)", + res, + found, + err, + ) + } + }) +} diff --git a/test/fs/lookup/finder_test.go b/test/fs/lookup/finder_test.go new file mode 100644 index 0000000..e325c4f --- /dev/null +++ b/test/fs/lookup/finder_test.go @@ -0,0 +1,235 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_lookup + +import ( + "path/filepath" + "slices" + "testing" + "time" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +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 := lookup.NewCache(lookup.WithFileSystem(m)) + filter, err := lookup.NewFilter( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithExclude(`/\.git/`), + ) + if err != nil { + t.Fatalf("NewFilter failed: %v", err) + } + if !filter.HasInclude() { + t.Fatal("expected filter.HasInclude() to be true") + } + + finder1, err := lookup.NewFinder( + lookup.WithCache(cache), + lookup.WithFilter(filter), + ) + if err != nil { + t.Fatalf("NewFinder 1 failed: %v", err) + } + finder2, err := lookup.NewFinder( + lookup.WithCache(cache), + lookup.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", + lookup.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 := lookup.NewFinder(lookup.WithFileSystem(m)) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + chain, err := finder.FindChain( + "/repo/sub/deep/main.dml", + lookup.FileEditorConfig, + lookup.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", + lookup.FileEditorConfig, + lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithExclude(`/(\.git|venv)/`), + lookup.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: lookup.FilterInclude, + }) { + t.Errorf( + "expected b.txt to trigger %s ignore event, got %+v", + lookup.FilterInclude, + ignored, + ) + } + if !slices.Contains(ignored, ignoredEvent{ + path: filepath.Clean("/ws/venv"), + isDir: true, + filter: lookup.FilterExclude, + }) { + t.Errorf( + "expected venv dir to trigger %s ignore event, got %+v", + lookup.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, + ) + } +} diff --git a/test/fs/lookup/ignore_test.go b/test/fs/lookup/ignore_test.go new file mode 100644 index 0000000..33b1a1a --- /dev/null +++ b/test/fs/lookup/ignore_test.go @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_lookup + +import ( + "errors" + iofs "io/fs" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +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 := lookup.NewIgnoreMatcher(lookup.WithFileSystem(m)) + + rs, err := matcher.LoadFile(lookup.DiscoveredFile{ + Path: "/repo/.gitignore", + Dir: "/repo", + Name: lookup.FileGitIgnore, + }) + if err != nil { + t.Fatalf("LoadFile failed: %v", err) + } + stack := []lookup.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 != lookup.FileGitIgnore { + t.Errorf( + "Match(%q) = %q, want %q", + p, + got, + lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.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 := lookup.NewIgnoreMatcher(lookup.WithFileSystem(m)) + finder, err := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithIgnoreMatcher(matcher), + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithStrictSecurity(true), + lookup.WithIgnoreFiles(lookup.FileGitIgnore), + ) + if err != nil { + t.Fatalf("NewFinder strict failed: %v", err) + } + _, err = strictFinder.Collect([]string{"/repo"}) + var secErr *lookup.SecurityError + if !errors.As(err, &secErr) || secErr.Reason != lookup.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 := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithInclude(`\.dml$`), + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.FileIgnore), + lookup.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: lookup.FileGitIgnore, + } + if !slices.Contains(events, wantEvent) { + t.Fatalf("expected ignore event %+v, got %+v", wantEvent, events) + } + }) +} + +func TestFinderMatchIgnore(t *testing.T) { + t0 := time.Unix(1700000000, 0) + m := buildMockRepo(t0) + m.setFileWithContent( + "/repo/.gitignore", + []byte("*.gen.dml\nbuild/\n"), + 1, + 1000, + t0, + ) + m.setFileWithContent( + "/repo/sub/.gitignore", + []byte("!keep.gen.dml\n"), + 1, + 1000, + t0, + ) + m.setDir("/repo/build", 1, 1000, t0) + m.setFile("/repo/build/a.dml", 0644, 10, 1, 1000, t0) + m.setFile("/repo/sub/skip.gen.dml", 0644, 10, 1, 1000, t0) + m.setFile("/repo/sub/keep.gen.dml", 0644, 10, 1, 1000, t0) + m.setFile("/repo/sub/deep/main.dml", 0644, 10, 1, 1000, t0) + + finder, err := lookup.NewFinder( + lookup.WithFileSystem(m), + lookup.WithIgnoreFiles(lookup.FileGitIgnore, lookup.FileIgnore), + ) + if err != nil { + t.Fatalf("NewFinder failed: %v", err) + } + + cases := []struct { + path string + want string + }{ + {"/repo/sub/deep/main.dml", ""}, + {"/repo/sub/keep.gen.dml", ""}, + {"/repo/sub/skip.gen.dml", lookup.FileGitIgnore}, + {"/repo/build/a.dml", lookup.FileGitIgnore}, + } + for _, tc := range cases { + got, matchErr := finder.MatchIgnore(tc.path) + if matchErr != nil { + t.Fatalf("MatchIgnore(%s) failed: %v", tc.path, matchErr) + } + if got != tc.want { + t.Errorf("MatchIgnore(%s) = %q, want %q", tc.path, got, tc.want) + } + } +} diff --git a/test/fs/lookup/mock_fs_test.go b/test/fs/lookup/mock_fs_test.go new file mode 100644 index 0000000..042306c --- /dev/null +++ b/test/fs/lookup/mock_fs_test.go @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Copyright (C) 2026 Sergei Timoshchenko + +package test_lookup + +import ( + "errors" + iofs "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/timoschenko/dmltools/pkg/fs/lookup" +) + +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 lookup.FileMeta + symlinkTo string + content []byte + statErr error + lstatErr error + readDirErr error + readFileErr error + evalOverride string +} + +type mockDirEntry struct { + name string + mode iofs.FileMode + meta lookup.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 lookup.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: lookup.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: lookup.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: lookup.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: lookup.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) (lookup.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 lookup.FileMeta{}, os.ErrNotExist + } + if n.statErr != nil { + return lookup.FileMeta{}, n.statErr + } + if n.symlinkTo == "" { + return n.meta, nil + } + clean = n.symlinkTo + } + return lookup.FileMeta{}, errors.New("too many levels of symbolic links") +} + +func (m *mockFS) Lstat(path string) (lookup.FileMeta, error) { + m.mu.Lock() + defer m.mu.Unlock() + clean := m.absLocked(path) + m.statCalls[clean]++ + n, ok := m.nodes[clean] + if !ok { + return lookup.FileMeta{}, os.ErrNotExist + } + if n.lstatErr != nil { + return lookup.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 +} diff --git a/test/fs/lookup_test.go b/test/fs/lookup/real_fs_test.go similarity index 99% rename from test/fs/lookup_test.go rename to test/fs/lookup/real_fs_test.go index c633fbf..cf0400d 100644 --- a/test/fs/lookup_test.go +++ b/test/fs/lookup/real_fs_test.go @@ -1,7 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only // Copyright (C) 2026 Sergei Timoshchenko -package test_fs +package test_lookup import ( "errors" diff --git a/test/fs/lookup_unix_test.go b/test/fs/lookup/real_fs_unix_test.go similarity index 97% rename from test/fs/lookup_unix_test.go rename to test/fs/lookup/real_fs_unix_test.go index e229ce3..7d707a5 100644 --- a/test/fs/lookup_unix_test.go +++ b/test/fs/lookup/real_fs_unix_test.go @@ -3,7 +3,7 @@ //go:build unix -package test_fs +package test_lookup import ( "errors"