ls.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/opencode-ai/opencode/internal/config"
  10. )
  11. type LSParams struct {
  12. Path string `json:"path"`
  13. Ignore []string `json:"ignore"`
  14. }
  15. type TreeNode struct {
  16. Name string `json:"name"`
  17. Path string `json:"path"`
  18. Type string `json:"type"` // "file" or "directory"
  19. Children []*TreeNode `json:"children,omitempty"`
  20. }
  21. type LSResponseMetadata struct {
  22. NumberOfFiles int `json:"number_of_files"`
  23. Truncated bool `json:"truncated"`
  24. }
  25. type lsTool struct{}
  26. const (
  27. LSToolName = "ls"
  28. MaxLSFiles = 1000
  29. lsDescription = `Directory listing tool that shows files and subdirectories in a tree structure, helping you explore and understand the project organization.
  30. WHEN TO USE THIS TOOL:
  31. - Use when you need to explore the structure of a directory
  32. - Helpful for understanding the organization of a project
  33. - Good first step when getting familiar with a new codebase
  34. HOW TO USE:
  35. - Provide a path to list (defaults to current working directory)
  36. - Optionally specify glob patterns to ignore
  37. - Results are displayed in a tree structure
  38. FEATURES:
  39. - Displays a hierarchical view of files and directories
  40. - Automatically skips hidden files/directories (starting with '.')
  41. - Skips common system directories like __pycache__
  42. - Can filter out files matching specific patterns
  43. LIMITATIONS:
  44. - Results are limited to 1000 files
  45. - Very large directories will be truncated
  46. - Does not show file sizes or permissions
  47. - Cannot recursively list all directories in a large project
  48. TIPS:
  49. - Use Glob tool for finding files by name patterns instead of browsing
  50. - Use Grep tool for searching file contents
  51. - Combine with other tools for more effective exploration`
  52. )
  53. func NewLsTool() BaseTool {
  54. return &lsTool{}
  55. }
  56. func (l *lsTool) Info() ToolInfo {
  57. return ToolInfo{
  58. Name: LSToolName,
  59. Description: lsDescription,
  60. Parameters: map[string]any{
  61. "path": map[string]any{
  62. "type": "string",
  63. "description": "The path to the directory to list (defaults to current working directory)",
  64. },
  65. "ignore": map[string]any{
  66. "type": "array",
  67. "description": "List of glob patterns to ignore",
  68. "items": map[string]any{
  69. "type": "string",
  70. },
  71. },
  72. },
  73. Required: []string{"path"},
  74. }
  75. }
  76. func (l *lsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  77. var params LSParams
  78. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  79. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  80. }
  81. searchPath := params.Path
  82. if searchPath == "" {
  83. searchPath = config.WorkingDirectory()
  84. }
  85. if !filepath.IsAbs(searchPath) {
  86. searchPath = filepath.Join(config.WorkingDirectory(), searchPath)
  87. }
  88. if _, err := os.Stat(searchPath); os.IsNotExist(err) {
  89. return NewTextErrorResponse(fmt.Sprintf("path does not exist: %s", searchPath)), nil
  90. }
  91. files, truncated, err := listDirectory(searchPath, params.Ignore, MaxLSFiles)
  92. if err != nil {
  93. return ToolResponse{}, fmt.Errorf("error listing directory: %w", err)
  94. }
  95. tree := createFileTree(files)
  96. output := printTree(tree, searchPath)
  97. if truncated {
  98. output = fmt.Sprintf("There are more than %d files in the directory. Use a more specific path or use the Glob tool to find specific files. The first %d files and directories are included below:\n\n%s", MaxLSFiles, MaxLSFiles, output)
  99. }
  100. return WithResponseMetadata(
  101. NewTextResponse(output),
  102. LSResponseMetadata{
  103. NumberOfFiles: len(files),
  104. Truncated: truncated,
  105. },
  106. ), nil
  107. }
  108. func listDirectory(initialPath string, ignorePatterns []string, limit int) ([]string, bool, error) {
  109. var results []string
  110. truncated := false
  111. err := filepath.Walk(initialPath, func(path string, info os.FileInfo, err error) error {
  112. if err != nil {
  113. return nil // Skip files we don't have permission to access
  114. }
  115. if shouldSkip(path, ignorePatterns) {
  116. if info.IsDir() {
  117. return filepath.SkipDir
  118. }
  119. return nil
  120. }
  121. if path != initialPath {
  122. if info.IsDir() {
  123. path = path + string(filepath.Separator)
  124. }
  125. results = append(results, path)
  126. }
  127. if len(results) >= limit {
  128. truncated = true
  129. return filepath.SkipAll
  130. }
  131. return nil
  132. })
  133. if err != nil {
  134. return nil, truncated, err
  135. }
  136. return results, truncated, nil
  137. }
  138. func shouldSkip(path string, ignorePatterns []string) bool {
  139. base := filepath.Base(path)
  140. if base != "." && strings.HasPrefix(base, ".") {
  141. return true
  142. }
  143. commonIgnored := []string{
  144. "__pycache__",
  145. "node_modules",
  146. "dist",
  147. "build",
  148. "target",
  149. "vendor",
  150. "bin",
  151. "obj",
  152. ".git",
  153. ".idea",
  154. ".vscode",
  155. ".DS_Store",
  156. "*.pyc",
  157. "*.pyo",
  158. "*.pyd",
  159. "*.so",
  160. "*.dll",
  161. "*.exe",
  162. }
  163. if strings.Contains(path, filepath.Join("__pycache__", "")) {
  164. return true
  165. }
  166. for _, ignored := range commonIgnored {
  167. if strings.HasSuffix(ignored, "/") {
  168. if strings.Contains(path, filepath.Join(ignored[:len(ignored)-1], "")) {
  169. return true
  170. }
  171. } else if strings.HasPrefix(ignored, "*.") {
  172. if strings.HasSuffix(base, ignored[1:]) {
  173. return true
  174. }
  175. } else {
  176. if base == ignored {
  177. return true
  178. }
  179. }
  180. }
  181. for _, pattern := range ignorePatterns {
  182. matched, err := filepath.Match(pattern, base)
  183. if err == nil && matched {
  184. return true
  185. }
  186. }
  187. return false
  188. }
  189. func createFileTree(sortedPaths []string) []*TreeNode {
  190. root := []*TreeNode{}
  191. pathMap := make(map[string]*TreeNode)
  192. for _, path := range sortedPaths {
  193. parts := strings.Split(path, string(filepath.Separator))
  194. currentPath := ""
  195. var parentPath string
  196. var cleanParts []string
  197. for _, part := range parts {
  198. if part != "" {
  199. cleanParts = append(cleanParts, part)
  200. }
  201. }
  202. parts = cleanParts
  203. if len(parts) == 0 {
  204. continue
  205. }
  206. for i, part := range parts {
  207. if currentPath == "" {
  208. currentPath = part
  209. } else {
  210. currentPath = filepath.Join(currentPath, part)
  211. }
  212. if _, exists := pathMap[currentPath]; exists {
  213. parentPath = currentPath
  214. continue
  215. }
  216. isLastPart := i == len(parts)-1
  217. isDir := !isLastPart || strings.HasSuffix(path, string(filepath.Separator))
  218. nodeType := "file"
  219. if isDir {
  220. nodeType = "directory"
  221. }
  222. newNode := &TreeNode{
  223. Name: part,
  224. Path: currentPath,
  225. Type: nodeType,
  226. Children: []*TreeNode{},
  227. }
  228. pathMap[currentPath] = newNode
  229. if i > 0 && parentPath != "" {
  230. if parent, ok := pathMap[parentPath]; ok {
  231. parent.Children = append(parent.Children, newNode)
  232. }
  233. } else {
  234. root = append(root, newNode)
  235. }
  236. parentPath = currentPath
  237. }
  238. }
  239. return root
  240. }
  241. func printTree(tree []*TreeNode, rootPath string) string {
  242. var result strings.Builder
  243. result.WriteString(fmt.Sprintf("- %s%s\n", rootPath, string(filepath.Separator)))
  244. for _, node := range tree {
  245. printNode(&result, node, 1)
  246. }
  247. return result.String()
  248. }
  249. func printNode(builder *strings.Builder, node *TreeNode, level int) {
  250. indent := strings.Repeat(" ", level)
  251. nodeName := node.Name
  252. if node.Type == "directory" {
  253. nodeName += string(filepath.Separator)
  254. }
  255. fmt.Fprintf(builder, "%s- %s\n", indent, nodeName)
  256. if node.Type == "directory" && len(node.Children) > 0 {
  257. for _, child := range node.Children {
  258. printNode(builder, child, level+1)
  259. }
  260. }
  261. }