diff --git a/assets/lore/commands.md b/assets/lore/commands.md index de37077..821ad74 100644 --- a/assets/lore/commands.md +++ b/assets/lore/commands.md @@ -5,7 +5,7 @@ - `cat` — Display file contents - `head` / `tail` — First/last N lines - `tree` — Directory tree visualization -- `find` — Find files by name or type +- `find` — Find files by name (`-name`, `-iname`), full path (`-path`, `-ipath`), type (`-type`), or depth (`-maxdepth`, `-mindepth`); use `find --help` - `stat` — File metadata - `wc` — Count lines, words, bytes - `du` — File space usage diff --git a/docs/reference/commands.md b/docs/reference/commands.md index cb0ac49..9aeb27c 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -78,7 +78,14 @@ Directories retain a trailing `/`, hidden entries appear only after an explicit | Command | Description | |---|---| | `grep` | Search patterns (`-E`, `-F`, `-i`, `-n`, `-r`, `-R`, `-o`, `-h`, `-c`, `-v`, `-l`); use `-E 'a|b'` for multiple patterns | -| `find` | Find files (`-name`, `-type f\|d\|l`). Alias docsets are links: `find` lists each file once under its canonical path; add `-L` to also walk aliases | +| `find` | Find files (`-name pat`, `-iname pat`, `-path pat`, `-ipath pat`, `-type f\|d\|l`, `-maxdepth N`, `-mindepth N`). Alias docsets are links: `find` lists each file once under its canonical path; add `-L` to also walk aliases | + +`find` ANDs its predicates. `-iname` and `-ipath` ignore case; `-path` and +`-ipath` match the full virtual path, with wildcards matching slashes too. +Quote patterns to prevent shell glob expansion. Depth is relative to the +starting point (depth 0); `-maxdepth 0` visits only that point, and +`-mindepth 1` excludes it. Depth limits must be non-negative integers. +Use `find --help` or `help find` for the supported options. ## Text processing diff --git a/pkg/shell/cmds/find.go b/pkg/shell/cmds/find.go index 090fa55..b1eac51 100644 --- a/pkg/shell/cmds/find.go +++ b/pkg/shell/cmds/find.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "path" + "strconv" "strings" "github.com/aakarim/go-openlore/pkg/vfs" @@ -12,36 +13,53 @@ import ( func CmdFind(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin io.Reader) int { root := ctx.Cwd() var namePattern string - var typeFilter string + var predicates []struct{ flag, pattern string } + minDepth, maxDepth := 0, -1 followAliases := false matchedResults := 0 matchedFiles := 0 for i := 0; i < len(args); i++ { switch args[i] { + case "--help": + return CmdHelp(ctx, []string{"find"}, w, errW, stdin) case "-L": followAliases = true - case "-name": + case "-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", "-mindepth": + flag := args[i] if i+1 >= len(args) { - fmt.Fprintln(errW, "find: option requires an argument -- 'name'") + fmt.Fprintf(errW, "find: option requires an argument -- '%s'\n", flag[1:]) return 1 } - namePattern = args[i+1] + value := args[i+1] i++ - case "-type": - if i+1 >= len(args) { - fmt.Fprintln(errW, "find: option requires an argument -- 'type'") - return 1 + if flag == "-maxdepth" || flag == "-mindepth" { + depth, err := strconv.Atoi(value) + if err != nil || value == "" || strings.Trim(value, "0123456789") != "" { + fmt.Fprintf(errW, "find: invalid depth '%s' for %s; expected a non-negative integer\n", value, flag) + return 1 + } + if flag == "-maxdepth" { + maxDepth = depth + } else { + minDepth = depth + } + continue } - typeFilter = args[i+1] - if typeFilter != "f" && typeFilter != "d" && typeFilter != "l" { - fmt.Fprintf(errW, "find: unsupported type '%s'. This shell supports -type f|d|l.\n", typeFilter) + if flag == "-type" && value != "f" && value != "d" && value != "l" { + fmt.Fprintf(errW, "find: unsupported type '%s'. This shell supports -type f|d|l.\n", value) return 1 } - i++ + if flag == "-name" || flag == "-iname" { + namePattern = value + } + if flag == "-iname" || flag == "-ipath" { + value = strings.ToLower(value) + } + predicates = append(predicates, struct{ flag, pattern string }{flag, value}) default: if strings.HasPrefix(args[i], "-") { - fmt.Fprintf(errW, "find: unsupported flag '%s'. This shell supports [-L] [path] [-name pat] [-type f|d|l]. To limit depth, use 'tree -L '.\n", args[i]) + fmt.Fprintf(errW, "find: unsupported flag '%s'. Use 'find --help' for supported options, including -maxdepth N.\n", args[i]) return 1 } root = ctx.Resolve(args[i]) @@ -49,8 +67,8 @@ func CmdFind(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin i } root = vfs.CleanPath(root) - var walk func(p string, info *vfs.FileInfo) - walk = func(p string, info *vfs.FileInfo) { + var walk func(p string, info *vfs.FileInfo, depth int) + walk = func(p string, info *vfs.FileInfo, depth int) { // Like find -P, an alias root below the starting point is reported as // a link and not descended into, so each file is listed once. -L // follows aliases; a starting point is always followed, like find -H. @@ -61,9 +79,27 @@ func CmdFind(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin i } else if info.Dir { kind = "d" } - matched := typeFilter == "" || typeFilter == kind - if matched && namePattern != "" { - matched, _ = path.Match(namePattern, info.FileName) + matched := depth >= minDepth + for _, predicate := range predicates { + if !matched { + break + } + if predicate.flag == "-type" { + matched = predicate.pattern == kind + continue + } + value := info.FileName + if predicate.flag == "-path" || predicate.flag == "-ipath" { + value = p + } + if predicate.flag == "-iname" || predicate.flag == "-ipath" { + value = strings.ToLower(value) + } + if predicate.flag == "-path" || predicate.flag == "-ipath" { + matched = findPathMatch(predicate.pattern, value) + } else { + matched, _ = path.Match(predicate.pattern, value) + } } if matched { fmt.Fprintln(w, p) @@ -72,7 +108,7 @@ func CmdFind(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin i matchedFiles++ } } - if kind != "d" { + if kind != "d" || (maxDepth >= 0 && depth >= maxDepth) { return } entries, err := ctx.FS().ReadDir(p) @@ -82,15 +118,68 @@ func CmdFind(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin i for _, entry := range entries { childPath := path.Join(p, entry.FileName) if child, err := ctx.FS().Stat(childPath); err == nil { - walk(childPath, child) + walk(childPath, child, depth+1) } } } if info, err := ctx.FS().Stat(root); err == nil { - walk(root, info) + walk(root, info, 0) } if namePattern != "" { emitSearchMetric(ctx, namePattern, []string{root}, matchedFiles, 0, matchedResults > 0) } return 0 } + +// findPathMatch uses path.Match's syntax, but lets * and ? match slashes. +// Character classes are matched unchanged so ranges retain their membership. +func findPathMatch(pattern, name string) bool { + if _, err := path.Match(pattern, ""); err != nil { + return false + } + var tokens []string + for p := []rune(pattern); len(p) > 0; { + end := 1 + switch p[0] { + case '\\': + end = 2 + case '[': + for p[end] != ']' { + if p[end] == '\\' { + end++ + } + end++ + } + end++ + } + tokens = append(tokens, string(p[:end])) + p = p[end:] + } + chars := []rune(name) + i, j, star, retry := 0, 0, -1, 0 + for j < len(chars) { + if i < len(tokens) && tokens[i] == "*" { + star, retry = i, j + i++ + continue + } + if i < len(tokens) { + matched, _ := path.Match(tokens[i], string(chars[j])) + if tokens[i] == "?" || matched { + i++ + j++ + continue + } + } + if star < 0 { + return false + } + // Extend the most recent star by one character and retry its suffix. + retry++ + i, j = star+1, retry + } + for i < len(tokens) && tokens[i] == "*" { + i++ + } + return i == len(tokens) +} diff --git a/pkg/shell/cmds/find_test.go b/pkg/shell/cmds/find_test.go index 2a1b297..721f28f 100644 --- a/pkg/shell/cmds/find_test.go +++ b/pkg/shell/cmds/find_test.go @@ -1,6 +1,7 @@ package cmds_test import ( + "slices" "strings" "testing" ) @@ -20,7 +21,7 @@ func TestFindTypeDir(t *testing.T) { } func TestFindRejectsUnsupportedFlag(t *testing.T) { - for _, flag := range []string{"-maxdepth", "-mindepth", "-exec"} { + for _, flag := range []string{"-exec", "-delete", "-unknown"} { t.Run(flag, func(t *testing.T) { out, errOut, code := execCmd(t, testFS(), "find /docs "+flag+" 1 -type f") if code != 1 { @@ -32,8 +33,8 @@ func TestFindRejectsUnsupportedFlag(t *testing.T) { if !strings.Contains(errOut, "unsupported flag '"+flag+"'") { t.Errorf("stderr = %q, want unsupported flag name", errOut) } - if !strings.Contains(errOut, "tree -L ") { - t.Errorf("stderr = %q, want supported depth-limiting alternative", errOut) + if !strings.Contains(errOut, "-maxdepth N") { + t.Errorf("stderr = %q, want supported options", errOut) } }) } @@ -46,6 +47,15 @@ func TestFindValidatesOptionArguments(t *testing.T) { wantErr string }{ {name: "missing name pattern", command: "find /docs -name", wantErr: "option requires an argument -- 'name'"}, + {name: "missing iname pattern", command: "find /docs -iname", wantErr: "option requires an argument -- 'iname'"}, + {name: "missing path pattern", command: "find /docs -path", wantErr: "option requires an argument -- 'path'"}, + {name: "missing ipath pattern", command: "find /docs -ipath", wantErr: "option requires an argument -- 'ipath'"}, + {name: "missing maxdepth", command: "find /docs -maxdepth", wantErr: "option requires an argument -- 'maxdepth'"}, + {name: "missing mindepth", command: "find /docs -mindepth", wantErr: "option requires an argument -- 'mindepth'"}, + {name: "negative depth", command: "find /docs -maxdepth -1", wantErr: "invalid depth '-1'"}, + {name: "nonnumeric depth", command: "find /docs -mindepth abc", wantErr: "invalid depth 'abc'"}, + {name: "empty depth", command: "find /docs -maxdepth ''", wantErr: "invalid depth ''"}, + {name: "overflow depth", command: "find /docs -maxdepth 99999999999999999999999", wantErr: "invalid depth"}, {name: "missing type", command: "find /docs -type", wantErr: "option requires an argument -- 'type'"}, {name: "unsupported type", command: "find /docs -type -maxdepth", wantErr: "unsupported type '-maxdepth'"}, } { @@ -77,6 +87,82 @@ func TestFindAllowsDashPrefixedNamePattern(t *testing.T) { } } +func TestFindPredicates(t *testing.T) { + fs := newMapFS() + fs.AddDir("/") + fs.AddDir("/Skills") + fs.AddDir("/Skills/nested") + fs.AddFile("/Skills/SKILL.md", "root skill\n") + fs.AddFile("/Skills/nested/SKILL.md", "nested skill\n") + fs.AddFile("/Skills/nested/notes.txt", "notes\n") + fs.AddFile("/Skills/nested/é.md", "unicode\n") + fs.AddFile("/Skills/nested/].txt", "bracket\n") + fs.AddFile("/Skills/skill.MD", "other case\n") + fs.AddFile("/Skills/-", "dash\n") + for _, tt := range []struct{ args, want string }{ + {"/Skills -iname 'skill.md'", "/Skills/SKILL.md\n/Skills/nested/SKILL.md\n/Skills/skill.MD\n"}, + {"/Skills -name 'skill.md'", ""}, + {"/ -path '*Skills*' -name SKILL.md", "/Skills/SKILL.md\n/Skills/nested/SKILL.md\n"}, + {"/ -path '*/SKILL.md'", "/Skills/SKILL.md\n/Skills/nested/SKILL.md\n"}, + {"/ -path '*/skills/*'", ""}, + {"/ -ipath '*/skills/*' -iname 'skill.md'", "/Skills/SKILL.md\n/Skills/nested/SKILL.md\n/Skills/skill.MD\n"}, + {"/ -path '/Skills/?KILL.[mM][dD]'", "/Skills/SKILL.md\n"}, + {"/ -path '[.-0]Skills'", "/Skills\n"}, + {"/ -ipath '[.-0]skills'", "/Skills\n"}, + {"/Skills -path '/Skills/[/-z]'", ""}, + {"/Skills -ipath '/skills/[/-z]'", ""}, + {"/ -path '?Skills'", "/Skills\n"}, + {"/ -path '[^a-z]Skills'", "/Skills\n"}, + {"/ -path '[^.-0]Skills'", ""}, + {"/ -path '/Skills/\\-*'", "/Skills/-\n"}, + {"/ -path '*n*e*/*.md' -name SKILL.md", "/Skills/nested/SKILL.md\n"}, + {"/ -path '*é.?d'", "/Skills/nested/é.md\n"}, + {"/ -path '*/[é].md'", "/Skills/nested/é.md\n"}, + {"/ -path '*/[\\]].txt'", "/Skills/nested/].txt\n"}, + {"/ -path '*/\\].txt'", "/Skills/nested/].txt\n"}, + {"/ -path '[broken'", ""}, + {"/ -path '*/nested' -type f", ""}, + {"/Skills -iname '*.md' -name 'S*' -path '*/nested/*'", "/Skills/nested/SKILL.md\n"}, + {"/Skills -name SKILL.md -name notes.txt", ""}, + {"/Skills -name ''", ""}, + {"/Skills -path ''", ""}, + {"/Skills -maxdepth 0", "/Skills\n"}, + {"/Skills -maxdepth 1 -type d", "/Skills\n/Skills/nested\n"}, + {"/Skills -mindepth 1 -maxdepth 1 -iname '*.md'", "/Skills/SKILL.md\n/Skills/skill.MD\n"}, + {"/Skills -mindepth 2 -maxdepth 2 -name SKILL.md", "/Skills/nested/SKILL.md\n"}, + {"/Skills -mindepth 2 -maxdepth 1", ""}, + {"/Skills/SKILL.md -maxdepth 0", "/Skills/SKILL.md\n"}, + {"/Skills/SKILL.md -mindepth 1", ""}, + {"/ -maxdepth 0", "/\n"}, + {"-maxdepth 0", "/\n"}, + {"/Skills/ -maxdepth 0", "/Skills\n"}, + } { + t.Run(tt.args, func(t *testing.T) { + out, errs, code := execCmd(t, fs, "find "+tt.args) + got, want := strings.Split(out, "\n"), strings.Split(tt.want, "\n") + slices.Sort(got) + slices.Sort(want) + if code != 0 || errs != "" || !slices.Equal(got, want) { + t.Fatalf("code=%d stderr=%q stdout=%q; want %q", code, errs, out, tt.want) + } + }) + } +} + +func TestFindHelp(t *testing.T) { + for _, command := range []string{"help find", "find --help"} { + out, errs, code := execCmd(t, testFS(), command) + if code != 0 || errs != "" { + t.Fatalf("%s: code=%d stderr=%q", command, code, errs) + } + for _, flag := range []string{"-iname", "-path", "-ipath", "-maxdepth", "-mindepth"} { + if !strings.Contains(out, flag) { + t.Errorf("%s missing %s: %q", command, flag, out) + } + } + } +} + func TestGlobExpansion(t *testing.T) { fs := testFS() fs.AddFile("/docs/.hidden.md", "hidden\n") diff --git a/pkg/shell/cmds/help.go b/pkg/shell/cmds/help.go index 0ed1bcb..6c0f1b4 100644 --- a/pkg/shell/cmds/help.go +++ b/pkg/shell/cmds/help.go @@ -63,7 +63,10 @@ func CmdHelp(ctx CmdContext, args []string, w io.Writer, errW io.Writer, stdin i fmt.Fprintln(w, "SEARCH") fmt.Fprintln(w, " grep [-EFinrRohcvl] [path] Search for pattern in files") fmt.Fprintln(w, " Basic regex by default; -E extended regex; -F fixed strings; use -E 'a|b' for multiple patterns") - fmt.Fprintln(w, " find [-L] [path] [-name pat] [-type f|d|l] Find files (-L follows aliases)") + fmt.Fprintln(w, " find [-L] [path] [-name pat|-iname pat] [-type f|d|l] Find files (-L follows aliases)") + fmt.Fprintln(w, " -path pat / -ipath pat match full virtual paths; -iname / -ipath ignore case") + fmt.Fprintln(w, " -maxdepth N / -mindepth N limit depth (starting point is 0); predicates are ANDed") + fmt.Fprintln(w, " Quote patterns; path wildcards match slashes; find --help shows this entry") fmt.Fprintln(w, "") fmt.Fprintln(w, "TEXT PROCESSING") fmt.Fprintln(w, " sort [-r|-n|-u|-f|-k N|-t SEP] Sort lines")