diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d784d2..0cdfc15 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,22 @@ jobs: - uses: astral-sh/setup-uv@v6 - run: echo "RUFF=$(uv export --only-group dev --no-hashes --frozen | grep '^ruff==')" >> "$GITHUB_ENV" - run: uvx --from "$RUFF" ruff format --check + # rustfmt and clippy, also on Windows, where the binary waits for Python. `make test` and + # the Windows job run the Rust tests. + rust: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy, rustfmt + - uses: Swatinem/rust-cache@v2 + - run: cargo fmt --check + - run: cargo clippy --workspace --all-targets -- -D warnings typecheck: runs-on: ubuntu-latest steps: @@ -31,6 +47,8 @@ jobs: - uses: astral-sh/setup-uv@v6 with: enable-cache: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - run: uv sync --frozen - run: make typecheck test: @@ -40,6 +58,8 @@ jobs: - uses: astral-sh/setup-uv@v6 with: enable-cache: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - run: uv sync --frozen - run: make test # The build's self-check runs the sandbox, which must also work on an instructor's Mac. @@ -50,6 +70,8 @@ jobs: - uses: astral-sh/setup-uv@v6 with: enable-cache: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - run: uv sync --frozen - run: make test # Students on Windows run the check panels, the export button, the selfcheck and the PDF. @@ -61,12 +83,16 @@ jobs: - uses: astral-sh/setup-uv@v6 with: enable-cache: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - run: uv sync --frozen + - run: cargo test --workspace - run: >- uv run pytest -q tests/test_config.py tests/test_source.py tests/test_transform.py tests/test_assertrewrite_guard.py tests/test_runner.py tests/test_check.py tests/test_loader.py tests/test_selfcheck.py tests/test_export.py tests/test_pdf.py + tests/test_binary.py # The autograder graded in Gradescope's base image. MOGS_REQUIRE_CONTAINER makes a missing # Docker fail the job instead of skipping the tests. docker: @@ -79,5 +105,7 @@ jobs: - uses: astral-sh/setup-uv@v6 with: enable-cache: true + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 - run: uv sync --frozen - run: uv run pytest -m docker -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..f5b0bf0 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,160 @@ +name: release +on: + release: + types: [published] +permissions: + contents: read +jobs: + # Tags look like `0.7`: the tag, padded with `.0` to three parts, must equal the version in + # Cargo.toml, which the wheels carry. + version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.check.outputs.version }} + steps: + - uses: actions/checkout@v4 + - id: check + env: + TAG: ${{ github.event.release.tag_name }} + run: | + version=$(sed -n 's/^version = "\(.*\)"$/\1/p' Cargo.toml) + padded="$TAG" + while [ "$(printf '%s' "$padded" | tr -cd . | wc -c)" -lt 2 ]; do + padded="$padded.0" + done + if [ "$padded" != "$version" ]; then + echo "::error::Release tag $TAG does not match version $version in Cargo.toml." + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + + # Each wheel is built on a runner of its architecture, so the smoke test can run it. + linux: + needs: version + strategy: + fail-fast: false + matrix: + runner: [ubuntu-latest, ubuntu-24.04-arm] + compatibility: [manylinux_2_17, musllinux_1_2] + include: + - runner: ubuntu-latest + target: x86_64 + - runner: ubuntu-24.04-arm + target: aarch64 + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.target }} + manylinux: ${{ matrix.compatibility }} + args: --release --out dist + - if: startsWith(matrix.compatibility, 'manylinux') + uses: astral-sh/setup-uv@v6 + # `mogs --version` imports only `mogs` and `packaging`, so no other dependency is needed. + - if: startsWith(matrix.compatibility, 'manylinux') + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + uv venv --python 3.13 smoke + uv pip install --python smoke --no-deps dist/*.whl packaging + test "$(smoke/bin/mogs --version)" = "mogs $VERSION" + - if: startsWith(matrix.compatibility, 'musllinux') + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + docker run --rm -v "$PWD/dist:/dist" -e VERSION python:3.13-alpine sh -euc ' + pip install --quiet --root-user-action=ignore --no-deps /dist/*.whl packaging + test "$(mogs --version)" = "mogs $VERSION" + ' + - uses: actions/upload-artifact@v4 + with: + name: wheels-linux-${{ matrix.target }}-${{ matrix.compatibility }} + path: dist + + # Both wheels are built on an arm64 runner. Only the arm64 one runs there. + macos: + needs: version + strategy: + fail-fast: false + matrix: + target: [aarch64, x86_64] + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.target }} + args: --release --out dist + - if: matrix.target == 'aarch64' + uses: astral-sh/setup-uv@v6 + - if: matrix.target == 'aarch64' + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + uv venv --python 3.13 smoke + uv pip install --python smoke --no-deps dist/*.whl packaging + test "$(smoke/bin/mogs --version)" = "mogs $VERSION" + - uses: actions/upload-artifact@v4 + with: + name: wheels-macos-${{ matrix.target }} + path: dist + + windows: + needs: version + strategy: + fail-fast: false + matrix: + include: + - runner: windows-latest + target: x64 + - runner: windows-11-arm + target: aarch64 + runs-on: ${{ matrix.runner }} + steps: + - uses: actions/checkout@v4 + - uses: PyO3/maturin-action@v1 + with: + target: ${{ matrix.target }} + args: --release --out dist + - uses: astral-sh/setup-uv@v6 + - shell: bash + env: + VERSION: ${{ needs.version.outputs.version }} + run: | + uv venv --python 3.13 smoke + uv pip install --python smoke --no-deps dist/*.whl packaging + test "$(smoke/Scripts/mogs.exe --version | tr -d '\r')" = "mogs $VERSION" + - uses: actions/upload-artifact@v4 + with: + name: wheels-windows-${{ matrix.target }} + path: dist + + sdist: + needs: version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: PyO3/maturin-action@v1 + with: + command: sdist + args: --out dist + - uses: actions/upload-artifact@v4 + with: + name: wheels-sdist + path: dist + + # Trusted publishing: PyPI trusts this workflow in the `pypi` environment. No token. + publish: + needs: [linux, macos, windows, sdist] + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@v4 + with: + pattern: wheels-* + merge-multiple: true + path: dist + - uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.gitignore b/.gitignore index 6489d71..7b8c5db 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ __pycache__/ .ruff_cache/ dist/ __marimo__/ +target/ diff --git a/AGENTS.md b/AGENTS.md index f36785d..1e3252e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ and a Gradescope autograder zip. Alpha: the API changes without deprecation. - Design, plans and progress notes live outside this repo, in the author's private planning directory. Never put design notes, plans or local paths in the repo. -- `src/mogs/`: the package, imported, published on PyPI and run as `mogs`. +- `src/mogs/`: the Python package, imported and published on PyPI. `config.py` reads the config from the notebook's `mogs.assignment(...)` and `mogs.grade(...)` calls (statically, from the AST) and edits the PEP 723 header as text. `scaffold.py` is `mogs init`. @@ -16,14 +16,28 @@ and a Gradescope autograder zip. Alpha: the API changes without deprecation. vendored for the PDF of written answers (`pdf.py`). They need the Typst version the `pdf` extra pins (`typst>=0.15,<0.16`): bump the pin and the vendored versions together. -- `tests/`: pytest suite. +- `crates/mogs/`: the `mogs` executable, in Rust. It runs + `python -P -m mogs.cli` with the interpreter in its own folder, found after + resolving symlinks. On Windows it then tries the folder above `Scripts`, + where a global `pip install` puts `python.exe`. Last comes + `$(uv tool dir)/mogs`, because uv copies tool executables on Windows. + maturin builds it into platform wheels together with + `src/mogs/`. The version is `[workspace.package] version` in `Cargo.toml`. + `src/mogs/_binary.py` finds and runs the installed executable. +- `tests/`: pytest suite. `cargo test` runs the Rust tests. - `tests/e2e/`: end-to-end tests. The `docker` ones build the demo autograder into Gradescope's base image (`tests/e2e/Dockerfile`) and grade submissions through the real `/autograder/run_autograder`. They need docker or podman (`MOGS_CONTAINER=docker|podman` picks one) and network, and take several - minutes. Without a runtime they skip; `MOGS_REQUIRE_CONTAINER=1` (set in CI) + minutes. The wheel for the image comes from `maturin build --zig` for + manylinux_2_17 x86_64, so it builds on any host. Without a runtime they skip; `MOGS_REQUIRE_CONTAINER=1` (set in CI) makes that a failure. The base image is amd64 only: on an arm64 host it runs under emulation, which is slow enough that grading timeouts may trip. +- `.github/workflows/release.yml`: on a published GitHub release (tags like + `0.7`, no `v`), checks the tag against the `Cargo.toml` version, builds the + wheels and the sdist, smoke-tests each wheel on a runner that can run it, + then publishes them all to PyPI through + trusted publishing. - `docs/`: the docs site (Astro Starlight, built with Bun), deployed to https://mogs.kristia.de by `.github/workflows/docs.yml`. Pages are `docs/src/content/docs/` (`index.md`, `instructors.md`, @@ -31,11 +45,14 @@ and a Gradescope autograder zip. Alpha: the API changes without deprecation. ## Commands -Always go through `uv` (never global Python). +Always go through `uv` (never global Python). The Rust toolchain is +`rust-toolchain.toml` (stable, with clippy and rustfmt). `uv sync` and +`uv run` rebuild the executable when `Cargo.toml`, `Cargo.lock` or a `.rs` +file changes. ```bash make sync # uv sync -make check # ruff check + format check, ty, pytest (the CI gate) +make check # ruff, cargo fmt + clippy, ty, cargo test, pytest (the CI gate) make docs # build the docs site into docs/dist (needs Bun) make docs-serve # live preview at localhost:4321 make test TESTS=tests/test_config.py ARGS="-k header" @@ -43,7 +60,7 @@ make test ARGS="-m slow" # only the slow tests (marimo via `uv run --with`; make test ARGS="-m network" # only the tests that resolve packages through uv (included by default) make test ARGS="-m 'not slow and not network'" # offline make test ARGS="-m docker" # only the Docker end-to-end tests: deselected unless `-m` names `docker` -make fix # ruff fixes, then format +make fix # ruff fixes, then ruff format and cargo fmt ``` ## Rules diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..de1ff0b --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,122 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "mogs" +version = "0.7.0" +dependencies = [ + "dunce", + "tempfile", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..321ed43 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[workspace] +members = ["crates/mogs"] +resolver = "3" + +[workspace.package] +version = "0.7.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/wiseodd/mogs" diff --git a/crates/mogs/Cargo.toml b/crates/mogs/Cargo.toml new file mode 100644 index 0000000..c6df8e7 --- /dev/null +++ b/crates/mogs/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "mogs" +description = "Build Gradescope autograders from marimo notebooks." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +dunce = "1" + +[dev-dependencies] +tempfile = "3" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Console"] } diff --git a/crates/mogs/src/main.rs b/crates/mogs/src/main.rs new file mode 100644 index 0000000..b519e64 --- /dev/null +++ b/crates/mogs/src/main.rs @@ -0,0 +1,59 @@ +//! The `mogs` command: runs `python -P -m mogs.cli` with the interpreter installed next to it. + +mod python; + +use std::process::{Command, ExitCode}; + +fn main() -> ExitCode { + let python = match python::interpreter() { + Ok(python) => python, + Err(error) => { + eprintln!("{error}"); + return ExitCode::FAILURE; + } + }; + + // `-P` keeps the working directory off `sys.path`, as for a console script. + let mut command = Command::new(&python); + command + .args(["-P", "-m", "mogs.cli"]) + .args(std::env::args_os().skip(1)); + + let error = run(command); + eprintln!("Cannot run {}: {error}", python.display()); + + ExitCode::FAILURE +} + +/// Replace this process with `command`. Returns only on failure. +#[cfg(unix)] +fn run(mut command: Command) -> std::io::Error { + use std::os::unix::process::CommandExt; + + command.exec() +} + +/// Run `command` and exit with its exit code. Returns only on failure. +/// +/// Ctrl+C reaches the child too, so this process ignores it and waits for the child to exit. +#[cfg(windows)] +fn run(mut command: Command) -> std::io::Error { + use windows_sys::Win32::Foundation::TRUE; + use windows_sys::Win32::System::Console::SetConsoleCtrlHandler; + use windows_sys::core::BOOL; + + unsafe extern "system" fn ignore(_event: u32) -> BOOL { + TRUE + } + + // SAFETY: `ignore` is a valid handler for the life of the process. + if unsafe { SetConsoleCtrlHandler(Some(ignore), TRUE) } == 0 { + let error = std::io::Error::last_os_error(); + return std::io::Error::new(error.kind(), format!("cannot ignore Ctrl+C: {error}")); + } + + match command.status() { + Ok(status) => std::process::exit(status.code().unwrap_or(1)), + Err(error) => error, + } +} diff --git a/crates/mogs/src/python.rs b/crates/mogs/src/python.rs new file mode 100644 index 0000000..8e33c50 --- /dev/null +++ b/crates/mogs/src/python.rs @@ -0,0 +1,308 @@ +//! The Python interpreter of the environment `mogs` is installed in. + +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Interpreter names to look for, in order. +#[cfg(windows)] +const NAMES: &[&str] = &["python.exe"]; +#[cfg(not(windows))] +const NAMES: &[&str] = &["python3", "python"]; + +/// The scripts folder of a uv tool environment. +#[cfg(windows)] +const TOOL_BIN: &str = "Scripts"; +#[cfg(not(windows))] +const TOOL_BIN: &str = "bin"; + +/// Why no interpreter was found. +#[derive(Debug)] +pub enum PythonNotFound { + /// The path of the running executable could not be resolved. + Executable(io::Error), + /// No folder searched has an interpreter. + Missing { + /// The folder of the executable. + beside: PathBuf, + /// The folder above `beside`, when `beside` is a Windows `Scripts` folder. + above: Option, + /// The scripts folder of the `mogs` uv tool environment, or why it is unknown. + tool: Result, + }, +} + +impl fmt::Display for PythonNotFound { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Executable(error) => { + write!(f, "Cannot find the path of the mogs executable: {error}") + } + Self::Missing { + beside, + above, + tool, + } => { + write!( + f, + "No Python interpreter ({}) in {}, the folder of the mogs executable", + NAMES.join(", "), + beside.display() + )?; + + if let Some(above) = above { + write!(f, ", or in {}, the folder above it", above.display())?; + } + + match tool { + Ok(folder) => write!( + f, + ", or in {}, the uv tool environment of mogs.", + folder.display() + ), + Err(reason) => write!(f, ". The uv tool environment is unknown: {reason}"), + } + } + } + } +} + +/// The interpreter of the environment the running executable is installed in. +/// +/// Looks in the executable's folder, symlinks resolved: the scripts folder of a virtual +/// environment, or of a uv tool environment on Unix. On Windows, when that folder is +/// `Scripts`, then looks in the folder above it, where a global `pip install` puts +/// `python.exe`. Last, looks in the scripts folder of the `mogs` environment under +/// `uv tool dir`, since uv copies tool executables on Windows. +pub fn interpreter() -> Result { + interpreter_from(&executable_folder()?, cfg!(windows), uv_tool_dir) +} + +/// The folder of the running executable, symlinks resolved. +/// +/// A plain path: on Windows, `dunce` drops the `\\?\` prefix of `canonicalize`, since the +/// interpreter path becomes `sys.executable` for Python and its children. +fn executable_folder() -> Result { + let executable = std::env::current_exe() + .and_then(dunce::canonicalize) + .map_err(PythonNotFound::Executable)?; + + match executable.parent() { + Some(folder) => Ok(folder.to_path_buf()), + None => { + let error = io::Error::other(format!("{} has no parent folder", executable.display())); + Err(PythonNotFound::Executable(error)) + } + } +} + +/// The interpreter in `beside`, else above it (see `script_parent`), else in the `mogs` tool +/// environment under `uv_tool_dir()`. +fn interpreter_from( + beside: &Path, + windows: bool, + uv_tool_dir: impl FnOnce() -> Result, +) -> Result { + if let Some(python) = interpreter_in(beside) { + return Ok(python); + } + + let above = script_parent(beside, windows); + + if let Some(python) = above.as_deref().and_then(interpreter_in) { + return Ok(python); + } + + // On Windows `uv tool install` copies the executable out of its environment. The tool + // environment found here may hold a different mogs version than this executable. + let tool = uv_tool_dir().map(|dir| dir.join("mogs").join(TOOL_BIN)); + + if let Ok(folder) = &tool + && let Some(python) = interpreter_in(folder) + { + return Ok(python); + } + + Err(PythonNotFound::Missing { + beside: beside.to_path_buf(), + above, + tool, + }) +} + +/// The folder above `folder`, on Windows when `folder` is named `Scripts` (any case). +fn script_parent(folder: &Path, windows: bool) -> Option { + let name = folder.file_name()?; + + if windows && name.eq_ignore_ascii_case("Scripts") { + return folder.parent().map(Path::to_path_buf); + } + + None +} + +/// The first interpreter in `folder`. +fn interpreter_in(folder: &Path) -> Option { + NAMES + .iter() + .map(|name| folder.join(name)) + .find(|path| path.is_file()) +} + +/// The folder of uv's tool environments, from `uv tool dir`. +fn uv_tool_dir() -> Result { + let output = match Command::new("uv").args(["tool", "dir"]).output() { + Ok(output) => output, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return Err("`uv` is not on PATH.".to_string()); + } + Err(error) => return Err(format!("cannot run `uv tool dir`: {error}")), + }; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!( + "`uv tool dir` failed ({}): {}", + output.status, + stderr.trim() + )); + } + + let stdout = String::from_utf8_lossy(&output.stdout); + + Ok(PathBuf::from(stdout.trim())) +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::{TempDir, tempdir}; + + /// A file standing in for an interpreter in `folder`. + fn fake_python(folder: &Path) -> PathBuf { + let python = folder.join(NAMES[0]); + std::fs::create_dir_all(folder).unwrap(); + std::fs::write(&python, "").unwrap(); + + python + } + + /// Two empty folders: the executable's and uv's tool folder. + fn folders() -> (TempDir, TempDir) { + (tempdir().unwrap(), tempdir().unwrap()) + } + + #[test] + fn executable_folder_is_a_plain_path() { + let folder = executable_folder().unwrap(); + + assert!(folder.is_absolute()); + assert!( + !folder.to_string_lossy().starts_with(r"\\?\"), + "{}", + folder.display() + ); + } + + #[test] + fn finds_sibling_interpreter() { + let beside = tempdir().unwrap(); + let python = fake_python(beside.path()); + + let found = interpreter_from(beside.path(), false, || panic!("uv must not be asked")); + + assert_eq!(found.unwrap(), python); + } + + #[test] + fn falls_back_to_uv_tool_environment() { + let (beside, tools) = folders(); + let python = fake_python(&tools.path().join("mogs").join(TOOL_BIN)); + + let found = interpreter_from(beside.path(), false, || Ok(tools.path().to_path_buf())); + + assert_eq!(found.unwrap(), python); + } + + #[test] + fn errors_without_one() { + let (beside, tools) = folders(); + let bin = tools.path().join("mogs").join(TOOL_BIN); + + let error = interpreter_from(beside.path(), false, || Ok(tools.path().to_path_buf())); + let message = error.unwrap_err().to_string(); + + assert!( + message.contains(&beside.path().display().to_string()), + "{message}" + ); + assert!(message.contains(&bin.display().to_string()), "{message}"); + } + + #[test] + fn errors_when_uv_is_unavailable() { + let beside = tempdir().unwrap(); + + let error = interpreter_from(beside.path(), false, || { + Err("`uv` is not on PATH".to_string()) + }); + let message = error.unwrap_err().to_string(); + + assert!( + message.contains(&beside.path().display().to_string()), + "{message}" + ); + assert!(message.contains("`uv` is not on PATH"), "{message}"); + assert!(!message.contains("the folder above it"), "{message}"); + } + + #[test] + fn script_parent_only_for_scripts_on_windows() { + let root = Path::new("python313"); + + assert_eq!( + script_parent(&root.join("Scripts"), true), + Some(root.to_path_buf()) + ); + assert_eq!( + script_parent(&root.join("scripts"), true), + Some(root.to_path_buf()) + ); + assert_eq!(script_parent(&root.join("Scripts"), false), None); + assert_eq!(script_parent(&root.join("bin"), true), None); + } + + #[test] + fn finds_interpreter_above_scripts() { + let root = tempdir().unwrap(); + let scripts = root.path().join("Scripts"); + std::fs::create_dir(&scripts).unwrap(); + let python = fake_python(root.path()); + + let found = interpreter_from(&scripts, true, || panic!("uv must not be asked")); + + assert_eq!(found.unwrap(), python); + } + + #[test] + fn errors_name_every_folder_searched() { + let (root, tools) = folders(); + let scripts = root.path().join("Scripts"); + std::fs::create_dir(&scripts).unwrap(); + let bin = tools.path().join("mogs").join(TOOL_BIN); + + let error = interpreter_from(&scripts, true, || Ok(tools.path().to_path_buf())); + let message = error.unwrap_err().to_string(); + + assert!( + message.contains(&scripts.display().to_string()), + "{message}" + ); + assert!( + message.contains(&format!("{}, the folder above it", root.path().display())), + "{message}" + ); + assert!(message.contains(&bin.display().to_string()), "{message}"); + } +} diff --git a/makefile b/makefile index 2946e9d..82d1ba3 100644 --- a/makefile +++ b/makefile @@ -15,16 +15,20 @@ sync: # make test TESTS=tests/test_config.py ARGS='-k header' # make test ARGS='-m docker' test: + cargo test --workspace $(UV) pytest $(TESTS) -q $(ARGS) lint: $(UV) ruff check $(UV) ruff format --check + cargo fmt --check + cargo clippy --workspace --all-targets -- -D warnings # Fix lint warnings, then format (order matters). fix: -$(UV) ruff check --fix $(UV) ruff format + cargo fmt typecheck: $(UV) ty check diff --git a/pyproject.toml b/pyproject.toml index 4813580..c3b691b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,7 @@ [project] name = "mogs" -version = "0.7.0" +# The version is `[workspace.package] version` in Cargo.toml. +dynamic = ["version"] description = "Build Gradescope autograders from marimo notebooks." authors = [{ name = "Agustinus Kristiadi", email = "agustinus@kristia.de" }] license = "MIT" @@ -17,20 +18,19 @@ dependencies = [ "pytest", ] -[project.scripts] -mogs = "mogs.cli:main" - [project.optional-dependencies] # The vendored Typst packages in `_typst` need Typst 0.15. pdf = ["typst>=0.15,<0.16"] [build-system] -requires = ["uv_build>=0.13.0,<0.14"] -build-backend = "uv_build" +requires = ["maturin>=1.9,<2"] +build-backend = "maturin" -[tool.uv.build-backend] -# The distribution is `mogs`; the import name is shorter. -module-name = "mogs" +# The wheel holds the Python package and the `mogs` executable built from crates/mogs. +[tool.maturin] +bindings = "bin" +python-source = "src" +manifest-path = "crates/mogs/Cargo.toml" [dependency-groups] dev = [ @@ -78,6 +78,15 @@ markers = [ ] [tool.uv] +# Rebuild the `mogs` executable when the Rust sources change. +cache-keys = [ + { file = "pyproject.toml" }, + { file = "Cargo.toml" }, + { file = "Cargo.lock" }, + { file = "rust-toolchain.toml" }, + { file = "crates/**/*.rs" }, + { file = "crates/**/Cargo.toml" }, +] # The lockfile must install on every CI platform: Linux, macOS and Windows. required-environments = [ "sys_platform == 'linux' and platform_machine == 'x86_64'", diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..d0ead5e --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "stable" +components = ["clippy", "rustfmt"] diff --git a/src/mogs/_binary.py b/src/mogs/_binary.py new file mode 100644 index 0000000..bf161a1 --- /dev/null +++ b/src/mogs/_binary.py @@ -0,0 +1,55 @@ +"""The `mogs` executable installed with this package.""" + +import os +import subprocess +import sysconfig +from pathlib import Path + +NAME = "mogs.exe" if os.name == "nt" else "mogs" + + +class BinaryError(Exception): + """The `mogs` executable is not installed next to this package.""" + + +def binary() -> Path: + """The `mogs` executable of this environment. + + Looks in the environment's scripts folder, then in the user scheme's scripts folder. + + Raises: + BinaryError: If neither folder has it. The message names both folders. + """ + + folders = [ + Path(sysconfig.get_path("scripts")), + Path(sysconfig.get_path("scripts", f"{os.name}_user")), + ] + + for folder in folders: + path = folder / NAME + if path.is_file(): + return path + + searched = " or ".join(str(folder) for folder in folders) + raise BinaryError(f"No {NAME} executable in {searched}.") + + +def run(args: list[str], stdin: str | None = None) -> subprocess.CompletedProcess[str]: + """Run the `mogs` executable with `args` and capture its output as text. + + Args: + args: Arguments after the command name. + stdin: Text for its standard input; inherited from this process when `None`. + + Returns: + The finished process. A non-zero exit code is not an error here. + """ + + return subprocess.run( + [binary(), *args], + input=stdin, + capture_output=True, + text=True, + check=False, + ) diff --git a/src/mogs/cli.py b/src/mogs/cli.py index 380c8b4..3bfc3c4 100644 --- a/src/mogs/cli.py +++ b/src/mogs/cli.py @@ -270,3 +270,7 @@ def _parser() -> argparse.ArgumentParser: ) return parser + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/test_gradescope_docker.py b/tests/e2e/test_gradescope_docker.py index 922218b..2537023 100644 --- a/tests/e2e/test_gradescope_docker.py +++ b/tests/e2e/test_gradescope_docker.py @@ -449,13 +449,33 @@ def build_context(context: Path, archive: Path) -> None: def build_wheel(out: Path) -> Path: - """Build a wheel of this checkout into `out`.""" + """Build a wheel of this checkout into `out` for the base image's Ubuntu on x86_64. + + maturin cross-compiles the `mogs` executable with zig, so this works from any host. + """ uv = shutil.which("uv") if uv is None: raise CommandError("`uv` is not on PATH; it builds the wheel") - run([uv, "build", "--wheel", "--out-dir", str(out), str(REPO)], timeout=300) + command = [ + uv, + "tool", + "run", + "--from", + "maturin[zig]>=1.9,<2", + "maturin", + "build", + "--release", + "--zig", + "--compatibility", + "manylinux_2_17", + "--target", + "x86_64-unknown-linux-gnu", + "--out", + str(out), + ] + run(command, timeout=600, cwd=REPO) [wheel] = out.glob("*.whl") return wheel @@ -722,9 +742,10 @@ def test_submission_files(assignment, tmp_path, name): def test_wheel_requirement_names_the_tool(): - requirement = wheel_requirement(Path("/x/mogs-0.1.0-py3-none-any.whl")) + wheel = "mogs-0.1.0-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl" + requirement = wheel_requirement(Path("/x") / wheel) - assert requirement == ("mogs @ file:///wheels/mogs-0.1.0-py3-none-any.whl") + assert requirement == f"mogs @ file:///wheels/{wheel}" assert normalized_name(requirement) == "mogs" diff --git a/tests/test_binary.py b/tests/test_binary.py new file mode 100644 index 0000000..9a26bba --- /dev/null +++ b/tests/test_binary.py @@ -0,0 +1,70 @@ +import os +import subprocess +import sysconfig +from importlib.metadata import version + +import pytest + +from mogs._binary import BinaryError, binary, run + + +def test_binary_is_in_scripts(): + assert binary().name == ("mogs.exe" if os.name == "nt" else "mogs") + + +def test_binary_version_matches_package(): + result = run(["--version"]) + + assert result.returncode == 0 + assert result.stdout == f"mogs {version('mogs')}\n" + + +def test_binary_forwards_to_python_cli(tmp_path): + missing = tmp_path / "missing-dir" + + result = run(["edit", str(missing)]) + + assert result.returncode == 1 + assert result.stdout == "" + assert result.stderr == f"Edit failed.\n{missing} does not exist.\n" + + +def test_binary_found_through_symlink(tmp_path): + link = tmp_path / binary().name + link.symlink_to(binary()) + + result = subprocess.run([link, "--version"], capture_output=True, text=True) + + assert result.returncode == 0 + assert result.stdout == f"mogs {version('mogs')}\n" + + +def test_binary_missing_names_paths(tmp_path, monkeypatch): + scripts = tmp_path / "scripts" + user = tmp_path / "user" + paths = {None: scripts, f"{os.name}_user": user} + monkeypatch.setattr(sysconfig, "get_path", lambda name, scheme=None: str(paths[scheme])) + + with pytest.raises(BinaryError) as error: + binary() + + assert str(scripts) in str(error.value) + assert str(user) in str(error.value) + + +def test_binary_is_a_file_not_a_folder(tmp_path, monkeypatch): + scripts = tmp_path / "scripts" + (scripts / binary().name).mkdir(parents=True) + monkeypatch.setattr(sysconfig, "get_path", lambda name, scheme=None: str(scripts)) + + with pytest.raises(BinaryError): + binary() + + +def test_binary_ignores_modules_in_working_directory(tmp_path): + (tmp_path / "packaging.py").write_text("raise SystemExit('shadowed')\n") + + result = subprocess.run([binary(), "--version"], capture_output=True, text=True, cwd=tmp_path) + + assert result.returncode == 0, result.stderr + assert result.stdout == f"mogs {version('mogs')}\n" diff --git a/tests/test_cli.py b/tests/test_cli.py index 4dbd8d6..be491da 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,22 +1,23 @@ -from importlib.metadata import entry_points +import subprocess +import sys +from importlib.metadata import version import pytest from mogs.cli import main -def test_the_command_is_mogs(): - scripts = { - script.name: script.value - for script in entry_points(group="console_scripts") - if script.value.startswith("mogs.") - } - - assert scripts == {"mogs": "mogs.cli:main"} - - def test_help_names_the_command(capsys): with pytest.raises(SystemExit): main(["--help"]) assert capsys.readouterr().out.startswith("usage: mogs ") + + +def test_module_runs_the_command(): + result = subprocess.run( + [sys.executable, "-m", "mogs.cli", "--version"], capture_output=True, text=True + ) + + assert result.returncode == 0 + assert result.stdout == f"mogs {version('mogs')}\n" diff --git a/uv.lock b/uv.lock index e6e7897..7d04434 100644 --- a/uv.lock +++ b/uv.lock @@ -257,7 +257,6 @@ wheels = [ [[package]] name = "mogs" -version = "0.7.0" source = { editable = "." } dependencies = [ { name = "marimo" },