diff --git a/crates/berth-api/src/types.rs b/crates/berth-api/src/types.rs index 0faf409..fc143e6 100644 --- a/crates/berth-api/src/types.rs +++ b/crates/berth-api/src/types.rs @@ -453,7 +453,8 @@ pub struct Argument { pub choices: String, /// `resource` for an argument of a provisioner that sizes the machine: /// its CPUs, memory or disk. `text` for one whose value has several - /// lines. Empty for any other argument. + /// lines. `boolean` for a yes or no, which the screens show as a switch. + /// Empty for any other argument. #[serde(default, skip_serializing_if = "String::is_empty")] pub kind: String, /// What it is for, in a sentence or two, beside its short label. @@ -467,6 +468,16 @@ pub struct Argument { /// is typed, nor kept, nor written to a job's output. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub secret: bool, + /// Why it keeps its default here and cannot be given another value, + /// such as destroying a machine no provisioner made. The screens show + /// it greyed and say this instead of changing it. Empty when it can be + /// changed. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub fixed: String, + /// For a yes or no: the question to answer yes to before the action + /// runs with it on, instead of the action's own. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub confirm: String, } impl Argument { @@ -475,12 +486,70 @@ impl Argument { /// The kind of an argument whose value has several lines, such as a /// Compose file. pub const TEXT: &'static str = "text"; + /// The kind of an argument that is a yes or no. + pub const BOOLEAN: &'static str = "boolean"; /// Whether it sizes the machine a provisioner creates. pub fn is_resource(&self) -> bool { self.kind == Self::RESOURCE } + /// Whether it is a yes or no: declared `boolean`, or taking just the + /// values yes and no, or true and false. + pub fn is_boolean(&self) -> bool { + if self.kind == Self::BOOLEAN { + return true; + } + let [one, other] = self.values.as_slice() else { + return false; + }; + let mut pair = [one.to_lowercase(), other.to_lowercase()]; + pair.sort(); + pair == ["no", "yes"] || pair == ["false", "true"] + } + + /// The values of a yes or no when it is on and when it is off: those it + /// declares, or `yes` and `no`. + pub fn switch_values(&self) -> (String, String) { + let declared = |on: bool| { + self.values + .iter() + .find(|value| parse_bool(value) == Some(on)) + .cloned() + }; + match (declared(true), declared(false)) { + (Some(on), Some(off)) => (on, off), + _ => ("yes".into(), "no".into()), + } + } + + /// Whether `value` turns a yes or no on. Empty is off. + pub fn is_on(value: &str) -> bool { + parse_bool(value) == Some(true) + } + + /// The value a yes or no has when it is set to `on`. + pub fn switched(&self, on: bool) -> String { + let (yes, no) = self.switch_values(); + match on { + true => yes, + false => no, + } + } + + /// A yes or no as it is given, such as on the command line, as the + /// value it declares. Says what it takes when it is neither. + pub fn read_switch(&self, value: &str) -> Result { + match parse_bool(value) { + Some(on) => Ok(self.switched(on)), + None if value.trim().is_empty() => Ok(self.switched(false)), + None => Err(format!( + "{} is yes or no (or true/false, on/off, 1/0), not {value}", + self.name + )), + } + } + /// The arguments of `given` a job may show as `NAME=VALUE`, in the order /// they are declared: never a secret one, nor one of several lines, such /// as what a command reads on its standard input. @@ -500,6 +569,16 @@ impl Argument { } } +/// A yes or no as a person writes it: `yes`, `true`, `on` or `1`, and their +/// opposites, in any case. `None` for anything else. +pub fn parse_bool(value: &str) -> Option { + match value.trim().to_lowercase().as_str() { + "yes" | "true" | "on" | "1" => Some(true), + "no" | "false" | "off" | "0" => Some(false), + _ => None, + } +} + /// An action of the host's controller: an entry of `/etc/berth/actions.json`. /// Listed without `run`. #[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)] @@ -1855,9 +1934,8 @@ impl Rollout { /// What the arguments of the `rollout` action ask for. pub fn from_arguments(arguments: &BTreeMap) -> Result { let flag = |name: &str| match arguments.get(name).map(|value| value.trim()) { - None | Some("" | "no" | "false") => Ok(false), - Some("yes" | "true") => Ok(true), - Some(other) => Err(format!("{name} is yes or no, not {other}")), + None | Some("") => Ok(false), + Some(value) => parse_bool(value).ok_or(format!("{name} is yes or no, not {value}")), }; let names = |key: &str| { arguments.get(key).map_or(vec![], |hosts| { @@ -1939,6 +2017,57 @@ pub struct RolloutReport { mod tests { use super::*; + #[test] + fn a_yes_or_no_is_declared_or_known_by_its_values() { + let with = |kind: &str, values: &[&str]| Argument { + name: "destroy".into(), + kind: kind.into(), + values: values.iter().map(|value| value.to_string()).collect(), + ..Argument::default() + }; + assert!(with(Argument::BOOLEAN, &[]).is_boolean()); + assert!(with("", &["no", "yes"]).is_boolean()); + assert!(with("", &["Yes", "no"]).is_boolean()); + assert!(with("", &["true", "false"]).is_boolean()); + assert!(!with("", &["no", "always"]).is_boolean()); + assert!(!with("", &["no", "yes", "always"]).is_boolean()); + assert!(!with("", &[]).is_boolean()); + // It keeps the values it declares, and is yes and no without. + assert_eq!( + with("", &["false", "true"]).switch_values(), + ("true".into(), "false".into()) + ); + assert_eq!( + with(Argument::BOOLEAN, &[]).switch_values(), + ("yes".into(), "no".into()) + ); + } + + #[test] + fn a_yes_or_no_is_read_in_the_usual_spellings() { + for on in ["yes", "YES", "true", "On", "1", " yes "] { + assert_eq!(parse_bool(on), Some(true), "{on}"); + } + for off in ["no", "False", "OFF", "0"] { + assert_eq!(parse_bool(off), Some(false), "{off}"); + } + assert_eq!(parse_bool("maybe"), None); + assert_eq!(parse_bool("y"), None); + let flag = Argument { + name: "destroy".into(), + kind: Argument::BOOLEAN.into(), + values: vec!["no".into(), "yes".into()], + ..Argument::default() + }; + assert_eq!(flag.read_switch("TRUE").as_deref(), Ok("yes")); + assert_eq!(flag.read_switch("off").as_deref(), Ok("no")); + assert_eq!(flag.read_switch("").as_deref(), Ok("no")); + assert_eq!( + flag.read_switch("maybe"), + Err("destroy is yes or no (or true/false, on/off, 1/0), not maybe".into()) + ); + } + #[test] fn a_job_shows_no_secret_argument_and_no_text() { let declared = vec![ diff --git a/crates/berth-core/src/plugins.rs b/crates/berth-core/src/plugins.rs index 5e8bf84..110853e 100644 --- a/crates/berth-core/src/plugins.rs +++ b/crates/berth-core/src/plugins.rs @@ -415,9 +415,11 @@ fn provisioner_arguments(entries: &Value) -> Vec { .filter(|argument| valid_name(&argument.name)) .map(|argument| berth_api::Argument { choices: String::new(), - kind: match argument.is_resource() || argument.kind == berth_api::Argument::TEXT { - true => argument.kind.clone(), - false => String::new(), + kind: match argument.kind.as_str() { + berth_api::Argument::RESOURCE + | berth_api::Argument::TEXT + | berth_api::Argument::BOOLEAN => argument.kind.clone(), + _ => String::new(), }, ..argument }) diff --git a/crates/berth-core/src/provision.rs b/crates/berth-core/src/provision.rs index 7c2fb55..5b32a22 100644 --- a/crates/berth-core/src/provision.rs +++ b/crates/berth-core/src/provision.rs @@ -233,6 +233,13 @@ pub(crate) fn values_of( .or_else(|| settings.get(&argument.name)) .cloned() .unwrap_or_else(|| argument.default.clone()); + // A yes or no is taken in any of its spellings, as the value it declares. + let value = match argument.is_boolean() && !value.trim().is_empty() { + true => argument + .read_switch(&value) + .map_err(|error| format!("{name}: {error}"))?, + false => value, + }; if argument.required && value.is_empty() { return Err(format!("{name} needs {}=VALUE", argument.name).into()); } @@ -2244,8 +2251,22 @@ print(out) assert_eq!(of(&none, &given("yes")).unwrap()["keep_volume"], "yes"); let kept = given("yes"); assert_eq!(of(&given("no"), &kept).unwrap()["keep_volume"], "no"); + // A yes or no is taken in any spelling, as the value declared. + assert_eq!(of(&given("TRUE"), &none).unwrap()["keep_volume"], "yes"); + assert_eq!(of(&given("off"), &none).unwrap()["keep_volume"], "no"); let said = of(&given("maybe"), &none).unwrap_err().to_string(); - assert_eq!(said, "lab/box takes keep_volume=no or yes only"); + assert_eq!( + said, + "lab/box: keep_volume is yes or no (or true/false, on/off, 1/0), not maybe" + ); + let restart = [berth_api::Argument { + name: "restart".into(), + values: vec!["no".into(), "always".into()], + ..Default::default() + }]; + let given = BTreeMap::from([("restart".to_owned(), "yes".to_owned())]); + let said = values_of("lab/box", &restart, &given, &none).unwrap_err(); + assert_eq!(said.to_string(), "lab/box takes restart=no or always only"); } #[test] diff --git a/crates/berth-page/src/app.rs b/crates/berth-page/src/app.rs index 71bc2b6..d908fcb 100644 --- a/crates/berth-page/src/app.rs +++ b/crates/berth-page/src/app.rs @@ -7,6 +7,7 @@ use crate::installed::{Installed, Outcome}; use crate::portal::{Link, Portal}; use crate::remote::Remote; use crate::setup::{Flow, Setup, draw_editor, masked_line}; +use berth_tui::form::{self, Did}; use berth_tui::host::{self, HostView, Pending, Pick, Request, State, View}; use berth_tui::screen::{ self, Platform, Spots, clear_hints, dialog, draw_arguments, draw_footer, draw_header, @@ -887,7 +888,7 @@ impl App { self.status = format!("{} cannot run now: {}", action.title(), action.why); return; } - if let Some((index, values)) = self.host.begin_action(index, false) { + if let Some((index, values)) = self.host.begin_action(&self.name, index, false) { self.launch(index, values); } } @@ -990,6 +991,19 @@ impl App { } return; } + if let Some(mut form) = self.host.form.take() { + match form::event(&mut form, &event, &mut Here) { + Did::Stay(said) => { + if let Some(said) = said { + self.status = said; + } + self.host.form = Some(form); + } + Did::Leave | Did::Switch(_) => {} + Did::Run((index, values)) => self.launch(index, values), + } + return; + } if self.host.question.is_some() { let Event::Key(key) = event else { return; @@ -997,7 +1011,9 @@ impl App { match key.code { Code::Char('y' | 'Y') => match self.host.question.take() { Some((_, Pending::Action(index))) => { - if let Some((index, values)) = self.host.begin_action(index, true) { + if let Some((index, values)) = + self.host.begin_action(&self.name, index, true) + { self.launch(index, values); } } @@ -1130,6 +1146,9 @@ impl App { draw_question(frame, question); } draw_arguments(frame, &self.host); + if let Some(form) = &self.host.form { + form.draw(frame, &self.status); + } } // ── The home screen ───────────────────────────────────────────────────── diff --git a/crates/berth-tui/src/flow.rs b/crates/berth-tui/src/flow.rs index b873f98..e6d0c40 100644 --- a/crates/berth-tui/src/flow.rs +++ b/crates/berth-tui/src/flow.rs @@ -20,7 +20,7 @@ pub struct Choice { } impl Choice { - fn new(key: &str, label: &str, help: &str) -> Choice { + pub fn new(key: &str, label: &str, help: &str) -> Choice { Choice { key: key.to_owned(), label: label.to_owned(), @@ -650,6 +650,9 @@ impl Flow { label => label.to_owned(), }; let asked = match argument.values.is_empty() { + _ if argument.is_boolean() => Asked::Confirm { + default: berth_api::Argument::is_on(&argument.default), + }, true => Asked::Text { default: argument.default.clone(), secret: argument.secret, @@ -676,6 +679,7 @@ impl Flow { Some(Answer::Choice(index)) => { argument.values.get(index).cloned().unwrap_or_default() } + Some(Answer::Confirm(on)) => argument.switched(on), _ => continue, }; self.machine.values.insert(argument.name.clone(), value); diff --git a/crates/berth-tui/src/form.rs b/crates/berth-tui/src/form.rs index a7c2d6b..f223ea1 100644 --- a/crates/berth-tui/src/form.rs +++ b/crates/berth-tui/src/form.rs @@ -1,12 +1,13 @@ //! The form of an action that asks for much: every argument on a row of its //! own, laid out and edited as a host's set-up is. A value of one line is //! typed in the box under the rows, one of a few values goes on to the next, -//! and a value of several lines opens the text editor. +//! a yes or no is a switch, and a value of several lines opens the text +//! editor. use crate::event::{self, Code, Event, Key}; use crate::fields::Kind; -use crate::page::{Launch, argument_label}; -use crate::screen::{self, Platform, draw_editor, draw_footer, draw_header, inside}; +use crate::page::{self, Launch, argument_label}; +use crate::screen::{self, Platform, draw_editor, draw_footer, draw_header, draw_question, inside}; use crate::setup::value_line; use crate::text::{Outcome, TextEditor}; use crate::{markdown, theme}; @@ -23,14 +24,24 @@ use std::collections::{BTreeMap, BTreeSet}; use tui_input::Input; /// Whether an action's arguments are asked for in a form: a value of several -/// lines needs the editor, and more than two values are too many to ask for -/// one after another. +/// lines needs the editor, a yes or no is a switch as on a set-up, and more +/// than two values are too many to ask for one after another. pub fn wants_form(action: &Action) -> bool { action.arguments.len() > 2 || action .arguments .iter() - .any(|argument| argument.kind == Argument::TEXT) + .any(|argument| argument.kind == Argument::TEXT || argument.is_boolean()) +} + +/// Whether the form can ask for all of an action's arguments. It offers no +/// values from a command, which only the dialog asks the host for. +pub fn takes(action: &Action) -> bool { + wants_form(action) + && action + .arguments + .iter() + .all(|argument| argument.choices.is_empty()) } /// A row of the form the cursor stops on. @@ -83,6 +94,8 @@ pub struct Form { text: Option, /// The suggestion the cursor is on while the suggestions have the keys. suggested: Option, + /// The action's question, asked over the form once Run is chosen. + asking: Option, /// Where the rows were drawn, with the place of each among those the /// cursor stops on, and where the suggestions were. hits: RefCell>, @@ -106,6 +119,7 @@ impl Form { editing: None, text: None, suggested: None, + asking: None, hits: RefCell::new(vec![]), suggestion_hits: RefCell::new(vec![]), } @@ -168,6 +182,7 @@ impl Form { self.offered = action .arguments .iter() + .filter(|argument| !argument.is_boolean()) .filter_map(|argument| { let values = narrowed.get(&argument.name).unwrap_or(&argument.values); (!values.is_empty()).then(|| (argument.name.clone(), values.clone())) @@ -185,18 +200,52 @@ impl Form { .is_none_or(|values| values.contains(value)) }); let value = match kept { + // One that cannot be changed here keeps its default. + _ if !argument.fixed.is_empty() => argument.default.clone(), Some(value) => value.clone(), None => { self.set.remove(&argument.name); argument.default.clone() } }; + // A switch is always on or off, as the action declares those. + let value = match argument.is_boolean() { + true => argument.switched(Argument::is_on(&value)), + false => value, + }; self.values.insert(argument.name.clone(), value); } self.problem.clear(); + self.asking = None; self.action = Some((index, action.clone())); } + /// The question asked before the action runs, while it is asked. + pub fn asking(&self) -> Option<&str> { + self.asking.as_deref() + } + + /// Turn the switch of the argument at `index` over. + fn toggle(&mut self, index: usize) { + if let Some(argument) = self.argument(index) { + let on = !Argument::is_on(self.value(argument)); + let value = argument.switched(on); + self.put(index, value); + } + } + + /// Whether the argument at `index` is a switch. + fn is_switch(&self, index: usize) -> bool { + self.argument(index).is_some_and(Argument::is_boolean) + } + + /// Why the argument at `index` cannot be changed here, if it cannot. + fn fixed(&self, index: usize) -> Option { + self.argument(index) + .map(|argument| argument.fixed.clone()) + .filter(|why| !why.is_empty()) + } + /// There is no action to fill it with, and why. pub fn fail(&mut self, why: String) { self.action = None; @@ -353,6 +402,11 @@ impl Form { }; let value = self.value(argument); let line = match (argument.secret, argument.kind == Argument::TEXT) { + // A switch shows the set-up's marker of on and off. + _ if argument.is_boolean() => { + let on = Argument::is_on(value).to_string(); + value_line(&name, &on, Kind::Toggle) + } (true, _) => value_line(&name, value, Kind::Secret), // A text shows its first line, and how many it has. (false, true) if !value.is_empty() => { @@ -368,6 +422,19 @@ impl Form { } _ => value_line(&name, value, Kind::Text), }; + // One that cannot be changed is greyed, as an action that cannot run now. + let line = match argument.fixed.is_empty() { + true => line, + false => { + let mut spans: Vec = line + .spans + .into_iter() + .map(|span| Span::styled(span.content, muted)) + .collect(); + spans.push(Span::styled(" · not now", muted)); + Line::from(spans) + } + }; lines.push((line, Some(Row::Argument(index)))); } lines.push((Line::raw(""), None)); @@ -407,7 +474,11 @@ impl Form { return String::new(); }; let mut text = argument.help.clone(); - if let Some(values) = self.offered.get(&argument.name) { + if !argument.fixed.is_empty() { + text += &format!("\n\nIt cannot be changed now: {}", argument.fixed); + } else if argument.is_boolean() { + text += "\n\nA switch. Enter, Space or a click turns it on or off."; + } else if let Some(values) = self.offered.get(&argument.name) { text += &format!( "\n\nOne of {}. Enter or Space goes on to the next, and → chooses from the suggestions.", values @@ -548,19 +619,28 @@ impl Form { let title = self.argument(index).map_or("Edit", argument_label); draw_editor(frame, edit, title, input, secret); } + let switch = matches!(selected, Some(Row::Argument(index)) if self.is_switch(index)); + let fixed = matches!(selected, Some(Row::Argument(index)) if self.fixed(index).is_some()); let keys = match (&self.editing, secret, self.suggested) { + // The question's own keys, while it is asked over the form. + _ if self.asking.is_some() => "y yes · n no · Esc back to the form".to_owned(), + (None, _, None) if fixed => "↑↓ select · Esc back".to_owned(), (Some(_), true, _) => "Enter accept · Esc cancel".to_owned(), (Some(_), false, _) => format!("Enter accept · Esc cancel · {}", screen::COPY_FIELD), (None, _, Some(_)) => "↑↓ select · Enter choose · Esc back to the rows".to_owned(), + (None, _, None) if switch => "↑↓ select · Space toggle · Esc back".to_owned(), (None, _, None) => "↑↓ select · Enter choose · x unset · Esc back".to_owned(), }; draw_footer(frame, footer, &keys, status, theme::ACCENT); + if let Some(question) = &self.asking { + draw_question(frame, question); + } } /// A click at a place of the screen: it selects the row there, and on /// the row selected it is the Enter key, which is given back. pub fn click(&mut self, column: u16, row: u16) -> Option { - if self.editing.is_some() || self.text.is_some() { + if self.editing.is_some() || self.text.is_some() || self.asking.is_some() { return None; } // A suggestion that is clicked is chosen as Enter on it would. @@ -581,7 +661,11 @@ impl Form { .iter() .find(|(rect, _)| inside(*rect, column, row)) .map(|(_, place)| *place)?; - if place == self.cursor { + // A switch turns over at the first click, as a box that is ticked. + let switch = + matches!(self.rows().get(place), Some(Row::Argument(index)) if self.is_switch(*index)); + if place == self.cursor || switch { + self.cursor = place; return Some(Key::plain(Code::Enter)); } self.cursor = place; @@ -611,6 +695,23 @@ impl Form { /// A key on the form. `platform` copies what is typed. pub fn key(&mut self, key: Key, platform: &mut dyn Platform) -> Did { + // The question is answered with y or n, as every other is. + if self.asking.is_some() { + return match key.code { + Code::Char('y' | 'Y') => { + self.asking = None; + match &self.action { + Some((index, _)) => Did::Run((*index, self.values.clone())), + None => Did::Stay(None), + } + } + Code::Char('n' | 'N') | Code::Esc => { + self.asking = None; + Did::Stay(Some("Not run".into())) + } + _ => Did::Stay(None), + }; + } if let Some(mut editor) = self.text.take() { match editor.handle(&key) { Outcome::Editing => self.text = Some(editor), @@ -679,16 +780,26 @@ impl Form { self.suggested = Some(current.unwrap_or(0)); } } - // Space goes on to the next of a few values, as on a set-up. - Code::Char(' ') if !self.suggestions().0.is_empty() => return self.enter(selected), + // Space goes on to the next of a few values, or turns a switch + // over, as on a set-up. + Code::Char(' ') + if !self.suggestions().0.is_empty() + || matches!(selected, Some(Row::Argument(index)) if self.is_switch(index)) => + { + return self.enter(selected); + } Code::Up | Code::Char('k') if count > 0 => { self.cursor = (self.cursor.min(count - 1) + count - 1) % count } Code::Down | Code::Char('j') if count > 0 => { self.cursor = (self.cursor.min(count - 1) + 1) % count } + // A switch has no unset value: it is on or off. Code::Char('x') => { - if let Some(Row::Argument(index)) = selected { + if let Some(Row::Argument(index)) = selected + && !self.is_switch(index) + && self.fixed(index).is_none() + { self.put(index, String::new()); } } @@ -705,12 +816,18 @@ impl Form { } Some(Row::Maker) => Did::Stay(Some("No other provisioner makes these".into())), Some(Row::Argument(index)) => { + // One that cannot be changed says why instead. + if let Some(why) = self.fixed(index) { + return Did::Stay(Some(why)); + } let Some(argument) = self.argument(index) else { return Did::Stay(None); }; let value = self.value(argument).to_owned(); // One of a few values goes on to the next, as a choice of the set-up does. - if let Some(values) = self.offered.get(&argument.name) { + if argument.is_boolean() { + self.toggle(index); + } else if let Some(values) = self.offered.get(&argument.name) { let next = values .iter() .position(|known| *known == value) @@ -737,9 +854,16 @@ impl Form { .unwrap_or(self.cursor); return Did::Stay(Some(format!("{label} is needed"))); } - match &self.action { - Some((index, _)) => Did::Run((*index, self.values.clone())), - None => Did::Stay(None), + // The question follows the values: a switch that is on may ask its own. + let Some((index, action)) = &self.action else { + return Did::Stay(None); + }; + match page::confirmation(action, &self.values) { + Some(question) => { + self.asking = Some(question); + Did::Stay(None) + } + None => Did::Run((*index, self.values.clone())), } } None => Did::Stay(None), @@ -905,6 +1029,178 @@ mod tests { assert_eq!(press(&mut form, Code::Esc), Did::Leave); } + /// berth's Remove of a host, with its switch, and a question to answer. + fn remove() -> Action { + Action { + name: "remove".into(), + label: "Remove".into(), + confirm: Some("Remove studio?".into()), + arguments: vec![Argument { + label: "Destroy its machine".into(), + default: "no".into(), + kind: Argument::BOOLEAN.into(), + values: vec!["no".into(), "yes".into()], + ..argument("destroy") + }], + ..Action::default() + } + } + + #[test] + fn a_yes_or_no_is_a_switch_in_a_form() { + let by_values = Action { + arguments: vec![Argument { + values: vec!["false".into(), "true".into()], + ..argument("restart") + }], + ..Action::default() + }; + let choice = Action { + arguments: vec![Argument { + values: vec!["no".into(), "always".into()], + ..argument("restart") + }], + ..Action::default() + }; + assert!(wants_form(&remove()) && wants_form(&by_values)); + assert!(!wants_form(&choice)); + let mut form = Form::of("studio", 4, &by_values, &BTreeMap::new()); + // Without a default it is off, as the value it declares. + assert_eq!(form.values["restart"], "false"); + assert_eq!(text(&form)[1], " restart ○ Off"); + assert_eq!(form.suggestions(), (vec![], None)); + press(&mut form, Code::Char(' ')); + assert_eq!(form.values["restart"], "true"); + assert_eq!(text(&form)[1], " restart ● On"); + // x leaves a switch as it is: it has no value that is unset. + press(&mut form, Code::Char('x')); + assert_eq!(form.values["restart"], "true"); + press(&mut form, Code::Enter); + assert_eq!(form.values["restart"], "false"); + assert!(form.help().contains("A switch.")); + } + + #[test] + fn a_click_turns_a_switch_over_and_run_asks_naming_it() { + let mut form = Form::of("studio", 2, &remove(), &BTreeMap::new()); + assert_eq!(form.context(), "studio › remove"); + let shown = screen(&form, ""); + assert!(shown.contains("Destroy its machine ○ Off"), "{shown}"); + assert!(shown.contains("Space toggle"), "{shown}"); + // Move to Run, then click the switch: one click turns it over. + press(&mut form, Code::Down); + let (rect, _) = form.hits.borrow()[0]; + let did = event( + &mut form, + &Event::Mouse(crate::event::Mouse { + click: crate::event::Click::Left, + column: rect.x + 4, + row: rect.y, + }), + &mut Nowhere, + ); + assert_eq!(did, Did::Stay(None)); + assert_eq!(form.values["destroy"], "yes"); + assert!(screen(&form, "").contains("Destroy its machine ● On")); + // Run asks the question over the form, with the switch that is on. + press(&mut form, Code::Down); + assert_eq!(press(&mut form, Code::Enter), Did::Stay(None)); + assert_eq!( + form.asking(), + Some("Remove studio? Destroy its machine is on.") + ); + let shown = screen(&form, ""); + assert!( + shown.contains("Are you sure?") && shown.contains("y yes"), + "{shown}" + ); + // Other keys wait for y or n; n goes back to the form. + assert_eq!(press(&mut form, Code::Enter), Did::Stay(None)); + assert_eq!( + press(&mut form, Code::Char('n')), + Did::Stay(Some("Not run".into())) + ); + assert!(form.asking().is_none()); + press(&mut form, Code::Enter); + let Did::Run((index, values)) = press(&mut form, Code::Char('y')) else { + panic!("not run"); + }; + assert_eq!((index, values["destroy"].as_str()), (2, "yes")); + // Off, the question is the action's own. + let mut form = Form::of("studio", 2, &remove(), &BTreeMap::new()); + press(&mut form, Code::Down); + press(&mut form, Code::Enter); + assert_eq!(form.asking(), Some("Remove studio?")); + let Did::Run((_, values)) = press(&mut form, Code::Char('Y')) else { + panic!("not run"); + }; + assert_eq!(values["destroy"], "no"); + } + + fn click(form: &mut Form, place: usize) -> Did { + let (rect, _) = form.hits.borrow()[place]; + let mouse = crate::event::Mouse { + click: crate::event::Click::Left, + column: rect.x + 4, + row: rect.y, + }; + event(form, &Event::Mouse(mouse), &mut Nowhere) + } + + #[test] + fn a_switch_that_cannot_be_on_is_greyed_and_says_why() { + let mut action = remove(); + action.arguments[0].fixed = "No provisioner made studio".into(); + let mut form = Form::of("studio", 2, &action, &BTreeMap::new()); + assert_eq!(text(&form)[1], " Destroy its machine ○ Off · not now"); + let row = &form.lines()[1].0; + assert!( + row.spans + .iter() + .all(|span| span.style.fg == Some(theme::MUTED)) + ); + let shown = screen(&form, ""); + let footer = shown.lines().last().unwrap(); + assert!( + footer.contains("Esc back") && !footer.contains("Space"), + "{shown}" + ); + assert!( + form.help() + .contains("It cannot be changed now: No provisioner made studio") + ); + let why = Did::Stay(Some("No provisioner made studio".into())); + assert_eq!(press(&mut form, Code::Char(' ')), why); + assert_eq!(press(&mut form, Code::Enter), why); + assert_eq!(click(&mut form, 0), why); + assert_eq!(form.values["destroy"], "no"); + // Run asks the action's own question, with nothing on. + press(&mut form, Code::Down); + press(&mut form, Code::Enter); + assert_eq!(form.asking(), Some("Remove studio?")); + } + + #[test] + fn a_switch_that_is_on_asks_its_own_question_with_the_dialogs_keys() { + let mut action = remove(); + action.arguments[0].confirm = "Remove studio and destroy its machine?".into(); + let mut form = Form::of("studio", 2, &action, &BTreeMap::new()); + press(&mut form, Code::Char(' ')); + press(&mut form, Code::Down); + press(&mut form, Code::Enter); + assert_eq!( + form.asking(), + Some("Remove studio and destroy its machine?") + ); + let shown = screen(&form, ""); + let footer = shown.lines().last().unwrap(); + assert!( + footer.contains("y yes") && footer.contains("Esc back to the form"), + "{shown}" + ); + assert!(!footer.contains("x unset"), "{shown}"); + } + fn screen(form: &Form, status: &str) -> String { let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(110, 16)).unwrap(); diff --git a/crates/berth-tui/src/host.rs b/crates/berth-tui/src/host.rs index 68bd266..6365ff1 100644 --- a/crates/berth-tui/src/host.rs +++ b/crates/berth-tui/src/host.rs @@ -3,6 +3,7 @@ //! business; requests go out through it and what happened comes back. use crate::event::{Key, key_bytes}; +use crate::form::{self, Form}; use crate::page::{self, Accepted, Begin}; pub use crate::page::{Arguments, Launch, argument_label}; use berth_api as api; @@ -257,6 +258,8 @@ pub struct HostView { pub password: Option, pub question: Option<(String, Pending)>, pub arguments: Option, + /// The form of an action with switches or a text, over the whole screen. + pub form: Option
, polled: Instant, /// The next `Opened` is a session started from here, and maybe a shell. starting: Option, @@ -280,6 +283,7 @@ impl Default for HostView { password: None, question: None, arguments: None, + form: None, polled: Instant::now(), starting: None, size: (24, 80), @@ -311,6 +315,7 @@ impl HostView { self.remote = None; self.view = None; self.host_actions.clear(); + self.form = None; self.sessions.clear(); self.stats = None; self.behind = None; @@ -357,10 +362,15 @@ impl HostView { } /// Begin an action: its question first, then its arguments. Returns the - /// action to run now when it needs neither. - pub fn begin_action(&mut self, index: usize, confirmed: bool) -> Option { - match page::begin(&self.actions(), index, confirmed) { + /// action to run now when it needs neither. `place` is the host's name, + /// for the top line of a form. + pub fn begin_action(&mut self, place: &str, index: usize, confirmed: bool) -> Option { + let actions = self.actions(); + match page::begin(&actions, index, confirmed) { Begin::Ask(question) => self.question = Some((question, Pending::Action(index))), + Begin::Arguments(_) if form::takes(&actions[index]) => { + self.form = Some(Form::of(place, index, &actions[index], &BTreeMap::new())); + } Begin::Arguments(dialog) => { self.arguments = Some(dialog); self.ask_choices(); diff --git a/crates/berth-tui/src/machine.rs b/crates/berth-tui/src/machine.rs index b4cd724..585e185 100644 --- a/crates/berth-tui/src/machine.rs +++ b/crates/berth-tui/src/machine.rs @@ -426,7 +426,14 @@ impl Machine { false => label(argument).to_owned(), }; let value = self.values.get(&argument.name).map_or("", String::as_str); - let mut line = value_line(&name, value, Kind::Text); + // A yes or no is a switch, as the set-up's own are. + let mut line = match argument.is_boolean() { + true => { + let on = berth_api::Argument::is_on(value).to_string(); + value_line(&name, &on, Kind::Toggle) + } + false => value_line(&name, value, Kind::Text), + }; line.spans.insert(0, Span::styled(branch, muted)); Row::entry(line, Entry::Machine(Pick::Argument(index))) }) @@ -591,9 +598,10 @@ impl Machine { if !argument.default.is_empty() { text += &format!(" Default: {}.", argument.default); } - match argument.values.is_empty() { - true => text + " Enter changes it.", - false => text + " Space or Enter switches to the next value.", + match (argument.is_boolean(), argument.values.is_empty()) { + (true, _) => text + " Space or Enter turns it on or off.", + (false, true) => text + " Enter changes it.", + (false, false) => text + " Space or Enter switches to the next value.", } } Pick::Create => "Creates the machine and sets it up as this host, with the profile saved first. The output is shown as it runs. When setting it up fails, the machine stays: Destroy removes it.".into(), @@ -615,6 +623,11 @@ impl Machine { return Next::Nothing; }; let value = self.value(index).unwrap_or("").to_owned(); + if argument.is_boolean() { + let next = argument.switched(!berth_api::Argument::is_on(&value)); + self.values.insert(argument.name.clone(), next); + return Next::Nothing; + } // One of a few values goes on to the next, as a choice field does. if !argument.values.is_empty() { let all = &argument.values; @@ -1069,24 +1082,40 @@ mod tests { help: "Whether deleting the machine keeps its volume.".into(), ..Default::default() }); + lab.arguments.push(Argument { + name: "runtime".into(), + default: "privileged".into(), + values: vec!["privileged".into(), "sysbox".into()], + ..Default::default() + }); let mut machine = without_machine(vec![lab]); assert_eq!( - machine.argument_choices(2), + machine.argument_choices(3), [ - ("no".to_owned(), "no".to_owned()), - ("yes".to_owned(), "yes".to_owned()) + ("privileged".to_owned(), "privileged".to_owned()), + ("sysbox".to_owned(), "sysbox".to_owned()) ] ); assert!(machine.argument_choices(1).is_empty()); // Enter goes on to the next value and around, as on a choice field. - assert_eq!(machine.enter(Pick::Argument(2), "studio"), Next::Nothing); + assert_eq!(machine.enter(Pick::Argument(3), "studio"), Next::Nothing); + assert_eq!(machine.value(3), Some("sysbox")); + machine.enter(Pick::Argument(3), "studio"); + assert_eq!(machine.value(3), Some("privileged")); + assert!( + machine + .help(Pick::Argument(3)) + .contains("Space or Enter switches to the next value") + ); + // A yes or no is a switch, turned on and off. + machine.enter(Pick::Argument(2), "studio"); assert_eq!(machine.value(2), Some("yes")); machine.enter(Pick::Argument(2), "studio"); assert_eq!(machine.value(2), Some("no")); // The label is a name; what it means is in the help. let help = machine.help(Pick::Argument(2)); assert!(help.starts_with("Keep volume on destroy (`keep_volume`). Whether deleting")); - assert!(help.contains("Space or Enter switches to the next value")); + assert!(help.contains("Space or Enter turns it on or off")); assert!( machine .help(Pick::Argument(1)) diff --git a/crates/berth-tui/src/page.rs b/crates/berth-tui/src/page.rs index 5b43b36..b7367df 100644 --- a/crates/berth-tui/src/page.rs +++ b/crates/berth-tui/src/page.rs @@ -163,12 +163,20 @@ impl Arguments { values: BTreeMap, argument: &Argument, ) -> Self { + // A yes or no, or one of a few values, is chosen from them. + let choices = match argument.is_boolean() { + true => { + let (on, off) = argument.switch_values(); + vec![off, on] + } + false => argument.values.clone(), + }; Arguments { action, index, values, input: Input::new(argument.default.clone()), - choices: vec![], + choices, chosen: None, secret: argument.secret, text: argument.kind == Argument::TEXT, @@ -215,12 +223,15 @@ pub enum Begin { } /// Begin an action: its question first, unless it was answered, then its -/// arguments. +/// arguments. An action asked for in a form asks its question when it is +/// run from there, so that the question can say which switches are on. pub fn begin(actions: &[Action], index: usize, confirmed: bool) -> Begin { let Some(action) = actions.get(index) else { return Begin::Nothing; }; - if let (Some(question), false) = (&action.confirm, confirmed) { + if let (Some(question), false) = (&action.confirm, confirmed) + && !crate::form::takes(action) + { return Begin::Ask(question.clone()); } match action.arguments.first() { @@ -229,6 +240,38 @@ pub fn begin(actions: &[Action], index: usize, confirmed: bool) -> Begin { } } +/// The question to answer yes to before an action runs with `values`, if it +/// has one. A switch that is on and has a question of its own, such as +/// destroying a machine, asks that one instead of the action's. The others +/// that are on are named after it. +pub fn confirmation(action: &Action, values: &BTreeMap) -> Option { + let on: Vec<&Argument> = action + .arguments + .iter() + .filter(|argument| argument.is_boolean()) + .filter(|argument| { + values + .get(&argument.name) + .is_some_and(|value| Argument::is_on(value)) + }) + .collect(); + let own = on.iter().find(|argument| !argument.confirm.is_empty()); + let question = match own { + Some(argument) => &argument.confirm, + None => action.confirm.as_ref()?, + }; + let named: Vec<&str> = on + .iter() + .filter(|argument| argument.confirm.is_empty()) + .map(|argument| argument_label(argument)) + .collect(); + Some(match named.as_slice() { + [] => question.clone(), + [one] => format!("{question} {one} is on."), + [rest @ .., last] => format!("{question} {} and {last} are on.", rest.join(", ")), + }) +} + /// What taking the value typed for an argument leads to. pub enum Accepted { /// The next argument is asked for. @@ -482,6 +525,99 @@ mod tests { ); } + fn switch(name: &str, label: &str) -> Argument { + Argument { + name: name.into(), + label: label.into(), + default: "no".into(), + kind: Argument::BOOLEAN.into(), + values: vec!["no".into(), "yes".into()], + ..Argument::default() + } + } + + #[test] + fn an_action_with_a_switch_asks_once_its_values_are_known() { + let rename = Action { + name: "rename".into(), + confirm: Some("Rename studio?".into()), + arguments: vec![ + Argument { + name: "new".into(), + required: true, + ..Argument::default() + }, + switch("hostname", "Also its hostname"), + ], + ..Action::default() + }; + // Its form asks the question when it is run from there. + let actions = [rename.clone()]; + assert!(matches!(begin(&actions, 0, false), Begin::Arguments(_))); + // One with values from a command is asked in the dialog, after the question. + let mut offered = rename.clone(); + offered.arguments[0].choices = "ls /srv".into(); + assert!(matches!(begin(&[offered], 0, false), Begin::Ask(_))); + let values = |hostname: &str| { + BTreeMap::from([ + ("new".to_owned(), "dock".to_owned()), + ("hostname".to_owned(), hostname.to_owned()), + ]) + }; + assert_eq!( + confirmation(&rename, &values("no")).as_deref(), + Some("Rename studio?") + ); + assert_eq!( + confirmation(&rename, &values("yes")).as_deref(), + Some("Rename studio? Also its hostname is on.") + ); + let mut both = rename.clone(); + both.arguments.push(switch("force", "Force")); + let mut given = values("yes"); + given.insert("force".into(), "yes".into()); + assert_eq!( + confirmation(&both, &given).as_deref(), + Some("Rename studio? Also its hostname and Force are on.") + ); + both.confirm = None; + assert_eq!(confirmation(&both, &given), None); + // A switch with a question of its own asks that one when it is on, + // even where the action asks none. + both.arguments[1].confirm = "Rename studio and its hostname?".into(); + assert_eq!( + confirmation(&both, &given).as_deref(), + Some("Rename studio and its hostname? Force is on.") + ); + assert_eq!(confirmation(&both, &values("no")), None); + } + + #[test] + fn a_dialog_offers_the_values_an_argument_takes() { + let mut restart = switch("restart", "Restart"); + restart.values = vec!["true".into(), "false".into()]; + let actions = [Action { + arguments: vec![ + Argument { + name: "source".into(), + values: vec!["release".into(), "here".into()], + ..Argument::default() + }, + restart, + ], + ..Action::default() + }]; + let Begin::Arguments(dialog) = begin(&actions, 0, true) else { + panic!("no arguments"); + }; + assert_eq!(dialog.choices, ["release", "here"]); + let Accepted::Next(dialog) = accept(&actions, dialog) else { + panic!("no next"); + }; + // A yes or no is offered off first, as the values it declares. + assert_eq!(dialog.choices, ["false", "true"]); + } + #[test] fn removing_a_host_a_provisioner_made_asks_to_forget_or_destroy() { let made = serde_json::json!({"name": "studio", "machine": {"provisioner": "incus", "external_id": "berth-studio", "state": "running"}}); diff --git a/crates/berth-tui/src/provisioners.rs b/crates/berth-tui/src/provisioners.rs index 830004d..4f234d7 100644 --- a/crates/berth-tui/src/provisioners.rs +++ b/crates/berth-tui/src/provisioners.rs @@ -751,7 +751,7 @@ impl Page { } Asked::Nothing(None) } - Begin::Arguments(_) if form::wants_form(&self.actions[index]) => { + Begin::Arguments(_) if form::takes(&self.actions[index]) => { let form = Form::of(&self.id, index, &self.actions[index], self.narrowed()); self.form = Some(form); Asked::Nothing(None) @@ -2428,25 +2428,25 @@ mod tests { panic!("not run"); }; assert_eq!((action.name.as_str(), values.len()), ("images", 0)); - // The next asks first, then offers what its argument takes. + // A switch opens the form, which asks the question when it is run. tab.key(key(Code::Down), &list, &mut Nowhere); assert_eq!( tab.key(key(Code::Enter), &list, &mut Nowhere), Asked::Nothing(None) ); - assert_eq!(tab.question(), Some("Prune?")); - assert!(tab.typing()); + assert!(tab.question().is_none() && tab.typing()); + let form = tab.form().unwrap(); + assert_eq!(form.context(), "docker/container › prune"); + tab.key(key(Code::Char(' ')), &list, &mut Nowhere); + tab.key(key(Code::Down), &list, &mut Nowhere); + tab.key(key(Code::Enter), &list, &mut Nowhere); + assert_eq!(tab.form().unwrap().asking(), Some("Prune? volumes is on.")); assert_eq!( tab.key(key(Code::Char('n')), &list, &mut Nowhere), Asked::Nothing(Some("Not run".into())) ); tab.key(key(Code::Enter), &list, &mut Nowhere); - tab.key(key(Code::Char('y')), &list, &mut Nowhere); - let (_, dialog) = tab.arguments().unwrap(); - assert_eq!(dialog.choices, ["no", "yes"]); - tab.key(key(Code::Down), &list, &mut Nowhere); - tab.key(key(Code::Down), &list, &mut Nowhere); - let Asked::Run { action, values, .. } = tab.key(key(Code::Enter), &list, &mut Nowhere) + let Asked::Run { action, values, .. } = tab.key(key(Code::Char('y')), &list, &mut Nowhere) else { panic!("not run"); }; diff --git a/crates/berth-tui/src/screen.rs b/crates/berth-tui/src/screen.rs index 27dd1f7..1047bc5 100644 --- a/crates/berth-tui/src/screen.rs +++ b/crates/berth-tui/src/screen.rs @@ -242,9 +242,14 @@ fn draw_said(frame: &mut Frame, footer: Rect, status: &str, colour: Color) { } /// A small centred box over the rest of the screen. Returns its area. -pub fn dialog(frame: &mut Frame, title: &str, keys: &str, lines: Vec) -> Rect { +pub fn dialog(frame: &mut Frame, title: &str, keys: &str, mut lines: Vec) -> Rect { let screen = frame.area(); let width = 62.min(screen.width); + // The keys are the last line inside the box, under a blank one, so no + // border runs through them at any width. + let keys = keys.trim(); + lines.push(Line::raw("")); + lines.push(theme::hints(keys)); let height = (lines.len() as u16 + 2).min(screen.height); let area = Rect::new( screen.x + (screen.width - width) / 2, @@ -252,17 +257,11 @@ pub fn dialog(frame: &mut Frame, title: &str, keys: &str, lines: Vec) -> R width, height, ); - note_hints( - keys.trim(), - area.x + 1, - area.bottom().saturating_sub(1), - true, - ); + // Inside the border and its padding of one column. + note_hints(keys, area.x + 2, area.bottom().saturating_sub(2), true); frame.render_widget(Clear, area); frame.render_widget( - Paragraph::new(lines).block( - theme::popup(title.trim(), theme::ACCENT).title_bottom(theme::hints(keys.trim())), - ), + Paragraph::new(lines).block(theme::popup(title.trim(), theme::ACCENT)), area, ); area @@ -802,6 +801,45 @@ mod tests { .collect() } + fn question_at(width: u16) -> Vec { + let mut terminal = Terminal::new(TestBackend::new(width, 12)).unwrap(); + terminal + .draw(|frame| draw_question(frame, "Remove studio? Its sessions end.")) + .unwrap(); + let buffer = terminal.backend().buffer().clone(); + (0..12) + .map(|y| { + (0..width) + .map(|x| buffer[(x, y)].symbol().to_owned()) + .collect::() + }) + .collect() + } + + #[test] + fn a_dialog_has_its_keys_inside_the_box_at_any_width() { + for width in [80, 62, 40] { + let rows = question_at(width); + let bottom = rows.iter().position(|row| row.contains('╰')).unwrap(); + let keys = rows.iter().position(|row| row.contains("y yes")).unwrap(); + assert_eq!(keys + 1, bottom, "{rows:#?}"); + // The keys sit between the box's sides, and the border is unbroken. + let row = &rows[keys]; + assert!( + row.trim().starts_with('│') && row.trim().ends_with('│'), + "{rows:#?}" + ); + assert!(!rows[bottom].contains("yes"), "{rows:#?}"); + assert!(rows[keys - 1].trim().trim_matches('│').trim().is_empty()); + } + // A click on a key's hint is that key. + let rows = question_at(80); + let y = rows.iter().position(|row| row.contains("y yes")).unwrap() as u16; + let x = rows[y as usize].find("y yes").unwrap(); + let x = rows[y as usize][..x].chars().count() as u16; + assert_eq!(hint_at(x, y), Some(Key::plain(Code::Char('y')))); + } + #[test] fn a_long_message_is_shown_whole_at_a_narrow_width() { let said = "✗ The USB installer is built where berth serve runs, with berth ui there"; diff --git a/crates/berth/src/cli/ask.rs b/crates/berth/src/cli/ask.rs index 40da609..1f5c2c2 100644 --- a/crates/berth/src/cli/ask.rs +++ b/crates/berth/src/cli/ask.rs @@ -301,6 +301,53 @@ pub fn text(label: &str, help: &str, flag: &str) -> Result { } } +/// Ask a yes or no that starts at `default`, or say which flag gives it. +pub fn yes_no(label: &str, help: &str, flag: &str, default: bool) -> Result { + let question = Question { + step: berth_tui::fields::Step::Install, + label: label.into(), + help: help.into(), + flag: flag.into(), + asked: Asked::Confirm { default }, + required: true, + }; + match ask(&question)? { + Answer::Confirm(on) => Ok(on), + _ => Err(Fail::usage(format!("{label} is missing: pass {flag}"))), + } +} + +/// Ask for one of `values`, starting at `default`, or say which flag gives it. +pub fn choice( + label: &str, + help: &str, + flag: &str, + values: &[String], + default: &str, +) -> Result { + let question = Question { + step: berth_tui::fields::Step::Install, + label: label.into(), + help: help.into(), + flag: flag.into(), + asked: Asked::Choice { + options: values + .iter() + .map(|value| Choice::new(value, value, "")) + .collect(), + default: values + .iter() + .position(|value| value == default) + .unwrap_or(0), + }, + required: true, + }; + match ask(&question)? { + Answer::Choice(index) if index < values.len() => Ok(index), + _ => Err(Fail::usage(format!("{label} is missing: pass {flag}"))), + } +} + /// Ask for a secret without showing it, or say which flag gives it. pub fn secret(label: &str, flag: &str) -> Result { let question = Question { diff --git a/crates/berth/src/cli/things.rs b/crates/berth/src/cli/things.rs index be25371..3f53200 100644 --- a/crates/berth/src/cli/things.rs +++ b/crates/berth/src/cli/things.rs @@ -11,7 +11,7 @@ use super::host; use super::out::{self, Style, Table, styled}; use super::pages; use berth_api::portal::{Piece, PortalStream}; -use berth_api::{Act, SessionKind}; +use berth_api::{Act, Argument, SessionKind}; use serde_json::{Value, json}; use std::collections::BTreeMap; use std::io::{IsTerminal, Write}; @@ -441,6 +441,33 @@ fn complete( given: &mut BTreeMap, subject: &str, ) -> Result<()> { + // A yes or no goes as the value the action declares, however it is spelt. + for argument in action + .arguments + .iter() + .filter(|argument| argument.is_boolean()) + { + if let Some(value) = given.get_mut(&argument.name) { + *value = argument.read_switch(value).map_err(Fail::usage)?; + } + } + // One the action cannot take another value of here says why. + for argument in action + .arguments + .iter() + .filter(|argument| !argument.fixed.is_empty()) + { + let default = match argument.is_boolean() { + true => argument.switched(Argument::is_on(&argument.default)), + false => argument.default.clone(), + }; + if given + .get(&argument.name) + .is_some_and(|value| !value.is_empty() && *value != default) + { + return Err(Fail::refused(argument.fixed.clone())); + } + } for argument in &action.arguments { if !argument.required || given @@ -454,9 +481,24 @@ fn complete( label => label.to_owned(), }; let flag = format!("{}=VALUE", argument.name); - let value = match argument.secret { - true => ask::secret(&label, &flag)?, - false => ask::text(&label, &argument.help, &flag)?, + let value = match (argument.secret, argument.is_boolean()) { + (true, _) => ask::secret(&label, &flag)?, + (false, true) => { + let flag = format!("{}=yes|no", argument.name); + let on = Argument::is_on(&argument.default); + argument.switched(ask::yes_no(&label, &argument.help, &flag, on)?) + } + (false, false) if !argument.values.is_empty() => { + let chosen = ask::choice( + &label, + &argument.help, + &flag, + &argument.values, + &argument.default, + )?; + argument.values[chosen].clone() + } + (false, false) => ask::text(&label, &argument.help, &flag)?, }; given.insert(argument.name.clone(), value); } @@ -466,8 +508,8 @@ fn complete( action.name, action.why ))); } - if let Some(question) = &action.confirm { - ask::confirm(question)?; + if let Some(question) = berth_tui::page::confirmation(action, given) { + ask::confirm(&question)?; } Ok(()) } @@ -1015,3 +1057,94 @@ pub fn resource(client: &Client, command: Resource) -> Result<()> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn remove() -> berth_api::Action { + berth_api::Action { + name: "remove".into(), + confirm: Some("Remove studio?".into()), + arguments: vec![Argument { + name: "destroy".into(), + label: "Destroy its machine".into(), + default: "no".into(), + kind: Argument::BOOLEAN.into(), + values: vec!["no".into(), "yes".into()], + ..Argument::default() + }], + available: true, + ..berth_api::Action::default() + } + } + + fn given(value: &str) -> BTreeMap { + arguments(&[format!("destroy={value}")]).unwrap() + } + + #[test] + fn a_yes_or_no_is_taken_in_any_spelling_and_named_in_the_question() { + // Nobody can be asked here, so the question comes back as the refusal. + let mut on = given("TRUE"); + let refused = complete(&remove(), &mut on, "studio").unwrap_err(); + assert_eq!(on["destroy"], "yes"); + assert!( + refused + .message + .starts_with("Remove studio? Destroy its machine is on. Confirm with --yes"), + "{}", + refused.message + ); + let mut off = given("Off"); + let refused = complete(&remove(), &mut off, "studio").unwrap_err(); + assert_eq!(off["destroy"], "no"); + assert!( + refused + .message + .starts_with("Remove studio? Confirm with --yes") + ); + let mut bad = given("maybe"); + let refused = complete(&remove(), &mut bad, "studio").unwrap_err(); + assert_eq!( + refused.message, + "destroy is yes or no (or true/false, on/off, 1/0), not maybe" + ); + } + + #[test] + fn a_needed_yes_or_no_says_how_to_give_it() { + let mut action = remove(); + action.confirm = None; + action.arguments[0].required = true; + let mut none = BTreeMap::new(); + let refused = complete(&action, &mut none, "studio").unwrap_err(); + assert_eq!( + refused.message, + "Destroy its machine is missing: pass destroy=yes|no" + ); + let mut on = given("1"); + complete(&action, &mut on, "studio").unwrap(); + assert_eq!(on["destroy"], "yes"); + } + + #[test] + fn a_switch_with_its_own_question_asks_it_and_a_fixed_one_says_why() { + let mut action = remove(); + action.arguments[0].confirm = "Remove studio and destroy its machine?".into(); + let refused = complete(&action, &mut given("yes"), "studio").unwrap_err(); + assert!( + refused + .message + .starts_with("Remove studio and destroy its machine? Confirm with --yes"), + "{}", + refused.message + ); + action.arguments[0].fixed = "No provisioner made studio".into(); + let refused = complete(&action, &mut given("on"), "studio").unwrap_err(); + assert_eq!(refused.message, "No provisioner made studio"); + // Off is what it is anyway, so the action's own question comes. + let refused = complete(&action, &mut given("no"), "studio").unwrap_err(); + assert!(refused.message.starts_with("Remove studio? Confirm")); + } +} diff --git a/crates/berth/src/local/serve/actions.rs b/crates/berth/src/local/serve/actions.rs index e6cf307..5732dc1 100644 --- a/crates/berth/src/local/serve/actions.rs +++ b/crates/berth/src/local/serve/actions.rs @@ -1352,12 +1352,12 @@ fn remove_action(seen: &Seen) -> Action { let (help, confirm) = match made(seen.machine) { Some(machine) => ( format!( - "Forget {name}: its profile, the passwords berth generated and keeps for it, and its host keys. With destroy, {} also destroys its machine {} with its disk, and berth removes its device from the tailnet. Without destroy the machine and its device are left as they are, and berth keeps it as a resource of {} with no host, which berth resource remove deletes later.", + "Forget {name}: its profile, the passwords berth generated and keeps for it, and its host keys. With Destroy its machine on, {} also destroys its machine {} with its disk, and berth removes its device from the tailnet. Off, the machine and its device are left as they are, and berth keeps it as a resource of {} with no host, which berth resource remove deletes later.", machine.provisioner, machine.external_id, machine.provisioner ), format!( - "Remove {name}? With destroy=yes {} destroys its machine {} and the disk it has; without, the machine is left as it is.", - machine.provisioner, machine.external_id + "Remove {name}? Its machine {} is left as it is, as a resource of {}.", + machine.external_id, machine.provisioner ), ), None => ( @@ -1367,13 +1367,26 @@ fn remove_action(seen: &Seen) -> Action { format!("Forget {name}? The machine is left as it is."), ), }; - let destroy = match made(seen.machine) { - Some(machine) => format!( - "Destroy the machine {} made, {}, with its disk, and remove its device from the tailnet. It cannot be undone.", - machine.provisioner, machine.external_id + let mut destroy = match made(seen.machine) { + Some(machine) => { + let help = format!( + "On, {} destroys the machine it made, {}, with its disk, and berth removes its device from the tailnet. It cannot be undone.", + machine.provisioner, machine.external_id + ); + let mut destroy = flag("destroy", "Destroy its machine", &help); + destroy.confirm = format!( + "Remove {name} and destroy its machine {} with {}, with its disk? It cannot be undone.", + machine.external_id, machine.provisioner + ); + destroy + } + None => flag( + "destroy", + "Destroy its machine", + "On, the provisioner that made the host's machine destroys it with its disk.", ), - None => "Destroy the machine a provisioner made for the host. This host has none, so yes is refused.".into(), }; + destroy.fixed = destroy_refused(name, seen.machine).unwrap_or_default(); let action = Action { name: "remove".into(), label: "Remove".into(), @@ -1381,7 +1394,7 @@ fn remove_action(seen: &Seen) -> Action { group: "Host".into(), role: Role::Admin, confirm: Some(confirm), - arguments: vec![flag("destroy", "Destroy its machine", &destroy)], + arguments: vec![destroy], ..Action::default() }; let why = seen @@ -1671,6 +1684,7 @@ fn flag(name: &str, label: &str, help: &str) -> Argument { label: label.into(), help: help.into(), default: "no".into(), + kind: Argument::BOOLEAN.into(), values: vec!["no".into(), "yes".into()], ..Argument::default() } @@ -1790,12 +1804,13 @@ fn rollout(state: Arc, _: String, act: Act) -> Run { /// The yes or no of a flag argument. fn yes(act: &Act, name: &str) -> Answer { match act.arguments.get(name).map(|value| value.trim()) { - None | Some("" | "no" | "false") => Ok(false), - Some("yes" | "true") => Ok(true), - Some(other) => Err(Fail::new( - code::BAD_REQUEST, - format!("{name} is yes or no, not {other}"), - )), + None | Some("") => Ok(false), + Some(value) => berth_api::parse_bool(value).ok_or_else(|| { + Fail::new( + code::BAD_REQUEST, + format!("{name} is yes or no, not {value}"), + ) + }), } } @@ -2122,7 +2137,7 @@ fn adopt_reach( let force = act .arguments .get("force") - .is_some_and(|value| value == "yes" || value == "true"); + .is_some_and(|value| Argument::is_on(value)); let address = given(act, "address").unwrap_or(""); let port = given(act, "port").unwrap_or(""); let key = given(act, "key"); @@ -2525,10 +2540,14 @@ mod tests { assert_eq!(remove.role, Role::Admin); assert_eq!( remove.confirm.as_deref(), - Some( - "Remove big? With destroy=yes incus destroys its machine berth-big and the disk it has; without, the machine is left as it is." - ) + Some("Remove big? Its machine berth-big is left as it is, as a resource of incus.") + ); + // Destroying asks its own question, and can be chosen. + assert_eq!( + remove.arguments[0].confirm, + "Remove big and destroy its machine berth-big with incus, with its disk? It cannot be undone." ); + assert!(remove.arguments[0].fixed.is_empty()); assert_eq!( ( remove.arguments[0].name.as_str(), @@ -2542,6 +2561,13 @@ mod tests { bare.confirm.as_deref(), Some("Forget big? The machine is left as it is.") ); + // With nothing to destroy, the switch stays off and says why. + assert!( + bare.arguments[0] + .fixed + .starts_with("No provisioner made big, so there is nothing for berth to destroy") + ); + assert!(bare.arguments[0].confirm.is_empty()); let refused = destroy_refused("big", None).unwrap(); assert!( refused diff --git a/crates/berth/src/local/serve/tests.rs b/crates/berth/src/local/serve/tests.rs index 5e1baa0..32369b5 100644 --- a/crates/berth/src/local/serve/tests.rs +++ b/crates/berth/src/local/serve/tests.rs @@ -5129,10 +5129,10 @@ async fn a_host_is_started_stopped_duplicated_and_removed_by_its_actions() { assert_eq!(status, 501, "{said}"); let remove = host_action(client, "studio", "remove").await; assert!( - remove["confirm"] + remove["arguments"][0]["confirm"] .as_str() .unwrap() - .contains("vm destroys its machine vm-1 and the disk it has"), + .contains("destroy its machine vm-1 with vm, with its disk"), "{remove}" ); let (status, acted) = send(client, "POST", &act("studio/actions/start"), Value::Null).await; diff --git a/docs/content/docs/(guide)/extend/writing-plugins.mdx b/docs/content/docs/(guide)/extend/writing-plugins.mdx index 7d010ee..a14a7ba 100644 --- a/docs/content/docs/(guide)/extend/writing-plugins.mdx +++ b/docs/content/docs/(guide)/extend/writing-plugins.mdx @@ -112,7 +112,7 @@ An action becomes an action of the host's controller named `PLUGIN:ACTION`. Appl help: { type: 'string', description: 'Help text in berth.' }, user: { type: '"agent" | "root" | "operator"', default: '"agent"', description: 'agent runs in its home with the desktop environment; operator is the SSH user.' }, agent: { type: 'boolean', default: 'false', description: 'Lets the agent run it itself with box run PLUGIN:ACTION.' }, - arguments: { type: 'Argument[]', description: 'Values asked for before it runs: {name, label, required, default, choices}.' }, + arguments: { type: 'Argument[]', description: 'Values asked for before it runs: {name, label, required, default, choices, values, kind}.' }, confirm: { type: 'string', description: 'A sentence to confirm before it runs, for something that cannot be taken back.' }, terminal: { type: 'boolean', default: 'false', description: 'For a command that asks something or shows a link to follow, such as a sign-in.' }, group: { type: 'string', description: 'The overview group: Host, Power, Access, Sync, Sign-In, or your own. Default: a group named after the plugin.' }, @@ -122,7 +122,7 @@ An action becomes an action of the host's controller named `PLUGIN:ACTION`. Appl ### Arguments -The command finds each argument as `BERTH_ARG_NAME` in its environment, upper-cased, with `_` for anything that is not a letter or digit. Values are never pasted into the command line. `choices` is a command whose output lines are the values to offer. +The command finds each argument as `BERTH_ARG_NAME` in its environment, upper-cased, with `_` for anything that is not a letter or digit. Values are never pasted into the command line. `choices` is a command whose output lines are the values to offer. `values` and `kind` mean what they mean for a provisioner's arguments, below. A yes or no is a switch here too. ### Steps of other actions @@ -403,13 +403,29 @@ Each entry of `arguments`, of the provisioner, of a kind or of an action, is one label: { type: 'string', default: 'the name', description: 'Name in berth.' }, required: { type: 'boolean', default: 'false', description: 'It is refused while it is empty.' }, default: { type: 'string', default: '""', description: 'The value it starts with.' }, - kind: { type: '"resource"', description: 'Marks a resource of the machine, such as CPUs, memory or disk. Without it, the argument is an ordinary one.' }, + kind: { type: '"resource" | "boolean"', description: 'resource marks a resource of the machine, such as CPUs, memory or disk. boolean marks a yes or no. Without it, the argument is an ordinary one.' }, help: { type: 'string', description: 'What the argument is for, in one or two short sentences, with an example value where it helps. berth shows it in the Information panel of the row. Keep the label to a name, such as Image.' }, values: { type: 'string[]', description: 'The values it takes, for a choice of a few, such as ["no", "yes"]. berth offers them like any other choice, and refuses another value.' }, secret: { type: 'boolean', default: 'false', description: 'For an action: what is given is a secret. It is not shown or kept, and is masked in the output.' }, }} /> +#### A yes or no + +Declare a yes or no with `"kind": "boolean"`, and give its two values too: + +```json +{"name": "keep_volumes", "label": "Keep volumes", "default": "no", "kind": "boolean", "values": ["no", "yes"]} +``` + +The screens show it as a switch, which Space, Enter or a click turns on or off. An argument whose `values` are just `yes` and `no`, or `true` and `false`, is a switch as well. Your program gets the value for on or off from `values`, or `yes` and `no` without them. On the command line it is given as one of these, in any case, and berth sends the declared value: + +| On | Off | +| --- | --- | +| `yes`, `true`, `on`, `1` | `no`, `false`, `off`, `0` | + +An action's `confirm` question names each switch that is on. Give the argument a `confirm` of its own, such as `"confirm": "Remove the deployment and its volumes?"`, and berth asks that question instead of the action's while the switch is on. + A provisioner's `status`, described below, lists the values an argument takes. berth does not run a `choices` command for a provisioner. A host's set-up tabs show the arguments of a machine: the provisioner's own first, then the machine kind's. diff --git a/docs/openapi/berth.openapi.json b/docs/openapi/berth.openapi.json index cac32af..bacdc74 100644 --- a/docs/openapi/berth.openapi.json +++ b/docs/openapi/berth.openapi.json @@ -258,15 +258,23 @@ "description": "A command whose lines are the values to offer.", "type": "string" }, + "confirm": { + "description": "For a yes or no: the question to answer yes to before the action\nruns with it on, instead of the action's own.", + "type": "string" + }, "default": { "type": "string" }, + "fixed": { + "description": "Why it keeps its default here and cannot be given another value,\nsuch as destroying a machine no provisioner made. The screens show\nit greyed and say this instead of changing it. Empty when it can be\nchanged.", + "type": "string" + }, "help": { "description": "What it is for, in a sentence or two, beside its short label.", "type": "string" }, "kind": { - "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. Empty for any other argument.", + "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. `boolean` for a yes or no, which the screens show as a switch.\nEmpty for any other argument.", "type": "string" }, "label": { diff --git a/docs/openapi/berth.operations.json b/docs/openapi/berth.operations.json index 5c9a4ea..a43da28 100644 --- a/docs/openapi/berth.operations.json +++ b/docs/openapi/berth.operations.json @@ -258,15 +258,23 @@ "description": "A command whose lines are the values to offer.", "type": "string" }, + "confirm": { + "description": "For a yes or no: the question to answer yes to before the action\nruns with it on, instead of the action's own.", + "type": "string" + }, "default": { "type": "string" }, + "fixed": { + "description": "Why it keeps its default here and cannot be given another value,\nsuch as destroying a machine no provisioner made. The screens show\nit greyed and say this instead of changing it. Empty when it can be\nchanged.", + "type": "string" + }, "help": { "description": "What it is for, in a sentence or two, beside its short label.", "type": "string" }, "kind": { - "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. Empty for any other argument.", + "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. `boolean` for a yes or no, which the screens show as a switch.\nEmpty for any other argument.", "type": "string" }, "label": { diff --git a/docs/openapi/berthd.openapi.json b/docs/openapi/berthd.openapi.json index 1f125f6..cce3e21 100644 --- a/docs/openapi/berthd.openapi.json +++ b/docs/openapi/berthd.openapi.json @@ -67,15 +67,23 @@ "description": "A command whose lines are the values to offer.", "type": "string" }, + "confirm": { + "description": "For a yes or no: the question to answer yes to before the action\nruns with it on, instead of the action's own.", + "type": "string" + }, "default": { "type": "string" }, + "fixed": { + "description": "Why it keeps its default here and cannot be given another value,\nsuch as destroying a machine no provisioner made. The screens show\nit greyed and say this instead of changing it. Empty when it can be\nchanged.", + "type": "string" + }, "help": { "description": "What it is for, in a sentence or two, beside its short label.", "type": "string" }, "kind": { - "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. Empty for any other argument.", + "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. `boolean` for a yes or no, which the screens show as a switch.\nEmpty for any other argument.", "type": "string" }, "label": { diff --git a/docs/openapi/berthd.operations.json b/docs/openapi/berthd.operations.json index 21f4709..1204dbc 100644 --- a/docs/openapi/berthd.operations.json +++ b/docs/openapi/berthd.operations.json @@ -67,15 +67,23 @@ "description": "A command whose lines are the values to offer.", "type": "string" }, + "confirm": { + "description": "For a yes or no: the question to answer yes to before the action\nruns with it on, instead of the action's own.", + "type": "string" + }, "default": { "type": "string" }, + "fixed": { + "description": "Why it keeps its default here and cannot be given another value,\nsuch as destroying a machine no provisioner made. The screens show\nit greyed and say this instead of changing it. Empty when it can be\nchanged.", + "type": "string" + }, "help": { "description": "What it is for, in a sentence or two, beside its short label.", "type": "string" }, "kind": { - "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. Empty for any other argument.", + "description": "`resource` for an argument of a provisioner that sizes the machine:\nits CPUs, memory or disk. `text` for one whose value has several\nlines. `boolean` for a yes or no, which the screens show as a switch.\nEmpty for any other argument.", "type": "string" }, "label": { diff --git a/plugins/docker/package.json b/plugins/docker/package.json index b03e8e3..1ce39d2 100644 --- a/plugins/docker/package.json +++ b/plugins/docker/package.json @@ -68,7 +68,7 @@ {"name": "volume", "label": "Volume", "default": "", "help": "The volume for /srv/agent, the agent's work. Empty uses berth-HOST-data."}, {"name": "cpus", "label": "CPUs", "default": "", "kind": "resource", "help": "How many CPUs the container may use, such as 4. Empty sets no limit."}, {"name": "memory", "label": "Memory", "default": "", "kind": "resource", "help": "How much memory the container may use, such as 8g. Empty sets no limit."}, - {"name": "keep_volume", "label": "Keep volume on destroy", "default": "no", "values": ["no", "yes"], "help": "Whether deleting the machine keeps its volume, so a new machine can take the agent's work over."} + {"name": "keep_volume", "label": "Keep volume on destroy", "default": "no", "kind": "boolean", "values": ["no", "yes"], "help": "Whether deleting the machine keeps its volume, so a new machine can take the agent's work over."} ] }, { @@ -77,7 +77,7 @@ "verbs": ["start", "stop", "change", "logs"], "spec": {"format": "compose", "label": "Compose file"}, "arguments": [ - {"name": "keep_volumes", "label": "Keep volumes on remove", "default": "no", "values": ["no", "yes"], "help": "Whether removing the deployment keeps the named volumes of its project. no removes them with what is in them."} + {"name": "keep_volumes", "label": "Keep volumes on remove", "default": "no", "kind": "boolean", "values": ["no", "yes"], "help": "Whether removing the deployment keeps the named volumes of its project. no removes them with what is in them."} ], "actions": [ {"name": "services", "label": "Services", "group": "Compose", "changes": false, "help": "Each container of the project, with its service and its state."}, @@ -175,7 +175,7 @@ {"name": "build", "label": "Build the image", "group": "Engine", "help": "Build the image the plugin brings, which a new machine starts from unless it names another. Creating the first machine builds it too; this does it ahead of time."}, {"name": "prune", "label": "Remove what berth left behind", "group": "Storage", "confirm": "Remove the images of older versions of this plugin that no container uses, and with volumes=yes the volumes berth made that no container uses?", "help": "Remove the images of older versions of this plugin that no container uses. With volumes=yes also the volumes berth made that no container uses, such as those kept with keep_volume, and the agent's work in them. Nothing berth did not make is touched, and no container is.", "arguments": [ - {"name": "volumes", "label": "Also volumes", "default": "no", "values": ["no", "yes"], "help": "yes also removes the volumes berth made that no container uses, with what is in them."} + {"name": "volumes", "label": "Also volumes", "default": "no", "kind": "boolean", "values": ["no", "yes"], "help": "yes also removes the volumes berth made that no container uses, with what is in them."} ]} ] } diff --git a/plugins/incus/package.json b/plugins/incus/package.json index 7a8c364..c399811 100644 --- a/plugins/incus/package.json +++ b/plugins/incus/package.json @@ -227,7 +227,7 @@ "arguments": [ {"name": "instance", "label": "Instance", "default": "", "help": "The instance's name as the server lists it, such as berth-studio for the host studio."}, {"name": "size", "label": "Size", "default": "", "help": "The new size of its root disk, larger than it is now, such as 80GiB."}, - {"name": "restart", "label": "Restart", "default": "no", "values": ["no", "yes"], "help": "Whether to restart a running virtual machine so that its guest sees the new size. A container needs no restart."} + {"name": "restart", "label": "Restart", "default": "no", "kind": "boolean", "values": ["no", "yes"], "help": "Whether to restart a running virtual machine so that its guest sees the new size. A container needs no restart."} ]} ] }, @@ -271,7 +271,7 @@ {"name": "disk", "label": "Disk size", "default": "20GiB", "kind": "resource", "help": "The size of its root disk, such as 20GiB."}, {"name": "pool", "label": "Storage pool", "default": "default", "help": "The storage pool of the Incus server its disk is in."}, {"name": "network", "label": "Network", "default": "", "help": "The network it is attached to. Empty takes the network of the default profile."}, - {"name": "nesting", "label": "Nesting", "default": "yes", "values": ["yes", "no"], "help": "Whether containers can run in it, such as Docker's. yes also lets the guest's systemd come up in an unprivileged container."} + {"name": "nesting", "label": "Nesting", "default": "yes", "kind": "boolean", "values": ["yes", "no"], "help": "Whether containers can run in it, such as Docker's. yes also lets the guest's systemd come up in an unprivileged container."} ] } ], @@ -411,7 +411,7 @@ "arguments": [ {"name": "instance", "label": "Instance", "default": "", "help": "The instance's name as the server lists it, such as berth-studio for the host studio."}, {"name": "size", "label": "Size", "default": "", "help": "The new size of its root disk, larger than it is now, such as 80GiB."}, - {"name": "restart", "label": "Restart", "default": "no", "values": ["no", "yes"], "help": "Whether to restart a running virtual machine so that its guest sees the new size. A container needs no restart."} + {"name": "restart", "label": "Restart", "default": "no", "kind": "boolean", "values": ["no", "yes"], "help": "Whether to restart a running virtual machine so that its guest sees the new size. A container needs no restart."} ]} ] }