diff --git a/functions/write_file.py b/functions/write_file.py new file mode 100644 index 0000000..be8c43f --- /dev/null +++ b/functions/write_file.py @@ -0,0 +1,27 @@ +import os + + +def write_file(working_directory, file_path, content): + try: + full_path = os.path.join(working_directory, file_path) + abs_working_directory = os.path.abspath(working_directory) + abs_target_path = os.path.abspath(full_path) + + if not abs_target_path.startswith(abs_working_directory): + return ( + f'Error: Cannot write to "{file_path}" as it is outside the permitted working directory' + ) + + parent_dir = os.path.dirname(abs_target_path) + if parent_dir and not os.path.exists(parent_dir): + os.makedirs(parent_dir, exist_ok=True) + + with open(abs_target_path, "w", encoding="utf-8") as f: + f.write(content) + + return ( + f'Successfully wrote to "{file_path}" ({len(content)} characters written)' + ) + + except Exception as e: + return f"Error: {e}" \ No newline at end of file diff --git a/tests.py b/tests.py index 92ab937..ac00bbe 100644 --- a/tests.py +++ b/tests.py @@ -1,25 +1,24 @@ -from functions.get_file_content import get_file_content +from functions.write_file import write_file def run_tests(): cases = [ - ("calculator", "main.py"), - ("calculator", "pkg/calculator.py"), - ("calculator", "/bin/cat"), - ("calculator", "pkg/does_not_exist.py"), + ("calculator", "lorem.txt", "wait, this isn't lorem ipsum"), + ("calculator", "pkg/morelorem.txt", "lorem ipsum dolor sit amet"), + ("calculator", "/tmp/temp.txt", "this should not be allowed"), ] - for working_dir, file_path in cases: - print(f'get_file_content("{working_dir}", "{file_path}"):') + for working_dir, file_path, content in cases: + print(f'write_file("{working_dir}", "{file_path}", "{content}"):') - result = get_file_content(working_dir, file_path) + result = write_file(working_dir, file_path, content) print("Result:") - # Indent each line of output + for line in result.splitlines(): print(" " + line) - print() # Blank line between cases + print() if __name__ == "__main__":