Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ Run `colab <command> --help` to view specific options, defaults, and detailed he
| Command | Description |
| --- | --- |
| `colab ls [-s NAME] [PATH]` | List remote files on the VM |
| `colab upload [-s NAME] LOCAL REMOTE` | Upload a local file to the VM filesystem |
| `colab download [-s NAME] REMOTE LOCAL` | Download a remote file from the VM filesystem |
| `colab upload [-s NAME] [-r] LOCAL REMOTE` | Upload a local file or directory (`-r`) to the VM filesystem |
| `colab download [-s NAME] [-r] REMOTE LOCAL` | Download a remote file or directory (`-r`) from the VM filesystem |
| `colab rm [-s NAME] PATH` | Delete a remote file on the VM filesystem |
| `colab edit [-s NAME] PATH` | Edit a remote file in-place using your local `$EDITOR` |

Expand Down
4 changes: 4 additions & 0 deletions docs/03_file_management.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
---
log:
2026-11-20: Took upstream PR #267 (`colab upload -r` / `colab download -r`, by Koji Shukawa) before Google merged it, with its review comments applied: no `ntpath` import (a drive-prefixed entry name is still refused on Windows, through `os.path.splitdrive`), simpler `posixpath.join` calls, `_is_local_symlink` so a destination given as `link/` is still seen as a symlink on POSIX, and HTTP errors without the URL (the fork's message, which hides the runtime proxy token). Tested live on a Colab web UI runtime: a tree with subfolders and an empty folder uploaded and downloaded back identical.
2026-11-19: Added `-r`/`--recursive` support to `colab upload` and `colab download` via `ContentsClient.mkdir`, `_ensure_dir`, `upload_dir`, and `download_dir` (preserving empty directories, skipping symlinks on upload, handling single-file `download -r` targets, normalizing remote paths, and enforcing entry-name, canonical local-symlink/containment, and recursion-depth checks). Reused a persistent `requests.Session` in `ContentsClient` with `close()`/context-manager cleanup (reopening a fresh client after `$EDITOR` in `colab edit`) for HTTP keep-alive, and redacted `colab-runtime-proxy-token` query params from `HTTPError` messages.
2026-11-12: Errors no longer show the runtime proxy token: `ContentsClient` reports an HTTP error as status and path (requests put the full URL, token included, in its message) and the file commands print errors through `common.redact_secrets`. Under Git Bash on Windows, remote paths that MSYS rewrote (`/content` -> `C:/Program Files/Git/content`) are turned back by `utils.undo_msys_path`. A failing editor in `colab edit` prints `[colab] ...: Editing failed` and exits 1 instead of a traceback (Typer vendors its own Click and does not handle `click.ClickException`).
---

Expand Down Expand Up @@ -32,11 +34,13 @@ File management on the Colab VM will be implemented using the Jupyter Contents A
```
- **Base64 Encoding**: Use `format: base64` for binary files.
- **Progress**: Implement a simple progress bar for large uploads by chunking or providing status updates.
- **Recursive (`-r` / `--recursive`)**: Walks a local directory top-down (`followlinks=False`), creates the remote directory (and any missing parent directories) with `PUT /api/contents/<path>` (`{"type": "directory"}`), and uploads files using POSIX `/` paths. Uploading a directory without `-r` exits non-zero with a `-r/--recursive` hint.

### 3. Downloading Files (`colab download`)
- **API**: `GET /api/contents/<remote_path>?content=1` (as seen in HAR).
- **Response**: JSON with `content` field.
- **Handling**: Decodes content based on `format` (`base64`, `json`, or plain `text`) and saves it locally.
- **Recursive (`-r` / `--recursive`)**: Walks remote directories returned by the Contents API, creates matching local directories (including empty directories), validates entry names against path traversal, and downloads nested files/notebooks (or falls back to downloading a single file if `remote_path` is not a directory). Non-recursive `download` raises `IsADirectoryError` with a `-r/--recursive` hint when targeting a directory.

### 4. Deleting Files (`colab rm`)
- **API**: `DELETE /api/contents/<remote_path>`.
Expand Down
112 changes: 88 additions & 24 deletions src/colab_cli/commands/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ def ls(
except Exception as e:
typer.echo(f"[colab] Error: {redact_secrets(str(e))}")
raise typer.Exit(1)
finally:
contents.close()


def rm(
Expand All @@ -78,36 +80,70 @@ def rm(
except Exception as e:
typer.echo(f"[colab] Error: {redact_secrets(str(e))}")
raise typer.Exit(1)
finally:
contents.close()


def upload(
session: Annotated[
Optional[str], typer.Option("-s", "--session", help="Session name")
] = None,
local_path: Annotated[str, typer.Argument(help="Local file to upload")] = ...,
local_path: Annotated[
str, typer.Argument(help="Local file or directory to upload")
] = ...,
remote_path: Annotated[str, typer.Argument(help="Remote path to upload to")] = ...,
recursive: Annotated[
bool,
typer.Option("-r", "--recursive", help="Recursively upload a directory"),
] = False,
):
"""Upload a file to a session"""
"""Upload a file or directory to a session"""
from colab_cli.common import state

name = state.resolve_session(session)
remote_path = undo_msys_path(remote_path)
s = state.get_session(name)
if not os.path.isfile(local_path):
typer.echo(f"[colab] Local file '{local_path}' not found.")
is_dir = os.path.isdir(local_path)
if is_dir and not recursive:
typer.echo(
f"[colab] '{local_path}' is a directory. Use -r/--recursive to upload directories."
)
raise typer.Exit(1)
if not is_dir and not os.path.isfile(local_path):
label = "path" if recursive else "file"
typer.echo(f"[colab] Local {label} '{local_path}' not found.")
raise typer.Exit(1)
contents = ContentsClient(s)
try:
contents.upload(local_path, remote_path)
state.history.log_event(
name,
"file_operation",
{"op": "upload", "local": local_path, "remote": remote_path},
)
typer.echo(f"[colab] Uploaded '{local_path}' to '{remote_path}'")
if is_dir:
count = contents.upload_dir(local_path, remote_path)
state.history.log_event(
name,
"file_operation",
{
"op": "upload",
"local": local_path,
"remote": remote_path,
"recursive": True,
"count": count,
},
)
typer.echo(
f"[colab] Uploaded directory '{local_path}' ({count} file(s)) to '{remote_path}'"
)
else:
contents.upload(local_path, remote_path)
state.history.log_event(
name,
"file_operation",
{"op": "upload", "local": local_path, "remote": remote_path},
)
typer.echo(f"[colab] Uploaded '{local_path}' to '{remote_path}'")
except Exception as e:
typer.echo(f"[colab] Upload failed: {redact_secrets(str(e))}")
raise typer.Exit(1)
finally:
contents.close()


def download(
Expand All @@ -118,27 +154,50 @@ def download(
str, typer.Argument(help="Remote path to download from")
] = ...,
local_path: Annotated[
str, typer.Argument(help="Local path to save the file")
str, typer.Argument(help="Local path to save the file or directory")
] = ...,
recursive: Annotated[
bool,
typer.Option("-r", "--recursive", help="Recursively download a directory"),
] = False,
):
"""Download a file from a session"""
"""Download a file or directory from a session"""
from colab_cli.common import state

name = state.resolve_session(session)
remote_path = undo_msys_path(remote_path)
s = state.get_session(name)
contents = ContentsClient(s)
try:
contents.download(remote_path, local_path)
state.history.log_event(
name,
"file_operation",
{"op": "download", "remote": remote_path, "local": local_path},
)
typer.echo(f"[colab] Downloaded '{remote_path}' to '{local_path}'")
if recursive:
count = contents.download_dir(remote_path, local_path)
state.history.log_event(
name,
"file_operation",
{
"op": "download",
"remote": remote_path,
"local": local_path,
"recursive": True,
"count": count,
},
)
typer.echo(
f"[colab] Downloaded '{remote_path}' ({count} file(s)) to '{local_path}'"
)
else:
contents.download(remote_path, local_path)
state.history.log_event(
name,
"file_operation",
{"op": "download", "remote": remote_path, "local": local_path},
)
typer.echo(f"[colab] Downloaded '{remote_path}' to '{local_path}'")
except Exception as e:
typer.echo(f"[colab] Download failed: {redact_secrets(str(e))}")
raise typer.Exit(1)
finally:
contents.close()


def _launch_editor(path: str) -> None:
Expand Down Expand Up @@ -184,8 +243,6 @@ def edit(
remote_path = undo_msys_path(remote_path)
s = state.get_session(name)

contents = ContentsClient(s)

def get_file_hash(path):
if not os.path.exists(path):
return None
Expand All @@ -201,11 +258,14 @@ def get_file_hash(path):
tmpdir, os.path.basename(remote_path.rstrip("/")) or "file"
)

dl_client = ContentsClient(s)
try:
contents.download(remote_path, local_path)
dl_client.download(remote_path, local_path)
except Exception:
# If download fails, assume file doesn't exist and start empty
pass
finally:
dl_client.close()
if not os.path.exists(local_path):
open(local_path, "wb").close()

Expand All @@ -222,7 +282,11 @@ def get_file_hash(path):
hash_after = get_file_hash(local_path)

if hash_after != hash_before:
contents.upload(local_path, remote_path)
ul_client = ContentsClient(s)
try:
ul_client.upload(local_path, remote_path)
finally:
ul_client.close()
state.history.log_event(
name,
"file_operation",
Expand Down
Loading
Loading