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
93 changes: 88 additions & 5 deletions crates/mogs-cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
use std::ffi::OsString;
use std::path::PathBuf;

use clap::Parser;
use clap::error::{ContextKind, ContextValue, ErrorKind};
use clap::{CommandFactory, Parser};

/// The `mogs` command.
#[derive(Debug, Parser)]
Expand Down Expand Up @@ -102,13 +103,61 @@ pub fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Command, Exit>

Cli::try_parse_from(argv)
.map(|cli| cli.command)
.map_err(|error| Exit {
text: error.render().to_string(),
to_stderr: error.use_stderr(),
code: error.exit_code(),
.map_err(|error| {
let error = without_hidden_suggestion(error);

Exit {
text: error.render().to_string(),
to_stderr: error.use_stderr(),
code: error.exit_code(),
}
})
}

/// `error` with hidden commands removed from its "similar subcommand" tip, and the tip dropped
/// when only hidden commands were suggested.
fn without_hidden_suggestion(error: clap::Error) -> clap::Error {
if error.kind() != ErrorKind::InvalidSubcommand {
return error;
}

let Some(ContextValue::Strings(suggested)) = error.get(ContextKind::SuggestedSubcommand) else {
return error;
};

let command = Cli::command();
let visible: Vec<String> = suggested
.iter()
.filter(|name| {
!command
.find_subcommand(name)
.is_some_and(clap::Command::is_hide_set)
})
.cloned()
.collect();

if visible.len() == suggested.len() {
return error;
}

let mut rebuilt = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(&command);

for kind in [ContextKind::InvalidSubcommand, ContextKind::Usage] {
if let Some(value) = error.get(kind) {
rebuilt.insert(kind, value.clone());
}
}

if !visible.is_empty() {
rebuilt.insert(
ContextKind::SuggestedSubcommand,
ContextValue::Strings(visible),
);
}

rebuilt
}

#[cfg(test)]
mod tests {
use clap::CommandFactory;
Expand Down Expand Up @@ -303,4 +352,38 @@ mod tests {
assert!(exit.text.starts_with("error: "), "{}", exit.text);
}
}

#[test]
fn typo_never_suggests_a_hidden_command() {
for args in [&["autograd"][..], &["a"]] {
let exit = parsed(args).unwrap_err();

assert_eq!(exit.code, 2, "{args:?}");
assert!(!exit.text.contains("autograde"), "{}", exit.text);
assert!(
exit.text.contains("unrecognized subcommand"),
"{}",
exit.text
);
}
}

#[test]
fn typo_suggests_a_visible_command() {
let exit = parsed(&["biuld"]).unwrap_err();

assert!(
exit.text.contains("a similar subcommand exists: 'build'"),
"{}",
exit.text
);
}

#[test]
fn typo_close_to_both_keeps_only_the_visible_tip() {
let exit = parsed(&["u"]).unwrap_err();

assert!(exit.text.contains("'build'"), "{}", exit.text);
assert!(!exit.text.contains("autograde"), "{}", exit.text);
}
}
15 changes: 14 additions & 1 deletion crates/mogs/src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,26 @@ mod platform {
use std::path::PathBuf;

use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyo3::types::{PyDict, PyString};

use crate::cli::fail;
use crate::python::pathlib;

/// Grade the submission and write `results.json`, whatever happens, with logs on stderr.
///
/// Exit code 0, since Gradescope treats any other as a crash and shows no results.
/// A missing `source` folder fails with exit code 1 and one plain error: Gradescope
/// always has it, so this only happens off Gradescope.
pub(crate) fn autograde(py: Python<'_>, paths: [PathBuf; 4]) -> PyResult<i64> {
let [source, submission, results, workdir] = paths;

if !source.is_dir() {
let shown = pathlib(py, &source)?.str()?;
let message = format!("mogs autograde runs only on Gradescope: {shown} not found.");

return fail(py, "Grading", PyString::new(py, &message));
}

let logging = py.import("logging")?;
let kwargs = PyDict::new(py);
kwargs.set_item("level", logging.getattr("INFO")?)?;
Expand Down
25 changes: 25 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,31 @@ def test_infinite_points_reach_results_json(paths):
assert '"score": Infinity' in paths.results.read_text(encoding="utf-8")


def test_autograde_without_source_folder_is_a_plain_error(tmp_path, capsys):
argv = [
"autograde",
"--source",
str(tmp_path / "nope"),
"--submission",
str(tmp_path / "s"),
"--results",
str(tmp_path / "r" / "results.json"),
"--workdir",
str(tmp_path / "w"),
]

code = main(argv)

stderr = capsys.readouterr().err
assert code == 1
assert stderr == (
f"Grading failed.\nmogs autograde runs only on Gradescope: {tmp_path / 'nope'} not found.\n"
)
assert "Traceback" not in stderr
assert not (tmp_path / "r").exists()
assert not (tmp_path / "w").exists()


def test_unreadable_bundle_still_writes_results(paths):
(paths.source / "bundle.json").write_text("{not json", encoding="utf-8")
paths.add("solution.py")
Expand Down
Loading