18 lines
807 B
Python
18 lines
807 B
Python
import os
|
|
|
|
def write_file(working_directory, file_path, content):
|
|
abs_path = os.path.abspath(working_directory)
|
|
new_file_path = os.path.normpath(os.path.join(abs_path, file_path))
|
|
valid_target_file = os.path.commonpath([abs_path, new_file_path]) == abs_path
|
|
if not valid_target_file:
|
|
return f'Error: Cannot write to "{file_path}" as it is outside the permitted working directory'
|
|
if os.path.isdir(new_file_path):
|
|
return f'Error: Cannot write to "{file_path}" as it is a directory'
|
|
|
|
os.makedirs(os.path.dirname(new_file_path), exist_ok=True)
|
|
try:
|
|
with open(new_file_path, "w") as f:
|
|
f.write(content)
|
|
except Exception as e:
|
|
return f"Error: {e}"
|
|
return f'Successfully wrote to "{file_path}" ({len(content)} characters written)' |