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: Add version update check and print in 'marimo edit' (#360)

Myles Scolnick42098a3181bd
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 3104e76d0e..e7c5495947 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -16,6 +16,7 @@ from marimo._ast import codegen
from marimo._cli import ipynb_to_marimo
from marimo._cli.envinfo import get_system_info
from marimo._cli.file_path import validate_name
+from marimo._cli.upgrade import check_for_updates
from marimo._server.server import start_server
DEVELOPMENT_MODE = False
@@ -183,6 +184,9 @@ def edit(
headless: bool,
name: Optional[str] = None,
) -> None:
+ # Check for version updates
+ check_for_updates()
+
if name is not None:
# Validate name, or download from URL
# The second return value is an optional temporary directory. It is
diff --git a/marimo/_cli/print.py b/marimo/_cli/print.py
new file mode 100644
index 0000000000..e9c00995a4
--- /dev/null
+++ b/marimo/_cli/print.py
@@ -0,0 +1,11 @@
+# Copyright 2023 Marimo. All rights reserved.
+
+# Print helpers
+
+
+def green(text: str) -> str:
+ return "\033[32m" + text + "\033[0m"
+
+
+def orange(text: str) -> str:
+ return "\033[33m" + text + "\033[0m"
diff --git a/marimo/_cli/test_upgrade.py b/marimo/_cli/test_upgrade.py
new file mode 100644
index 0000000000..fde2031417
--- /dev/null
+++ b/marimo/_cli/test_upgrade.py
@@ -0,0 +1,104 @@
+# Copyright 2023 Marimo. All rights reserved.
+from datetime import datetime
+from typing import Any
+from unittest.mock import mock_open, patch
+
+from marimo._cli.upgrade import (
+ MarimoCLIState,
+ _update_with_latest_version,
+ check_for_updates,
+)
+
+
+@patch("marimo._cli.upgrade.current_version", "0.1.0")
+@patch("marimo._cli.upgrade.os.path.exists")
+@patch("marimo._cli.upgrade.os.makedirs")
+@patch(
+ "__main__.open",
+ new_callable=mock_open,
+)
+@patch("marimo._cli.upgrade._update_with_latest_version")
+@patch("builtins.print")
+def test_check_for_updates(
+ mock_print: Any,
+ mock_update_with_latest_version: Any,
+ mock_open_file: Any,
+ mock_makedirs: Any,
+ mock_path_exists: Any,
+) -> None:
+ # Mocks
+ mock_update_with_latest_version.return_value = MarimoCLIState(
+ latest_version="0.1.2", last_checked_at="2020-01-01"
+ )
+ mock_path_exists.return_value = True
+ mock_open_file.side_effect = FileNotFoundError()
+
+ # Call the function to test
+ check_for_updates()
+
+ # Assert that the makedirs function was not called
+ mock_makedirs.assert_not_called()
+
+ # Assert prints
+ assert any(
+ "0.1.0 → 0.1.2" in call[0][0] for call in mock_print.call_args_list
+ )
+ assert any(
+ "pip install --upgrade marimo" in call[0][0]
+ for call in mock_print.call_args_list
+ )
+
+
+@patch("marimo._cli.upgrade._fetch_data_from_url")
+def test_update_with_latest_version(mock_fetch_data_from_url: Any) -> None:
+ # Mocks
+ state = MarimoCLIState(
+ latest_version="0.1.0", last_checked_at="2020-01-01"
+ )
+ mock_fetch_data_from_url.return_value = {"info": {"version": "0.1.2"}}
+
+ # Run
+ updated_state = _update_with_latest_version(state)
+
+ # Assert that the latest_version was updated
+ assert updated_state.latest_version == "0.1.2"
+ # Assert that the last_checked_at was updated to the current date
+ today = datetime.now().date()
+ assert updated_state.last_checked_at == today.strftime("%Y-%m-%d")
+
+
+@patch("marimo._cli.upgrade._fetch_data_from_url")
+def test_update_with_latest_version_fails(
+ mock_fetch_data_from_url: Any,
+) -> None:
+ # Mocks
+ state = MarimoCLIState(
+ latest_version="0.1.0", last_checked_at="2020-01-01"
+ )
+ # Raises
+ mock_fetch_data_from_url.side_effect = Exception("pypi down!")
+
+ # Run
+ updated_state = _update_with_latest_version(state)
+
+ # Assert state is unchanged
+ assert state == updated_state
+
+
+@patch("marimo._cli.upgrade._fetch_data_from_url")
+def test_update_with_within_the_same_day(
+ mock_fetch_data_from_url: Any,
+) -> None:
+ # Mocks
+ state = MarimoCLIState(
+ latest_version="0.1.0",
+ last_checked_at=datetime.now().date().strftime("%Y-%m-%d"),
+ )
+
+ # Run
+ updated_state = _update_with_latest_version(state)
+
+ # Assert state is unchanged
+ assert state == updated_state
+ # Assert that the _fetch_data_from_url was not called
+ mock_fetch_data_from_url.assert_not_called()
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
new file mode 100644
index 0000000000..8638adae31
--- /dev/null
+++ b/marimo/_cli/upgrade.py
@@ -0,0 +1,118 @@
+# Copyright 2023 Marimo. All rights reserved.
+import json
+import os
+import urllib.request
+from dataclasses import asdict, dataclass
+from datetime import datetime
+from typing import Any, Dict, Optional
+
+import tomlkit
+from packaging import version
+
+from marimo import __version__ as current_version
+from marimo._cli.print import green, orange
+from marimo._utils.parse_dataclass import parse_raw
+
+
+@dataclass
+class MarimoCLIState:
+ latest_version: Optional[str] = None
+ last_checked_at: Optional[str] = None
+
+
+def check_for_updates() -> None:
+ try:
+ _check_for_updates_internal()
+ except Exception:
+ # Errors are caught internally
+ # but as a last resort, we don't want to crash the CLI
+ pass
+
+
+def _check_for_updates_internal() -> None:
+ # Find the state file
+ state_file = ".marimo/state.toml"
+ home_expansion = os.path.expanduser("~")
+ if home_expansion == "~":
+ # path expansion failed
+ return None
+ home_directory = os.path.realpath(home_expansion)
+ file_path = os.path.join(home_directory, state_file)
+
+ # Load the state file or create a default state if it doesn't exist
+ state: MarimoCLIState
+ try:
+ with open(file_path, "r") as file:
+ data = tomlkit.parse(file.read())
+ state = parse_raw(data, MarimoCLIState)
+ except FileNotFoundError:
+ state = MarimoCLIState()
+
+ # Maybe update the state with the latest version
+ state = _update_with_latest_version(state)
+
+ if not state.latest_version:
+ # We couldn't get the latest version, so do nothing
+ return
+
+ # Compare versions and warn if there's a new version
+ if current_version and version.parse(state.latest_version) > version.parse(
+ current_version
+ ):
+ message = (
+ f"Update available {(current_version)} → {state.latest_version}"
+ )
+ print(orange(message))
+ print(f"Run {green('pip install --upgrade marimo')} to upgrade.")
+ print()
+
+ # Save the state, create directories if necessary
+ _maybe_create_directory(file_path)
+ with open(file_path, "w") as file:
+ tomlkit.dump(asdict(state), file)
+
+
+def _maybe_create_directory(file_path: str) -> None:
+ marimo_directory = os.path.dirname(file_path)
+ if not os.path.exists(marimo_directory):
+ os.makedirs(marimo_directory)
+
+
+def _update_with_latest_version(state: MarimoCLIState) -> MarimoCLIState:
+ """
+ If we have not saved the latest version,
+ or its newer than the one we have, update it.
+ """
+ pypi_api_url = "https://pypi.org/pypi/marimo/json"
+
+ # Check if a day has passed since the last check
+ if state.last_checked_at:
+ last_checked_date = datetime.strptime(
+ state.last_checked_at, "%Y-%m-%d"
+ ).date()
+ if (datetime.now().date() - last_checked_date).days < 1:
+ # Less than a day has passed, so do nothing
+ return state
+
+ # Fetch the latest version from PyPI
+ try:
+ response = _fetch_data_from_url(pypi_api_url)
+ version = response["info"]["version"]
+ state.latest_version = version
+ state.last_checked_at = datetime.now().strftime("%Y-%m-%d")
+ return state
+ except Exception:
+ # Avoid errors blocking the CLI or adding noise
+ return state
+
+
+def _fetch_data_from_url(url: str) -> Dict[str, Any]:
+ with urllib.request.urlopen(url) as response:
+ if response.status == 200:
+ data = response.read()
+ encoding = response.info().get_content_charset("utf-8")
+ return json.loads(data.decode(encoding)) # type: ignore
+ else:
+ raise Exception(
+ f"HTTP request failed with status code {response.status}"
+ )