#[cfg(unix)]
pub mod access;
pub mod autostart;
pub mod dispatch;
pub mod done;
#[cfg(unix)]
pub mod fetch;
#[cfg(unix)]
pub mod fleet_link;
pub mod exec;
pub mod inbox;
pub mod inspect;
#[cfg(unix)]
pub mod login;
pub mod logs;
pub mod ls;
#[cfg(unix)]
pub mod machine;
pub mod port;
pub mod profile;
pub mod ps;
pub mod rebuild;
pub mod rename;
pub mod rm;
pub mod run;
pub mod services;
pub mod start;
pub mod stop;
pub mod subnet;
pub mod trust_origin;
#[cfg(unix)]
pub mod tunnel;
pub mod update;
pub mod vscode;
use std::io::IsTerminal;
use anyhow::{bail, Result};
use crate::ask::{self, Answer, Choice};
use crate::runtime::{backend, NAME_PREFIX};
use crate::state::{Instance, PhaseView, Progress, State};
pub(crate) const SCHEMA: u32 = 1;
#[derive(serde::Serialize)]
pub(crate) struct Envelope<T: serde::Serialize> {
schema: u32,
data: T,
}
impl<T: serde::Serialize> Envelope<T> {
pub(crate) fn new(data: T) -> Self {
Envelope { schema: SCHEMA, data }
}
}
pub(crate) fn not_ready(key: &str, view: Option<&PhaseView>) -> Option<String> {
match view? {
PhaseView::InFlight(label) => Some(format!("`{key}` is still {}", doing(label))),
PhaseView::Failed { at, error } => Some(format!(
"`{key}` failed at {at}: {error}; `devsandbox rebuild {key}` retries, \
`devsandbox rm {key}` removes it"
)),
}
}
pub(crate) fn no_container_yet(key: &str, view: Option<&PhaseView>) -> Option<String> {
let pre = |label: &str| matches!(label, "preparing" | "building" | "creating");
match view? {
PhaseView::InFlight(label) if pre(label) => Some(format!("`{key}` is still {label}: no container yet")),
PhaseView::Failed { at, .. } if pre(at) => not_ready(key, view),
_ => None,
}
}
pub(crate) fn in_flight(key: &str, progress: Option<&Progress>, view: Option<&PhaseView>) -> Option<String> {
match (progress, view) {
(Some(p), Some(PhaseView::InFlight(label))) => Some(format!(
"`{key}` is still {} (pid {}): wait for it, or Ctrl-C it",
doing(label),
p.pid
)),
_ => None,
}
}
pub(crate) fn doing(label: &str) -> String {
match label {
"preparing" | "building" | "creating" => label.to_string(),
step => format!("running {step}"),
}
}
pub(crate) fn resolve_instance(state: &State, name: &str) -> Result<String> {
resolve_instance_with(state, name, std::io::stdin().is_terminal())
}
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 mut matches = instance_matches(state, name);
match matches.len() {
0 => bail!("{}", no_instance_matches(name)),
1 => Ok(matches.remove(0)),
_ => {
if !interactive {
bail!("{}", ambiguous_instance(name, &matches));
}
let refs: Vec<&str> = matches.iter().map(String::as_str).collect();
Ok(matches.remove(pick(&ambiguous_prompt(name), &refs)?))
}
}
}
pub(crate) fn no_instance_matches(name: &str) -> String {
format!("no sandbox instance matches `{name}` (see `devsandbox ps -a`)")
}
pub(crate) fn ambiguous_instance(name: &str, matches: &[String]) -> String {
format!("`{name}` is ambiguous: {}", matches.join(", "))
}
pub(crate) fn ambiguous_prompt(name: &str) -> String {
format!("`{name}` matches multiple instances")
}
pub(crate) fn instance_matches(state: &State, name: &str) -> Vec<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 matches = keys(&|instance, info| instance == name || info.instance_id == name);
if !matches.is_empty() {
return matches;
}
keys(&|_, info| info.sandbox == name || info.folder.file_name().is_some_and(|f| f == name))
}
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);
}
Ok(choose(prompt, &[("Yes", 'y'), ("No", 'n')], 1)? == Some(0))
}
pub(crate) fn pick(prompt: &str, options: &[&str]) -> Result<usize> {
let choices: Vec<Choice> = options.iter().map(|o| Choice::new(*o)).collect();
match ask::select(prompt, &choices, 0)? {
Answer::Picked(i) => Ok(i),
Answer::Cancelled => bail!("cancelled"),
}
}
pub(crate) fn choose(question: &str, choices: &[(&str, char)], default: usize) -> Result<Option<usize>> {
let choices: Vec<Choice> = choices.iter().map(|(label, key)| Choice::new(*label).hotkey(*key)).collect();
Ok(match ask::select(question, &choices, default)? {
Answer::Picked(i) => Some(i),
Answer::Cancelled => None,
})
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::state::{Instance, State};
use super::{drift_decision, in_flight, no_container_yet, not_ready, instance_matches, resolve_instance, resolve_instance_with};
use crate::state::{Phase, PhaseView, Progress};
#[test]
fn not_ready_says_what_the_instance_is_doing_or_how_it_failed() {
assert_eq!(not_ready("web", None), None);
let building = PhaseView::InFlight("building".into());
assert_eq!(not_ready("web", Some(&building)).unwrap(), "`web` is still building");
let step = PhaseView::InFlight("postCreateCommand".into());
assert_eq!(not_ready("web", Some(&step)).unwrap(), "`web` is still running postCreateCommand");
let failed = PhaseView::Failed { at: "creating".into(), error: "interrupted".into() };
let why = not_ready("web", Some(&failed)).unwrap();
assert!(why.starts_with("`web` failed at creating: interrupted;"), "{why}");
assert!(why.contains("`devsandbox rebuild web` retries"), "{why}");
assert!(why.contains("`devsandbox rm web` removes it"), "{why}");
}
#[test]
fn exec_waits_only_for_the_container() {
assert_eq!(no_container_yet("web", None), None);
let building = PhaseView::InFlight("building".into());
assert_eq!(no_container_yet("web", Some(&building)).unwrap(), "`web` is still building: no container yet");
let pre = PhaseView::Failed { at: "creating".into(), error: "boom".into() };
assert!(no_container_yet("web", Some(&pre)).unwrap().starts_with("`web` failed at creating"));
let step = PhaseView::InFlight("postCreateCommand".into());
assert_eq!(no_container_yet("web", Some(&step)), None);
let failed = PhaseView::Failed { at: "postCreateCommand".into(), error: "exit 1".into() };
assert_eq!(no_container_yet("web", Some(&failed)), None);
}
#[test]
fn only_a_live_in_flight_instance_is_untouchable() {
let p = Progress { phase: Phase::Building, pid: 4242, boot: None, error: None };
let live = PhaseView::InFlight("building".into());
assert_eq!(
in_flight("web", Some(&p), Some(&live)).unwrap(),
"`web` is still building (pid 4242): wait for it, or Ctrl-C it"
);
let dead = PhaseView::Failed { at: "building".into(), error: "interrupted".into() };
assert_eq!(in_flight("web", Some(&p), Some(&dead)), None);
assert_eq!(in_flight("web", None, None), None);
}
#[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,
folders: Vec::new(),
shell_history: None,
workspace: "/w".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
home: None,
browser_sandbox: None,
tool_env: Default::default(),
ssh_auth_sock: None,
devsbd_arch: None,
devsbd_error: None,
volumes: Vec::new(),
bind_dirs: Vec::new(),
dispatcher: None,
profile: None,
config_dir: None,
extra_env: Default::default(),
forwarded_ports: Default::default(),
done: None,
incarnation: None,
intercept: None,
claims: Vec::new(),
progress: None,
github_repos: Vec::new(),
build_notes: Vec::new(),
git_env: 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,
folders: Vec::new(),
shell_history: None,
workspace: "/w".into(),
workspace_file: None,
remote_env: BTreeMap::new(),
remote_user: None,
home: None,
browser_sandbox: None,
tool_env: Default::default(),
ssh_auth_sock: None,
devsbd_arch: None,
devsbd_error: None,
volumes: Vec::new(),
bind_dirs: Vec::new(),
dispatcher: None,
profile: None,
config_dir: None,
extra_env: Default::default(),
forwarded_ports: Default::default(),
done: None,
incarnation: None,
intercept: None,
claims: Vec::new(),
progress: None,
github_repos: Vec::new(),
build_notes: Vec::new(),
git_env: 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}");
}
#[test]
fn instance_matches_lists_the_winning_tier_sorted() {
let s = state();
assert_eq!(instance_matches(&s, "web"), ["web-aaaa", "web-bbbb"]);
assert_eq!(instance_matches(&s, "web-bbbb"), ["web-bbbb"]);
assert!(instance_matches(&s, "nope").is_empty());
}
}