1package tools
  2
  3import (
  4	"bufio"
  5	"context"
  6	"encoding/json"
  7	"fmt"
  8	"io"
  9	"os"
 10	"path/filepath"
 11	"strings"
 12
 13	"github.com/charmbracelet/crush/internal/config"
 14	"github.com/charmbracelet/crush/internal/lsp"
 15)
 16
 17type ViewParams struct {
 18	FilePath string `json:"file_path"`
 19	Offset   int    `json:"offset"`
 20	Limit    int    `json:"limit"`
 21}
 22
 23type viewTool struct {
 24	lspClients map[string]*lsp.Client
 25}
 26
 27type ViewResponseMetadata struct {
 28	FilePath string `json:"file_path"`
 29	Content  string `json:"content"`
 30}
 31
 32const (
 33	ViewToolName     = "view"
 34	MaxReadSize      = 250 * 1024
 35	DefaultReadLimit = 2000
 36	MaxLineLength    = 2000
 37	viewDescription  = `File viewing tool that reads and displays the contents of files with line numbers, allowing you to examine code, logs, or text data.
 38
 39WHEN TO USE THIS TOOL:
 40- Use when you need to read the contents of a specific file
 41- Helpful for examining source code, configuration files, or log files
 42- Perfect for looking at text-based file formats
 43
 44HOW TO USE:
 45- Provide the path to the file you want to view
 46- Optionally specify an offset to start reading from a specific line
 47- Optionally specify a limit to control how many lines are read
 48
 49FEATURES:
 50- Displays file contents with line numbers for easy reference
 51- Can read from any position in a file using the offset parameter
 52- Handles large files by limiting the number of lines read
 53- Automatically truncates very long lines for better display
 54- Suggests similar file names when the requested file isn't found
 55
 56LIMITATIONS:
 57- Maximum file size is 250KB
 58- Default reading limit is 2000 lines
 59- Lines longer than 2000 characters are truncated
 60- Cannot display binary files or images
 61- Images can be identified but not displayed
 62
 63WINDOWS NOTES:
 64- Handles both Windows (CRLF) and Unix (LF) line endings automatically
 65- File paths work with both forward slashes (/) and backslashes (\)
 66- Text encoding is detected automatically for most common formats
 67
 68TIPS:
 69- Use with Glob tool to first find files you want to view
 70- For code exploration, first use Grep to find relevant files, then View to examine them
 71- When viewing large files, use the offset parameter to read specific sections`
 72)
 73
 74func NewViewTool(lspClients map[string]*lsp.Client) BaseTool {
 75	return &viewTool{
 76		lspClients,
 77	}
 78}
 79
 80func (v *viewTool) Info() ToolInfo {
 81	return ToolInfo{
 82		Name:        ViewToolName,
 83		Description: viewDescription,
 84		Parameters: map[string]any{
 85			"file_path": map[string]any{
 86				"type":        "string",
 87				"description": "The path to the file to read",
 88			},
 89			"offset": map[string]any{
 90				"type":        "integer",
 91				"description": "The line number to start reading from (0-based)",
 92			},
 93			"limit": map[string]any{
 94				"type":        "integer",
 95				"description": "The number of lines to read (defaults to 2000)",
 96			},
 97		},
 98		Required: []string{"file_path"},
 99	}
100}
101
102// Run implements Tool.
103func (v *viewTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
104	var params ViewParams
105	if err := json.Unmarshal([]byte(call.Input), ¶ms); err != nil {
106		return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
107	}
108
109	if params.FilePath == "" {
110		return NewTextErrorResponse("file_path is required"), nil
111	}
112
113	// Handle relative paths
114	filePath := params.FilePath
115	if !filepath.IsAbs(filePath) {
116		filePath = filepath.Join(config.WorkingDirectory(), filePath)
117	}
118
119	// Check if file exists
120	fileInfo, err := os.Stat(filePath)
121	if err != nil {
122		if os.IsNotExist(err) {
123			// Try to offer suggestions for similarly named files
124			dir := filepath.Dir(filePath)
125			base := filepath.Base(filePath)
126
127			dirEntries, dirErr := os.ReadDir(dir)
128			if dirErr == nil {
129				var suggestions []string
130				for _, entry := range dirEntries {
131					if strings.Contains(strings.ToLower(entry.Name()), strings.ToLower(base)) ||
132						strings.Contains(strings.ToLower(base), strings.ToLower(entry.Name())) {
133						suggestions = append(suggestions, filepath.Join(dir, entry.Name()))
134						if len(suggestions) >= 3 {
135							break
136						}
137					}
138				}
139
140				if len(suggestions) > 0 {
141					return NewTextErrorResponse(fmt.Sprintf("File not found: %s\n\nDid you mean one of these?\n%s",
142						filePath, strings.Join(suggestions, "\n"))), nil
143				}
144			}
145
146			return NewTextErrorResponse(fmt.Sprintf("File not found: %s", filePath)), nil
147		}
148		return ToolResponse{}, fmt.Errorf("error accessing file: %w", err)
149	}
150
151	// Check if it's a directory
152	if fileInfo.IsDir() {
153		return NewTextErrorResponse(fmt.Sprintf("Path is a directory, not a file: %s", filePath)), nil
154	}
155
156	// Check file size
157	if fileInfo.Size() > MaxReadSize {
158		return NewTextErrorResponse(fmt.Sprintf("File is too large (%d bytes). Maximum size is %d bytes",
159			fileInfo.Size(), MaxReadSize)), nil
160	}
161
162	// Set default limit if not provided
163	if params.Limit <= 0 {
164		params.Limit = DefaultReadLimit
165	}
166
167	// Check if it's an image file
168	isImage, imageType := isImageFile(filePath)
169	// TODO: handle images
170	if isImage {
171		return NewTextErrorResponse(fmt.Sprintf("This is an image file of type: %s\nUse a different tool to process images", imageType)), nil
172	}
173
174	// Read the file content
175	content, lineCount, err := readTextFile(filePath, params.Offset, params.Limit)
176	if err != nil {
177		return ToolResponse{}, fmt.Errorf("error reading file: %w", err)
178	}
179
180	notifyLspOpenFile(ctx, filePath, v.lspClients)
181	output := "<file>\n"
182	// Format the output with line numbers
183	output += addLineNumbers(content, params.Offset+1)
184
185	// Add a note if the content was truncated
186	if lineCount > params.Offset+len(strings.Split(content, "\n")) {
187		output += fmt.Sprintf("\n\n(File has more lines. Use 'offset' parameter to read beyond line %d)",
188			params.Offset+len(strings.Split(content, "\n")))
189	}
190	output += "\n</file>\n"
191	output += getDiagnostics(filePath, v.lspClients)
192	recordFileRead(filePath)
193	return WithResponseMetadata(
194		NewTextResponse(output),
195		ViewResponseMetadata{
196			FilePath: filePath,
197			Content:  content,
198		},
199	), nil
200}
201
202func addLineNumbers(content string, startLine int) string {
203	if content == "" {
204		return ""
205	}
206
207	lines := strings.Split(content, "\n")
208
209	var result []string
210	for i, line := range lines {
211		line = strings.TrimSuffix(line, "\r")
212
213		lineNum := i + startLine
214		numStr := fmt.Sprintf("%d", lineNum)
215
216		if len(numStr) >= 6 {
217			result = append(result, fmt.Sprintf("%s|%s", numStr, line))
218		} else {
219			paddedNum := fmt.Sprintf("%6s", numStr)
220			result = append(result, fmt.Sprintf("%s|%s", paddedNum, line))
221		}
222	}
223
224	return strings.Join(result, "\n")
225}
226
227func readTextFile(filePath string, offset, limit int) (string, int, error) {
228	file, err := os.Open(filePath)
229	if err != nil {
230		return "", 0, err
231	}
232	defer file.Close()
233
234	lineCount := 0
235
236	scanner := NewLineScanner(file)
237	if offset > 0 {
238		for lineCount < offset && scanner.Scan() {
239			lineCount++
240		}
241		if err = scanner.Err(); err != nil {
242			return "", 0, err
243		}
244	}
245
246	if offset == 0 {
247		_, err = file.Seek(0, io.SeekStart)
248		if err != nil {
249			return "", 0, err
250		}
251	}
252
253	var lines []string
254	lineCount = offset
255
256	for scanner.Scan() && len(lines) < limit {
257		lineCount++
258		lineText := scanner.Text()
259		if len(lineText) > MaxLineLength {
260			lineText = lineText[:MaxLineLength] + "..."
261		}
262		lines = append(lines, lineText)
263	}
264
265	// Continue scanning to get total line count
266	for scanner.Scan() {
267		lineCount++
268	}
269
270	if err := scanner.Err(); err != nil {
271		return "", 0, err
272	}
273
274	return strings.Join(lines, "\n"), lineCount, nil
275}
276
277func isImageFile(filePath string) (bool, string) {
278	ext := strings.ToLower(filepath.Ext(filePath))
279	switch ext {
280	case ".jpg", ".jpeg":
281		return true, "JPEG"
282	case ".png":
283		return true, "PNG"
284	case ".gif":
285		return true, "GIF"
286	case ".bmp":
287		return true, "BMP"
288	case ".svg":
289		return true, "SVG"
290	case ".webp":
291		return true, "WebP"
292	default:
293		return false, ""
294	}
295}
296
297type LineScanner struct {
298	scanner *bufio.Scanner
299}
300
301func NewLineScanner(r io.Reader) *LineScanner {
302	return &LineScanner{
303		scanner: bufio.NewScanner(r),
304	}
305}
306
307func (s *LineScanner) Scan() bool {
308	return s.scanner.Scan()
309}
310
311func (s *LineScanner) Text() string {
312	return s.scanner.Text()
313}
314
315func (s *LineScanner) Err() error {
316	return s.scanner.Err()
317}