ls.go

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