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 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	rootPath  string
112}
113
114func NewFastGlobWalker(searchPath string) *FastGlobWalker {
115	walker := &FastGlobWalker{
116		rootPath: searchPath,
117	}
118
119	// Load gitignore if it exists
120	gitignorePath := filepath.Join(searchPath, ".gitignore")
121	if _, err := os.Stat(gitignorePath); err == nil {
122		if gi, err := ignore.CompileIgnoreFile(gitignorePath); err == nil {
123			walker.gitignore = gi
124		}
125	}
126
127	return walker
128}
129
130func (w *FastGlobWalker) shouldSkip(path string) bool {
131	if SkipHidden(path) {
132		return true
133	}
134
135	if w.gitignore != nil {
136		relPath, err := filepath.Rel(w.rootPath, path)
137		if err == nil && w.gitignore.MatchesPath(relPath) {
138			return true
139		}
140	}
141
142	return false
143}
144
145func GlobWithDoubleStar(pattern, searchPath string, limit int) ([]string, bool, error) {
146	walker := NewFastGlobWalker(searchPath)
147	var matches []FileInfo
148	conf := fastwalk.Config{
149		Follow: true,
150		// Use forward slashes when running a Windows binary under WSL or MSYS
151		ToSlash: fastwalk.DefaultToSlash(),
152		Sort:    fastwalk.SortFilesFirst,
153	}
154	err := fastwalk.Walk(&conf, searchPath, func(path string, d os.DirEntry, err error) error {
155		if err != nil {
156			return nil // Skip files we can't access
157		}
158
159		if d.IsDir() {
160			if walker.shouldSkip(path) {
161				return filepath.SkipDir
162			}
163			return nil
164		}
165
166		if walker.shouldSkip(path) {
167			return nil
168		}
169
170		// Check if path matches the pattern
171		relPath, err := filepath.Rel(searchPath, path)
172		if err != nil {
173			relPath = path
174		}
175
176		matched, err := doublestar.Match(pattern, relPath)
177		if err != nil || !matched {
178			return nil
179		}
180
181		info, err := d.Info()
182		if err != nil {
183			return nil
184		}
185
186		matches = append(matches, FileInfo{Path: path, ModTime: info.ModTime()})
187		if limit > 0 && len(matches) >= limit*2 {
188			return filepath.SkipAll
189		}
190		return nil
191	})
192	if err != nil {
193		return nil, false, fmt.Errorf("fastwalk error: %w", err)
194	}
195
196	sort.Slice(matches, func(i, j int) bool {
197		return matches[i].ModTime.After(matches[j].ModTime)
198	})
199
200	truncated := false
201	if limit > 0 && len(matches) > limit {
202		matches = matches[:limit]
203		truncated = true
204	}
205
206	results := make([]string, len(matches))
207	for i, m := range matches {
208		results[i] = m.Path
209	}
210	return results, truncated, nil
211}
212
213func PrettyPath(path string) string {
214	// replace home directory with ~
215	homeDir, err := os.UserHomeDir()
216	if err == nil {
217		path = strings.ReplaceAll(path, homeDir, "~")
218	}
219	return path
220}
221
222func DirTrim(pwd string, lim int) string {
223	var (
224		out string
225		sep = string(filepath.Separator)
226	)
227	dirs := strings.Split(pwd, sep)
228	if lim > len(dirs)-1 || lim <= 0 {
229		return pwd
230	}
231	for i := len(dirs) - 1; i > 0; i-- {
232		out = sep + out
233		if i == len(dirs)-1 {
234			out = dirs[i]
235		} else if i >= len(dirs)-lim {
236			out = string(dirs[i][0]) + out
237		} else {
238			out = "..." + out
239			break
240		}
241	}
242	out = filepath.Join("~", out)
243	return out
244}