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
137 changes: 133 additions & 4 deletions crates/berth-api/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 {
Expand All @@ -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<String, String> {
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.
Expand All @@ -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<bool> {
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)]
Expand Down Expand Up @@ -1855,9 +1934,8 @@ impl Rollout {
/// What the arguments of the `rollout` action ask for.
pub fn from_arguments(arguments: &BTreeMap<String, String>) -> Result<Rollout, String> {
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| {
Expand Down Expand Up @@ -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![
Expand Down
8 changes: 5 additions & 3 deletions crates/berth-core/src/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,11 @@ fn provisioner_arguments(entries: &Value) -> Vec<berth_api::Argument> {
.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
})
Expand Down
23 changes: 22 additions & 1 deletion crates/berth-core/src/provision.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
Expand Down Expand Up @@ -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]
Expand Down
23 changes: 21 additions & 2 deletions crates/berth-page/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -990,14 +991,29 @@ 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;
};
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);
}
}
Expand Down Expand Up @@ -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 ─────────────────────────────────────────────────────
Expand Down
6 changes: 5 additions & 1 deletion crates/berth-tui/src/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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,
Expand All @@ -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);
Expand Down
Loading
Loading