-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreadFile.js
58 lines (54 loc) · 1.83 KB
/
readFile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
// src/tools/readFile.js
import fs from 'fs/promises';
import path from 'path';
readFile.spec = {
name: readFile.name,
description: 'Retrieves the full content of the file and some relevant info. Line numbers are artifially added to the content.',
parameters: {
type: 'object',
properties: {
filepath: {
type: 'string',
description: 'The path to the file within the working directory.',
},
range: {
type: 'string',
pattern: '^d+-d+$',
description: 'Optional. A range of line numbers to read, formatted as "start-end".',
},
},
required: ['filepath'],
},
};
export default async function readFile({ filepath, range, omitLineNumbers = false }) {
console.log(`Reading ${filepath}${range ? ` Lines: ${range}` : ''}`);
const fullPath = path.resolve(filepath);
try {
let content = await fs.readFile(fullPath, 'utf8');
if (omitLineNumbers) {
if (range) {
const [start, end] = range.split('-').map(Number);
const lines = content.split('\n');
content = lines.slice(start - 1, end).join('\n');
}
return { content };
}
content = addLineNumbers(content);
if (range) {
const [start, end] = range.split('-').map(Number);
const lines = content.split('\n');
content = lines.slice(start - 1, end).join('\n');
}
return {
content,
};
} catch (error) {
throw error; // Rethrow the error to be handled by the caller
}
}
function addLineNumbers(content) {
const withNumbers = content.split('\n').map((l, i) => {
return `${i + 1} ${l}`;
});
return withNumbers.join('\n');
}