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) Info() ToolInfo {
 89	return ToolInfo{
 90		Name:        LSToolName,
 91		Description: lsDescription,
 92		Parameters: map[string]any{
 93			"path": map[string]any{
 94				"type":        "string",
 95				"description": "The path to the directory to list (defaults to current working directory)",
 96			},
 97			"ignore": map[string]any{
 98				"type":        "array",
 99				"description": "List of glob patterns to ignore",
100				"items": map[string]any{
101					"type": "string",
102				},
103			},
104		},
105		Required: []string{"path"},
106	}
107}
108
109func (l *lsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
110	var params LSParams
111	if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
112		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
113	}
114
115	searchPath := params.Path
116	if searchPath == "" {
117		searchPath = l.workingDir
118	}
119
120	var err error
121	searchPath, err = fsext.Expand(searchPath)
122	if err != nil {
123		return ToolResponse{}, fmt.Errorf("error expanding path: %w", err)
124	}
125
126	if !filepath.IsAbs(searchPath) {
127		searchPath = filepath.Join(l.workingDir, searchPath)
128	}
129
130	// Check if directory is outside working directory and request permission if needed
131	absWorkingDir, err := filepath.Abs(l.workingDir)
132	if err != nil {
133		return ToolResponse{}, fmt.Errorf("error resolving working directory: %w", err)
134	}
135
136	absSearchPath, err := filepath.Abs(searchPath)
137	if err != nil {
138		return ToolResponse{}, fmt.Errorf("error resolving search path: %w", err)
139	}
140
141	relPath, err := filepath.Rel(absWorkingDir, absSearchPath)
142	if err != nil || strings.HasPrefix(relPath, "..") {
143		// Directory is outside working directory, request permission
144		sessionID, messageID := GetContextValues(ctx)
145		if sessionID == "" || messageID == "" {
146			return ToolResponse{}, fmt.Errorf("session ID and message ID are required for accessing directories outside working directory")
147		}
148
149		granted := l.permissions.Request(
150			permission.CreatePermissionRequest{
151				SessionID:   sessionID,
152				Path:        absSearchPath,
153				ToolCallID:  call.ID,
154				ToolName:    LSToolName,
155				Action:      "list",
156				Description: fmt.Sprintf("List directory outside working directory: %s", absSearchPath),
157				Params:      LSPermissionsParams(params),
158			},
159		)
160
161		if !granted {
162			return ToolResponse{}, permission.ErrorPermissionDenied
163		}
164	}
165
166	output, err := ListDirectoryTree(searchPath, params.Ignore)
167	if err != nil {
168		return ToolResponse{}, err
169	}
170
171	// Get file count for metadata
172	files, truncated, err := fsext.ListDirectory(searchPath, params.Ignore, MaxLSFiles)
173	if err != nil {
174		return ToolResponse{}, fmt.Errorf("error listing directory for metadata: %w", err)
175	}
176
177	return WithResponseMetadata(
178		NewTextResponse(output),
179		LSResponseMetadata{
180			NumberOfFiles: len(files),
181			Truncated:     truncated,
182		},
183	), nil
184}
185
186func ListDirectoryTree(searchPath string, ignore []string) (string, error) {
187	if _, err := os.Stat(searchPath); os.IsNotExist(err) {
188		return "", fmt.Errorf("path does not exist: %s", searchPath)
189	}
190
191	files, truncated, err := fsext.ListDirectory(searchPath, ignore, MaxLSFiles)
192	if err != nil {
193		return "", fmt.Errorf("error listing directory: %w", err)
194	}
195
196	tree := createFileTree(files, searchPath)
197	output := printTree(tree, searchPath)
198
199	if truncated {
200		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)
201	}
202
203	return output, nil
204}
205
206func createFileTree(sortedPaths []string, rootPath string) []*TreeNode {
207	root := []*TreeNode{}
208	pathMap := make(map[string]*TreeNode)
209
210	for _, path := range sortedPaths {
211		relativePath := strings.TrimPrefix(path, rootPath)
212		parts := strings.Split(relativePath, string(filepath.Separator))
213		currentPath := ""
214		var parentPath string
215
216		var cleanParts []string
217		for _, part := range parts {
218			if part != "" {
219				cleanParts = append(cleanParts, part)
220			}
221		}
222		parts = cleanParts
223
224		if len(parts) == 0 {
225			continue
226		}
227
228		for i, part := range parts {
229			if currentPath == "" {
230				currentPath = part
231			} else {
232				currentPath = filepath.Join(currentPath, part)
233			}
234
235			if _, exists := pathMap[currentPath]; exists {
236				parentPath = currentPath
237				continue
238			}
239
240			isLastPart := i == len(parts)-1
241			isDir := !isLastPart || strings.HasSuffix(relativePath, string(filepath.Separator))
242			nodeType := "file"
243			if isDir {
244				nodeType = "directory"
245			}
246			newNode := &TreeNode{
247				Name:     part,
248				Path:     currentPath,
249				Type:     nodeType,
250				Children: []*TreeNode{},
251			}
252
253			pathMap[currentPath] = newNode
254
255			if i > 0 && parentPath != "" {
256				if parent, ok := pathMap[parentPath]; ok {
257					parent.Children = append(parent.Children, newNode)
258				}
259			} else {
260				root = append(root, newNode)
261			}
262
263			parentPath = currentPath
264		}
265	}
266
267	return root
268}
269
270func printTree(tree []*TreeNode, rootPath string) string {
271	var result strings.Builder
272
273	result.WriteString("- ")
274	result.WriteString(rootPath)
275	if rootPath[len(rootPath)-1] != '/' {
276		result.WriteByte(filepath.Separator)
277	}
278	result.WriteByte('\n')
279
280	for _, node := range tree {
281		printNode(&result, node, 1)
282	}
283
284	return result.String()
285}
286
287func printNode(builder *strings.Builder, node *TreeNode, level int) {
288	indent := strings.Repeat("  ", level)
289
290	nodeName := node.Name
291	if node.Type == "directory" {
292		nodeName = nodeName + string(filepath.Separator)
293	}
294
295	fmt.Fprintf(builder, "%s- %s\n", indent, nodeName)
296
297	if node.Type == "directory" && len(node.Children) > 0 {
298		for _, child := range node.Children {
299			printNode(builder, child, level+1)
300		}
301	}
302}