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/fsext"
 12	"github.com/charmbracelet/crush/internal/permission"
 13)
 14
 15type LSParams struct {
 16	Path   string   `json:"path"`
 17	Ignore []string `json:"ignore"`
 18}
 19
 20type LSPermissionsParams struct {
 21	Path   string   `json:"path"`
 22	Ignore []string `json:"ignore"`
 23}
 24
 25type TreeNode struct {
 26	Name     string      `json:"name"`
 27	Path     string      `json:"path"`
 28	Type     string      `json:"type"` // "file" or "directory"
 29	Children []*TreeNode `json:"children,omitempty"`
 30}
 31
 32type LSResponseMetadata struct {
 33	NumberOfFiles int  `json:"number_of_files"`
 34	Truncated     bool `json:"truncated"`
 35}
 36
 37type lsTool struct {
 38	workingDir  string
 39	permissions permission.Service
 40}
 41
 42const (
 43	LSToolName    = "ls"
 44	MaxLSFiles    = 1000
 45	lsDescription = `Directory listing tool that shows files and subdirectories in a tree structure, helping you explore and understand the project organization.
 46
 47WHEN TO USE THIS TOOL:
 48- Use when you need to explore the structure of a directory
 49- Helpful for understanding the organization of a project
 50- Good first step when getting familiar with a new codebase
 51
 52HOW TO USE:
 53- Provide a path to list (defaults to current working directory)
 54- Optionally specify glob patterns to ignore
 55- Results are displayed in a tree structure
 56
 57FEATURES:
 58- Displays a hierarchical view of files and directories
 59- Automatically skips hidden files/directories (starting with '.')
 60- Skips common system directories like __pycache__
 61- Can filter out files matching specific patterns
 62
 63LIMITATIONS:
 64- Results are limited to 1000 files
 65- Very large directories will be truncated
 66- Does not show file sizes or permissions
 67- Cannot recursively list all directories in a large project
 68
 69WINDOWS NOTES:
 70- Hidden file detection uses Unix convention (files starting with '.')
 71- Windows-specific hidden files (with hidden attribute) are not automatically skipped
 72- Common Windows directories like System32, Program Files are not in default ignore list
 73- Path separators are handled automatically (both / and \ work)
 74
 75TIPS:
 76- Use Glob tool for finding files by name patterns instead of browsing
 77- Use Grep tool for searching file contents
 78- Combine with other tools for more effective exploration`
 79)
 80
 81func NewLsTool(permissions permission.Service, workingDir string) BaseTool {
 82	return &lsTool{
 83		workingDir:  workingDir,
 84		permissions: permissions,
 85	}
 86}
 87
 88func (l *lsTool) Name() string {
 89	return LSToolName
 90}
 91
 92func (l *lsTool) Info() ToolInfo {
 93	return ToolInfo{
 94		Name:        LSToolName,
 95		Description: lsDescription,
 96		Parameters: map[string]any{
 97			"path": map[string]any{
 98				"type":        "string",
 99				"description": "The path to the directory to list (defaults to current working directory)",
100			},
101			"ignore": map[string]any{
102				"type":        "array",
103				"description": "List of glob patterns to ignore",
104				"items": map[string]any{
105					"type": "string",
106				},
107			},
108		},
109		Required: []string{"path"},
110	}
111}
112
113func (l *lsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
114	var params LSParams
115	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
116		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
117	}
118
119	searchPath := params.Path
120	if searchPath == "" {
121		searchPath = l.workingDir
122	}
123
124	if !filepath.IsAbs(searchPath) {
125		searchPath = filepath.Join(l.workingDir, searchPath)
126	}
127
128	// Check if directory is outside working directory and request permission if needed
129	absWorkingDir, err := filepath.Abs(l.workingDir)
130	if err != nil {
131		return ToolResponse{}, fmt.Errorf("error resolving working directory: %w", err)
132	}
133
134	absSearchPath, err := filepath.Abs(searchPath)
135	if err != nil {
136		return ToolResponse{}, fmt.Errorf("error resolving search path: %w", err)
137	}
138
139	relPath, err := filepath.Rel(absWorkingDir, absSearchPath)
140	if err != nil || strings.HasPrefix(relPath, "..") {
141		// Directory is outside working directory, request permission
142		sessionID, messageID := GetContextValues(ctx)
143		if sessionID == "" || messageID == "" {
144			return ToolResponse{}, fmt.Errorf("session ID and message ID are required for accessing directories outside working directory")
145		}
146
147		granted := l.permissions.Request(
148			permission.CreatePermissionRequest{
149				SessionID:   sessionID,
150				Path:        absSearchPath,
151				ToolCallID:  call.ID,
152				ToolName:    LSToolName,
153				Action:      "list",
154				Description: fmt.Sprintf("List directory outside working directory: %s", absSearchPath),
155				Params:      LSPermissionsParams(params),
156			},
157		)
158
159		if !granted {
160			return ToolResponse{}, permission.ErrorPermissionDenied
161		}
162	}
163
164	output, err := ListDirectoryTree(searchPath, params.Ignore)
165	if err != nil {
166		return ToolResponse{}, err
167	}
168
169	// Get file count for metadata
170	files, truncated, err := fsext.ListDirectory(searchPath, params.Ignore, MaxLSFiles)
171	if err != nil {
172		return ToolResponse{}, fmt.Errorf("error listing directory for metadata: %w", err)
173	}
174
175	return WithResponseMetadata(
176		NewTextResponse(output),
177		LSResponseMetadata{
178			NumberOfFiles: len(files),
179			Truncated:     truncated,
180		},
181	), nil
182}
183
184func ListDirectoryTree(searchPath string, ignore []string) (string, error) {
185	if _, err := os.Stat(searchPath); os.IsNotExist(err) {
186		return "", fmt.Errorf("path does not exist: %s", searchPath)
187	}
188
189	files, truncated, err := fsext.ListDirectory(searchPath, ignore, MaxLSFiles)
190	if err != nil {
191		return "", fmt.Errorf("error listing directory: %w", err)
192	}
193
194	tree := createFileTree(files)
195	output := printTree(tree, searchPath)
196
197	if truncated {
198		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)
199	}
200
201	return output, nil
202}
203
204func createFileTree(sortedPaths []string) []*TreeNode {
205	root := []*TreeNode{}
206	pathMap := make(map[string]*TreeNode)
207
208	for _, path := range sortedPaths {
209		parts := strings.Split(path, string(filepath.Separator))
210		currentPath := ""
211		var parentPath string
212
213		var cleanParts []string
214		for _, part := range parts {
215			if part != "" {
216				cleanParts = append(cleanParts, part)
217			}
218		}
219		parts = cleanParts
220
221		if len(parts) == 0 {
222			continue
223		}
224
225		for i, part := range parts {
226			if currentPath == "" {
227				currentPath = part
228			} else {
229				currentPath = filepath.Join(currentPath, part)
230			}
231
232			if _, exists := pathMap[currentPath]; exists {
233				parentPath = currentPath
234				continue
235			}
236
237			isLastPart := i == len(parts)-1
238			isDir := !isLastPart || strings.HasSuffix(path, string(filepath.Separator))
239			nodeType := "file"
240			if isDir {
241				nodeType = "directory"
242			}
243			newNode := &TreeNode{
244				Name:     part,
245				Path:     currentPath,
246				Type:     nodeType,
247				Children: []*TreeNode{},
248			}
249
250			pathMap[currentPath] = newNode
251
252			if i > 0 && parentPath != "" {
253				if parent, ok := pathMap[parentPath]; ok {
254					parent.Children = append(parent.Children, newNode)
255				}
256			} else {
257				root = append(root, newNode)
258			}
259
260			parentPath = currentPath
261		}
262	}
263
264	return root
265}
266
267func printTree(tree []*TreeNode, rootPath string) string {
268	var result strings.Builder
269
270	result.WriteString(fmt.Sprintf("- %s%s\n", rootPath, string(filepath.Separator)))
271
272	for _, node := range tree {
273		printNode(&result, node, 1)
274	}
275
276	return result.String()
277}
278
279func printNode(builder *strings.Builder, node *TreeNode, level int) {
280	indent := strings.Repeat("  ", level)
281
282	nodeName := node.Name
283	if node.Type == "directory" {
284		nodeName = nodeName + string(filepath.Separator)
285	}
286
287	fmt.Fprintf(builder, "%s- %s\n", indent, nodeName)
288
289	if node.Type == "directory" && len(node.Children) > 0 {
290		for _, child := range node.Children {
291			printNode(builder, child, level+1)
292		}
293	}
294}