diff --git a/.gitignore b/.gitignore index 4c49bd7..fcfcb28 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ .env +__pycache__ +functions/__pycache__ \ No newline at end of file diff --git a/functions/__pycache__/get_files_info.cpython-312.pyc b/functions/__pycache__/get_files_info.cpython-312.pyc deleted file mode 100644 index a8099de..0000000 Binary files a/functions/__pycache__/get_files_info.cpython-312.pyc and /dev/null differ diff --git a/functions/config.py b/functions/config.py new file mode 100644 index 0000000..f830741 --- /dev/null +++ b/functions/config.py @@ -0,0 +1 @@ +MAX_FILE_CONTENT_CHARS = 10000 \ No newline at end of file diff --git a/functions/get_file_content.py b/functions/get_file_content.py new file mode 100644 index 0000000..1fc90c0 --- /dev/null +++ b/functions/get_file_content.py @@ -0,0 +1,30 @@ +import os +from functions.config import MAX_FILE_CONTENT_CHARS + + +def get_file_content(working_directory, file_path): + 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 read "{file_path}" as it is outside the permitted working directory' + ) + + if not os.path.isfile(abs_target_path): + return f'Error: File not found or is not a regular file: "{file_path}"' + + with open(abs_target_path, "r", encoding="utf-8", errors="replace") as f: + content = f.read() + + if len(content) > MAX_FILE_CONTENT_CHARS: + truncated = content[:MAX_FILE_CONTENT_CHARS] + return truncated + f'\n[...File "{file_path}" truncated at {MAX_FILE_CONTENT_CHARS} characters]' + else: + return content + + except Exception as e: + return f"Error: {e}" \ No newline at end of file diff --git a/tests.py b/tests.py index c29a555..92ab937 100644 --- a/tests.py +++ b/tests.py @@ -1,29 +1,25 @@ -from functions.get_files_info import get_files_info +from functions.get_file_content import get_file_content def run_tests(): cases = [ - ("calculator", "."), - ("calculator", "pkg"), - ("calculator", "/bin"), - ("calculator", "../"), + ("calculator", "main.py"), + ("calculator", "pkg/calculator.py"), + ("calculator", "/bin/cat"), + ("calculator", "pkg/does_not_exist.py"), ] - for working_dir, directory in cases: - print(f'get_files_info("{working_dir}", "{directory}"):') + for working_dir, file_path in cases: + print(f'get_file_content("{working_dir}", "{file_path}"):') - result = get_files_info(working_dir, directory) + result = get_file_content(working_dir, file_path) - if directory == ".": - print("Result for current directory:") - else: - print(f"Result for '{directory}' directory:") - - # Indent each line of result + print("Result:") + # Indent each line of output for line in result.splitlines(): - print(f" {line}") + print(" " + line) - print() # Extra newline between test cases + print() # Blank line between cases if __name__ == "__main__":