| 1 | from helpers.api import ApiHandler, Input, Output, Request |
| 2 | from helpers.file_browser import FileBrowser |
| 3 | from helpers import runtime, extension |
| 4 | from api import get_work_dir_files |
| 5 | from api.download_work_dir_files import normalize_paths |
| 6 | |
| 7 | |
| 8 | class DeleteWorkDirFiles(ApiHandler): |
| 9 | async def process(self, input: Input, request: Request) -> Output: |
| 10 | try: |
| 11 | paths = normalize_paths(input.get("paths", [])) |
| 12 | except ValueError as exc: |
| 13 | return {"error": str(exc)} |
| 14 | |
| 15 | current_path = input.get("currentPath", "") |
| 16 | |
| 17 | if not paths: |
| 18 | return {"error": "No file paths provided"} |
| 19 | |
| 20 | result = await runtime.call_development_function(delete_files, paths) |
| 21 | deleted = result["deleted"] |
| 22 | failed = result["failed"] |
| 23 | |
| 24 | if deleted: |
| 25 | await extension.call_extensions_async( |
| 26 | "workdir_file_mutation_after", |
| 27 | agent=None, |
| 28 | data={ |
| 29 | "action": "bulk_delete", |
| 30 | "path": deleted[0], |
| 31 | "paths": deleted, |
| 32 | "current_path": current_path, |
| 33 | }, |
| 34 | ) |
| 35 | |
| 36 | files_result = await runtime.call_development_function( |
| 37 | get_work_dir_files.get_files, current_path |
| 38 | ) |
| 39 | |
| 40 | if not deleted: |
| 41 | return { |
| 42 | "error": "Selected items could not be deleted", |
| 43 | "data": files_result, |
| 44 | "deleted": deleted, |
| 45 | "failed": failed, |
| 46 | } |
| 47 | |
| 48 | return { |
| 49 | "data": files_result, |
| 50 | "deleted": deleted, |
| 51 | "failed": failed, |
| 52 | } |
| 53 | |
| 54 | |
| 55 | async def delete_files(paths: list[str]) -> dict: |
| 56 | browser = FileBrowser() |
| 57 | deleted: list[str] = [] |
| 58 | failed: list[str] = [] |
| 59 | |
| 60 | for path in collapse_nested_paths(paths): |
| 61 | if path == "/": |
| 62 | failed.append(path) |
| 63 | continue |
| 64 | |
| 65 | if browser.delete_file(path): |
| 66 | deleted.append(path) |
| 67 | else: |
| 68 | failed.append(path) |
| 69 | |
| 70 | return {"deleted": deleted, "failed": failed} |
| 71 | |
| 72 | |
| 73 | def collapse_nested_paths(paths: list[str]) -> list[str]: |
| 74 | collapsed: list[str] = [] |
| 75 | for path in sorted(normalize_paths(paths), key=lambda item: item.count("/")): |
| 76 | clean_path = "/" + path.strip("/") |
| 77 | if any( |
| 78 | clean_path == parent or clean_path.startswith(parent.rstrip("/") + "/") |
| 79 | for parent in collapsed |
| 80 | ): |
| 81 | continue |
| 82 | collapsed.append(clean_path) |
| 83 | return collapsed |