pub mod autostart;
pub mod dispatch;
pub mod exec;
pub mod inspect;
pub mod logs;
pub mod ls;
pub mod port;
pub mod ps;
pub mod rebuild;
pub mod rename;
pub mod rm;
pub mod run;
pub mod services;
pub mod start;
pub mod stats;
pub mod status;
pub mod stop;
pub mod vscode;
use std::io::{IsTerminal, Write};
use anyhow::{bail, Context, Result};
use crate::runtime::{backend, NAME_PREFIX};
use crate::state::{Instance, State};
pub(crate) fn resolve_instance(state: &State, name: &str) -> Result<String> {
resolve_instance_with(state, name, std::io::stdin().is_terminal())
}
#[cfg_attr(not(unix), allow(dead_code))]
pub(crate) fn resolve_instance_noninteractive(state: &State, name: &str) -> Result<String> {
resolve_instance_with(state, name, false)
}
fn resolve_instance_with(state: &State, name: &str, interactive: bool) -> Result<String> {
let keys = |pred: &dyn Fn(&str, &Instance) -> bool| -> Vec<String> {
let mut keys: Vec<String> = state
.instances
.iter()
.filter(|(instance, info)| pred(instance, info))
.map(|(instance, _)| instance.clone())
.collect();
keys.sort();
keys
};
let mut matches = keys(&|instance, info| instance == name || info.instance_id == name);
if matches.is_empty() {
matches = keys(&|_, info| {
info.sandbox == name || info.folder.file_name().is_some_and(|f| f == name)
});
}
match matches.len() {
0 => bail!("no sandbox instance matches `{name}` (see `devsandbox ps -a`)"),
1 => Ok(matches.remove(0)),
_ => {
if !interactive {
bail!("`{name}` is ambiguous: {}", matches.join(", "));
}
let refs: Vec<&str> = matches.iter().map(String::as_str).collect();
Ok(matches.remove(pick(&format!("`{name}` matches multiple instances"), &refs)?))
}
}
}
pub(crate) fn resolve_container(state: &State, name: &str) -> Result<String> {
let instance_err = match resolve_instance(state, name) {
Ok(key) => {
let info = state.instances.get(&key).expect("key came from state");
return Ok(info.container.clone());
}
Err(e) => e,
};
let prefixed = format!("{NAME_PREFIX}{name}");
backend()
.list(true, NAME_PREFIX)
.unwrap_or_default()
.into_iter()
.map(|row| row.name)
.find(|n| n == name || n == &prefixed)
.ok_or(instance_err)
}
pub(crate) fn container_drifted(
container: &str,
expected_config: &str,
expected_build: &str,
) -> Result<bool> {
let rt = backend();
let config_label = rt.label(container, "devsandbox.config_hash")?;
let build_label = rt.label(container, "devsandbox.build_hash")?;
Ok(drift_decision(
config_label.as_deref(),
expected_config,
build_label.as_deref(),
expected_build,
))
}
pub(crate) fn drift_decision(
config_label: Option<&str>,
expected_config: &str,
build_label: Option<&str>,
expected_build: &str,
) -> bool {
let config_drift = config_label.is_some_and(|h| h != expected_config);
let build_drift =
!expected_build.is_empty() && build_label.is_some_and(|h| h != expected_build);
config_drift || build_drift
}
pub(crate) fn confirm(prompt: &str) -> Result<bool> {
if !std::io::stdin().is_terminal() {
return Ok(false);
}
eprint!("{prompt} [y/N] ");
std::io::stderr().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
Ok(matches!(answer.trim(), "y" | "Y" | "yes"))
}
pub(crate) fn pick(prompt: &str, options: &[&str]) -> Result<usize> {
eprintln!("{prompt}:");
for (i, option) in options.iter().enumerate() {
eprintln!(" {}) {option}", i + 1);
}
eprint!("> ");
std::io::stderr().flush()?;
let mut answer = String::new();
std::io::stdin().read_line(&mut answer)?;
let choice: usize = answer.trim().parse().context("invalid selection")?;
if choice == 0 || choice > options.len() {
bail!("selection out of range");
}
Ok(choice - 1)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::state::{Instance, State};
use super::{drift_decision, resolve_instance, resolve_instance_with};
#[test]
fn drift_rule_covers_label_presence_and_expected_emptiness() {
let cases: &[(Option<&str>, &str, Option<&str>, &str, bool)] = &[
(None, "cfg", None, "b", false),
(None, "cfg", None, "", false),
(Some("cfg"), "cfg", None, "b", false),
(Some("old"), "cfg", None, "", true),
(Some("cfg"), "cfg", Some("old"), "b", true),
(Some("cfg"), "cfg", Some("anything"), "", false),
(Some("cfg"), "cfg", Some("b"), "b", false),
(Some("cfg"), "cfg", None, "b", false),
];
for &(cfg_label, exp_cfg, build_label, exp_build, want) in cases {
assert_eq!(
drift_decision(cfg_label, exp_cfg, build_label, exp_build),
want,
"cfg_label={cfg_label:?} exp_cfg={exp_cfg} build_label={build_label:?} exp_build={exp_build}"
);
}
}
fn state() -> State {
let mut state = State::default();
let mk = |sandbox: &str, folder: &str| Instance {
sandbox: sandbox.to_string(),
instance_id: String::new(),
project: "proj".into(),
container: "devsandbox-x".into(),
folder: folder.into(),
base_folder: folder.into(),
worktree: None,
branch: None,
branch_created: true,
shell_history: None,
workspace: "/w".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
ssh_auth_sock: None,
devsbd_arch: None,
volumes: Vec::new(),
dispatcher: None,
config_dir: None,
extra_env: Default::default(),
forwarded_ports: Default::default(),
created_unix: 0,
};
state.instances.insert("web-aaaa".into(), mk("web", "/home/u/site"));
state.instances.insert("web-bbbb".into(), mk("web", "/home/u/other"));
state
}
#[test]
fn matches_exact_instance_name() {
let s = state();
assert_eq!(resolve_instance(&s, "web-aaaa").unwrap(), "web-aaaa");
}
#[test]
fn matches_unique_sandbox_name() {
let mut s = State::default();
s.instances.insert(
"api-cccc".into(),
Instance {
sandbox: "api".into(),
instance_id: "api-cccc".into(),
project: "proj".into(),
container: "devsandbox-x".into(),
folder: "/home/u/api".into(),
base_folder: "/home/u/api".into(),
worktree: None,
branch: None,
branch_created: true,
shell_history: None,
workspace: "/w".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
ssh_auth_sock: None,
devsbd_arch: None,
volumes: Vec::new(),
dispatcher: None,
config_dir: None,
extra_env: Default::default(),
forwarded_ports: Default::default(),
created_unix: 0,
},
);
assert_eq!(resolve_instance(&s, "api").unwrap(), "api-cccc");
}
#[test]
fn matches_folder_basename() {
let s = state();
assert_eq!(resolve_instance(&s, "site").unwrap(), "web-aaaa");
}
#[test]
fn matches_persistent_id_after_rename() {
let mut s = State::default();
let mut info = state().instances.remove("web-aaaa").unwrap();
info.instance_id = "web-aaaa".into();
s.instances.insert("new-name".into(), info);
assert_eq!(resolve_instance(&s, "web-aaaa").unwrap(), "new-name");
}
#[test]
fn no_match_errors() {
let s = state();
let err = resolve_instance(&s, "nope").unwrap_err().to_string();
assert!(err.contains("no sandbox instance matches `nope`"), "{err}");
}
#[test]
fn ambiguous_sandbox_name_errors_without_tty() {
let s = state();
let err = resolve_instance_with(&s, "web", false).unwrap_err().to_string();
assert!(err.contains("is ambiguous"), "{err}");
assert!(err.contains("web-aaaa"), "{err}");
assert!(err.contains("web-bbbb"), "{err}");
}
#[test]
fn exact_name_beats_sandbox_name() {
let mut s = state();
let a = s.instances.remove("web-aaaa").unwrap();
let b = s.instances.remove("web-bbbb").unwrap();
s.instances.insert("web".into(), Instance { instance_id: "web".into(), ..a });
s.instances.insert("web-2".into(), Instance { instance_id: "web-2".into(), ..b });
assert_eq!(resolve_instance_with(&s, "web", false).unwrap(), "web");
assert_eq!(resolve_instance_with(&s, "web", true).unwrap(), "web");
assert_eq!(resolve_instance_with(&s, "web-2", false).unwrap(), "web-2");
}
#[test]
fn exact_id_beats_folder_basename() {
let mut s = state();
let mut a = s.instances.remove("web-aaaa").unwrap();
a.instance_id = "other".into();
s.instances.insert("renamed".into(), a);
assert_eq!(resolve_instance_with(&s, "other", false).unwrap(), "renamed");
}
#[test]
fn exact_tier_tie_is_ambiguous() {
let mut s = state();
let mut a = s.instances.remove("web-aaaa").unwrap();
a.instance_id = "web-bbbb".into();
s.instances.insert("renamed".into(), a);
let err = resolve_instance_with(&s, "web-bbbb", false).unwrap_err().to_string();
assert!(err.contains("is ambiguous: renamed, web-bbbb"), "{err}");
}
}