48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
import os
|
|
|
|
from google.genai import types
|
|
|
|
|
|
def write_file(working_directory: str, file_path: str, content: str) -> str:
|
|
try:
|
|
wdp = os.path.abspath(working_directory)
|
|
target = os.path.normpath(os.path.join(wdp, file_path))
|
|
valid_target_dir = os.path.commonpath([wdp, target]) == wdp
|
|
|
|
if not valid_target_dir:
|
|
return f'Error: Cannot write to "{file_path}" as it is outside the permitted working directory'
|
|
|
|
if os.path.isdir(target):
|
|
return f'Error: Cannot write to "{file_path}" as it is a directory'
|
|
|
|
os.makedirs("/".join(target.split("/")[:-1]), exist_ok=True)
|
|
|
|
with open(target, "w") as f:
|
|
f.write(content)
|
|
|
|
return (
|
|
f'Successfully wrote to "{file_path}" ({len(content)} characters written)'
|
|
)
|
|
except Exception as e:
|
|
return f"Error: {e}"
|
|
|
|
|
|
schema_write_file = types.FunctionDeclaration(
|
|
name="write_file",
|
|
description="",
|
|
parameters=types.Schema(
|
|
type=types.Type.OBJECT,
|
|
properties={
|
|
"file_path": types.Schema(
|
|
type=types.Type.STRING,
|
|
description="",
|
|
),
|
|
"content": types.Schema(
|
|
type=types.Type.STRING,
|
|
description="",
|
|
),
|
|
},
|
|
required=["file_path", "content"],
|
|
),
|
|
)
|