Class: Ask::Tools::Read
- Inherits:
-
Ask::Tool
- Object
- Ask::Tool
- Ask::Tools::Read
- Defined in:
- lib/ask/tools/shell/read.rb
Overview
Read file contents with line numbers, or list directory contents. Output is truncated to 2000 lines.
Constant Summary collapse
- MAX_LINES =
2000
Instance Method Summary collapse
Instance Method Details
#execute(path:, offset: nil, limit: nil) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/ask/tools/shell/read.rb', line 20 def execute(path:, offset: nil, limit: nil) path = File.(path) unless File.exist?(path) return Ask::Result.error(message: "Path does not exist: #{path}") end if File.directory?(path) entries = Dir.children(path).sort entries.map! do |e| full = File.join(path, e) "#{e}#{File.directory?(full) ? '/' : ''}" end return Ask::Result.ok(data: entries.join("\n"), metadata: { type: "directory", count: entries.size }) end unless File.file?(path) return Ask::Result.error(message: "Not a file: #{path}") end if File.size(path) > 1_000_000 return Ask::Result.error( message: "File too large (#{File.size(path)} bytes). Use offset/limit to read portions." ) end lines = File.readlines(path, chomp: true) total = lines.size offset_val = offset.to_i.clamp(0, total) limit_val = limit || MAX_LINES selected = lines[offset_val, limit_val] truncated = selected.size < (total - offset_val) result = selected.each_with_index.map do |line, i| "#{offset_val + i + 1}: #{line}" end.join("\n") result << "\n... (#{total - offset_val - selected.size} more lines)" if truncated Ask::Result.ok(data: result, metadata: { total_lines: total, start_line: offset_val + 1, end_line: offset_val + selected.size, truncated: truncated }) end |