62159
Sy
symb / files
symb / internal / filesearch / filesearch.go
4.4 KB
1// Package filesearch provides file and content search with fuzzy matching and gitignore support. 2package filesearch 3 4import ( 5 "bufio" 6 "context" 7 "fmt" 8 "os" 9 "path/filepath" 10 "regexp" 11 "strings" 12) 13 14// Result represents a single search result. 15type Result struct { 16 Path string // Relative path from search root 17 Line int // Line number (1-indexed), 0 for file-only matches 18 Content string // Line content, empty for file-only matches 19} 20 21// Options configures the search behavior. 22type Options struct { 23 Pattern string // Pattern to search for (filename or content) 24 ContentSearch bool // If true, search file contents; otherwise just filenames 25 MaxResults int // Maximum results to return (0 = unlimited) 26 CaseSensitive bool // Case-sensitive matching 27 RootDir string // Root directory to search from (defaults to current dir) 28} 29 30// Searcher performs file and content searches. 31type Searcher struct { 32 gitignore *GitignoreMatcher 33} 34 35// NewSearcher creates a new searcher for the given root directory. 36func NewSearcher(rootDir string) (*Searcher, error) { 37 gitignorePath := filepath.Join(rootDir, ".gitignore") 38 matcher, err := NewGitignoreMatcher(gitignorePath) 39 if err != nil { 40 // Non-fatal: just won't filter gitignored files 41 matcher, _ = NewGitignoreMatcher("") 42 } 43 44 return &Searcher{ 45 gitignore: matcher, 46 }, nil 47} 48 49// Search performs a search with the given options. 50func (s *Searcher) Search(ctx context.Context, opts Options) ([]Result, error) { 51 if opts.RootDir == "" { 52 var err error 53 opts.RootDir, err = os.Getwd() 54 if err != nil { 55 return nil, fmt.Errorf("get working directory: %w", err) 56 } 57 } 58 59 pattern := opts.Pattern 60 if !opts.CaseSensitive { 61 pattern = "(?i)" + pattern 62 } 63 64 regex, err := regexp.Compile(pattern) 65 if err != nil { 66 return nil, fmt.Errorf("invalid pattern: %w", err) 67 } 68 69 var results []Result 70 err = filepath.WalkDir(opts.RootDir, func(path string, d os.DirEntry, walkErr error) error { 71 if walkErr != nil { 72 return nil 73 } 74 select { 75 case <-ctx.Done(): 76 return ctx.Err() 77 default: 78 } 79 if skip := s.shouldSkip(path, d, opts.RootDir); skip != nil { 80 return *skip 81 } 82 matches := s.matchEntry(path, opts.RootDir, regex, opts.ContentSearch) 83 results = append(results, matches...) 84 if opts.MaxResults > 0 && len(results) >= opts.MaxResults { 85 return filepath.SkipAll 86 } 87 return nil 88 }) 89 90 if err != nil && err != filepath.SkipAll { 91 return nil, err 92 } 93 return results, nil 94} 95 96const maxSearchFileSize = 10 * 1024 * 1024 // 10 MB 97 98// shouldSkip decides whether to skip a directory entry. Returns nil to proceed, 99// or a pointer to the error to return from the walk callback. 100func (s *Searcher) shouldSkip(path string, d os.DirEntry, rootDir string) *error { 101 relPath, err := filepath.Rel(rootDir, path) 102 if err != nil { 103 skip := error(nil) 104 return &skip 105 } 106 if d.IsDir() && d.Name() == ".git" { 107 skip := filepath.SkipDir 108 return &skip 109 } 110 if s.gitignore.Matches(relPath, d.IsDir()) { 111 if d.IsDir() { 112 skip := filepath.SkipDir 113 return &skip 114 } 115 skip := error(nil) 116 return &skip 117 } 118 if d.IsDir() { 119 skip := error(nil) 120 return &skip 121 } 122 info, err := d.Info() 123 if err != nil || info.Size() > maxSearchFileSize { 124 skip := error(nil) 125 return &skip 126 } 127 return nil 128} 129 130// matchEntry checks a single file against the search pattern. 131func (s *Searcher) matchEntry(path, rootDir string, regex *regexp.Regexp, contentSearch bool) []Result { 132 relPath, _ := filepath.Rel(rootDir, path) 133 if contentSearch { 134 matches, err := s.searchFileContent(path, relPath, regex) 135 if err != nil { 136 return nil 137 } 138 return matches 139 } 140 if regex.MatchString(filepath.Base(path)) || regex.MatchString(relPath) { 141 return []Result{{Path: relPath}} 142 } 143 return nil 144} 145 146// searchFileContent searches a single file for pattern matches. 147func (s *Searcher) searchFileContent(absPath, relPath string, regex *regexp.Regexp) ([]Result, error) { 148 file, err := os.Open(absPath) 149 if err != nil { 150 return nil, err 151 } 152 defer file.Close() 153 154 var results []Result 155 scanner := bufio.NewScanner(file) 156 lineNum := 0 157 158 for scanner.Scan() { 159 lineNum++ 160 line := scanner.Text() 161 162 // Skip binary files (heuristic: check for null bytes) 163 if strings.Contains(line, "\x00") { 164 return nil, nil 165 } 166 167 if regex.MatchString(line) { 168 results = append(results, Result{ 169 Path: relPath, 170 Line: lineNum, 171 Content: line, 172 }) 173 } 174 } 175 176 if err := scanner.Err(); err != nil { 177 return nil, err 178 } 179 180 return results, nil 181}