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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: file explorer panel (#700)
Myles Scolnick36d3d24db7b8
diff --git a/frontend/package.json b/frontend/package.jsonindex a1fa37a334..23963f7261 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -90,6 +90,7 @@"mermaid": "^10.7.0","partysocket": "0.0.25","plotly.js": "^2.28.0",+ "react-arborist": "^3.4.0","react-day-picker": "^8.10.0","react-dropzone": "^14.2.3","react-error-boundary": "^4.0.12",@@ -103,6 +104,7 @@"tailwind-merge": "^1.14.0","tailwindcss-animate": "^1.0.7","timestring": "^7.0.0",+ "use-resize-observer": "^9.1.0","vega-lite": "^5.16.3","vega-loader": "^4.5.1","vscode-languageserver-protocol": "^3.17.5",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 5e14461402..0283df7c8b 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -239,6 +239,9 @@ dependencies:plotly.js:specifier: ^2.28.0version: 2.28.0([email protected])+ react-arborist:+ specifier: ^3.4.0react-day-picker:specifier: ^8.10.0version: 8.10.0([email protected])([email protected])@@ -278,6 +281,9 @@ dependencies:timestring:specifier: ^7.0.0version: 7.0.0+ use-resize-observer:+ specifier: ^9.1.0+ version: 9.1.0([email protected])([email protected])vega-lite:specifier: ^5.16.3version: 5.16.3([email protected])@@ -4813,6 +4819,18 @@ packages:react: 18.2.0dev: false+ /@react-dnd/[email protected]:+ resolution: {integrity: sha512-kLy0PJDDwvwwTXxqTFNAAllPHD73AycE9ypWeln/IguoGBEbvFcPDbCV03G52bEcC5E+YgupBE0VzHGdC8SIXg==}+ dev: false++ /@react-dnd/[email protected]:+ resolution: {integrity: sha512-xL4RCQBCBDJ+GRwKTFhGUW8GXa4yoDfJrPbLblc3U09ciS+9ZJXJ3Qrcs/x2IODOdIE5kQxvMmE2UKyqUictUw==}+ dev: false++ /@react-dnd/[email protected]:+ resolution: {integrity: sha512-Pc/AFTdwZwEKJxFJvlxrSmGe/di+aAOBn60sremrpLo6VI/6cmiUYNNwlI5KNYttg7uypzA3ILPMPgxB2GYZEg==}+ dev: false+/@react-stately/[email protected]([email protected]):resolution: {integrity: sha512-yPKFY1F88HxuZ15BG2qwAYxtpE4HnIU0Ofi4CuBE0xC6I8mwo4OQjDzi+DZjxQngM9D6AeTTD6F1V8gkozA0Gw==}peerDependencies:@@ -9273,6 +9291,14 @@ packages:resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}+ resolution: {integrity: sha512-+PVS2VPTgKFPYWo3vAFEA8WPbTf7/xo43TifH9G8S1KqnrQu0o77A3unrF5yOugy4mIz7K5wAVFHUcha7wsz6A==}+ dependencies:+ '@react-dnd/asap': 4.0.1+ '@react-dnd/invariant': 2.0.0+ redux: 4.2.1+ dev: false+resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}engines: {node: '>=0.10.0'}@@ -12142,6 +12168,10 @@ packages:engines: {node: '>= 0.6'}dev: true+ resolution: {integrity: sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q==}+ dev: false+resolution: {integrity: sha512-/EuHYwAPdLtXwAwSZkh/Gutery6pD2KYd44oQLhAvQp/50mpyduZh8Q7PYHXTCJ+wuXxt7oij2LXyIJOOYFPog==}dependencies:@@ -13884,6 +13914,25 @@ packages:unpipe: 1.0.0dev: true+ resolution: {integrity: sha512-QI46oRGXJr0oaQfqqVobIiIoqPp5Y5gM69D2A2P7uHVif+X75XWnScR5drC7YDKgJ4CXVaDeFwnYKOWRRfncMg==}+ peerDependencies:+ react: '>= 16.14'+ react-dom: '>= 16.14'+ dependencies:+ react: 18.2.0+ react-dnd: 14.0.5(@types/[email protected])([email protected])+ react-dnd-html5-backend: 14.1.0+ react-dom: 18.2.0([email protected])+ react-window: 1.8.10([email protected])([email protected])+ redux: 5.0.1+ use-sync-external-store: 1.2.0([email protected])+ transitivePeerDependencies:+ - '@types/hoist-non-react-statics'+ - '@types/node'+ - '@types/react'+ dev: false+resolution: {integrity: sha512-1exovf0uGTGyq5mXQT0zgQ80uvj2PCwvF8zY1RN9/vbJVSjSo3fsB/4L3ObbF7u70NduSiK4xu4Y6q1MHoUGEw==}peerDependencies:@@ -13904,6 +13953,36 @@ packages:react: 18.2.0dev: false+ resolution: {integrity: sha512-6ONeqEC3XKVf4eVmMTe0oPds+c5B9Foyj8p/ZKLb7kL2qh9COYxiBHv3szd6gztqi/efkmriywLUVlPotqoJyw==}+ dependencies:+ dnd-core: 14.0.1+ dev: false++ resolution: {integrity: sha512-9i1jSgbyVw0ELlEVt/NkCUkxy1hmhJOkePoCH713u75vzHGyXhPDm28oLfc2NMSBjZRM1Y+wRjHXJT3sPrTy+A==}+ peerDependencies:+ '@types/hoist-non-react-statics': '>= 3.3.1'+ '@types/node': '>= 12'+ '@types/react': '>= 16'+ react: '>= 16.14'+ peerDependenciesMeta:+ '@types/hoist-non-react-statics':+ optional: true+ '@types/node':+ optional: true+ '@types/react':+ optional: true+ dependencies:+ '@react-dnd/invariant': 2.0.0+ '@react-dnd/shallowequal': 2.0.0+ '@types/react': 18.2.48+ dnd-core: 14.0.1+ fast-deep-equal: 3.1.3+ hoist-non-react-statics: 3.3.2+ react: 18.2.0+ dev: false+resolution: {integrity: sha512-tvg2ZtOpOi6QDwsb3GZhOjDkkX0h8Z2gipvTg6OVMUyoYoURhEiRNePT8NZItTVCDh39JJHnLdfCOkzoLbFnTg==}peerDependencies:@@ -14172,6 +14251,19 @@ packages:vega-lite: 5.16.3([email protected])dev: false+ resolution: {integrity: sha512-Y0Cx+dnU6NLa5/EvoHukUD0BklJ8qITCtVEPY1C/nL8wwoZ0b5aEw8Ff1dOVHw7fCzMt55XfJDd8S8W8LCaUCg==}+ engines: {node: '>8.0.0'}+ peerDependencies:+ react: ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0+ react-dom: ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0+ dependencies:+ '@babel/runtime': 7.23.8+ memoize-one: 5.2.1+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ dev: false+resolution: {integrity: sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==}engines: {node: '>=0.10.0'}@@ -14302,6 +14394,16 @@ packages:strip-indent: 4.0.0dev: true+ resolution: {integrity: sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==}+ dependencies:+ '@babel/runtime': 7.23.8+ dev: false++ resolution: {integrity: sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==}+ dev: false+resolution: {integrity: sha512-ECkTw8TmJwW60lOTR+ZkODISW6RQ8+2CL3COqtiJKLd6MmB45hN51HprHFziKLGkAuTGQhBb91V8cy+KHlaCjw==}engines: {node: '>= 0.4'}diff --git a/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsxnew file mode 100644index 0000000000..3fe1f38af9--- /dev/null+++ b/frontend/src/components/editor/chrome/panels/file-explorer-panel.tsx@@ -0,0 +1,16 @@+/* Copyright 2024 Marimo. All rights reserved. */++import React from "react";+import useResizeObserver from "use-resize-observer";+import { FileExplorer } from "../../file-tree/file-explorer";++export const FileExplorerPanel: React.FC = (props) => {+ const { ref, height = 1 } = useResizeObserver<HTMLDivElement>();++ return (+ <div ref={ref} className="h-full">+ <div id="noop-dnd-container" />+ <FileExplorer height={height} />+ </div>+ );+};diff --git a/frontend/src/components/editor/chrome/types.ts b/frontend/src/components/editor/chrome/types.tsindex 647ba477da..cdbfee5a69 100644--- a/frontend/src/components/editor/chrome/types.ts+++ b/frontend/src/components/editor/chrome/types.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */export type PanelType =+ | "files"| "errors"| "variables"| "outline"diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsxindex 32660d923d..b4a8ef70be 100644--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx@@ -19,6 +19,7 @@ import { DependencyGraphPanel } from "@/components/editor/chrome/panels/dependenimport { VariablePanel } from "../panels/variable-panel";import { LogsPanel } from "../panels/logs-panel";import { DocumentationPanel } from "../panels/documentation-panel";+import { FileExplorerPanel } from "../panels/file-explorer-panel";export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {const { isOpen, selectedPanel, panelLocation } = useChromeState();@@ -86,6 +87,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {<XIcon className="w-4 h-4" /></Button></div>+ {selectedPanel === "files" && <FileExplorerPanel />}{selectedPanel === "errors" && <ErrorsPanel />}{selectedPanel === "variables" && <VariablePanel />}{selectedPanel === "dependencies" && <DependencyGraphPanel />}diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsxindex 2c387c5990..273b98d84d 100644--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx@@ -10,6 +10,7 @@ import {FileTextIcon,MessageCircleQuestionIcon,BookMarkedIcon,+ FolderTreeIcon,} from "lucide-react";import { cn } from "@/utils/cn";import { useChromeActions, useChromeState } from "../state";@@ -37,6 +38,13 @@ export const Footer: React.FC = () => {/><span className="font-mono mt-[0.125rem]">{errorCount}</span></FooterItem>+ <FooterItem+ tooltip="View files"+ selected={selectedPanel === "files"}+ onClick={() => openApplication("files")}+ >+ <FolderTreeIcon className={cn("h-5 w-5")} />+ </FooterItem><FooterItemtooltip="Explore variables"selected={selectedPanel === "variables"}diff --git a/frontend/src/components/editor/file-tree/file-explorer.tsx b/frontend/src/components/editor/file-tree/file-explorer.tsxnew file mode 100644index 0000000000..ff200f08ad--- /dev/null+++ b/frontend/src/components/editor/file-tree/file-explorer.tsx@@ -0,0 +1,149 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { NodeApi, NodeRendererProps, Tree, SimpleTree } from "react-arborist";++import React, { useMemo, useState } from "react";+import { ChevronDownIcon, ChevronRightIcon } from "lucide-react";+import { useOnMount } from "@/hooks/useLifecycle";+import { sendListFiles } from "@/core/network/requests";+import { FileInfo } from "@/core/network/types";+import {+ FILE_TYPE_ICONS,+ FileType,+ PYTHON_CODE_FOR_FILE_TYPE,+ guessFileType,+} from "./types";+import { toast } from "@/components/ui/use-toast";++export const FileExplorer: React.FC<{+ height: number;+}> = ({ height }) => {+ const [data, setData] = useState<FileInfo[]>([]);+ const tree = useMemo(() => new SimpleTree<FileInfo>(data), [data]);++ useOnMount(() => {+ if (data.length > 0) {+ return;+ }+ // Fetch initial data on mount+ sendListFiles({ path: undefined }).then((data) => {+ setData(data.files);+ });+ });++ // This is a HACK so that we don't opt into react-arborist's drag and drop+ // Their DnD implementation is removable and it causes issues with our+ // our own DnD+ const element = document.getElementById("noop-dnd-container");+ if (!element) {+ return null;+ }++ return (+ <>+ <Tree<FileInfo>+ width="100%"+ height={height}+ className="h-full"+ data={tree.data}+ dndRootElement={element}+ openByDefault={false}+ onToggle={(id) => {+ const node = tree.find(id);+ if (!node) {+ return;+ }+ if (!node.data.isDirectory) {+ return;+ }++ // We may attempt to load empty directories multiple times+ // but that is fine+ if (node.children && node.children.length > 0) {+ // Already loaded+ return;+ }++ sendListFiles({ path: id }).then((data) => {+ tree.update({ id, changes: { children: data.files } });+ setData(tree.data);+ });+ }}+ padding={15}+ rowHeight={30}+ indent={INDENT_STEP}+ overscanCount={1000}+ // Disable all interactions+ disableMultiSelection={true}+ disableDrag={true}+ disableDrop={true}+ disableEdit={true}+ >+ {Node}+ </Tree>+ <div id="noop-dnd-container" />+ </>+ );+};++const INDENT_STEP = 15;++const Node = ({ node, style }: NodeRendererProps<FileInfo>) => {+ const fileType: FileType = node.data.isDirectory+ ? "directory"+ : guessFileType(node.data.name);++ const Icon = FILE_TYPE_ICONS[fileType];++ return (+ <div+ style={style}+ className="flex items-center cursor-pointer gap-2 ml-2 text-muted-foreground whitespace-nowrap"+ onClick={(evt) => {+ if (node.data.isDirectory) {+ node.toggle();+ evt.stopPropagation();+ }+ }}+ >+ <FolderArrow node={node} />+ <span+ className="flex items-center gap-2 px-2 py-1 cursor-pointer hover:bg-accent/50 hover:text-accent-foreground rounded-l flex-1"+ draggable={true}+ onDragStart={(e) => {+ const { path } = node.data;+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);+ e.dataTransfer.setData("text/plain", pythonCode);+ e.stopPropagation();+ }}+ onClick={() => {+ if (node.data.isDirectory) {+ return;+ }++ toast({+ title: "Copied to clipboard",+ description:+ "Code to open the file has been copied to your clipboard. You can also drag and drop this file into the editor",+ });+ const { path } = node.data;+ const pythonCode = PYTHON_CODE_FOR_FILE_TYPE[fileType](path);+ navigator.clipboard.writeText(pythonCode);+ }}+ >+ <Icon className="w-5 h-5 flex-shrink-0" /> <span>{node.data.name}</span>+ </span>+ </div>+ );+};++const FolderArrow = ({ node }: { node: NodeApi<FileInfo> }) => {+ if (!node.data.isDirectory) {+ return <span className="w-5 h-5 flex-shrink-0" />;+ }++ return node.isOpen ? (+ <ChevronDownIcon className="w-5 h-5 flex-shrink-0" />+ ) : (+ <ChevronRightIcon className="w-5 h-5 flex-shrink-0" />+ );+};diff --git a/frontend/src/components/editor/file-tree/types.ts b/frontend/src/components/editor/file-tree/types.tsnew file mode 100644index 0000000000..9c457142b4--- /dev/null+++ b/frontend/src/components/editor/file-tree/types.ts@@ -0,0 +1,85 @@+/* Copyright 2024 Marimo. All rights reserved. */+import {+ DatabaseIcon,+ FileCodeIcon,+ FileIcon,+ FileJsonIcon,+ FileTextIcon,+ FolderIcon,+ ImageIcon,+ LucideIcon,+} from "lucide-react";++/* Copyright 2024 Marimo. All rights reserved. */+export type FileType =+ | "directory"+ | "python"+ | "code"+ | "json"+ | "text"+ | "image"+ | "data"+ | "unknown";++export function guessFileType(name: string): FileType {+ const ext = name.split(".").pop();+ if (ext === undefined) {+ return "unknown";+ }+ switch (ext.toLowerCase()) {+ case "py":+ return "python";+ case "txt":+ case "md":+ return "text";+ case "png":+ case "jpg":+ case "jpeg":+ case "gif":+ return "image";+ case "csv":+ return "data";+ case "json":+ return "json";+ // Non-exhaustive list of code file extensions+ case "js":+ case "ts":+ case "tsx":+ case "html":+ case "css":+ case "toml":+ case "yaml":+ case "yml":+ return "code";+ default:+ return "unknown";+ }+}++export const FILE_TYPE_ICONS: Record<FileType, LucideIcon> = {+ directory: FolderIcon,+ python: FileCodeIcon,+ json: FileJsonIcon,+ code: FileCodeIcon,+ text: FileTextIcon,+ image: ImageIcon,+ data: DatabaseIcon,+ unknown: FileIcon,+};++const TAB = " ";++export const PYTHON_CODE_FOR_FILE_TYPE: Record<+ FileType,+ (path: string) => string+> = {+ directory: (path) => `os.listdir("${path}")`,+ python: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,+ json: (path) =>+ `with open("${path}", "r") as _f:\n${TAB}_data = json.load(_f)\n`,+ code: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,+ text: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,+ image: (path) => `with open("${path}", "rb") as _f:\n${TAB}...\n`,+ data: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,+ unknown: (path) => `with open("${path}", "r") as _f:\n${TAB}...\n`,+};diff --git a/frontend/src/core/codemirror/dnd/extension.ts b/frontend/src/core/codemirror/dnd/extension.tsnew file mode 100644index 0000000000..63a605b009--- /dev/null+++ b/frontend/src/core/codemirror/dnd/extension.ts@@ -0,0 +1,29 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { Extension } from "@codemirror/state";+import { EditorView } from "@codemirror/view";++export function dndBundle(): Extension {+ return [+ EditorView.domEventHandlers({+ drop: (event: DragEvent, view: EditorView) => {+ const text = event.dataTransfer?.getData("text/plain");+ if (text) {+ event.preventDefault();+ const pos = view.posAtCoords({+ x: event.clientX,+ y: event.clientY,+ });+ if (pos !== null) {+ view.dispatch({+ changes: { from: pos, to: pos, insert: text },+ scrollIntoView: true,+ });+ }+ }+ },+ dragover: (event: DragEvent) => {+ event.preventDefault();+ },+ }),+ ];+}diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.tsindex 2ac37d13e3..9546ce2018 100644--- a/frontend/src/core/network/requests.ts+++ b/frontend/src/core/network/requests.ts@@ -22,6 +22,7 @@ import {RunRequests,EditRequests,SendStdin,+ FileListResponse,} from "./types";import { invariant } from "@/utils/invariant";@@ -134,6 +135,12 @@ function createNetworkRequests(): EditRequests & RunRequests {readCode: () => {return API.post<{}, { contents: string }>("/kernel/read_code", {});},+ sendListFiles: (request) => {+ return API.post<{ path: string | undefined }, FileListResponse>(+ "/files/list_files",+ request+ );+ },};}@@ -155,4 +162,5 @@ export const {saveCellConfig,sendFunctionRequest,readCode,+ sendListFiles,} = isStaticNotebook() ? createStaticRequests() : createNetworkRequests();diff --git a/frontend/src/core/network/static-requests.ts b/frontend/src/core/network/static-requests.tsindex ed0312bcc6..90c1f0e4d4 100644--- a/frontend/src/core/network/static-requests.ts+++ b/frontend/src/core/network/static-requests.ts@@ -50,5 +50,6 @@ export function createStaticRequests(): EditRequests & RunRequests {saveCellConfig: throwNotInEditMode,sendStdin: throwNotInEditMode,readCode: throwNotInEditMode,+ sendListFiles: throwNotInEditMode,};}diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.tsindex d1974f4991..9f9f497ab4 100644--- a/frontend/src/core/network/types.ts+++ b/frontend/src/core/network/types.ts@@ -106,6 +106,18 @@ interface ValueUpdate {value: unknown;}+export interface FileInfo {+ id: string;+ path: string;+ name: string;+ isDirectory: boolean;+ children: FileInfo[];+}++export interface FileListResponse {+ files: FileInfo[];+}+/*** Requests sent to the BE during run/edit mode.*/@@ -135,4 +147,8 @@ export interface EditRequests {saveAppConfig: (request: SaveAppConfigRequest) => Promise<null>;saveCellConfig: (request: SaveCellConfigRequest) => Promise<null>;readCode: () => Promise<{ contents: string }>;+ // File explorer requests+ sendListFiles: (request: {+ path: string | undefined;+ }) => Promise<FileListResponse>;}diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pynew file mode 100644index 0000000000..f655446ef9--- /dev/null+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -0,0 +1,91 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from starlette.authentication import requires+from starlette.requests import Request++from marimo import _loggers+from marimo._server.api.utils import parse_request+from marimo._server.files.os_file_system import OSFileSystem+from marimo._server.models.files import (+ FileCreateRequest,+ FileCreateResponse,+ FileDeleteRequest,+ FileDeleteResponse,+ FileDetailsRequest,+ FileDetailsResponse,+ FileListRequest,+ FileListResponse,+ FileUpdateRequest,+ FileUpdateResponse,+)+from marimo._server.router import APIRouter++LOGGER = _loggers.marimo_logger()++# Router for file system endpoints+router = APIRouter()++file_system = OSFileSystem()++[email protected]("/list_files")+@requires("edit")+async def list_files(+ *,+ request: Request,+) -> FileListResponse:+ """List files and directories in a given path."""+ body = await parse_request(request, cls=FileListRequest)+ files = file_system.list_files(body.path or file_system.get_root())+ return FileListResponse(files=files)++[email protected]("/file_details")+@requires("edit")+async def file_details(+ *,+ request: Request,+) -> FileDetailsResponse:+ """Get details of a specific file or directory."""+ body = await parse_request(request, cls=FileDetailsRequest)+ file_info = file_system.get_details(body.path)+ return FileDetailsResponse(file=file_info)++[email protected]("/create")+@requires("edit")+async def create_file_or_directory(+ *,+ request: Request,+) -> FileCreateResponse:+ """Create a new file or directory."""+ body = await parse_request(request, cls=FileCreateRequest)+ success = file_system.create_file_or_directory(+ body.path, body.type, body.name+ )+ return FileCreateResponse(success=success)++[email protected]("/delete")+@requires("edit")+async def delete_file_or_directory(+ *,+ request: Request,+) -> FileDeleteResponse:+ """Delete a file or directory."""+ body = await parse_request(request, cls=FileDeleteRequest)+ success = file_system.delete_file_or_directory(body.path)+ return FileDeleteResponse(success=success)++[email protected]("/update")+@requires("edit")+async def update_file_or_directory(+ *,+ request: Request,+) -> FileUpdateResponse:+ """Rename or move a file or directory."""+ body = await parse_request(request, cls=FileUpdateRequest)+ success = file_system.update_file_or_directory(body.path, body.new_path)+ return FileUpdateResponse(success=success)diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.pyindex d8195b306c..adb88f7365 100644--- a/marimo/_server/api/router.py+++ b/marimo/_server/api/router.py@@ -5,6 +5,7 @@ from marimo._server.api.endpoints.assets import router as assets_routerfrom marimo._server.api.endpoints.config import router as config_routerfrom marimo._server.api.endpoints.editing import router as editing_routerfrom marimo._server.api.endpoints.execution import router as execution_router+from marimo._server.api.endpoints.file_explorer import router as file_explorerfrom marimo._server.api.endpoints.files import router as files_routerfrom marimo._server.api.endpoints.ws import router as ws_routerfrom marimo._server.router import APIRouter@@ -17,6 +18,9 @@ app_router.include_router(app_router.include_router(config_router, prefix="/api/kernel", name="config")app_router.include_router(editing_router, prefix="/api/kernel", name="editing")app_router.include_router(files_router, prefix="/api/kernel", name="files")+app_router.include_router(+ file_explorer, prefix="/api/files", name="file_explorer"+)app_router.include_router(assets_router)app_router.include_router(ws_router)diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.pynew file mode 100644index 0000000000..f2abd19443--- /dev/null+++ b/marimo/_server/files/file_system.py@@ -0,0 +1,44 @@+# Copyright 2024 Marimo. All rights reserved.+from abc import ABC, abstractmethod+from typing import List++from marimo._server.models.files import FileInfo+++class FileSystem(ABC):+ @abstractmethod+ def get_root(self) -> str:+ """Get the root path."""+ pass++ @abstractmethod+ def list_files(self, path: str) -> List[FileInfo]:+ """List files and directories in a given path."""+ pass++ @abstractmethod+ def get_details(self, path: str) -> FileInfo:+ """Get details of a specific file or directory."""+ pass++ @abstractmethod+ def open_file(self, path: str) -> str:+ """Open and read the content of a file."""+ pass++ @abstractmethod+ def create_file_or_directory(+ self, path: str, file_type: str, name: str+ ) -> bool:+ """Create a new file or directory."""+ pass++ @abstractmethod+ def delete_file_or_directory(self, path: str) -> bool:+ """Delete a file or directory."""+ pass++ @abstractmethod+ def update_file_or_directory(self, path: str, new_path: str) -> bool:+ """Rename or move a file or directory."""+ passdiff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pynew file mode 100644index 0000000000..a49fbaa456--- /dev/null+++ b/marimo/_server/files/os_file_system.py@@ -0,0 +1,91 @@+# Copyright 2024 Marimo. All rights reserved.+import os+import shutil+from typing import List++from marimo._server.files.file_system import FileSystem+from marimo._server.models.files import FileInfo++IGNORE_LIST = [+ "__pycache__",+ "node_modules",+]++IGNORE_PREFIXES = [+ ".",+]+++class OSFileSystem(FileSystem):+ def get_root(self) -> str:+ return os.getcwd()++ def list_files(self, path: str) -> List[FileInfo]:+ files: List[FileInfo] = []+ with os.scandir(path) as it:+ for entry in it:+ if entry.name in IGNORE_LIST:+ continue+ if any(+ entry.name.startswith(prefix) for prefix in IGNORE_PREFIXES+ ):+ continue++ info = FileInfo(+ id=entry.path,+ path=entry.path,+ name=entry.name,+ is_directory=entry.is_dir(),+ last_modified_date=entry.stat().st_mtime,+ )+ files.append(info)++ # Sort by directory first, then by name+ files.sort(key=lambda f: (not f.is_directory, f.name))++ return files++ def get_details(self, path: str) -> FileInfo:+ stat = os.stat(path)+ return FileInfo(+ id=path,+ path=path,+ name=os.path.basename(path),+ is_directory=os.path.isdir(path),+ last_modified_date=stat.st_mtime,+ )++ def open_file(self, path: str) -> str:+ with open(path, "r") as file:+ return file.read()++ def create_file_or_directory(+ self, path: str, file_type: str, name: str+ ) -> bool:+ full_path = os.path.join(path, name)+ try:+ if file_type == "directory":+ os.makedirs(full_path)+ else:+ with open(full_path, "w"):+ pass # Create an empty file+ return True+ except Exception:+ return False++ def delete_file_or_directory(self, path: str) -> bool:+ try:+ if os.path.isdir(path):+ shutil.rmtree(path)+ else:+ os.remove(path)+ return True+ except Exception:+ return False++ def update_file_or_directory(self, path: str, new_path: str) -> bool:+ try:+ shutil.move(path, new_path)+ return True+ except Exception:+ return Falsediff --git a/marimo/_server/models/base.py b/marimo/_server/models/base.pyindex 0a1eab735a..09c25b13c2 100644--- a/marimo/_server/models/base.py+++ b/marimo/_server/models/base.py@@ -17,10 +17,19 @@ def to_camel_case(snake_str: str) -> str:def deep_to_camel_case(snake_dict: Any) -> dict[str, Any]:+ if isinstance(snake_dict, list):+ return [deep_to_camel_case(item) for item in snake_dict] # type: ignore+ if isinstance(snake_dict, str):+ return to_camel_case(snake_dict) # type: ignore+camel_dict: dict[str, Any] = {}for key, value in snake_dict.items():if isinstance(value, dict):camel_dict[to_camel_case(key)] = deep_to_camel_case(value)+ elif isinstance(value, list):+ camel_dict[to_camel_case(key)] = [+ deep_to_camel_case(item) for item in value+ ]else:camel_dict[to_camel_case(key)] = valuereturn camel_dictdiff --git a/marimo/_server/models/files.py b/marimo/_server/models/files.pynew file mode 100644index 0000000000..3d7ffe5643--- /dev/null+++ b/marimo/_server/models/files.py@@ -0,0 +1,99 @@+# Copyright 2024 Marimo. All rights reserved.+from dataclasses import dataclass, field+from typing import List, Optional+++@dataclass+class FileInfo:+ id: str+ path: str+ name: str+ is_directory: bool+ last_modified_date: Optional[float] = None+ children: List["FileInfo"] = field(default_factory=list)+++@dataclass+class FileListRequest:+ # The directory path to list files from+ # If None, the root directory will be used+ path: Optional[str] = None+++@dataclass+class FileDetailsRequest:+ # The path of the file or directory+ path: str+++@dataclass+class FileOpenRequest:+ # The path of the file to open+ path: str+++@dataclass+class FileTreeRequest:+ # The root directory path for the tree+ path: str+++@dataclass+class FileCreateRequest:+ # The path where to create the file or directory+ path: str+ # 'file' or 'directory'+ type: str+ # The name of the file or directory+ name: str+++@dataclass+class FileDeleteRequest:+ # The path of the file or directory to delete+ path: str+++@dataclass+class FileUpdateRequest:+ # The current path of the file or directory+ path: str+ # The new path or name for the file or directory+ new_path: str+++@dataclass+class FileListResponse:+ files: List[FileInfo]+++@dataclass+class FileDetailsResponse:+ file: FileInfo+++@dataclass+class FileOpenResponse:+ # The content of the file+ content: str+++@dataclass+class FileCreateResponse:+ success: bool+ # Additional information, e.g., error message+ message: Optional[str] = None+++@dataclass+class FileDeleteResponse:+ success: bool+ # Additional information, e.g., error message+ message: Optional[str] = None+++@dataclass+class FileUpdateResponse:+ success: bool+ # Additional information, e.g., error message+ message: Optional[str] = Nonediff --git a/marimo/_server/models/test_base.py b/marimo/_server/models/test_base.pyindex 7cdca36001..b5fbd4ce2a 100644--- a/marimo/_server/models/test_base.py+++ b/marimo/_server/models/test_base.py@@ -1,5 +1,5 @@# Copyright 2024 Marimo. All rights reserved.-from marimo._server.models.base import to_camel_case+from marimo._server.models.base import deep_to_camel_case, to_camel_casedef test_camel_case() -> None:@@ -14,3 +14,48 @@ def test_camel_case() -> None:assert to_camel_case("") == ""assert to_camel_case("alreadyCamelCase") == "alreadyCamelCase"assert to_camel_case("With_Some_CAPS") == "withSomeCaps"+++def test_deep_to_camel_case() -> None:+ # Simple dictionary+ input_dict = {"first_key": "value1", "second_key": 2}+ expected_output = {"firstKey": "value1", "secondKey": 2}+ assert deep_to_camel_case(input_dict) == expected_output++ # Nested dictionary+ input_dict = {"outer_key": {"inner_key": "value"}}+ expected_output = {"outerKey": {"innerKey": "value"}}+ assert deep_to_camel_case(input_dict) == expected_output++ # List of dictionaries+ input_dict = {+ "list_key": [+ {"item_key": "item_value"},+ {"item_key_2": "item_value_2"},+ ]+ }+ expected_output = {+ "listKey": [{"itemKey": "item_value"}, {"itemKey2": "item_value_2"}]+ }+ assert deep_to_camel_case(input_dict) == expected_output++ # Mixed types and nested structures+ input_dict = {+ "first_level": {+ "second_level": [+ {"third_level_key_1": "value1"},+ {"third_level_key_2": "value2"},+ ],+ "another_second_level": "value",+ }+ }+ expected_output = {+ "firstLevel": {+ "secondLevel": [+ {"thirdLevelKey1": "value1"},+ {"thirdLevelKey2": "value2"},+ ],+ "anotherSecondLevel": "value",+ }+ }+ assert deep_to_camel_case(input_dict) == expected_outputdiff --git a/marimo/_server/router.py b/marimo/_server/router.pyindex 8d4cd0deff..8dc5bd96a6 100644--- a/marimo/_server/router.py+++ b/marimo/_server/router.py@@ -66,13 +66,32 @@ class APIRouter(Router):return decoratordef get(- self, path: str+ self, path: str, include_in_schema: bool = True) -> Callable[[DecoratedCallable], DecoratedCallable]:"""Get method."""def decorator(func: DecoratedCallable) -> DecoratedCallable:self.add_route(- path=self.prefix + path, endpoint=func, methods=["GET"]+ path=self.prefix + path,+ endpoint=func,+ methods=["GET"],+ include_in_schema=include_in_schema,+ )+ return func++ return decorator++ def delete(+ self, path: str, include_in_schema: bool = True+ ) -> Callable[[DecoratedCallable], DecoratedCallable]:+ """Delete method."""++ def decorator(func: DecoratedCallable) -> DecoratedCallable:+ self.add_route(+ path=self.prefix + path,+ endpoint=func,+ methods=["DELETE"],+ include_in_schema=include_in_schema,)return funcdiff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pynew file mode 100644index 0000000000..e91bf9df4f--- /dev/null+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -0,0 +1,81 @@+# Copyright 2024 Marimo. All rights reserved.+++import os+from tempfile import TemporaryDirectory++from starlette.testclient import TestClient++HEADERS = {+ "Marimo-Server-Token": "fake-token",+}++temp_dir = TemporaryDirectory()+test_dir = temp_dir.name+test_file_name = "test_file.txt"+test_file_path = os.path.join(test_dir, test_file_name)+test_content = "Hello, World!"+with open(test_file_path, "w") as f:+ f.write(test_content)+++def test_list_files(client: TestClient) -> None:+ response = client.post(+ "/api/files/list_files",+ headers=HEADERS,+ json={"path": test_dir},+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "files" in response.json()+++def test_file_details(client: TestClient) -> None:+ response = client.post(+ "/api/files/file_details",+ headers=HEADERS,+ json={"path": test_file_path},+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert "file" in response.json()+++def test_create_and_delete_file_or_directory(client: TestClient) -> None:+ # Create a file+ response = client.post(+ "/api/files/create",+ headers=HEADERS,+ json={+ "path": test_dir,+ "type": "file",+ "name": "new_file.txt",+ },+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert response.json()["success"] is True++ # Delete the file+ response = client.post(+ "/api/files/delete",+ headers=HEADERS,+ json={"path": f"{test_dir}/new_file.txt"},+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert response.json()["success"] is True+++def test_update_file_or_directory(client: TestClient) -> None:+ response = client.post(+ "/api/files/update",+ headers=HEADERS,+ json={+ "path": test_file_path,+ "new_path": os.path.join(test_dir, "renamed.txt"),+ },+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert response.json()["success"] is Truediff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pynew file mode 100644index 0000000000..876f338ffe--- /dev/null+++ b/tests/_server/files/test_os_file_system.py@@ -0,0 +1,77 @@+import os+import unittest+from tempfile import TemporaryDirectory++from marimo._server.files.os_file_system import OSFileSystem+from marimo._server.models.files import FileInfo+++class TestOSFileSystem(unittest.TestCase):+ def setUp(self):+ # Create a temporary directory for the tests+ self.temp_dir = TemporaryDirectory()+ self.test_dir = self.temp_dir.name+ self.fs = OSFileSystem()++ def tearDown(self):+ # Cleanup the temporary directory after each test+ self.temp_dir.cleanup()++ def test_create_file(self):+ test_file_name = "test_file.txt"+ self.fs.create_file_or_directory(self.test_dir, "file", test_file_name)+ expected_path = os.path.join(self.test_dir, test_file_name)+ assert os.path.exists(expected_path)++ def test_create_directory(self):+ test_dir_name = "test_dir"+ self.fs.create_file_or_directory(+ self.test_dir, "directory", test_dir_name+ )+ expected_path = os.path.join(self.test_dir, test_dir_name)+ assert os.path.isdir(expected_path)++ def test_list_files(self):+ # Create a test file and directory+ self.test_create_file()+ self.test_create_directory()+ files = self.fs.list_files(self.test_dir)+ assert len(files) == 2 # Expecting 1 file and 1 directory++ def test_get_details(self):+ test_file_name = "test_file.txt"+ self.fs.create_file_or_directory(self.test_dir, "file", test_file_name)+ file_info = self.fs.get_details(+ os.path.join(self.test_dir, test_file_name)+ )+ assert isinstance(file_info, FileInfo)+ assert file_info.name == test_file_name++ def test_open_file(self):+ test_file_name = "test_file.txt"+ test_content = "Hello, World!"+ with open(os.path.join(self.test_dir, test_file_name), "w") as f:+ f.write(test_content)+ content = self.fs.open_file(+ os.path.join(self.test_dir, test_file_name)+ )+ assert content == test_content++ def test_delete_file(self):+ test_file_name = "test_file.txt"+ file_path = os.path.join(self.test_dir, test_file_name)+ with open(file_path, "w"):+ pass+ self.fs.delete_file_or_directory(file_path)+ assert not os.path.exists(file_path)++ def test_update_file(self):+ original_file_name = "original.txt"+ new_file_name = "new.txt"+ original_path = os.path.join(self.test_dir, original_file_name)+ new_path = os.path.join(self.test_dir, new_file_name)+ with open(original_path, "w") as f:+ f.write("Test")+ self.fs.update_file_or_directory(original_path, new_path)+ assert os.path.exists(new_path)+ assert not os.path.exists(original_path)