use std::path::{Path, PathBuf};
use anyhow::{Result, bail};
use serde::Deserialize;
use serde_json::{Value, json};
use super::{Call, CliVerb, Fed, Reply, Ui, reply, routed};
use crate::serve::api;
use crate::serve::machines::cli::found_of;
use crate::serve::machines::{Where, parse_name};
use crate::serve::proto::Response;
pub(super) const QUESTION: &str = "[u]pdate / [c]ontinue as is (don't ask again) / [s]kip this time: ";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Ask {
pub root: PathBuf,
pub machine: Option<String>,
pub scope: Scope,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Scope {
Sandboxes(Vec<String>),
Used,
All,
Ids(Vec<String>),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Findings {
file: PathBuf,
format: String,
file_hash: String,
findings: Vec<Finding>,
}
#[derive(Debug, Clone, PartialEq, Deserialize)]
struct Finding {
id: String,
table: String,
kind: String,
key: String,
value: String,
edit: Option<String>,
sandboxes: Vec<String>,
acked: bool,
}
impl Finding {
fn line(&self) -> String {
match &self.edit {
Some(edit) => edit.clone(),
None => format!("{}: {} = \"{}\" is under /root (fix by hand)", self.table, self.key, self.value),
}
}
fn counts(&self, scope: &Scope) -> bool {
!self.acked
&& match scope {
Scope::Sandboxes(names) => self.sandboxes.iter().any(|s| names.contains(s)),
Scope::Used => !self.sandboxes.is_empty(),
Scope::All => true,
Scope::Ids(ids) => ids.contains(&self.id),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Group {
root: PathBuf,
machine: Option<String>,
file: PathBuf,
yaml: bool,
file_hash: String,
findings: Vec<Finding>,
}
impl Group {
fn label(&self) -> String {
match &self.machine {
Some(m) => format!("{m}:{}", self.file.display()),
None => self.file.display().to_string(),
}
}
#[cfg(test)]
pub(crate) fn sample(root: &str, findings: &[(&str, &str)]) -> Group {
let findings = findings
.iter()
.map(|(id, edit)| Finding {
id: id.to_string(),
table: "sandbox.web".into(),
kind: "root-target".into(),
key: "mounts".into(),
value: "/root/x".into(),
edit: Some(edit.to_string()),
sandboxes: vec!["web".into()],
acked: false,
})
.collect();
let root = PathBuf::from(root);
Group { file: root.join("devsandboxes.toml"), root, machine: None, yaml: false, file_hash: "h".into(), findings }
}
fn params(&self, params: Value) -> Value {
let mut params = params;
params["root"] = json!(self.root);
routed(params, self.machine.as_deref())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Choice {
Update,
Keep,
Skip,
}
fn choice(answer: &str) -> Option<Choice> {
match answer.trim().to_ascii_lowercase().as_str() {
"u" | "update" => Some(Choice::Update),
"c" | "continue" => Some(Choice::Keep),
"s" | "skip" | "" => Some(Choice::Skip),
_ => None,
}
}
pub(super) fn prompt(asks: Vec<Ask>, call: &mut Call, ui: &mut Ui) -> Result<()> {
if !ui.tty {
return Ok(());
}
let groups = gather(asks, call);
if groups.is_empty() {
return Ok(());
}
(ui.say)(&listing(&groups).join("\n"));
let choice = loop {
if let Some(c) = choice(&(ui.ask)(QUESTION)?) {
break c;
}
};
answer(&groups, choice, call, &mut *ui.say)
}
pub(crate) fn answer(groups: &[Group], choice: Choice, call: &mut Call, say: &mut dyn FnMut(&str)) -> Result<()> {
for group in groups {
match choice {
Choice::Skip => {}
Choice::Update => update(group, call, say)?,
Choice::Keep => keep(group, call, say)?,
}
}
Ok(())
}
pub(crate) fn gather(asks: Vec<Ask>, call: &mut Call) -> Vec<Group> {
let mut groups = Vec::new();
for ask in asks {
let params = routed(json!({ "root": ask.root }), ask.machine.as_deref());
let Ok(Reply::Ok(v)) = call("config.findings", params).map(reply) else { continue };
let Ok(found) = serde_json::from_value::<Findings>(v) else { continue };
let findings: Vec<Finding> = found.findings.into_iter().filter(|f| f.counts(&ask.scope)).collect();
if findings.is_empty() {
continue;
}
groups.push(Group {
root: ask.root,
machine: ask.machine,
file: found.file,
yaml: found.format == "yaml",
file_hash: found.file_hash,
findings,
});
}
groups
}
pub(crate) fn listing(groups: &[Group]) -> Vec<String> {
let mut out = Vec::new();
for g in groups {
out.push(format!("{} assumes root in the container, which breaks under identity = \"host\":", g.label()));
for f in &g.findings {
out.push(format!(" {}", f.line()));
}
}
out
}
fn update(g: &Group, call: &mut Call, say: &mut dyn FnMut(&str)) -> Result<()> {
let ids: Vec<&str> = g.findings.iter().filter(|f| f.edit.is_some()).map(|f| f.id.as_str()).collect();
if ids.is_empty() {
say(&format!("{}: nothing to update automatically; fix the entries above by hand", g.label()));
return Ok(());
}
migrate(g, json!({ "ids": ids, "fileHash": g.file_hash }), call, say)
}
fn keep(g: &Group, call: &mut Call, say: &mut dyn FnMut(&str)) -> Result<()> {
let (users, others): (Vec<&Finding>, Vec<&Finding>) =
g.findings.iter().partition(|f| f.kind == "root-user" && !g.yaml);
if !others.is_empty() {
let ids: Vec<&str> = others.iter().map(|f| f.id.as_str()).collect();
match call("config.ack", g.params(json!({ "ids": ids }))).map(reply) {
Ok(Reply::Ok(_)) => {
let n = ids.len();
let entries = if n == 1 { "1 entry".to_string() } else { format!("{n} entries") };
say(&format!("{}: {entries} kept as is, not asked about again", g.label()));
}
Ok(Reply::Err(e)) => say(&format!("warning: could not record that for {}: {}", g.label(), e.message)),
Ok(Reply::Old(why)) => say(&format!("warning: could not record that for {}: {why}", g.label())),
Err(e) => say(&format!("warning: could not record that for {}: {e:#}", g.label())),
}
}
if !users.is_empty() {
let keep: Vec<&str> = users.iter().map(|f| f.id.as_str()).collect();
migrate(g, json!({ "ids": [], "keep": keep, "fileHash": g.file_hash }), call, say)?;
}
Ok(())
}
fn migrate(g: &Group, params: Value, call: &mut Call, say: &mut dyn FnMut(&str)) -> Result<()> {
let warn = |why: &str| format!("warning: could not update {}: {why}", g.label());
match call("config.migrate", g.params(params)).map(reply) {
Ok(Reply::Ok(v)) => {
let edits = v["edits"].as_u64().unwrap_or(0);
let drifted: Vec<String> =
v["drifted"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect();
say(&updated(&g.file, edits, &drifted, g.machine.as_deref()));
}
Ok(Reply::Err(e)) if e.code == "conflict" => {
bail!("{} changed while you were asked; nothing written, run the command again", g.label())
}
Ok(Reply::Err(e)) if e.code == "unsupported" => say(&format!("{}: {}", g.label(), e.message)),
Ok(Reply::Err(e)) => say(&warn(&e.message)),
Ok(Reply::Old(why)) => say(&warn(&why)),
Err(e) => say(&warn(&format!("{e:#}"))),
}
Ok(())
}
fn updated(file: &Path, edits: u64, drifted: &[String], machine: Option<&str>) -> String {
let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| file.display().to_string());
let edits = if edits == 1 { "1 edit".to_string() } else { format!("{edits} edits") };
let mut line = format!("updated {name} ({edits})");
if !drifted.is_empty() {
let names: Vec<String> = drifted
.iter()
.map(|n| match machine {
Some(m) => format!("{m}/{n}"),
None => n.clone(),
})
.collect();
line.push_str(&format!("; now drifted: {} → devsandbox rebuild <name>", names.join(", ")));
}
line
}
pub(super) fn local_call(method: &str, params: Value) -> Result<Response> {
if !matches!(method, "config.findings" | "config.migrate" | "config.ack" | "instances.resolve") {
bail!("`{method}` needs devsandbox serve");
}
let ctx = api::Ctx { inbox: Path::new(""), client: "cli", bridges: None, forwards: None, host: None };
Ok(match api::call(method, params, &ctx) {
Ok(v) => Response::ok(None, v),
Err(e) => Response::err(None, e.code, e.message),
})
}
pub(super) fn local_asks(verb: &CliVerb, root: &Path, fed: &Fed, call: &mut Call) -> Result<Vec<Ask>> {
let here = |scope| vec![Ask { root: root.to_path_buf(), machine: None, scope }];
let bare = |name: &str| -> Result<String> { Ok(if fed.machines { parse_name(name)?.1 } else { name.to_string() }) };
Ok(match verb {
CliVerb::Run { sandbox: Some(s), json: false, .. } => here(Scope::Sandboxes(vec![bare(s)?])),
CliVerb::Rebuild { target: Some(name), .. } | CliVerb::Start { target: Some(name), .. } => {
let Ok(Reply::Ok(v)) = call("instances.resolve", json!({ "name": bare(name)? })).map(reply) else {
return Ok(Vec::new());
};
let mut sandboxes: Vec<String> = found_of(v, &Where::Local)?.into_iter().filter_map(|f| f.sandbox).collect();
sandboxes.sort();
sandboxes.dedup();
match sandboxes.is_empty() {
true => Vec::new(),
false => here(Scope::Sandboxes(sandboxes)),
}
}
CliVerb::Rebuild { target: None, .. } | CliVerb::Start { target: None, .. } => here(Scope::Used),
_ => Vec::new(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn answers_read_case_blind_and_empty_skips() {
assert_eq!(choice("u\n"), Some(Choice::Update));
assert_eq!(choice(" Update "), Some(Choice::Update));
assert_eq!(choice("C"), Some(Choice::Keep));
assert_eq!(choice("s"), Some(Choice::Skip));
assert_eq!(choice(""), Some(Choice::Skip), "Enter, or stdin's end");
assert_eq!(choice("y"), None);
}
#[test]
fn the_report_names_the_file_and_what_drifted() {
let file = Path::new("/cfg/devsandboxes.toml");
assert_eq!(updated(file, 1, &[], None), "updated devsandboxes.toml (1 edit)");
let drifted = ["web".to_string(), "web-2".to_string()];
assert_eq!(
updated(file, 5, &drifted, None),
"updated devsandboxes.toml (5 edits); now drifted: web, web-2 → devsandbox rebuild <name>"
);
assert_eq!(updated(file, 2, &drifted[..1], Some("a")), "updated devsandboxes.toml (2 edits); now drifted: a/web → devsandbox rebuild <name>");
}
}