Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 2.7 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4export interface ToolResult {
5 success: boolean;
6 output: string;
7 error?: string;
8}
9
10/**
11 * Read a file and return its contents
12 */
13export function readFile(filePath: string): ToolResult {
14 try {
15 if (!fs.existsSync(filePath)) {
16 return {
17 success: false,
18 output: `Error: File does not exist: ${filePath}`,
19 error: `File not found: ${filePath}`,
20 };
21 }
22
23 const content = fs.readFileSync(filePath, "utf-8");
24 return {
25 success: true,
26 output: `File content:\n${content}`,
27 };
28 } catch (error) {
29 return {
30 success: false,
31 output: `Error reading file: ${error instanceof Error ? error.message : String(error)}`,
32 error: error instanceof Error ? error.message : String(error),
33 };
34 }
35}
36
37/**
38 * Write content to a file
39 */
40export function writeFile(filePath: string, content: string): ToolResult {
41 try {
42 // Create directory if it doesn't exist
43 const dirPath = path.dirname(filePath);
44 if (!fs.existsSync(dirPath)) {
45 fs.mkdirSync(dirPath, { recursive: true });
46 }
47
48 fs.writeFileSync(filePath, content, "utf-8");
49 return {
50 success: true,
51 output: `Successfully wrote to file: ${filePath}`,
52 };
53 } catch (error) {
54 return {
55 success: false,
56 output: `Error writing to file: ${error instanceof Error ? error.message : String(error)}`,
57 error: error instanceof Error ? error.message : String(error),
58 };
59 }
60}
61
62/**
63 * List files in a directory
64 */
65export function listFiles(dirPath: string): ToolResult {
66 try {
67 if (!fs.existsSync(dirPath)) {
68 return {
69 success: false,
70 output: `Error: Directory does not exist: ${dirPath}`,
71 error: `Directory not found: ${dirPath}`,
72 };
73 }
74
75 if (!fs.statSync(dirPath).isDirectory()) {
76 return {
77 success: false,
78 output: `Error: Path is not a directory: ${dirPath}`,
79 error: `Not a directory: ${dirPath}`,
80 };
81 }
82
83 const files = fs.readdirSync(dirPath);
84 const fileDetails = files.map((file) => {
85 const fullPath = path.join(dirPath, file);
86 const stats = fs.statSync(fullPath);
87 const type = stats.isDirectory() ? "directory" : "file";
88 const size = stats.isFile() ? `${stats.size} bytes` : "";
89 return `${file} (${type}${size ? `, ${size}` : ""})`;
90 });
91
92 return {
93 success: true,
94 output: `Files in ${dirPath}:\n${fileDetails.join("\n")}`,
95 };
96 } catch (error) {
97 return {
98 success: false,
99 output: `Error listing files: ${error instanceof Error ? error.message : String(error)}`,
100 error: error instanceof Error ? error.message : String(error),
101 };
102 }
103}