Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: backend-based file and directory duplication (#9142)

Daizue4021a34ffda
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index b822535956..87596fce8f 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -51,6 +51,7 @@ export const MockRequestClient = {
.mockResolvedValue({ files: [], query: "", total_found: 0 }),
sendCreateFileOrFolder: vi.fn().mockResolvedValue({}),
sendDeleteFileOrFolder: vi.fn().mockResolvedValue({}),
+ sendCopyFileOrFolder: vi.fn().mockResolvedValue({}),
sendRenameFileOrFolder: vi.fn().mockResolvedValue({}),
sendUpdateFile: vi.fn().mockResolvedValue({}),
sendFileDetails: vi.fn().mockResolvedValue({}),
diff --git a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
index 87404110b2..3a332cfbaa 100644
--- a/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
+++ b/frontend/src/components/editor/file-tree/__tests__/requesting-tree.test.ts
@@ -8,6 +8,7 @@ import { RequestingTree } from "../requesting-tree";
const sendListFiles = vi.fn();
const sendCreateFileOrFolder = vi.fn();
const sendDeleteFileOrFolder = vi.fn();
+const sendCopyFileOrFolder = vi.fn();
const sendRenameFileOrFolder = vi.fn();
vi.mock("@/components/ui/use-toast", () => MockModules.toast());
@@ -21,6 +22,7 @@ describe("RequestingTree", () => {
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
sendListFiles.mockResolvedValue({
@@ -169,6 +171,17 @@ describe("RequestingTree", () => {
`);
});
+ test("copy should duplicate a file", async () => {
+ sendCopyFileOrFolder.mockResolvedValue({ success: true });
+
+ await requestingTree.copy("1.1", "file1_copy");
+ expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file1_copy",
+ });
+ expect(mockOnChange).toHaveBeenCalled();
+ });
+
test("createFile should create a new file", async () => {
sendCreateFileOrFolder.mockResolvedValue({ success: true });
@@ -236,6 +249,7 @@ describe("RequestingTree", () => {
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
sendListFiles.mockRejectedValue(new Error("Network error"));
@@ -263,6 +277,23 @@ describe("RequestingTree", () => {
});
});
+ test("copy should handle API failure", async () => {
+ sendCopyFileOrFolder.mockResolvedValue({
+ success: false,
+ message: "Error duplicating",
+ });
+
+ await requestingTree.copy("1.1", "file1_copy");
+ expect(sendCopyFileOrFolder).toHaveBeenCalledWith({
+ path: "/root/file1",
+ newPath: "/root/file1_copy",
+ });
+ expect(toast).toHaveBeenCalledWith({
+ title: "Failed",
+ description: "Error duplicating",
+ });
+ });
+
test("move should handle missing parent node gracefully", async () => {
await requestingTree.move(["1.x"], "2");
expect(sendRenameFileOrFolder).not.toHaveBeenCalled();
@@ -284,6 +315,7 @@ describe("RequestingTree", () => {
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
@@ -305,6 +337,7 @@ describe("RequestingTree", () => {
listFiles: sendListFiles,
createFileOrFolder: sendCreateFileOrFolder,
deleteFileOrFolder: sendDeleteFileOrFolder,
+ copyFileOrFolder: sendCopyFileOrFolder,
renameFileOrFolder: sendRenameFileOrFolder,
});
diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsx
index 0a05cfa226..7505dd2ba0 100644
--- a/frontend/src/components/editor/file-tree/file-explorer.tsx
+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx
@@ -419,8 +419,7 @@ const Edit = ({ node }: { node: NodeApi<FileInfo> }) => {
};
const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
- const { openFile, sendCreateFileOrFolder, sendFileDetails } =
- useRequestClient();
+ const { openFile, sendFileDetails } = useRequestClient();
const disableFileDownloads = useAtomValue(disableFileDownloadsAtom);
const fileType: FileIconType = node.data.isDirectory
@@ -502,37 +501,14 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
});
const handleDuplicate = useEvent(async () => {
- if (!tree || node.data.isDirectory) {
+ if (!tree) {
return;
}
const [name, extension] = fileSplit(node.data.name);
const duplicateName = `${name}_copy${extension}`;
- try {
- // First get the file contents
- const details = await sendFileDetails({ path: node.data.path });
-
- // Get the parent directory path
- const parentPath = node.parent?.data.path || "";
-
- // Create the duplicate file by creating a new file with the same contents
- await sendCreateFileOrFolder({
- path: parentPath,
- type: "file",
- name: duplicateName,
- contents: details.contents ? btoa(details.contents) : undefined,
- });
-
- // Refresh the parent folder to show the new file
- await tree.refreshAll([parentPath]);
- } catch {
- toast({
- title: "Failed to duplicate file",
- description: "Unable to create a duplicate of the file",
- variant: "danger",
- });
- }
+ await tree.copy(node.id, duplicateName);
});
const renderActions = () => {
@@ -581,12 +557,10 @@ const Node = ({ node, style, dragHandle }: NodeRendererProps<FileInfo>) => {
<Edit3Icon className={ic} />
Rename
</DropdownMenuItem>
- {!node.data.isDirectory && (
- <DropdownMenuItem onSelect={handleDuplicate}>
- <CopyIcon className={ic} />
- Duplicate
- </DropdownMenuItem>
- )}
+ <DropdownMenuItem onSelect={handleDuplicate}>
+ <CopyIcon className={ic} />
+ Duplicate
+ </DropdownMenuItem>
<DropdownMenuItem
onSelect={async () => {
await copyToClipboard(node.data.path);
diff --git a/frontend/src/components/editor/file-tree/requesting-tree.tsx b/frontend/src/components/editor/file-tree/requesting-tree.tsx
index e59cc730f8..f1b1515757 100644
--- a/frontend/src/components/editor/file-tree/requesting-tree.tsx
+++ b/frontend/src/components/editor/file-tree/requesting-tree.tsx
@@ -17,6 +17,7 @@ export class RequestingTree {
listFiles: EditRequests["sendListFiles"];
createFileOrFolder: EditRequests["sendCreateFileOrFolder"];
deleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"];
+ copyFileOrFolder: EditRequests["sendCopyFileOrFolder"];
renameFileOrFolder: EditRequests["sendRenameFileOrFolder"];
};
@@ -24,6 +25,7 @@ export class RequestingTree {
listFiles: EditRequests["sendListFiles"];
createFileOrFolder: EditRequests["sendCreateFileOrFolder"];
deleteFileOrFolder: EditRequests["sendDeleteFileOrFolder"];
+ copyFileOrFolder: EditRequests["sendCopyFileOrFolder"];
renameFileOrFolder: EditRequests["sendRenameFileOrFolder"];
}) {
this.callbacks = callbacks;
@@ -74,9 +76,44 @@ export class RequestingTree {
return true;
}
+ async copy(id: string, newName: string): Promise<void> {
+ const node = this.delegate.find(id);
+ if (!node) {
+ toast({
+ title: "Failed",
+ description: `Node with id ${id} not found in the tree`,
+ });
+ return;
+ }
+ const currentPath = node.data.path as FilePath;
+ const parentPath = this.path.dirname(currentPath);
+ const newPath = this.path.join(parentPath, newName);
+ const newFile = await this.callbacks
+ .copyFileOrFolder({
+ path: currentPath,
+ newPath: newPath,
+ })
+ .then(this.handleResponse);
+ if (!newFile?.info) {
+ return;
+ }
+ this.delegate.create({
+ parentId: node.parent?.id ?? null,
+ index: 0,
+ data: newFile.info,
+ });
+ this.onChange(this.delegate.data);
+ // Refresh the parent folder
+ await this.refreshAll([parentPath]);
+ }
+
async rename(id: string, name: string): Promise<void> {
const node = this.delegate.find(id);
if (!node) {
+ toast({
+ title: "Failed",
+ description: `Node with id ${id} not found in the tree`,
+ });
return;
}
const currentPath = node.data.path as FilePath;
@@ -172,6 +209,10 @@ export class RequestingTree {
async delete(id: string): Promise<void> {
const node = this.delegate.find(id);
if (!node) {
+ toast({
+ title: "Failed",
+ description: `Node with id ${id} not found in the tree`,
+ });
return;
}
diff --git a/frontend/src/components/editor/file-tree/state.tsx b/frontend/src/components/editor/file-tree/state.tsx
index 06586d41c1..cdcd65f317 100644
--- a/frontend/src/components/editor/file-tree/state.tsx
+++ b/frontend/src/components/editor/file-tree/state.tsx
@@ -15,6 +15,7 @@ export const treeAtom = atom<RequestingTree>((get) => {
listFiles: client.sendListFiles,
createFileOrFolder: client.sendCreateFileOrFolder,
deleteFileOrFolder: client.sendDeleteFileOrFolder,
+ copyFileOrFolder: client.sendCopyFileOrFolder,
renameFileOrFolder: client.sendRenameFileOrFolder,
});
});
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index f52f632926..2f720c2070 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -237,6 +237,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
sendPdb = throwNotImplemented;
sendCreateFileOrFolder = throwNotImplemented;
sendDeleteFileOrFolder = throwNotImplemented;
+ sendCopyFileOrFolder = throwNotImplemented;
sendRenameFileOrFolder = throwNotImplemented;
sendUpdateFile = throwNotImplemented;
sendFileDetails = throwNotImplemented;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index 6ff8af2af8..9840cb86ff 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -90,6 +90,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
sendSearchFiles: "startConnection",
sendCreateFileOrFolder: "throwError",
sendDeleteFileOrFolder: "throwError",
+ sendCopyFileOrFolder: "throwError",
sendRenameFileOrFolder: "throwError",
sendUpdateFile: "throwError",
sendFileDetails: "throwError",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index c23e5f237e..d361c6490b 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -312,6 +312,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponse);
},
+ sendCopyFileOrFolder: async (request) => {
+ await waitForConnectionOpen();
+ return getClient()
+ .POST("/api/files/copy", {
+ body: request,
+ })
+ .then(handleResponse);
+ },
sendRenameFileOrFolder: async (request) => {
await waitForConnectionOpen();
return getClient()
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 8ac611382c..285d117b65 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -66,6 +66,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
sendPdb: throwNotInEditMode,
sendCreateFileOrFolder: throwNotInEditMode,
sendDeleteFileOrFolder: throwNotInEditMode,
+ sendCopyFileOrFolder: throwNotInEditMode,
sendRenameFileOrFolder: throwNotInEditMode,
sendUpdateFile: throwNotInEditMode,
sendFileDetails: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index 76b6d0c397..f91e960df1 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -51,6 +51,7 @@ export function createErrorToastingRequests(
sendPdb: "Failed to start debug session",
sendCreateFileOrFolder: "Failed to create file or folder",
sendDeleteFileOrFolder: "Failed to delete file or folder",
+ sendCopyFileOrFolder: "Failed to duplicate file or folder",
sendRenameFileOrFolder: "Failed to rename file or folder",
sendUpdateFile: "Failed to update file",
sendFileDetails: "Failed to get file details",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index e2c257b909..2a5b6c1e47 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -23,6 +23,8 @@ export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];
export type ExportAsScriptRequest = schemas["ExportAsScriptRequest"];
export type ExportAsPDFRequest = schemas["ExportAsPDFRequest"];
export type UpdateCellOutputsRequest = schemas["UpdateCellOutputsRequest"];
+export type FileCopyRequest = schemas["FileCopyRequest"];
+export type FileCopyResponse = schemas["FileCopyResponse"];
export type FileCreateRequest = schemas["FileCreateRequest"];
export type FileCreateResponse = schemas["FileCreateResponse"];
export type FileDeleteRequest = schemas["FileDeleteRequest"];
@@ -168,6 +170,7 @@ export interface EditRequests {
sendDeleteFileOrFolder: (
request: FileDeleteRequest,
) => Promise<FileDeleteResponse>;
+ sendCopyFileOrFolder: (request: FileCopyRequest) => Promise<FileCopyResponse>;
sendRenameFileOrFolder: (
request: FileMoveRequest,
) => Promise<FileMoveResponse>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 2d42f1264a..23565ed393 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -17,6 +17,7 @@ import type {
EditRequests,
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
+ FileCopyResponse,
FileCreateResponse,
FileDeleteResponse,
FileDetailsResponse,
@@ -443,6 +444,16 @@ export class PyodideBridge implements RunRequests, EditRequests {
return response as FileDeleteResponse;
};
+ sendCopyFileOrFolder: EditRequests["sendCopyFileOrFolder"] = async (
+ request,
+ ) => {
+ const response = await this.rpc.proxy.request.bridge({
+ functionName: "copy_file_or_directory",
+ payload: request,
+ });
+ return response as FileCopyResponse;
+ };
+
sendRenameFileOrFolder: EditRequests["sendRenameFileOrFolder"] = async (
request,
) => {
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index b0c79254cb..d58f07e845 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -11,6 +11,8 @@ import type {
CopyNotebookRequest,
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
+ FileCopyRequest,
+ FileCopyResponse,
FileCreateRequest,
FileCreateResponse,
FileDeleteRequest,
@@ -86,6 +88,7 @@ export interface RawBridge {
delete_file_or_directory(
request: FileDeleteRequest,
): Promise<FileDeleteResponse>;
+ copy_file_or_directory(request: FileCopyRequest): Promise<FileCopyResponse>;
move_file_or_directory(request: FileMoveRequest): Promise<FileMoveResponse>;
update_file(request: FileUpdateRequest): Promise<FileUpdateResponse>;
load_packages(request: string): Promise<string>;
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index 5312e3e25f..ac7eca9096 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -369,6 +369,7 @@ const namesThatRequireSync = new Set<keyof RawBridge>([
"rename_file",
"create_file_or_directory",
"delete_file_or_directory",
+ "copy_file_or_directory",
"move_file_or_directory",
"update_file",
]);
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index fd9db2c0ff..32364a942e 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -367,6 +367,8 @@ def _generate_server_api_schema() -> dict[str, Any]:
files.FileSearchResponse,
files.FileMoveRequest,
files.FileMoveResponse,
+ files.FileCopyRequest,
+ files.FileCopyResponse,
files.FileOpenRequest,
files.FileUpdateRequest,
files.FileUpdateResponse,
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index afe2346958..4fb4d776fa 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -46,6 +46,8 @@ from marimo._server.export.exporter import Exporter
from marimo._server.files.os_file_system import OSFileSystem
from marimo._server.models.export import ExportAsHTMLRequest
from marimo._server.models.files import (
+ FileCopyRequest,
+ FileCopyResponse,
FileCreateRequest,
FileCreateResponse,
FileDeleteRequest,
@@ -369,6 +371,20 @@ class PyodideBridge:
response = FileDeleteResponse(success=success)
return self._dump(response)
+ def copy_file_or_directory(
+ self,
+ request: str,
+ ) -> str:
+ body = self._parse(request, FileCopyRequest)
+ try:
+ info = self.file_system.copy_file_or_directory(
+ body.path, body.new_path
+ )
+ response = FileCopyResponse(success=True, info=info)
+ except Exception as e:
+ response = FileCopyResponse(success=False, message=str(e))
+ return self._dump(response)
+
def move_file_or_directory(
self,
request: str,
diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.py
index 1566f72baa..6a9451672c 100644
--- a/marimo/_server/api/endpoints/file_explorer.py
+++ b/marimo/_server/api/endpoints/file_explorer.py
@@ -11,6 +11,8 @@ from marimo._server.api.deps import AppState
from marimo._server.api.utils import parse_request
from marimo._server.files.os_file_system import OSFileSystem
from marimo._server.models.files import (
+ FileCopyRequest,
+ FileCopyResponse,
FileCreateRequest,
FileCreateResponse,
FileDeleteRequest,
@@ -157,6 +159,7 @@ async def delete_file_or_directory(
"""
body = await parse_request(request, cls=FileDeleteRequest)
try:
+ # TODO: Refactor this side-effect based validation to a dedicated validation.
file_system.get_details(body.path)
success = file_system.delete_file_or_directory(body.path)
return FileDeleteResponse(success=success)
@@ -165,6 +168,37 @@ async def delete_file_or_directory(
return FileDeleteResponse(success=False, message=str(e))
+@requires("edit")
+async def copy_file_or_directory(
+ *,
+ request: Request,
+) -> FileCopyResponse:
+ """
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/FileCopyRequest"
+ responses:
+ 200:
+ description: Copy a file or directory
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/FileCopyResponse"
+ """
+ body = await parse_request(request, cls=FileCopyRequest)
+ try:
+ # TODO: Refactor this side-effect based validation to a dedicated validation.
+ file_system.get_details(body.path)
+ info = file_system.copy_file_or_directory(body.path, body.new_path)
+ return FileCopyResponse(success=True, info=info)
+ except Exception as e:
+ LOGGER.error(f"Error copying file or directory: {e}")
+ return FileCopyResponse(success=False, message=str(e))
+
+
@router.post("/move")
@requires("edit")
async def move_file_or_directory(
@@ -187,11 +221,12 @@ async def move_file_or_directory(
"""
body = await parse_request(request, cls=FileMoveRequest)
try:
+ # TODO: Refactor this side-effect based validation to a dedicated validation.
file_system.get_details(body.path)
info = file_system.move_file_or_directory(body.path, body.new_path)
return FileMoveResponse(success=True, info=info)
except Exception as e:
- LOGGER.error(f"Error updating file or directory: {e}")
+ LOGGER.error(f"Error moving file or directory: {e}")
return FileMoveResponse(success=False, message=str(e))
@@ -218,6 +253,7 @@ async def update_file(
app_state = AppState(request)
body = await parse_request(request, cls=FileUpdateRequest)
try:
+ # TODO: Refactor this side-effect based validation to a dedicated validation.
file_system.get_details(body.path)
info = file_system.update_file(body.path, body.contents)
@@ -253,6 +289,7 @@ async def open_file(
"""
body = await parse_request(request, cls=FileOpenRequest)
try:
+ # TODO: Refactor this side-effect based validation to a dedicated validation.
file_system.get_details(body.path)
success = file_system.open_in_editor(body.path, body.line_number)
return SuccessResponse(success=success)
diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.py
index cb61e94b5d..61e5dca771 100644
--- a/marimo/_server/files/file_system.py
+++ b/marimo/_server/files/file_system.py
@@ -50,6 +50,10 @@ class FileSystem(ABC):
def delete_file_or_directory(self, path: str) -> bool:
"""Delete a file or directory."""
+ @abstractmethod
+ def copy_file_or_directory(self, path: str, new_path: str) -> FileInfo:
+ """Duplicate or copy a file or directory."""
+
@abstractmethod
def move_file_or_directory(self, path: str, new_path: str) -> FileInfo:
"""Rename or move a file or directory."""
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index 51572c6611..7be1e5088c 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -148,18 +148,7 @@ class OSFileSystem(FileSystem):
raise ValueError("Cannot create file or directory with empty name")
full_path = Path(path) / name
- # If the file already exists, generate a new name
- if full_path.exists():
- i = 1
- name_without_extension = full_path.stem
- extension = full_path.suffix
- while True:
- new_name = f"{name_without_extension}_{i}{extension}"
- new_full_path = full_path.parent / new_name
- if not new_full_path.exists():
- full_path = new_full_path
- break
- i += 1
+ full_path = _generate_unique_path(full_path)
if file_type == "directory":
full_path.mkdir(parents=True, exist_ok=True)
@@ -197,16 +186,22 @@ class OSFileSystem(FileSystem):
os.remove(path)
return True
+ def copy_file_or_directory(self, path: str, new_path: str) -> FileInfo:
+ new_path = str(_generate_unique_path(new_path))
+ if not _is_allowed_paths(path, new_path):
+ raise ValueError(f"Cannot copy to {new_path}")
+ if Path(path).is_dir():
+ shutil.copytree(path, new_path)
+ else:
+ shutil.copy2(path, new_path)
+ return self.get_details(new_path).file
+
def move_file_or_directory(self, path: str, new_path: str) -> FileInfo:
- file_name = os.path.basename(new_path)
- # Disallow renaming to . or ..
- if file_name in DISALLOWED_NAMES:
+ if not _is_allowed_paths(path, new_path):
raise ValueError(f"Cannot rename to {new_path}")
- # Disallow moving to an existing path or directory
- if os.path.exists(new_path) or os.path.isdir(new_path):
- raise ValueError(
- f"Destination path {new_path} already exists or is a directory"
- )
+ # Disallow moving to an existing path
+ if os.path.exists(new_path):
+ raise ValueError(f"Destination path {new_path} already exists")
safe_move(path, new_path)
return self.get_details(new_path).file
@@ -459,3 +454,29 @@ def safe_move(src: str, dst: str) -> None:
else:
shutil.copy2(src, dst)
src_path.unlink()
+
+
+def _generate_unique_path(new_path: str | Path) -> Path:
+ # If the file already exists, generate a new name
+ new_path = Path(new_path)
+ if not new_path.exists():
+ return new_path
+ i = 1
+ name_without_extension = new_path.stem
+ extension = new_path.suffix
+ while True:
+ new_name = f"{name_without_extension}_{i}{extension}"
+ new_path = new_path.parent / new_name
+ if not new_path.exists():
+ return new_path
+ i += 1
+
+
+def _is_allowed_paths(path: str | Path, new_path: str | Path) -> bool:
+ file_name = os.path.basename(new_path)
+ if file_name in DISALLOWED_NAMES or not file_name.strip():
+ return False
+
+ src = Path(path).resolve()
+ dst = Path(new_path).resolve()
+ return not (src.is_dir() and dst.is_relative_to(src))
diff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.py
index e0da19843f..9096e3b10d 100644
--- a/marimo/_server/models/files.py
+++ b/marimo/_server/models/files.py
@@ -73,6 +73,13 @@ class FileDeleteRequest(msgspec.Struct, rename="camel"):
path: str
+class FileCopyRequest(msgspec.Struct, rename="camel"):
+ # The current path of the file or directory
+ path: str
+ # The new path or name for the file or directory
+ new_path: str
+
+
class FileMoveRequest(msgspec.Struct, rename="camel"):
# The current path of the file or directory
path: str
@@ -116,6 +123,12 @@ class FileUpdateResponse(BaseResponse):
info: FileInfo | None = None
+class FileCopyResponse(BaseResponse):
+ # Additional information, e.g., error message
+ message: str | None = None
+ info: FileInfo | None = None
+
+
class FileMoveResponse(BaseResponse):
# Additional information, e.g., error message
message: str | None = None
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 2fa1ce09aa..34a57bd58e 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1632,6 +1632,35 @@ components:
- download
title: ExportAsScriptRequest
type: object
+ FileCopyRequest:
+ properties:
+ newPath:
+ type: string
+ path:
+ type: string
+ required:
+ - path
+ - newPath
+ title: FileCopyRequest
+ type: object
+ FileCopyResponse:
+ properties:
+ info:
+ anyOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/FileInfo'
+ default: null
+ message:
+ anyOf:
+ - type: string
+ - type: 'null'
+ default: null
+ success:
+ type: boolean
+ required:
+ - success
+ title: FileCopyResponse
+ type: object
FileCreateRequest:
properties:
contents:
@@ -6026,6 +6055,20 @@ paths:
description: Update the cell outputs
400:
description: File must be saved before downloading
+ /api/files/copy:
+ post:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FileCopyRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/FileCopyResponse'
+ description: Copy a file or directory
/api/files/create:
post:
requestBody:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 081a60be3d..c05abdb21b 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1088,6 +1088,45 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/files/copy": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["FileCopyRequest"];
+ };
+ };
+ responses: {
+ /** @description Copy a file or directory */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["FileCopyResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/files/create": {
parameters: {
query?: never;
@@ -4302,6 +4341,19 @@ export interface components {
ExportAsScriptRequest: {
download: boolean;
};
+ /** FileCopyRequest */
+ FileCopyRequest: {
+ newPath: string;
+ path: string;
+ };
+ /** FileCopyResponse */
+ FileCopyResponse: {
+ /** @default null */
+ info?: null | components["schemas"]["FileInfo"];
+ /** @default null */
+ message?: string | null;
+ success: boolean;
+ };
/** FileCreateRequest */
FileCreateRequest: {
/** @default null */
diff --git a/tests/_pyodide/test_pyodide_session.py b/tests/_pyodide/test_pyodide_session.py
index c602227eb3..07ab96fb9a 100644
--- a/tests/_pyodide/test_pyodide_session.py
+++ b/tests/_pyodide/test_pyodide_session.py
@@ -761,6 +761,31 @@ def test_pyodide_bridge_move_file(
assert new_path.exists()
+def test_pyodide_bridge_copy_file(
+ pyodide_bridge: PyodideBridge,
+ tmp_path: Path,
+) -> None:
+ """Test copying file through the bridge."""
+ test_file = tmp_path / "original.py"
+ test_file.write_text("# copy me")
+ new_path = tmp_path / "copied.py"
+
+ request_json = json.dumps(
+ {
+ "path": str(test_file),
+ "newPath": str(new_path),
+ }
+ )
+
+ result = pyodide_bridge.copy_file_or_directory(request_json)
+ response = json.loads(result)
+
+ assert response["success"] is True
+ assert test_file.exists()
+ assert new_path.exists()
+ assert new_path.read_text() == "# copy me"
+
+
def test_pyodide_bridge_update_file(
pyodide_bridge: PyodideBridge,
tmp_path: Path,
diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.py
index 086a9fdc91..e21d07ae73 100644
--- a/tests/_server/api/endpoints/test_file_explorer.py
+++ b/tests/_server/api/endpoints/test_file_explorer.py
@@ -172,6 +172,44 @@ def test_move_file_or_directory(client: TestClient) -> None:
assert response.json()["success"] is True
+def test_copy_file(client: TestClient) -> None:
+ file_path = Path(test_dir).joinpath("test_file.txt")
+ file_path.write_text("This is a test file for copying.")
+ copy_path = Path(test_dir).joinpath("test_file_copy.txt")
+ response = client.post(
+ "/api/files/copy",
+ headers=HEADERS,
+ json={
+ "path": test_file_path,
+ "newPath": str(copy_path),
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["success"] is True
+ assert copy_path.exists()
+ assert copy_path.read_text() == file_path.read_text()
+
+
+def test_copy_directory(client: TestClient) -> None:
+ sub_dir = Path(test_dir).joinpath("test_subdir")
+ sub_dir.mkdir(exist_ok=True)
+ inner_file = sub_dir.joinpath("inner.txt")
+ inner_file.write_text("inner content")
+
+ copy_sub_dir = Path(test_dir).joinpath("test_subdir_copy")
+ response = client.post(
+ "/api/files/copy",
+ headers=HEADERS,
+ json={
+ "path": str(sub_dir),
+ "newPath": str(copy_sub_dir),
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["success"] is True
+ assert copy_sub_dir.joinpath("inner.txt").read_text() == "inner content"
+
+
def test_open_file(client: TestClient) -> None:
response = client.post(
"/api/files/open",
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index e2c32fbd2b..55f57293cf 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -1,11 +1,16 @@
from __future__ import annotations
+import sys
from pathlib import Path
from typing import Literal
import pytest
-from marimo._server.files.os_file_system import OSFileSystem
+from marimo._server.files.os_file_system import (
+ OSFileSystem,
+ _generate_unique_path,
+ _is_allowed_paths,
+)
from marimo._server.models.files import FileDetailsResponse
from marimo._utils.files import natural_sort
@@ -681,3 +686,46 @@ def test_search_includes_file_metadata(
assert file_info.is_directory is False
assert file_info.is_marimo_file is False
assert file_info.last_modified is not None
+
+
+def test_generate_unique_path_new_path(tmp_path: Path) -> None:
+ base_path = tmp_path / "file.txt"
+ unique_path = _generate_unique_path(base_path)
+ assert unique_path == base_path
+
+
+def test_generate_unique_path_existing_path(tmp_path: Path) -> None:
+ base_path = tmp_path / "file.txt"
+ base_path.touch()
+ existing_path = tmp_path / "file_1.txt"
+ existing_path.touch()
+
+ unique_path = _generate_unique_path(base_path)
+ assert not unique_path.exists()
+ assert unique_path.name == "file_2.txt"
+
+
[email protected]("new_path", [".", "..", ""])
+def test_is_allowed_paths_disallowed_names(new_path: str) -> None:
+ assert not _is_allowed_paths("path/to/file.txt", f"path/to/{new_path}")
+
+
+def test_is_allowed_paths_subdirectory(tmp_path: Path) -> None:
+ base_path = tmp_path / "subdir"
+ base_path.mkdir()
+ assert not _is_allowed_paths(tmp_path, base_path)
+ assert not _is_allowed_paths(base_path, base_path)
+ assert not _is_allowed_paths(base_path, base_path / "../subdir/subsubdir")
+ assert _is_allowed_paths(base_path, base_path / "../subdir2")
+
+
+ sys.platform == "win32",
+ reason="Symlinks on Windows require Admin privileges",
+)
+def test_is_allowed_paths_recursive_symlink(tmp_path: Path) -> None:
+ src = tmp_path / "src"
+ src.mkdir()
+ dst_link = tmp_path / "link_to_src"
+ dst_link.symlink_to(src)
+ assert not _is_allowed_paths(src, dst_link / "child")