fileutil.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package fsext
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "slices"
  8. "strings"
  9. "time"
  10. "github.com/bmatcuk/doublestar/v4"
  11. "github.com/charlievieth/fastwalk"
  12. "github.com/charmbracelet/crush/internal/csync"
  13. "github.com/charmbracelet/crush/internal/home"
  14. )
  15. type FileInfo struct {
  16. Path string
  17. ModTime time.Time
  18. }
  19. func SkipHidden(path string) bool {
  20. // Check for hidden files (starting with a dot)
  21. base := filepath.Base(path)
  22. if base != "." && strings.HasPrefix(base, ".") {
  23. return true
  24. }
  25. commonIgnoredDirs := map[string]bool{
  26. ".crush": true,
  27. "node_modules": true,
  28. "vendor": true,
  29. "dist": true,
  30. "build": true,
  31. "target": true,
  32. ".git": true,
  33. ".idea": true,
  34. ".vscode": true,
  35. "__pycache__": true,
  36. "bin": true,
  37. "obj": true,
  38. "out": true,
  39. "coverage": true,
  40. "logs": true,
  41. "generated": true,
  42. "bower_components": true,
  43. "jspm_packages": true,
  44. }
  45. parts := strings.SplitSeq(path, string(os.PathSeparator))
  46. for part := range parts {
  47. if commonIgnoredDirs[part] {
  48. return true
  49. }
  50. }
  51. return false
  52. }
  53. // FastGlobWalker provides gitignore-aware file walking with fastwalk
  54. // It uses hierarchical ignore checking like git does, checking .gitignore/.crushignore
  55. // files in each directory from the root to the target path.
  56. type FastGlobWalker struct {
  57. directoryLister *directoryLister
  58. }
  59. func NewFastGlobWalker(searchPath string) *FastGlobWalker {
  60. return &FastGlobWalker{
  61. directoryLister: NewDirectoryLister(searchPath),
  62. }
  63. }
  64. // ShouldSkip checks if a path should be skipped based on hierarchical gitignore,
  65. // crushignore, and hidden file rules
  66. func (w *FastGlobWalker) ShouldSkip(path string) bool {
  67. return w.directoryLister.shouldIgnore(path, nil)
  68. }
  69. func GlobWithDoubleStar(pattern, searchPath string, limit int) ([]string, bool, error) {
  70. // Normalize pattern to forward slashes on Windows so their config can use
  71. // backslashes
  72. pattern = filepath.ToSlash(pattern)
  73. walker := NewFastGlobWalker(searchPath)
  74. found := csync.NewSlice[FileInfo]()
  75. conf := fastwalk.Config{
  76. Follow: true,
  77. ToSlash: fastwalk.DefaultToSlash(),
  78. Sort: fastwalk.SortFilesFirst,
  79. }
  80. err := fastwalk.Walk(&conf, searchPath, func(path string, d os.DirEntry, err error) error {
  81. if err != nil {
  82. return nil // Skip files we can't access
  83. }
  84. if d.IsDir() {
  85. if walker.ShouldSkip(path) {
  86. return filepath.SkipDir
  87. }
  88. }
  89. if walker.ShouldSkip(path) {
  90. return nil
  91. }
  92. relPath, err := filepath.Rel(searchPath, path)
  93. if err != nil {
  94. relPath = path
  95. }
  96. // Normalize separators to forward slashes
  97. relPath = filepath.ToSlash(relPath)
  98. // Check if path matches the pattern
  99. matched, err := doublestar.Match(pattern, relPath)
  100. if err != nil || !matched {
  101. return nil
  102. }
  103. info, err := d.Info()
  104. if err != nil {
  105. return nil
  106. }
  107. found.Append(FileInfo{Path: path, ModTime: info.ModTime()})
  108. if limit > 0 && found.Len() >= limit*2 { // NOTE: why x2?
  109. return filepath.SkipAll
  110. }
  111. return nil
  112. })
  113. if err != nil && !errors.Is(err, filepath.SkipAll) {
  114. return nil, false, fmt.Errorf("fastwalk error: %w", err)
  115. }
  116. matches := slices.SortedFunc(found.Seq(), func(a, b FileInfo) int {
  117. return b.ModTime.Compare(a.ModTime)
  118. })
  119. matches, truncated := truncate(matches, limit)
  120. results := make([]string, len(matches))
  121. for i, m := range matches {
  122. results[i] = m.Path
  123. }
  124. return results, truncated || errors.Is(err, filepath.SkipAll), nil
  125. }
  126. // ShouldExcludeFile checks if a file should be excluded from processing
  127. // based on common patterns and ignore rules
  128. func ShouldExcludeFile(rootPath, filePath string) bool {
  129. return NewDirectoryLister(rootPath).
  130. shouldIgnore(filePath, nil)
  131. }
  132. func PrettyPath(path string) string {
  133. return home.Short(path)
  134. }
  135. func DirTrim(pwd string, lim int) string {
  136. var (
  137. out string
  138. sep = string(filepath.Separator)
  139. )
  140. dirs := strings.Split(pwd, sep)
  141. if lim > len(dirs)-1 || lim <= 0 {
  142. return pwd
  143. }
  144. for i := len(dirs) - 1; i > 0; i-- {
  145. out = sep + out
  146. if i == len(dirs)-1 {
  147. out = dirs[i]
  148. } else if i >= len(dirs)-lim {
  149. out = string(dirs[i][0]) + out
  150. } else {
  151. out = "..." + out
  152. break
  153. }
  154. }
  155. out = filepath.Join("~", out)
  156. return out
  157. }
  158. // PathOrPrefix returns the prefix if the path starts with it, or falls back to
  159. // the path otherwise.
  160. func PathOrPrefix(path, prefix string) string {
  161. if HasPrefix(path, prefix) {
  162. return prefix
  163. }
  164. return path
  165. }
  166. // HasPrefix checks if the given path starts with the specified prefix.
  167. // Uses filepath.Rel to determine if path is within prefix.
  168. func HasPrefix(path, prefix string) bool {
  169. rel, err := filepath.Rel(prefix, path)
  170. if err != nil {
  171. return false
  172. }
  173. // If path is within prefix, Rel will not return a path starting with ".."
  174. return !strings.HasPrefix(rel, "..")
  175. }
  176. // ToUnixLineEndings converts Windows line endings (CRLF) to Unix line endings (LF).
  177. func ToUnixLineEndings(content string) (string, bool) {
  178. if strings.Contains(content, "\r\n") {
  179. return strings.ReplaceAll(content, "\r\n", "\n"), true
  180. }
  181. return content, false
  182. }
  183. // ToWindowsLineEndings converts Unix line endings (LF) to Windows line endings (CRLF).
  184. func ToWindowsLineEndings(content string) (string, bool) {
  185. if !strings.Contains(content, "\r\n") {
  186. return strings.ReplaceAll(content, "\n", "\r\n"), true
  187. }
  188. return content, false
  189. }
  190. func truncate[T any](input []T, limit int) ([]T, bool) {
  191. if limit > 0 && len(input) > limit {
  192. return input[:limit], true
  193. }
  194. return input, false
  195. }