fileutil.go

  1package fsext
  2
  3import (
  4	"fmt"
  5	"log/slog"
  6	"os"
  7	"os/exec"
  8	"path/filepath"
  9	"sort"
 10	"strings"
 11	"time"
 12
 13	"github.com/bmatcuk/doublestar/v4"
 14	"github.com/charlievieth/fastwalk"
 15	"github.com/charmbracelet/crush/internal/log"
 16
 17	ignore "github.com/sabhiram/go-gitignore"
 18)
 19
 20var rgPath string
 21
 22func init() {
 23	var err error
 24	rgPath, err = exec.LookPath("rg")
 25	if err != nil {
 26		if log.Initialized() {
 27			slog.Warn("Ripgrep (rg) not found in $PATH. Some grep features might be limited or slower.")
 28		}
 29	}
 30}
 31
 32func GetRgCmd(globPattern string) *exec.Cmd {
 33	if rgPath == "" {
 34		return nil
 35	}
 36	rgArgs := []string{
 37		"--files",
 38		"-L",
 39		"--null",
 40	}
 41	if globPattern != "" {
 42		if !filepath.IsAbs(globPattern) && !strings.HasPrefix(globPattern, "/") {
 43			globPattern = "/" + globPattern
 44		}
 45		rgArgs = append(rgArgs, "--glob", globPattern)
 46	}
 47	return exec.Command(rgPath, rgArgs...)
 48}
 49
 50func GetRgSearchCmd(pattern, path, include string) *exec.Cmd {
 51	if rgPath == "" {
 52		return nil
 53	}
 54	// Use -n to show line numbers and include the matched line
 55	args := []string{"-H", "-n", pattern}
 56	if include != "" {
 57		args = append(args, "--glob", include)
 58	}
 59	args = append(args, path)
 60
 61	return exec.Command(rgPath, args...)
 62}
 63
 64type FileInfo struct {
 65	Path    string
 66	ModTime time.Time
 67}
 68
 69func SkipHidden(path string) bool {
 70	// Check for hidden files (starting with a dot)
 71	base := filepath.Base(path)
 72	if base != "." && strings.HasPrefix(base, ".") {
 73		return true
 74	}
 75
 76	commonIgnoredDirs := map[string]bool{
 77		".crush":           true,
 78		"node_modules":     true,
 79		"vendor":           true,
 80		"dist":             true,
 81		"build":            true,
 82		"target":           true,
 83		".git":             true,
 84		".idea":            true,
 85		".vscode":          true,
 86		"__pycache__":      true,
 87		"bin":              true,
 88		"obj":              true,
 89		"out":              true,
 90		"coverage":         true,
 91		"tmp":              true,
 92		"temp":             true,
 93		"logs":             true,
 94		"generated":        true,
 95		"bower_components": true,
 96		"jspm_packages":    true,
 97	}
 98
 99	parts := strings.SplitSeq(path, string(os.PathSeparator))
100	for part := range parts {
101		if commonIgnoredDirs[part] {
102			return true
103		}
104	}
105	return false
106}
107
108// FastGlobWalker provides gitignore-aware file walking with fastwalk
109type FastGlobWalker struct {
110	gitignore   *ignore.GitIgnore
111	crushignore *ignore.GitIgnore
112	rootPath    string
113}
114
115func NewFastGlobWalker(searchPath string) *FastGlobWalker {
116	walker := &FastGlobWalker{
117		rootPath: searchPath,
118	}
119
120	// Load gitignore if it exists
121	gitignorePath := filepath.Join(searchPath, ".gitignore")
122	if _, err := os.Stat(gitignorePath); err == nil {
123		if gi, err := ignore.CompileIgnoreFile(gitignorePath); err == nil {
124			walker.gitignore = gi
125		}
126	}
127
128	// Load crushignore if it exists
129	crushignorePath := filepath.Join(searchPath, ".crushignore")
130	if _, err := os.Stat(crushignorePath); err == nil {
131		if ci, err := ignore.CompileIgnoreFile(crushignorePath); err == nil {
132			walker.crushignore = ci
133		}
134	}
135
136	return walker
137}
138
139func (w *FastGlobWalker) shouldSkip(path string) bool {
140	if SkipHidden(path) {
141		return true
142	}
143
144	relPath, err := filepath.Rel(w.rootPath, path)
145	if err != nil {
146		return false
147	}
148
149	if w.gitignore != nil {
150		if w.gitignore.MatchesPath(relPath) {
151			return true
152		}
153	}
154
155	if w.crushignore != nil {
156		if w.crushignore.MatchesPath(relPath) {
157			return true
158		}
159	}
160
161	return false
162}
163
164func GlobWithDoubleStar(pattern, searchPath string, limit int) ([]string, bool, error) {
165	walker := NewFastGlobWalker(searchPath)
166	var matches []FileInfo
167	conf := fastwalk.Config{
168		Follow: true,
169		// Use forward slashes when running a Windows binary under WSL or MSYS
170		ToSlash: fastwalk.DefaultToSlash(),
171		Sort:    fastwalk.SortFilesFirst,
172	}
173	err := fastwalk.Walk(&conf, searchPath, func(path string, d os.DirEntry, err error) error {
174		if err != nil {
175			return nil // Skip files we can't access
176		}
177
178		if d.IsDir() {
179			if walker.shouldSkip(path) {
180				return filepath.SkipDir
181			}
182			return nil
183		}
184
185		if walker.shouldSkip(path) {
186			return nil
187		}
188
189		// Check if path matches the pattern
190		relPath, err := filepath.Rel(searchPath, path)
191		if err != nil {
192			relPath = path
193		}
194
195		matched, err := doublestar.Match(pattern, relPath)
196		if err != nil || !matched {
197			return nil
198		}
199
200		info, err := d.Info()
201		if err != nil {
202			return nil
203		}
204
205		matches = append(matches, FileInfo{Path: path, ModTime: info.ModTime()})
206		if limit > 0 && len(matches) >= limit*2 {
207			return filepath.SkipAll
208		}
209		return nil
210	})
211	if err != nil {
212		return nil, false, fmt.Errorf("fastwalk error: %w", err)
213	}
214
215	sort.Slice(matches, func(i, j int) bool {
216		return matches[i].ModTime.After(matches[j].ModTime)
217	})
218
219	truncated := false
220	if limit > 0 && len(matches) > limit {
221		matches = matches[:limit]
222		truncated = true
223	}
224
225	results := make([]string, len(matches))
226	for i, m := range matches {
227		results[i] = m.Path
228	}
229	return results, truncated, nil
230}
231
232func PrettyPath(path string) string {
233	// replace home directory with ~
234	homeDir, err := os.UserHomeDir()
235	if err == nil {
236		path = strings.ReplaceAll(path, homeDir, "~")
237	}
238	return path
239}
240
241func DirTrim(pwd string, lim int) string {
242	var (
243		out string
244		sep = string(filepath.Separator)
245	)
246	dirs := strings.Split(pwd, sep)
247	if lim > len(dirs)-1 || lim <= 0 {
248		return pwd
249	}
250	for i := len(dirs) - 1; i > 0; i-- {
251		out = sep + out
252		if i == len(dirs)-1 {
253			out = dirs[i]
254		} else if i >= len(dirs)-lim {
255			out = string(dirs[i][0]) + out
256		} else {
257			out = "..." + out
258			break
259		}
260	}
261	out = filepath.Join("~", out)
262	return out
263}