use crate::verb::{Resolution, Runtime, Verb, resolve};
const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, PartialEq, Eq)]
pub struct Output {
pub out: String,
pub err: String,
pub code: u8,
}
impl Output {
pub(crate) fn ok(out: String) -> Self {
Self {
out,
err: String::new(),
code: 0,
}
}
pub(crate) fn usage(err: String) -> Self {
Self {
out: String::new(),
err,
code: 2,
}
}
pub(crate) fn usage_err(msg: String) -> Self {
Self::usage(format!("{msg}\n{}", crate::docs::usage()))
}
pub(crate) fn breach(out: String, err: String) -> Self {
Self { out, err, code: 1 }
}
}
pub type Input<'a> = &'a dyn Fn() -> String;
#[must_use]
pub fn run(args: &[String]) -> Output {
run_with(args, &stdin_text)
}
#[must_use]
pub fn run_with(args: &[String], input: Input) -> Output {
match args.split_first() {
None => Output::usage(crate::docs::usage()),
Some((first, rest)) => head(first, rest, input),
}
}
fn stdin_text() -> String {
let mut buf = Vec::new();
let _ = std::io::Read::read_to_end(&mut std::io::stdin().lock(), &mut buf);
String::from_utf8_lossy(&buf).into_owned()
}
fn head(first: &str, rest: &[String], input: Input) -> Output {
match first {
"--version" | "-V" => Output::ok(format!("itok {VERSION}\n")),
"--help" | "-h" => Output::ok(crate::docs::usage()),
"docs" => Output::ok(crate::docs::markdown()),
verb => run_verb(verb, rest, input),
}
}
fn run_verb(verb: &str, rest: &[String], input: Input) -> Output {
handle(resolve(verb), verb, rest, input)
}
fn handle(
res: Resolution,
verb: &str,
rest: &[String],
input: Input,
) -> Output {
match res {
Resolution::Verb(v) => dispatch(v, rest, input),
Resolution::Ambiguous(c) => Output::usage(ambiguous_msg(verb, &c)),
Resolution::Unknown(n) => Output::usage(unknown_msg(verb, &n)),
}
}
#[cfg(feature = "session")]
fn runtime(v: Runtime, rest: &[String], input: Input) -> Output {
match v {
Runtime::Trace => crate::tracecmd::trace(rest),
Runtime::Top => crate::topcmd::top(rest),
Runtime::Headroom => crate::headroom::headroom(rest),
Runtime::Calibrate => crate::calibrate::calibrate(rest),
Runtime::Rate => crate::ratecmd::rate(rest, input),
}
}
#[cfg(not(feature = "session"))]
fn runtime(_v: Runtime, _rest: &[String], _input: Input) -> Output {
Output::usage_err(
"itok: the runtime verbs need the `session` feature".to_owned(),
)
}
fn dispatch(v: Verb, rest: &[String], input: Input) -> Output {
match v {
Verb::Cap => crate::capcmd::cap(rest, &input()),
Verb::Guard => crate::guardcmd::guard(&input()),
Verb::Estimate => crate::estcmd::estimate(rest),
Verb::Doctor => crate::doctor::doctor(rest),
Verb::Diff => crate::diffcmd::diff(rest),
Verb::Show => crate::showcmd::show(rest),
Verb::Log => crate::logcmd::log(rest),
Verb::Check => crate::checkcmd::check(rest),
Verb::Fit => crate::fitcmd::fit(rest),
Verb::Runtime(r) => runtime(r, rest, input),
}
}
fn ambiguous_msg(verb: &str, cands: &[&str]) -> String {
let usage = crate::docs::usage();
format!("itok: '{verb}' is ambiguous: {}\n{usage}", cands.join(", "))
}
fn unknown_msg(verb: &str, near: &[&str]) -> String {
let usage = crate::docs::usage();
if near.is_empty() {
format!("itok: unknown command '{verb}'\n{usage}")
} else {
format!(
"itok: unknown command '{verb}' -- did you mean {}?\n{usage}",
near.join(", ")
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
const DIR: &str = env!("CARGO_MANIFEST_DIR");
fn args(parts: &[&str]) -> Vec<String> {
parts.iter().map(|s| (*s).to_owned()).collect()
}
fn nothing() -> String {
String::new()
}
#[test]
fn version_names_the_tool() {
let o = run(&args(&["--version"]));
assert!(o.out.contains("itok"));
assert_eq!(o.code, 0);
}
#[test]
fn version_short_flag_works() {
assert_eq!(run(&args(&["-V"])).code, 0);
}
#[test]
fn help_lists_the_commands() {
let o = run(&args(&["--help"]));
assert!(o.out.contains("estimate"));
assert_eq!(o.code, 0);
}
#[test]
fn docs_gives_the_markdown_reference() {
let o = run(&args(&["docs"]));
assert_eq!(o.code, 0);
assert!(o.out.starts_with("## Commands"));
assert!(o.out.contains("### `estimate`"));
assert!(o.err.is_empty(), "read-only: {:?}", o.err);
}
#[test]
fn no_command_is_a_usage_error() {
let o = run(&[]);
assert_eq!(o.code, 2);
assert!(o.err.contains("usage"));
}
#[test]
fn unknown_command_is_a_usage_error() {
let o = run(&args(&["bogus"]));
assert_eq!(o.code, 2);
assert!(o.err.contains("unknown command"));
}
#[test]
fn a_verb_prefix_resolves_and_runs() {
let o = run(&args(&["e", "-C", DIR, "Cargo.toml"]));
assert!(o.out.contains("itok"));
assert_eq!(o.code, 0);
}
#[test]
fn a_typo_suggests_and_does_not_run() {
let o = run(&args(&["esimate"]));
assert_eq!(o.code, 2);
assert!(o.err.contains("did you mean"));
assert!(o.err.contains("estimate"));
assert!(o.out.is_empty(), "must not run: {:?}", o.out);
}
#[test]
fn an_ambiguous_resolution_lists_candidates() {
let res = Resolution::Ambiguous(vec!["diff", "doctor"]);
let o = handle(res, "d", &[], ¬hing);
assert_eq!(o.code, 2);
assert!(o.err.contains("ambiguous"));
assert!(o.err.contains("diff") && o.err.contains("doctor"));
}
#[cfg(feature = "session")]
#[test]
fn each_runtime_verb_reaches_its_own_module() {
let f = format!("{DIR}/tests/fixtures/session/tool-shapes.jsonl");
let out = |v: &str| run(&args(&[v, &f, "--format", "json"])).out;
assert!(out("headroom").contains("\"rate_unit\""), "headroom");
assert!(out("top").contains("\"summary\":true"), "top");
assert!(out("trace").contains("\"ts\":"), "trace");
assert!(out("rate").contains("\"per_hour\":"), "rate");
}
#[test]
fn cap_reads_the_input_source_and_announces_its_cut() {
let text = || "one\ntwo\nthree\n".to_owned();
let o = run_with(&args(&["cap", "2"]), &text);
assert_eq!(o.code, 0);
assert!(
o.out.starts_with("one\n"),
"body passes through: {:?}",
o.out
);
assert!(o.out.contains("[itok cap:"), "footer: {:?}", o.out);
assert!(o.out.contains("resume:"), "selector: {:?}", o.out);
}
fn arg() -> impl Strategy<Value = String> {
prop_oneof![
Just("estimate".to_owned()),
Just("-s".to_owned()),
Just("--top".to_owned()),
Just("3".to_owned()),
"[a-z0-9._/-]{0,5}",
"-{1,2}[a-z]{1,3}",
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(48))]
#[test]
fn run_never_panics(a in prop::collection::vec(arg(), 0..7)) {
let o = run_with(&a, ¬hing);
prop_assert!(o.code == 0 || o.code == 1 || o.code == 2);
}
}
}