getting file content
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1 +1,3 @@
|
||||
.env
|
||||
__pycache__
|
||||
functions/__pycache__
|
||||
Binary file not shown.
1
functions/config.py
Normal file
1
functions/config.py
Normal file
@@ -0,0 +1 @@
|
||||
MAX_FILE_CONTENT_CHARS = 10000
|
||||
30
functions/get_file_content.py
Normal file
30
functions/get_file_content.py
Normal file
@@ -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}"
|
||||
28
tests.py
28
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__":
|
||||
|
||||
Reference in New Issue
Block a user