list dirs
This commit is contained in:
BIN
functions/__pycache__/get_files_info.cpython-312.pyc
Normal file
BIN
functions/__pycache__/get_files_info.cpython-312.pyc
Normal file
Binary file not shown.
33
functions/get_files_info.py
Normal file
33
functions/get_files_info.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import os
|
||||
|
||||
def get_files_info(working_directory, directory="."):
|
||||
try:
|
||||
full_path = os.path.join(working_directory, directory)
|
||||
|
||||
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 list "{directory}" as it is outside the permitted working directory'
|
||||
)
|
||||
|
||||
if not os.path.isdir(abs_target_path):
|
||||
return f'Error: "{directory}" is not a directory'
|
||||
|
||||
results = []
|
||||
for entry in os.listdir(abs_target_path):
|
||||
entry_path = os.path.join(abs_target_path, entry)
|
||||
try:
|
||||
is_dir = os.path.isdir(entry_path)
|
||||
size = os.path.getsize(entry_path)
|
||||
results.append(
|
||||
f"- {entry}: file_size={size} bytes, is_dir={str(is_dir)}"
|
||||
)
|
||||
except Exception as e:
|
||||
results.append(f"- {entry}: Error accessing file info ({e})")
|
||||
|
||||
return "\n".join(results)
|
||||
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
30
tests.py
Normal file
30
tests.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from functions.get_files_info import get_files_info
|
||||
|
||||
|
||||
def run_tests():
|
||||
cases = [
|
||||
("calculator", "."),
|
||||
("calculator", "pkg"),
|
||||
("calculator", "/bin"),
|
||||
("calculator", "../"),
|
||||
]
|
||||
|
||||
for working_dir, directory in cases:
|
||||
print(f'get_files_info("{working_dir}", "{directory}"):')
|
||||
|
||||
result = get_files_info(working_dir, directory)
|
||||
|
||||
if directory == ".":
|
||||
print("Result for current directory:")
|
||||
else:
|
||||
print(f"Result for '{directory}' directory:")
|
||||
|
||||
# Indent each line of result
|
||||
for line in result.splitlines():
|
||||
print(f" {line}")
|
||||
|
||||
print() # Extra newline between test cases
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
Reference in New Issue
Block a user