chapter 2.3
This commit is contained in:
20
functions/get_file_content.py
Normal file
20
functions/get_file_content.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
from functions.config import FILE_LENGTH_LIMIT
|
||||
|
||||
def get_file_content(working_directory, file_path):
|
||||
abs_working_dir = os.path.abspath(working_directory)
|
||||
abs_file_path = os.path.abspath(os.path.join(working_directory, file_path))
|
||||
if not abs_file_path.startswith(abs_working_dir):
|
||||
return f'Error: Cannot read "{file_path}" as it is outside the permitted working directory'
|
||||
if not os.path.isfile(abs_file_path):
|
||||
return f'Error: File not found or is not a regular file: "{file_path}"'
|
||||
try:
|
||||
with open(abs_file_path, "r") as f:
|
||||
content = f.read(FILE_LENGTH_LIMIT)
|
||||
if os.path.getsize(abs_file_path) > FILE_LENGTH_LIMIT:
|
||||
content += (
|
||||
f'[...File "{file_path}" truncated at {FILE_LENGTH_LIMIT} characters]'
|
||||
)
|
||||
return content
|
||||
except Exception as e:
|
||||
return f'Error reading file "{file_path}": {e}'
|
||||
Reference in New Issue
Block a user