feat: Allow relative paths for all tools (#253)
This commit is contained in:
@@ -20,14 +20,16 @@ export async function edit(args: EditArgs): Promise<EditResult> {
|
||||
"Edit",
|
||||
);
|
||||
const { file_path, old_string, new_string, replace_all = false } = args;
|
||||
if (!path.isAbsolute(file_path))
|
||||
throw new Error(`File path must be absolute, got: ${file_path}`);
|
||||
const userCwd = process.env.USER_CWD || process.cwd();
|
||||
const resolvedPath = path.isAbsolute(file_path)
|
||||
? file_path
|
||||
: path.resolve(userCwd, file_path);
|
||||
if (old_string === new_string)
|
||||
throw new Error(
|
||||
"No changes to make: old_string and new_string are exactly the same.",
|
||||
);
|
||||
try {
|
||||
const content = await fs.readFile(file_path, "utf-8");
|
||||
const content = await fs.readFile(resolvedPath, "utf-8");
|
||||
const occurrences = content.split(old_string).length - 1;
|
||||
if (occurrences === 0)
|
||||
throw new Error(
|
||||
@@ -48,22 +50,21 @@ export async function edit(args: EditArgs): Promise<EditResult> {
|
||||
content.substring(index + old_string.length);
|
||||
replacements = 1;
|
||||
}
|
||||
await fs.writeFile(file_path, newContent, "utf-8");
|
||||
await fs.writeFile(resolvedPath, newContent, "utf-8");
|
||||
return {
|
||||
message: `Successfully replaced ${replacements} occurrence${replacements !== 1 ? "s" : ""} in ${file_path}`,
|
||||
message: `Successfully replaced ${replacements} occurrence${replacements !== 1 ? "s" : ""} in ${resolvedPath}`,
|
||||
replacements,
|
||||
};
|
||||
} catch (error) {
|
||||
const err = error as NodeJS.ErrnoException;
|
||||
if (err.code === "ENOENT") {
|
||||
const userCwd = process.env.USER_CWD || process.cwd();
|
||||
throw new Error(
|
||||
`File does not exist. Current working directory: ${userCwd}`,
|
||||
`File does not exist. Attempted path: ${resolvedPath}. Current working directory: ${userCwd}`,
|
||||
);
|
||||
} else if (err.code === "EACCES")
|
||||
throw new Error(`Permission denied: ${file_path}`);
|
||||
throw new Error(`Permission denied: ${resolvedPath}`);
|
||||
else if (err.code === "EISDIR")
|
||||
throw new Error(`Path is a directory: ${file_path}`);
|
||||
throw new Error(`Path is a directory: ${resolvedPath}`);
|
||||
else if (err.message) throw err;
|
||||
else throw new Error(`Failed to edit file: ${err}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user