Skip to content

Commit e79fadb

Browse files
committed
Support API to delete dirs and files
1 parent 969b827 commit e79fadb

File tree

3 files changed

+41
-81
lines changed

3 files changed

+41
-81
lines changed

src/api/api.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,9 @@ class CreateDirectoryRequest(BaseModel):
8888
directoryPath: str
8989

9090

91-
class DeleteDirectoryRequest(BaseModel):
92-
"""Request model for deleting a directory."""
93-
directoryPath: str
91+
class DeleteDirsFilesRequest(BaseModel):
92+
"""Request model for deleting directores or files."""
93+
paths: List[str]
9494

9595

9696
class UploadFileRequest(BaseModel):
@@ -100,11 +100,6 @@ class UploadFileRequest(BaseModel):
100100
fileContent: str # Base64-encoded content
101101

102102

103-
class DeleteFilesRequest(BaseModel):
104-
"""Request model for deleting files."""
105-
filePaths: List[str]
106-
107-
108103
class FileMetadata(BaseModel):
109104
"""Metadata for a file."""
110105
type: str

src/rest/rest.py

Lines changed: 8 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,8 @@
99
UpdateNamespaceRequest,
1010
ListNamespaceResponse,
1111
CreateDirectoryRequest,
12-
DeleteDirectoryRequest,
12+
DeleteDirsFilesRequest,
1313
UploadFileRequest,
14-
DeleteFilesRequest,
1514
ListDirectoryResponse,
1615
)
1716
from src.logger import logger
@@ -104,10 +103,9 @@ def __init__(self, file_service: FileService):
104103
def _setup_routes(self):
105104
"""Setup API routes."""
106105
self.router.post("/directories")(self.create_directory)
107-
self.router.delete("/directories")(self.delete_directory)
108106
self.router.get("/directories", response_model=ListDirectoryResponse)(self.list_directory)
109107
self.router.post("/files")(self.upload_file)
110-
self.router.delete("/files")(self.delete_files)
108+
self.router.post("/delete-dirs-files")(self.delete_dirs_files)
111109

112110
async def create_directory(self, request: CreateDirectoryRequest):
113111
"""
@@ -126,22 +124,18 @@ async def create_directory(self, request: CreateDirectoryRequest):
126124
raise HTTPException(status_code=409, detail=str(e))
127125
raise HTTPException(status_code=400, detail=str(e))
128126

129-
async def delete_directory(self, request: DeleteDirectoryRequest):
127+
async def delete_dirs_files(self, request: DeleteDirsFilesRequest):
130128
"""
131-
Delete a directory.
129+
Delete directories or files.
132130
133131
Returns:
134132
200: Succeed
135133
400: Bad Request
136-
404: Not Found (Directory does not exist)
137134
"""
138-
try:
139-
self.file_service.delete_directory(request.directoryPath)
140-
return {"message": "Directory deleted successfully"}
141-
except ValueError as e:
142-
if "Not Found" in str(e):
143-
raise HTTPException(status_code=404, detail=str(e))
144-
raise HTTPException(status_code=400, detail=str(e))
135+
result = self.file_service.delete_dirs_files(request.paths)
136+
if result["hasFailure"] is True:
137+
print(result)
138+
return result
145139

146140
async def list_directory(self, directoryPath: str):
147141
"""
@@ -174,24 +168,6 @@ async def upload_file(self, request: UploadFileRequest):
174168
except ValueError as e:
175169
raise HTTPException(status_code=400, detail=str(e))
176170

177-
async def delete_files(self, request: DeleteFilesRequest):
178-
"""
179-
Delete files.
180-
181-
Returns:
182-
200: Succeed
183-
400: Bad Request
184-
404: Not Found
185-
"""
186-
try:
187-
self.file_service.delete_files(request.filePaths)
188-
return {"message": "Files deleted successfully"}
189-
except ValueError as e:
190-
if "Not Found" in str(e):
191-
raise HTTPException(status_code=404, detail=str(e))
192-
raise HTTPException(status_code=400, detail=str(e))
193-
194-
195171
class SessionAPI:
196172
"""Class to encapsulate session-related API endpoints."""
197173

src/service/file.py

Lines changed: 30 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import base64
3+
import shutil
34
from datetime import datetime
45
from typing import List, Dict
56

@@ -28,30 +29,6 @@ def create_directory(self, directory_path: str):
2829
except Exception as e:
2930
raise ValueError(f"Bad Request: Unable to create directory. {str(e)}")
3031

31-
def delete_directory(self, directory_path: str):
32-
"""
33-
Delete a directory.
34-
35-
Args:
36-
directory_path (str): Path of the directory to delete.
37-
38-
Raises:
39-
ValueError: If the directory does not exist or the path is invalid.
40-
"""
41-
if not os.path.exists(directory_path):
42-
raise ValueError("Not Found: Directory does not exist.")
43-
if not os.path.isdir(directory_path):
44-
raise ValueError("Bad Request: Path is not a directory.")
45-
try:
46-
for root, dirs, files in os.walk(directory_path, topdown=False):
47-
for file in files:
48-
os.remove(os.path.join(root, file))
49-
for dir in dirs:
50-
os.rmdir(os.path.join(root, dir))
51-
os.rmdir(directory_path)
52-
except Exception as e:
53-
raise ValueError(f"Bad Request: Unable to delete directory. {str(e)}")
54-
5532
def list_directory(self, directory_path: str) -> Dict[str, List[Dict[str, str]]]:
5633
"""
5734
List files and directories in a specified directory.
@@ -122,27 +99,39 @@ def upload_file(self, directory_path: str, file_name: str, file_content: str):
12299
except Exception as e:
123100
raise ValueError(f"Bad Request: Unable to upload file. {str(e)}")
124101

125-
def delete_files(self, file_paths: List[str]):
102+
def delete_dirs_files(self, paths: List[str]) -> Dict[str, any]:
126103
"""
127-
Delete specified files.
104+
Delete multiple files or directories.
128105
129106
Args:
130-
file_paths (List[str]): List of file paths to delete.
107+
paths (List[str]): List of paths (files or directories) to delete.
131108
132-
Raises:
133-
ValueError: If a file does not exist or the path is invalid.
109+
Returns:
110+
Dict[str, any]: A dictionary containing the deletion status for each path.
134111
"""
135-
errors = []
136-
for file_path in file_paths:
137-
if not os.path.exists(file_path):
138-
errors.append(f"Not Found: {file_path}")
139-
continue
140-
if not os.path.isfile(file_path):
141-
errors.append(f"Bad Request: {file_path} is not a file.")
142-
continue
112+
results = {
113+
"hasFailure": False,
114+
"paths": [],
115+
}
116+
117+
for path in paths:
143118
try:
144-
os.remove(file_path)
119+
if not os.path.exists(path):
120+
results["paths"].append({"path": path, "status": "not found"})
121+
results["hasFailure"] = True
122+
continue
123+
124+
if os.path.isfile(path):
125+
os.remove(path) # Remove file
126+
results["paths"].append({"path": path, "status": "file deleted"})
127+
elif os.path.isdir(path):
128+
shutil.rmtree(path) # Recursively delete directory
129+
results["paths"].append({"path": path, "status": "directory deleted"})
130+
else:
131+
results["paths"].append({"path": path, "status": "invalid path type"})
132+
results["hasFailure"] = True
145133
except Exception as e:
146-
errors.append(f"Unable to delete {file_path}. {str(e)}")
147-
if errors:
148-
raise ValueError("; ".join(errors))
134+
results["paths"].append({"path": path, "status": "error", "message": str(e)})
135+
results["hasFailure"] = True
136+
137+
return results

0 commit comments

Comments
 (0)