Refactor
This commit is contained in:
+23
-58
@@ -1,8 +1,7 @@
|
||||
import os
|
||||
import logging
|
||||
import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
from tools.utils import format_relative_time
|
||||
from tools.utils import format_relative_time, ToolError, get_file_info_list, sort_file_list
|
||||
|
||||
logger = logging.getLogger("MattCP")
|
||||
|
||||
@@ -12,65 +11,24 @@ async def handle(args: Dict[str, Any]):
|
||||
Directories are listed first, then files.
|
||||
Supports pagination and sorting.
|
||||
"""
|
||||
path = args.get("path")
|
||||
path_str = args.get("path")
|
||||
page = int(args.get("page", 1))
|
||||
page_size = int(args.get("page_size", 64))
|
||||
sort_by = args.get("sort_by", "mtime")
|
||||
|
||||
if not path:
|
||||
return {"text": "Error: Missing path argument"}
|
||||
if not os.path.isdir(path):
|
||||
return {"text": f"Error: {path} is not a directory."}
|
||||
if not path_str:
|
||||
raise ToolError("Missing path argument")
|
||||
|
||||
path = Path(path_str)
|
||||
if not path.is_dir():
|
||||
raise ToolError(f"{path_str} is not a directory.")
|
||||
|
||||
try:
|
||||
entries = os.listdir(path)
|
||||
except Exception as e:
|
||||
return {"text": f"Error reading directory: {e}"}
|
||||
|
||||
all_items = []
|
||||
for entry in entries:
|
||||
full_path = os.path.join(path, entry)
|
||||
try:
|
||||
stats = os.stat(full_path)
|
||||
mtime_rel = format_relative_time(stats.st_mtime)
|
||||
|
||||
if os.path.isdir(full_path):
|
||||
try:
|
||||
count = len(os.listdir(full_path))
|
||||
except:
|
||||
count = 0
|
||||
all_items.append({
|
||||
"type": "dir",
|
||||
"name": entry,
|
||||
"info": f"{count} items",
|
||||
"mtime": mtime_rel,
|
||||
"mtime_raw": stats.st_mtime,
|
||||
"size": stats.st_size
|
||||
})
|
||||
else:
|
||||
size_kb = stats.st_size / 1024
|
||||
all_items.append({
|
||||
"type": "file",
|
||||
"name": entry,
|
||||
"info": f"{size_kb:.1f}KB",
|
||||
"mtime": mtime_rel,
|
||||
"mtime_raw": stats.st_mtime,
|
||||
"size": stats.st_size
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error(f"Could not stat {entry}: {e}")
|
||||
|
||||
# Sort Logic: Directories always come first, then apply secondary sort
|
||||
if sort_by == "mtime":
|
||||
all_items.sort(key=lambda x: (x["type"] == "file", -x["mtime_raw"]))
|
||||
elif sort_by == "size":
|
||||
all_items.sort(key=lambda x: (x["type"] == "file", -x["size"]))
|
||||
else:
|
||||
all_items.sort(key=lambda x: (x["type"] == "file", x["name"].lower()))
|
||||
all_items = get_file_info_list(path)
|
||||
all_items = sort_file_list(all_items, sort_by)
|
||||
|
||||
total_items = len(all_items)
|
||||
|
||||
# Custom Pagination: show all if <= 100, otherwise paginate by 64
|
||||
# Custom Pagination: show all if <= 100, otherwise paginate by page_size
|
||||
if total_items <= 100:
|
||||
start_idx = 0
|
||||
end_idx = total_items
|
||||
@@ -89,11 +47,18 @@ async def handle(args: Dict[str, Any]):
|
||||
|
||||
output = []
|
||||
for item in paged_items:
|
||||
if item["type"] == "dir":
|
||||
output.append(f"[DIR] {item['name']} | {item['info']} | {item['mtime']}")
|
||||
mtime_rel = format_relative_time(item["mtime"])
|
||||
if item["is_dir"]:
|
||||
try:
|
||||
count = len(list(item["path"].iterdir()))
|
||||
info = f"{count} items"
|
||||
except:
|
||||
info = "0 items"
|
||||
output.append(f"[DIR] {item['name']} | {info} | {mtime_rel}")
|
||||
else:
|
||||
output.append(f" {item['name']} | {item['info']} | {item['mtime']}")
|
||||
size_kb = item["size"] / 1024
|
||||
output.append(f" {item['name']} | {size_kb:.1f}KB | {mtime_rel}")
|
||||
|
||||
header = f"Listing of {path}\nPage {effective_page} of {total_pages} ({total_items} total items). Showing {start_idx+1}-{min(end_idx, total_items)}."
|
||||
header = f"Listing of {path_str}\nPage {effective_page} of {total_pages} ({total_items} total items). Showing {start_idx+1}-{min(end_idx, total_items)}."
|
||||
|
||||
return {"text": f"{header}\n\n" + "\n".join(output)}
|
||||
|
||||
Reference in New Issue
Block a user