use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{anyhow, bail, Context, Result};
use serde::Deserialize;
use toml::{Table, Value};
use crate::runtime::identity::Identity;
pub const CONFIG_FILE: &str = "devsandboxes.toml";
const CONFIG_FILES: [&str; 3] = [CONFIG_FILE, "devsandboxes.yaml", "devsandboxes.yml"];
const LEGACY_CONFIG_FILE: &str = "config.toml";
pub fn candidates(dir: &Path) -> impl Iterator<Item = PathBuf> + '_ {
CONFIG_FILES.iter().chain([&LEGACY_CONFIG_FILE]).map(move |f| dir.join(f))
}
pub fn find(dir: &Path) -> Result<Option<PathBuf>> {
let present: Vec<PathBuf> =
CONFIG_FILES.iter().map(|f| dir.join(f)).filter(|p| p.is_file()).collect();
match present.as_slice() {
[] => Ok(legacy(dir)),
[one] => Ok(Some(one.clone())),
many => bail!(
"several config files in {}: {}; keep only one",
dir.display(),
many.iter().filter_map(|p| p.file_name()?.to_str()).collect::<Vec<_>>().join(", ")
),
}
}
pub fn display_path(dir: &Path) -> PathBuf {
find(dir).ok().flatten().unwrap_or_else(|| dir.join(CONFIG_FILE))
}
fn legacy(dir: &Path) -> Option<PathBuf> {
let path = dir.join(LEGACY_CONFIG_FILE);
let table: Table = toml::from_str(&std::fs::read_to_string(&path).ok()?).ok()?;
["sandbox", "template", "services"]
.iter()
.any(|k| table.contains_key(*k))
.then_some(path)
}
pub fn migrate_legacy(dir: &Path) -> Result<Option<PathBuf>> {
let Some(old) = find(dir)? else { return Ok(None) };
if old.file_name().and_then(|n| n.to_str()) != Some(LEGACY_CONFIG_FILE) {
return Ok(None);
}
let new = dir.join(CONFIG_FILE);
std::fs::rename(&old, &new)
.with_context(|| format!("cannot rename {} to {}", old.display(), new.display()))?;
Ok(Some(new))
}
#[derive(Debug, Default, Deserialize)]
pub struct Config {
#[serde(default)]
pub services: BTreeMap<String, Table>,
#[serde(default, rename = "template")]
pub templates: BTreeMap<String, Table>,
#[serde(default, rename = "sandbox")]
pub sandboxes: BTreeMap<String, Table>,
}
#[cfg_attr(not(unix), allow(dead_code))] #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, Deserialize)]
pub struct SandboxText {
pub original: String,
pub resolved: String,
pub hash: String,
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn table_text(table: &Table) -> String {
match toml::to_string_pretty(table) {
Ok(s) => s,
Err(e) => format!("cannot serialize config: {e}"),
}
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SandboxProperties {
pub folder: Option<String>,
pub services: Option<Vec<String>>,
pub caches: Option<Vec<String>>,
#[serde(rename = "persist-shell-history")]
pub persist_shell_history: Option<bool>,
#[serde(rename = "worktree-branch")]
pub worktree_branch: Option<String>,
#[serde(rename = "worktree-base")]
pub worktree_base: Option<String>,
#[serde(rename = "worktree-include")]
pub worktree_include: Option<Vec<String>>,
#[serde(rename = "worktree-link")]
pub worktree_link: Option<Vec<String>>,
#[serde(rename = "shell-rc")]
pub shell_rc: Option<Vec<String>>,
pub folders: Option<BTreeMap<String, FolderEntry>>,
pub autostart: Option<Autostart>,
pub dispatcher: Option<Dispatcher>,
pub inbox: Option<bool>,
pub placement: Option<Placement>,
pub image: Option<String>,
pub build: Option<Build>,
pub workspace_folder: Option<String>,
pub container_env: Option<BTreeMap<String, String>>,
pub remote_env: Option<BTreeMap<String, String>>,
pub initialize_command: Option<LifecycleCommand>,
pub on_create_command: Option<LifecycleCommand>,
pub update_content_command: Option<LifecycleCommand>,
pub post_create_command: Option<LifecycleCommand>,
pub post_start_command: Option<LifecycleCommand>,
pub post_attach_command: Option<LifecycleCommand>,
pub customizations: Option<Customizations>,
pub features: Option<BTreeMap<String, FeatureOptions>>,
pub privileged: Option<bool>,
pub forward_ports: Option<Vec<ForwardPort>>,
pub mounts: Option<Vec<Mount>>,
pub container_user: Option<String>,
pub remote_user: Option<String>,
pub identity: Option<Identity>,
#[serde(rename = "updateRemoteUserUID")]
pub update_remote_user_uid: Option<bool>,
pub userns: Option<bool>,
pub init: Option<bool>,
pub name: Option<Value>,
pub app_port: Option<Value>,
pub ports_attributes: Option<Value>,
pub other_ports_attributes: Option<Value>,
pub run_args: Option<Value>,
pub workspace_mount: Option<Value>,
pub override_feature_install_order: Option<Value>,
pub user_env_probe: Option<Value>,
pub override_command: Option<Value>,
pub shutdown_action: Option<Value>,
pub cap_add: Option<Value>,
pub security_opt: Option<Value>,
pub host_requirements: Option<Value>,
pub wait_for: Option<Value>,
pub secrets: Option<Value>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Autostart {
#[default]
Off,
Devsandbox,
Runtime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Placement {
Home,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Dispatcher {
#[serde(default)]
pub spawn: Vec<String>,
#[serde(rename = "max-instances")]
pub max_instances: Option<u32>,
}
impl Dispatcher {
pub const ANY: &'static str = "*";
pub const DEFAULT_MAX_INSTANCES: u32 = 10;
pub fn cap(&self) -> u32 {
self.max_instances.unwrap_or(Self::DEFAULT_MAX_INSTANCES)
}
pub fn may_spawn(&self, sandbox: &str) -> bool {
self.spawn.iter().any(|s| s == Self::ANY || s == sandbox)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(
untagged,
expecting = "a host dir string or { path = \"…\", worktree = \"auto\" | \"always\" | \"never\" }"
)]
pub enum FolderEntry {
Path(String),
Table(FolderTable),
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FolderTable {
pub path: String,
#[serde(default)]
pub worktree: Option<FolderWorktree>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum FolderWorktree {
#[default]
Auto,
Always,
Never,
}
impl FolderEntry {
pub fn path(&self) -> &str {
match self {
Self::Path(path) => path,
Self::Table(table) => &table.path,
}
}
pub fn worktree_mode(&self) -> FolderWorktree {
match self {
Self::Path(_) => FolderWorktree::Auto,
Self::Table(table) => table.worktree.unwrap_or_default(),
}
}
}
impl<'de> Deserialize<'de> for Autostart {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> std::result::Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = Autostart;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("`true`, `false` or `\"runtime\"`")
}
fn visit_bool<E: serde::de::Error>(self, v: bool) -> std::result::Result<Autostart, E> {
Ok(if v { Autostart::Devsandbox } else { Autostart::Off })
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<Autostart, E> {
match v {
"runtime" => Ok(Autostart::Runtime),
_ => Err(E::invalid_value(serde::de::Unexpected::Str(v), &self)),
}
}
}
de.deserialize_any(V)
}
}
impl SandboxProperties {
pub fn identity(&self) -> Identity {
match (self.identity, self.update_remote_user_uid) {
(Some(identity), _) => identity,
(None, Some(false)) => Identity::Image,
(None, _) => Identity::Host,
}
}
pub fn userns(&self) -> bool {
self.userns != Some(false)
}
pub fn ignored(&self) -> Vec<String> {
let mut out = Vec::new();
macro_rules! flag {
($($field:ident => $name:literal),* $(,)?) => {
$(if self.$field.is_some() { out.push($name.to_string()); })*
};
}
flag!(
name => "name",
app_port => "appPort",
ports_attributes => "portsAttributes",
other_ports_attributes => "otherPortsAttributes",
run_args => "runArgs",
workspace_mount => "workspaceMount",
override_feature_install_order => "overrideFeatureInstallOrder",
user_env_probe => "userEnvProbe",
override_command => "overrideCommand",
shutdown_action => "shutdownAction",
cap_add => "capAdd",
security_opt => "securityOpt",
host_requirements => "hostRequirements",
wait_for => "waitFor",
secrets => "secrets",
);
if let Some(customizations) = &self.customizations {
if let Some(vscode) = &customizations.vscode {
if vscode.settings.is_some() {
out.push("customizations.vscode.settings".into());
}
for key in vscode.other.keys() {
out.push(format!("customizations.vscode.{key}"));
}
}
for tool in customizations.other.keys() {
out.push(format!("customizations.{tool}"));
}
}
out
}
pub fn vscode_extensions(&self) -> Option<&[String]> {
self.customizations
.as_ref()?
.vscode
.as_ref()?
.extensions
.as_deref()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ForwardPort {
pub host: Option<u16>,
pub service: Option<String>,
pub port: u16,
}
impl ForwardPort {
pub fn parse(entry: &str) -> std::result::Result<ForwardPort, String> {
let port = |s: &str| match s.parse::<u16>() {
Ok(0) | Err(_) => Err(format!("forwardPorts entry `{entry}`: `{s}` is not a port number")),
Ok(p) => Ok(p),
};
let service = |s: &str| {
if s.is_empty() || s.parse::<u16>().is_ok() {
Err(format!("forwardPorts entry `{entry}`: `{s}` is not a service name"))
} else {
Ok(s.to_string())
}
};
match entry.split(':').collect::<Vec<_>>()[..] {
[p] => Ok(ForwardPort { host: None, service: None, port: port(p)? }),
[a, p] if a.parse::<u16>().is_ok() => Ok(ForwardPort { host: Some(port(a)?), service: None, port: port(p)? }),
[s, p] => Ok(ForwardPort { host: None, service: Some(service(s)?), port: port(p)? }),
[h, s, p] => Ok(ForwardPort { host: Some(port(h)?), service: Some(service(s)?), port: port(p)? }),
_ => Err(format!("forwardPorts entry `{entry}`: expected `[host:][service:]port`")),
}
}
pub fn key(&self) -> String {
let mut key = String::new();
if let Some(host) = self.host {
key.push_str(&format!("{host}:"));
}
if let Some(service) = &self.service {
key.push_str(&format!("{service}:"));
}
key.push_str(&self.port.to_string());
key
}
pub fn base(&self) -> u16 {
self.host.unwrap_or(self.port)
}
}
impl<'de> Deserialize<'de> for ForwardPort {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> std::result::Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = ForwardPort;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a port number or a `[host:][service:]port` string")
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> std::result::Result<ForwardPort, E> {
ForwardPort::parse(&v.to_string()).map_err(E::custom)
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> std::result::Result<ForwardPort, E> {
ForwardPort::parse(&v.to_string()).map_err(E::custom)
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> std::result::Result<ForwardPort, E> {
ForwardPort::parse(v).map_err(E::custom)
}
}
de.deserialize_any(V)
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum FeatureOptions {
Options(BTreeMap<String, Value>),
Version(String),
Enabled(bool),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Mount {
Shorthand(String),
Object(MountObject),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct MountObject {
#[serde(rename = "type")]
pub kind: Option<String>,
pub source: Option<String>,
pub target: String,
pub readonly: Option<bool>,
}
#[derive(Clone, Copy)]
pub struct MountContext<'a> {
pub config_dir: &'a str,
pub workspace_folder: &'a str,
pub workspace_folder_basename: &'a str,
pub shared_volumes: &'a str,
pub instance: &'a str,
pub container_env: Option<&'a ContainerEnv>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContainerEnv {
pub sandbox: BTreeMap<String, String>,
pub image: Vec<(String, String)>,
pub home: String,
}
impl ContainerEnv {
fn get(&self, name: &str) -> Option<String> {
match self.sandbox.get(name) {
Some(v) => Some(v.clone()),
None => self.from_image(name),
}
}
fn from_image(&self, name: &str) -> Option<String> {
match self.image.iter().rev().find(|(k, _)| k == name) {
Some((_, v)) => Some(v.clone()),
None if name == "HOME" => Some(self.home.clone()),
None => None,
}
}
pub fn resolve(
sandbox_env: Option<&BTreeMap<String, String>>,
image: Vec<(String, String)>,
home: String,
ctx: &MountContext,
) -> ContainerEnv {
let mut env = ContainerEnv { sandbox: BTreeMap::new(), image, home };
let image_only = MountContext { container_env: Some(&env), ..*ctx };
let resolved = sandbox_env
.into_iter()
.flatten()
.map(|(key, value)| (key.clone(), substitute(value, &image_only)))
.collect();
env.sandbox = resolved;
env
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedMount {
pub kind: String,
pub source: Option<String>,
pub target: String,
pub readonly: bool,
pub per_instance: bool,
}
pub(crate) const INSTANCE_VARS: [&str; 2] = ["${instance}", "${devcontainerId}"];
impl Mount {
pub fn resolve(&self, ctx: &MountContext) -> Result<ResolvedMount> {
let (kind, source, target, readonly) = match self {
Mount::Shorthand(s) => parse_shorthand(s)?,
Mount::Object(o) => (
o.kind.clone(),
o.source.clone(),
o.target.clone(),
o.readonly.unwrap_or(false),
),
};
let kind = kind.unwrap_or_else(|| "bind".to_string());
let per_instance = kind == "volume"
&& source
.as_deref()
.is_some_and(|s| INSTANCE_VARS.iter().any(|v| s.contains(v)));
let source = source.map(|s| substitute(&s, ctx));
let target = substitute(&target, ctx);
if kind == "bind" && source.is_none() {
bail!("bind mount to `{target}` is missing a source");
}
Ok(ResolvedMount {
kind,
source,
target,
readonly,
per_instance,
})
}
}
impl ResolvedMount {
pub fn to_arg(&self) -> String {
let mut arg = format!("type={}", self.kind);
if let Some(source) = &self.source {
arg.push_str(&format!(",source={source}"));
}
arg.push_str(&format!(",target={}", self.target));
if self.readonly {
arg.push_str(",readonly");
}
arg
}
}
pub(crate) type MountParts = (Option<String>, Option<String>, String, bool);
pub(crate) fn parse_shorthand(spec: &str) -> Result<MountParts> {
let (mut kind, mut source, mut target, mut readonly) = (None, None, None, false);
for part in spec.split(',') {
let part = part.trim();
if part.is_empty() {
continue;
}
let (key, value) = match part.split_once('=') {
Some((k, v)) => (k.trim(), Some(v.trim().to_string())),
None => (part, None),
};
match key {
"type" => kind = value,
"source" | "src" => source = value,
"target" | "destination" | "dst" => target = value,
"readonly" | "ro" => readonly = value.as_deref() != Some("false"),
"consistency" | "bind-propagation" => {} other => bail!("unknown mount field `{other}` in `{spec}`"),
}
}
let target = target.with_context(|| format!("mount `{spec}` is missing a target"))?;
Ok((kind, source, target, readonly))
}
pub const SUPPORTED_CACHES: &[&str] = &["pnpm", "cargo", "npm", "yarn", "go", "pip"];
pub fn known_cache(name: &str) -> Option<(&'static str, &'static str, &'static [&'static str])> {
Some(match name {
"pnpm" => (
"pnpm-store",
"/var/cache/devsandbox/pnpm-store",
&["npm_config_store_dir", "pnpm_config_store_dir"],
),
"cargo" => ("cargo", "/var/cache/devsandbox/cargo", &["CARGO_HOME"]),
"npm" => ("npm", "/var/cache/devsandbox/npm", &["npm_config_cache"]),
"yarn" => ("yarn", "/var/cache/devsandbox/yarn", &["YARN_CACHE_FOLDER"]),
"go" => ("go-mod", "/var/cache/devsandbox/go-mod", &["GOMODCACHE"]),
"pip" => ("pip", "/var/cache/devsandbox/pip", &["PIP_CACHE_DIR"]),
_ => return None,
})
}
pub fn substitute(input: &str, ctx: &MountContext) -> String {
let mut out = String::new();
let mut rest = input;
while let Some(start) = rest.find("${") {
out.push_str(&rest[..start]);
let after = &rest[start + 2..];
match after.find('}') {
Some(end) => {
let expr = &after[..end];
match resolve_var(expr, ctx) {
Some(value) => out.push_str(&value),
None => out.push_str(&rest[start..start + 2 + end + 1]),
}
rest = &after[end + 1..];
}
None => {
out.push_str(&rest[start..]);
return out;
}
}
}
out.push_str(rest);
out
}
fn resolve_var(expr: &str, ctx: &MountContext) -> Option<String> {
resolve_var_with(
expr,
ctx,
|name| crate::worker_policy::local_env_allowed(Path::new(ctx.config_dir), name),
|name| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()),
)
}
fn resolve_var_with(
expr: &str,
ctx: &MountContext,
local_env_allowed: impl Fn(&str) -> bool,
local_env: impl Fn(&str) -> Option<String>,
) -> Option<String> {
if let Some(rest) = expr.strip_prefix("localEnv:") {
let (name, default) = env_name_and_default(rest);
if !local_env_allowed(name) {
return None;
}
return Some(local_env(name).unwrap_or_else(|| default.to_string()));
}
if let Some(rest) = expr.strip_prefix("containerEnv:") {
let (name, default) = env_name_and_default(rest);
return ctx.container_env.map(|env| env.get(name).unwrap_or_else(|| default.to_string()));
}
match expr {
"configDir" => Some(ctx.config_dir.to_string()),
"localWorkspaceFolder" => Some(ctx.workspace_folder.to_string()),
"localWorkspaceFolderBasename" => Some(ctx.workspace_folder_basename.to_string()),
"sharedVolumes" => Some(ctx.shared_volumes.to_string()),
"instance" | "devcontainerId" => Some(ctx.instance.to_string()),
_ => None,
}
}
fn env_name_and_default(body: &str) -> (&str, &str) {
body.split_once(':').unwrap_or((body, ""))
}
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Build {
pub dockerfile: Option<String>,
pub context: Option<String>,
pub args: Option<BTreeMap<String, String>>,
pub target: Option<String>,
pub cache_from: Option<StringOrList>,
pub options: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
pub struct Customizations {
pub vscode: Option<VscodeCustomizations>,
#[serde(flatten)]
pub other: Table,
}
#[derive(Debug, Deserialize)]
pub struct VscodeCustomizations {
pub extensions: Option<Vec<String>>,
pub settings: Option<Value>,
#[serde(flatten)]
pub other: Table,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum StringOrList {
One(String),
Many(Vec<String>),
}
impl StringOrList {
pub fn to_vec(&self) -> Vec<&str> {
match self {
Self::One(s) => vec![s],
Self::Many(v) => v.iter().map(String::as_str).collect(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum LifecycleCommand {
Simple(SimpleCommand),
Parallel(BTreeMap<String, SimpleCommand>),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum SimpleCommand {
Shell(String),
Args(Vec<String>),
}
impl SimpleCommand {
fn argv(&self) -> Vec<String> {
match self {
Self::Shell(s) => vec!["sh".into(), "-c".into(), s.clone()],
Self::Args(a) => a.clone(),
}
}
}
impl LifecycleCommand {
pub fn commands(&self) -> Vec<Vec<String>> {
match self {
Self::Simple(c) => vec![c.argv()],
Self::Parallel(map) => map.values().map(SimpleCommand::argv).collect(),
}
}
}
#[derive(Debug)]
pub struct ResolvedSandbox {
pub name: String,
pub properties: SandboxProperties,
pub config_hash: String,
}
impl ResolvedSandbox {
pub fn folder(&self) -> Option<&str> {
self.properties.folder.as_deref()
}
pub fn source(&self) -> String {
if let Some(image) = &self.properties.image {
return format!("image {image}");
}
if let Some(dockerfile) = self
.properties
.build
.as_ref()
.and_then(|b| b.dockerfile.as_deref())
{
return format!("dockerfile {dockerfile}");
}
"?".into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ServiceScope {
#[default]
Isolated,
Global,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Service {
#[serde(default)]
pub scope: ServiceScope,
pub image: Option<String>,
pub build: Option<Build>,
#[serde(default)]
pub env: BTreeMap<String, String>,
#[serde(default)]
pub ports: Vec<String>,
#[serde(default)]
pub command: Option<StringOrList>,
}
#[derive(Debug)]
pub struct ResolvedService {
pub name: String,
pub spec: Service,
pub config_hash: String,
}
impl Config {
pub fn parse(contents: &str) -> Result<Self> {
toml::from_str(contents).context("invalid config")
}
pub fn parse_yaml(contents: &str) -> Result<Self> {
let config: Option<Self> =
serde_saphyr::from_str(contents).map_err(|e| anyhow!("{e}")).context("invalid config")?;
Ok(config.unwrap_or_default())
}
pub fn resolve_service(&self, name: &str) -> Result<ResolvedService> {
let table = self
.services
.get(name)
.with_context(|| format!("unknown service `{name}`"))?;
let config_hash = config_hash(table);
let spec: Service = table
.clone()
.try_into()
.map_err(|e| anyhow!("service `{name}`: {e}"))?;
match (&spec.image, &spec.build) {
(Some(_), Some(_)) => bail!("service `{name}`: set only one of `image` or `build`"),
(None, None) => bail!("service `{name}`: needs an `image` or a `build`"),
_ => {}
}
Ok(ResolvedService {
name: name.to_string(),
spec,
config_hash,
})
}
pub fn load(dir: &Path) -> Result<Self> {
let path = find(dir)?.unwrap_or_else(|| dir.join(CONFIG_FILE));
let contents = std::fs::read_to_string(&path)
.with_context(|| format!("cannot read {}", path.display()))?;
let parsed = match path.extension().and_then(|e| e.to_str()) {
Some("yaml" | "yml") => Self::parse_yaml(&contents),
_ => Self::parse(&contents),
};
parsed.with_context(|| format!("in {}", path.display()))
}
pub fn resolve_sandbox(&self, name: &str) -> Result<ResolvedSandbox> {
let sandbox = self
.sandboxes
.get(name)
.with_context(|| format!("unknown sandbox `{name}`"))?;
let mut properties = self.resolve_extends(sandbox, &mut Vec::new())?;
properties.remove("extends");
let config_hash = sandbox_hash(&properties);
let mut properties: SandboxProperties = properties
.try_into()
.map_err(|e| anyhow!("sandbox `{name}`: {e}"))?;
if let Some(forwards) = &mut properties.forward_ports {
let mut seen = std::collections::BTreeSet::new();
forwards.retain(|f| seen.insert(f.key()));
let services = properties.services.as_deref().unwrap_or_default();
for f in forwards.iter() {
if let Some(svc) = &f.service
&& !services.contains(svc)
{
bail!("sandbox `{name}`: forwardPorts entry `{}` names `{svc}`, which isn't in its `services`", f.key());
}
}
}
Ok(ResolvedSandbox {
name: name.to_string(),
properties,
config_hash,
})
}
pub fn sandbox_table(&self, name: &str) -> Result<&Table> {
self.sandboxes
.get(name)
.with_context(|| format!("unknown sandbox `{name}`"))
}
pub fn resolved_table(&self, name: &str) -> Result<(Table, String)> {
let sandbox = self.sandbox_table(name)?;
let mut properties = self.resolve_extends(sandbox, &mut Vec::new())?;
properties.remove("extends");
let hash = sandbox_hash(&properties);
Ok((properties, hash))
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn sandbox_text(&self, name: &str) -> SandboxText {
let original = match self.sandbox_table(name) {
Ok(t) => table_text(t),
Err(e) => format!("{e:#}"),
};
let (resolved, hash) = match self.resolved_table(name) {
Ok((t, hash)) => (table_text(&t), hash),
Err(e) => (format!("{e:#}"), String::new()),
};
SandboxText { original, resolved, hash }
}
#[cfg_attr(not(unix), allow(dead_code))] pub fn service_text(&self, name: &str) -> Option<String> {
self.services.get(name).map(table_text)
}
fn resolve_extends(&self, table: &Table, stack: &mut Vec<String>) -> Result<Table> {
self.merge_extends(table, stack, &mut Vec::new())
}
#[cfg_attr(not(test), allow(dead_code))] pub fn extends_chain(&self, table: &Table) -> Result<Vec<String>> {
let mut chain = Vec::new();
self.merge_extends(table, &mut Vec::new(), &mut chain)?;
Ok(chain)
}
fn merge_extends(&self, table: &Table, stack: &mut Vec<String>, chain: &mut Vec<String>) -> Result<Table> {
let names = match table.get("extends") {
None => Vec::new(),
Some(Value::String(name)) => vec![name.clone()],
Some(Value::Array(items)) => items
.iter()
.map(|v| {
v.as_str().map(str::to_string).ok_or_else(|| {
anyhow!("`extends` array must contain template names (strings)")
})
})
.collect::<Result<Vec<_>>>()?,
Some(other) => bail!(
"`extends` must be a template name or an array of names, got {}",
other.type_str()
),
};
let mut merged = Table::new();
for name in names {
if stack.contains(&name) {
bail!("cyclic `extends`: {} -> {name}", stack.join(" -> "));
}
let template = self
.templates
.get(&name)
.with_context(|| format!("extends unknown template `{name}`"))?;
stack.push(name.clone());
let resolved = self.merge_extends(template, stack, chain)?;
stack.pop();
chain.push(name);
merged = deep_merge(merged, resolved);
}
let mut body = table.clone();
body.remove("extends");
Ok(deep_merge(merged, body))
}
pub fn resolve_all(&self) -> Result<Vec<ResolvedSandbox>> {
let all = self
.sandboxes
.keys()
.map(|name| self.resolve_sandbox(name))
.collect::<Result<Vec<_>>>()?;
for sandbox in &all {
self.validate_dispatcher(sandbox)?;
}
Ok(all)
}
pub fn validate_dispatcher(&self, sandbox: &ResolvedSandbox) -> Result<()> {
let Some(dispatcher) = &sandbox.properties.dispatcher else {
return Ok(());
};
for entry in &dispatcher.spawn {
if entry != Dispatcher::ANY && !self.sandboxes.contains_key(entry) {
bail!(
"sandbox `{}`: `dispatcher.spawn` names unknown sandbox `{entry}`",
sandbox.name
);
}
}
Ok(())
}
}
pub fn short_hash(text: &str) -> String {
fnv_hex(text.as_bytes())
}
fn fnv_hex(bytes: &[u8]) -> String {
let mut h: u64 = 0xcbf29ce484222325;
for &b in bytes {
h ^= b as u64;
h = h.wrapping_mul(0x100000001b3);
}
format!("{h:016x}")
}
pub fn build_hash(dir: &Path, build: Option<&Build>) -> String {
let Some(dockerfile) = build.and_then(|b| b.dockerfile.as_deref()) else {
return String::new();
};
match std::fs::read(dir.join(dockerfile)) {
Ok(bytes) => short_hash(&String::from_utf8_lossy(&bytes)),
Err(_) => String::new(),
}
}
pub fn sandbox_build_hash(dir: &Path, props: &SandboxProperties) -> String {
let build = build_hash(dir, props.build.as_ref());
match crate::features::local_features_fingerprint(dir, props.features.as_ref()) {
None => build,
Some(mut bytes) => {
bytes.extend_from_slice(build.as_bytes());
fnv_hex(&bytes)
}
}
}
fn config_hash(table: &Table) -> String {
short_hash(&toml::to_string(table).unwrap_or_default())
}
fn sandbox_hash(table: &Table) -> String {
let mut table = table.clone();
table.remove("autostart");
table.remove("placement");
table.remove("dispatcher");
table.remove("inbox");
table.remove("forwardPorts");
if let Some(toml::Value::Table(folders)) = table.get_mut("folders") {
normalize_folders(folders);
}
config_hash(&table)
}
fn normalize_folders(folders: &mut Table) {
for (_, entry) in folders.iter_mut() {
let toml::Value::Table(t) = entry else { continue };
let Some(toml::Value::String(path)) = t.get("path") else { continue };
let default_mode = match t.get("worktree") {
None => true,
Some(toml::Value::String(mode)) => mode == "auto",
Some(_) => false,
};
if default_mode && t.len() == 1 + usize::from(t.contains_key("worktree")) {
*entry = toml::Value::String(path.clone());
}
}
}
fn deep_merge(base: Table, over: Table) -> Table {
let mut merged = base;
for (key, value) in over {
match (merged.remove(&key), value) {
(Some(Value::Table(base_table)), Value::Table(over_table)) => {
merged.insert(key, Value::Table(deep_merge(base_table, over_table)));
}
(Some(Value::Array(mut base_arr)), Value::Array(over_arr)) => {
base_arr.extend(over_arr);
merged.insert(key, Value::Array(base_arr));
}
(_, value) => {
merged.insert(key, value);
}
}
}
merged
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE: &str = r#"
[services.database]
image = "postgres"
[template.base-sandbox]
caches = ["pnpm"]
build.args = { A = "1", B = "2" }
[sandbox.repository-1]
extends = "base-sandbox"
folder = "../repository-1"
image = "node-22"
[sandbox.repository-2]
extends = "base-sandbox"
folder = "../repository-2"
services = ["database"]
build.dockerfile = "./Dockerfile"
build.args = { B = "3" }
"#;
#[test]
fn parses_example() {
let config = Config::parse(EXAMPLE).unwrap();
assert_eq!(config.services.len(), 1);
assert_eq!(config.templates.len(), 1);
assert_eq!(config.sandboxes.len(), 2);
}
const EXAMPLE_YAML: &str = r#"
services:
database:
image: postgres
template:
base-sandbox:
caches: [pnpm]
build:
args: { A: "1", B: "2" }
sandbox:
repository-1:
extends: base-sandbox
folder: ../repository-1
image: node-22
repository-2:
extends: base-sandbox
folder: ../repository-2
services: [database]
build:
dockerfile: ./Dockerfile
args: { B: "3" }
"#;
#[test]
fn yaml_resolves_and_hashes_like_toml() {
let toml = Config::parse(EXAMPLE).unwrap();
let yaml = Config::parse_yaml(EXAMPLE_YAML).unwrap();
for name in ["repository-1", "repository-2"] {
let (t, t_hash) = toml.resolved_table(name).unwrap();
let (y, y_hash) = yaml.resolved_table(name).unwrap();
assert_eq!(t, y, "{name}");
assert_eq!(t_hash, y_hash, "{name}");
}
assert_eq!(
toml.resolve_service("database").unwrap().config_hash,
yaml.resolve_service("database").unwrap().config_hash
);
}
#[test]
fn yaml_empty_and_invalid() {
assert!(Config::parse_yaml("").unwrap().sandboxes.is_empty());
assert!(Config::parse_yaml("# nothing yet\n").unwrap().sandboxes.is_empty());
assert!(Config::parse_yaml("sandbox: [").is_err());
assert!(Config::parse_yaml("sandbox: {s: {image: ~}}").is_err());
}
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("devsandbox-cfgfile-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn load_picks_format_by_extension() {
let dir = scratch("ext");
std::fs::write(dir.join("devsandboxes.yml"), EXAMPLE_YAML).unwrap();
assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
std::fs::write(dir.join("devsandboxes.toml"), EXAMPLE).unwrap();
let err = format!("{:#}", Config::load(&dir).unwrap_err());
assert!(err.contains("devsandboxes.toml, devsandboxes.yml"), "{err}");
std::fs::remove_file(dir.join("devsandboxes.yml")).unwrap();
assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn legacy_config_is_read_then_migrated() {
let dir = scratch("legacy");
std::fs::write(dir.join("config.toml"), EXAMPLE).unwrap();
assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
assert_eq!(migrate_legacy(&dir).unwrap(), Some(dir.join(CONFIG_FILE)));
assert!(!dir.join("config.toml").exists());
assert_eq!(Config::load(&dir).unwrap().sandboxes.len(), 2);
assert_eq!(migrate_legacy(&dir).unwrap(), None);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn unrelated_config_toml_is_left_alone() {
let dir = scratch("unrelated");
std::fs::write(dir.join("config.toml"), "baseURL = \"https://example.org\"\n").unwrap();
assert_eq!(migrate_legacy(&dir).unwrap(), None);
assert!(dir.join("config.toml").exists());
assert!(Config::load(&dir).is_err());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn resolve_merges_template() {
let config = Config::parse(EXAMPLE).unwrap();
let sandbox = config.resolve_sandbox("repository-1").unwrap();
assert_eq!(sandbox.folder(), Some("../repository-1"));
assert_eq!(sandbox.source(), "image node-22");
assert_eq!(sandbox.properties.caches.as_deref(), Some(&["pnpm".to_string()][..]));
}
#[test]
fn resolve_deep_merges_nested_tables() {
let config = Config::parse(EXAMPLE).unwrap();
let sandbox = config.resolve_sandbox("repository-2").unwrap();
assert_eq!(sandbox.source(), "dockerfile ./Dockerfile");
let args = sandbox.properties.build.as_ref().unwrap().args.as_ref().unwrap();
assert_eq!(args["A"], "1");
assert_eq!(args["B"], "3");
}
#[test]
fn folders_parses_and_merges_through_extends() {
let config = Config::parse(
r#"
[template.base]
folders = { "/workspaces/.shared" = "../.shared" }
[sandbox.app]
extends = "base"
folder = "../app"
image = "img"
folders = { "/workspaces/docs" = "../docs", "/workspaces/lib" = { path = "../lib", worktree = "always" }, "/workspaces/scratch" = { path = "../scratch", worktree = "never" }, "/workspaces/other" = { path = "../other" } }
"#,
)
.unwrap();
let sandbox = config.resolve_sandbox("app").unwrap();
assert!(!sandbox.config_hash.is_empty());
let folders = sandbox.properties.folders.as_ref().unwrap();
let entry = |k: &str| (folders[k].path(), folders[k].worktree_mode());
assert_eq!(entry("/workspaces/.shared"), ("../.shared", FolderWorktree::Auto));
assert_eq!(entry("/workspaces/docs"), ("../docs", FolderWorktree::Auto));
assert_eq!(entry("/workspaces/lib"), ("../lib", FolderWorktree::Always));
assert_eq!(entry("/workspaces/scratch"), ("../scratch", FolderWorktree::Never));
assert_eq!(entry("/workspaces/other"), ("../other", FolderWorktree::Auto));
}
#[test]
fn folders_reject_bad_table_entries() {
for bad in [
r#"{ path = "../lib", worktree = "sometimes" }"#,
r#"{ path = "../lib", wroktree = "never" }"#,
r#"{ worktree = "never" }"#,
"1",
] {
let result = Config::parse(&format!(
"[sandbox.app]\nfolder = \"../app\"\nimage = \"img\"\nfolders = {{ \"/workspaces/lib\" = {bad} }}\n"
))
.and_then(|c| c.resolve_sandbox("app"));
let err = format!("{:#}", result.unwrap_err());
assert!(err.contains("host dir string"), "{bad}: {err}");
}
}
#[test]
fn folders_worktree_mode_changes_config_hash() {
let hash = |entry: &str| {
Config::parse(&format!(
"[sandbox.app]\nfolder = \"../app\"\nimage = \"img\"\nfolders = {{ \"/workspaces/lib\" = {entry} }}\n"
))
.unwrap()
.resolve_sandbox("app")
.unwrap()
.config_hash
};
let plain = hash(r#""../lib""#);
assert_ne!(plain, hash(r#"{ path = "../lib", worktree = "never" }"#));
assert_ne!(plain, hash(r#"{ path = "../lib", worktree = "always" }"#));
assert_eq!(plain, hash(r#"{ path = "../lib" }"#));
assert_eq!(plain, hash(r#"{ path = "../lib", worktree = "auto" }"#));
assert_ne!(plain, hash(r#"{ path = "../other" }"#));
}
#[test]
fn config_hash_is_stable_and_sensitive() {
let config = Config::parse(EXAMPLE).unwrap();
let a = config.resolve_sandbox("repository-1").unwrap().config_hash;
let b = config.resolve_sandbox("repository-1").unwrap().config_hash;
assert_eq!(a, b, "same config must hash identically");
let c = config.resolve_sandbox("repository-2").unwrap().config_hash;
assert_ne!(a, c, "different configs must hash differently");
}
fn identity_props(body: &str) -> Result<SandboxProperties> {
let config = Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))?;
Ok(config.resolve_sandbox("app")?.properties)
}
#[test]
fn identity_parses_and_hint_applies() {
let cases = [
("", Identity::Host),
("identity = \"host\"\n", Identity::Host),
("identity = \"image\"\n", Identity::Image),
("updateRemoteUserUID = true\n", Identity::Host),
("updateRemoteUserUID = false\n", Identity::Image),
("identity = \"host\"\nupdateRemoteUserUID = false\n", Identity::Host),
("identity = \"image\"\nupdateRemoteUserUID = true\n", Identity::Image),
];
for (body, want) in cases {
let props = identity_props(body).unwrap();
assert_eq!(props.identity(), want, "{body:?}");
assert!(props.ignored().is_empty(), "{body:?}: {:?}", props.ignored());
}
}
#[test]
fn identity_rejects_other_values() {
let err = format!("{:#}", identity_props("identity = \"root\"\n").unwrap_err());
assert!(err.contains("host") && err.contains("image"), "{err}");
assert!(identity_props("updateRemoteUserUID = \"false\"\n").is_err());
}
#[test]
fn identity_parses_from_yaml() {
let props = |yaml: &str| {
Config::parse_yaml(yaml).unwrap().resolve_sandbox("app").unwrap().properties.identity()
};
assert_eq!(props("sandbox:\n app:\n identity: image\n"), Identity::Image);
assert_eq!(props("sandbox:\n app:\n updateRemoteUserUID: false\n"), Identity::Image);
assert_eq!(props("sandbox:\n app:\n identity: host\n"), Identity::Host);
let toml = Config::parse("[sandbox.app]\nidentity = \"image\"\n").unwrap();
let yaml = Config::parse_yaml("sandbox:\n app:\n identity: image\n").unwrap();
assert_eq!(toml.resolved_table("app").unwrap(), yaml.resolved_table("app").unwrap());
}
#[test]
fn identity_and_hint_change_config_hash() {
let hash = |body: &str| {
Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))
.unwrap()
.resolve_sandbox("app")
.unwrap()
.config_hash
};
let plain = hash("");
assert_eq!(plain, hash(""));
assert_ne!(plain, hash("identity = \"image\"\n"));
assert_ne!(hash("identity = \"host\"\n"), hash("identity = \"image\"\n"));
assert_ne!(plain, hash("updateRemoteUserUID = false\n"));
assert_ne!(hash("updateRemoteUserUID = true\n"), hash("updateRemoteUserUID = false\n"));
}
#[test]
fn userns_defaults_on_and_changes_config_hash() {
assert!(identity_props("").unwrap().userns());
assert!(identity_props("userns = true\n").unwrap().userns());
assert!(!identity_props("userns = false\n").unwrap().userns());
assert!(identity_props("userns = \"no\"\n").is_err());
let hash = |body: &str| {
Config::parse(&format!("[sandbox.app]\nfolder = \"../app\"\n{body}"))
.unwrap()
.resolve_sandbox("app")
.unwrap()
.config_hash
};
assert_ne!(hash(""), hash("userns = false\n"));
assert_ne!(hash("userns = true\n"), hash("userns = false\n"));
}
fn autostart_of(value: &str) -> Result<Option<Autostart>> {
let config = Config::parse(&format!(
"[sandbox.app]\nfolder = \"../app\"\nautostart = {value}\n"
))?;
Ok(config.resolve_sandbox("app")?.properties.autostart)
}
#[test]
fn autostart_parses_bool_and_runtime() {
assert_eq!(autostart_of("true").unwrap(), Some(Autostart::Devsandbox));
assert_eq!(autostart_of("false").unwrap(), Some(Autostart::Off));
assert_eq!(autostart_of("\"runtime\"").unwrap(), Some(Autostart::Runtime));
let unset = Config::parse(EXAMPLE).unwrap().resolve_sandbox("repository-1").unwrap();
assert_eq!(unset.properties.autostart, None);
}
#[test]
fn autostart_rejects_other_values() {
for bad in ["\"bogus\"", "1"] {
let err = format!("{:#}", autostart_of(bad).unwrap_err());
assert!(err.contains("runtime") && err.contains("true"), "{bad}: {err}");
}
}
#[test]
fn autostart_excluded_from_config_hash() {
let base = "[sandbox.app]\nfolder = \"../app\"\n";
let plain = Config::parse(base).unwrap();
let with = Config::parse(&format!("{base}autostart = true\n")).unwrap();
let hash = plain.resolve_sandbox("app").unwrap().config_hash;
assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
let (table, table_hash) = with.resolved_table("app").unwrap();
assert_eq!(table_hash, hash);
assert!(table.contains_key("autostart"));
}
#[test]
fn dispatcher_parses_and_rejects_unknown_keys() {
let config = Config::parse(
"[sandbox.d]\nfolder = \".\"\ndispatcher = { spawn = [\"web\", \"*\"], max-instances = 3 }\n\
[sandbox.web]\nfolder = \".\"\n",
)
.unwrap();
let d = config.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
assert_eq!(d.spawn, vec!["web", "*"]);
assert_eq!(d.max_instances, Some(3));
assert_eq!(d.cap(), 3);
assert_eq!(Dispatcher::default().cap(), Dispatcher::DEFAULT_MAX_INSTANCES);
assert!(d.may_spawn("anything"));
assert_eq!(config.resolve_sandbox("web").unwrap().properties.dispatcher, None);
let bad = Config::parse("[sandbox.d]\ndispatcher = { spawn = [], max = 3 }\n").unwrap();
let err = format!("{:#}", bad.resolve_sandbox("d").unwrap_err());
assert!(err.contains("max"), "{err}");
let bad = Config::parse("[sandbox.d]\ndispatcher = { max_instances = 3 }\n").unwrap();
assert!(bad.resolve_sandbox("d").is_err());
}
#[test]
fn dispatcher_spawn_list_is_checked_by_resolve_all() {
let ok = Config::parse(
"[sandbox.d]\ndispatcher = { spawn = [\"web\", \"*\", \"d\"] }\n[sandbox.web]\n",
)
.unwrap();
assert!(ok.resolve_all().is_ok());
let d = ok.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
assert!(d.may_spawn("web") && d.may_spawn("d"));
let bad = Config::parse("[sandbox.d]\ndispatcher = { spawn = [\"nope\"] }\n").unwrap();
let err = bad.resolve_all().unwrap_err().to_string();
assert!(err.contains("unknown sandbox `nope`"), "{err}");
let only = bad.resolve_sandbox("d").unwrap().properties.dispatcher.unwrap();
assert!(!only.may_spawn("web"));
}
#[test]
fn dispatcher_excluded_from_config_hash() {
let base = "[sandbox.app]\nfolder = \"../app\"\n";
let plain = Config::parse(base).unwrap();
let with = Config::parse(&format!("{base}dispatcher = {{ spawn = [\"app\"] }}\n")).unwrap();
let hash = plain.resolve_sandbox("app").unwrap().config_hash;
assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
assert_eq!(with.resolved_table("app").unwrap().1, hash);
}
#[test]
fn inbox_parses_merges_and_is_not_drift() {
let config = Config::parse(
"[template.owner]\ninbox = true\n\
[sandbox.a]\nfolder = \".\"\nextends = [\"owner\"]\n\
[sandbox.b]\nfolder = \".\"\nextends = [\"owner\"]\ninbox = false\n\
[sandbox.c]\nfolder = \".\"\n",
)
.unwrap();
assert_eq!(config.resolve_sandbox("a").unwrap().properties.inbox, Some(true));
assert_eq!(config.resolve_sandbox("b").unwrap().properties.inbox, Some(false));
assert_eq!(config.resolve_sandbox("c").unwrap().properties.inbox, None);
let hash = |s| config.resolve_sandbox(s).unwrap().config_hash;
assert_eq!(hash("a"), hash("c"));
assert_eq!(hash("b"), hash("c"));
let bad = Config::parse("[sandbox.a]\ninbox = \"yes\"\n").unwrap();
assert!(bad.resolve_sandbox("a").is_err());
}
#[test]
fn placement_parses_merges_and_is_not_drift() {
let config = Config::parse(
"[template.pinned]\nplacement = \"home\"\n\
[sandbox.a]\nfolder = \".\"\nextends = [\"pinned\"]\n\
[sandbox.b]\nfolder = \".\"\nplacement = \"home\"\n\
[sandbox.c]\nfolder = \".\"\n",
)
.unwrap();
let placement = |s| config.resolve_sandbox(s).unwrap().properties.placement;
assert_eq!(placement("a"), Some(Placement::Home));
assert_eq!(placement("b"), Some(Placement::Home));
assert_eq!(placement("c"), None);
let hash = |s| config.resolve_sandbox(s).unwrap().config_hash;
assert_eq!(hash("a"), hash("c"));
assert_eq!(hash("b"), hash("c"));
let bad = Config::parse("[sandbox.a]\nplacement = \"anywhere\"\n").unwrap();
let err = format!("{:#}", bad.resolve_sandbox("a").unwrap_err());
assert!(err.contains("anywhere") && err.contains("home"), "{err}");
}
#[test]
fn forward_ports_excluded_from_config_hash() {
let base = "[sandbox.app]\nfolder = \"../app\"\n";
let plain = Config::parse(base).unwrap();
let with = Config::parse(&format!("{base}forwardPorts = [3000]\n")).unwrap();
let hash = plain.resolve_sandbox("app").unwrap().config_hash;
assert_eq!(hash, with.resolve_sandbox("app").unwrap().config_hash);
assert_eq!(with.resolved_table("app").unwrap().1, hash);
}
#[test]
fn forward_port_entries_parse() {
let fp = |host, service: Option<&str>, port| ForwardPort { host, service: service.map(str::to_string), port };
assert_eq!(ForwardPort::parse("3000"), Ok(fp(None, None, 3000)));
assert_eq!(ForwardPort::parse("8080:3000"), Ok(fp(Some(8080), None, 3000)));
assert_eq!(ForwardPort::parse("db:5432"), Ok(fp(None, Some("db"), 5432)));
assert_eq!(ForwardPort::parse("15432:db:5432"), Ok(fp(Some(15432), Some("db"), 5432)));
for bad in ["", "0", "x", "70000", "8080:0", ":3000", "1:2:3", "db:", "a:b:c:d"] {
assert!(ForwardPort::parse(bad).is_err(), "{bad}");
}
assert_eq!(fp(Some(15432), Some("db"), 5432).key(), "15432:db:5432");
assert_eq!(fp(Some(15432), Some("db"), 5432).base(), 15432);
assert_eq!(fp(None, Some("db"), 5432).base(), 5432);
}
#[test]
fn forward_ports_accept_numbers_and_strings_dedupe_and_check_services() {
let config = Config::parse(
r#"
[services.db]
image = "postgres"
[template.t]
forwardPorts = [3000]
[sandbox.app]
extends = "t"
services = ["db"]
forwardPorts = ["3000", "8080:3000", "db:5432"]
[sandbox.bad]
forwardPorts = ["db:5432"]
[sandbox.worse]
forwardPorts = [true]
"#,
)
.unwrap();
let app = config.resolve_sandbox("app").unwrap();
let keys: Vec<String> = app.properties.forward_ports.as_ref().unwrap().iter().map(ForwardPort::key).collect();
assert_eq!(keys, ["3000", "8080:3000", "db:5432"]);
assert!(app.properties.ignored().is_empty());
let err = config.resolve_sandbox("bad").unwrap_err().to_string();
assert!(err.contains("isn't in its `services`"), "{err}");
assert!(config.resolve_sandbox("worse").is_err());
}
#[test]
fn build_hash_none_and_missing_are_empty() {
let dir = std::env::temp_dir();
assert_eq!(build_hash(&dir, None), "");
let no_dockerfile = Build::default();
assert_eq!(build_hash(&dir, Some(&no_dockerfile)), "");
let missing = Build {
dockerfile: Some("does-not-exist-xyz.Dockerfile".into()),
..Build::default()
};
assert_eq!(build_hash(&dir, Some(&missing)), "");
}
#[test]
fn build_hash_tracks_dockerfile_contents() {
let dir = std::env::temp_dir().join(format!("devsandbox-bh-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("Dockerfile");
let build = Build {
dockerfile: Some("Dockerfile".into()),
..Build::default()
};
std::fs::write(&path, "FROM alpine\n").unwrap();
let first = build_hash(&dir, Some(&build));
assert!(!first.is_empty());
assert_eq!(first, build_hash(&dir, Some(&build)));
std::fs::write(&path, "FROM alpine\nRUN echo hi\n").unwrap();
assert_ne!(first, build_hash(&dir, Some(&build)));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn sandbox_build_hash_tracks_local_features_only() {
let dir = std::env::temp_dir().join(format!("devsandbox-sbh-{}", std::process::id()));
let feature = dir.join("features/toolkit");
std::fs::create_dir_all(&feature).unwrap();
std::fs::write(feature.join("devcontainer-feature.json"), r#"{"id": "toolkit"}"#).unwrap();
std::fs::write(feature.join("install.sh"), "#!/bin/sh\n").unwrap();
let hash = |body: &str| {
let sandbox = Config::parse(body).unwrap().resolve_sandbox("app").unwrap();
sandbox_build_hash(&dir, &sandbox.properties)
};
let local = r#"
[template.base.features."./features/toolkit"]
ripgrep = true
[sandbox.app]
extends = "base"
image = "alpine"
folder = "app"
"#;
let first = hash(local);
assert!(!first.is_empty());
assert_eq!(first, hash(&local.replace("folder = \"app\"", "folder = \"other\"\nremoteUser = \"x\"")));
assert_eq!(first, hash(&local.replace("ripgrep = true", "ripgrep = false")));
std::fs::write(feature.join("install.sh"), "#!/bin/sh\napk add ripgrep\n").unwrap();
assert_ne!(first, hash(local));
let oci = r#"
[sandbox.app]
image = "alpine"
[sandbox.app.features."ghcr.io/devcontainers/features/node:1"]
"#;
assert_eq!(hash(oci), "");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn resolved_table_merges_and_drops_extends() {
let config = Config::parse(EXAMPLE).unwrap();
let (table, hash) = config.resolved_table("repository-2").unwrap();
assert!(!table.contains_key("extends"));
assert_eq!(table["folder"].as_str(), Some("../repository-2"));
assert_eq!(table["caches"].as_array().unwrap().len(), 1); let args = table["build"].as_table().unwrap()["args"].as_table().unwrap();
assert_eq!(args["A"].as_str(), Some("1"));
assert_eq!(args["B"].as_str(), Some("3"));
assert_eq!(hash, config.resolve_sandbox("repository-2").unwrap().config_hash);
}
#[test]
fn resolved_table_unknown_sandbox_errors() {
let config = Config::parse(EXAMPLE).unwrap();
assert!(config.resolved_table("nope").is_err());
}
#[test]
fn extends_chain_is_merge_order() {
let config = Config::parse(
"[template.a]\n[template.b]\nextends = \"a\"\n[template.c]\nextends = [\"b\", \"a\"]\n\
[template.x]\nextends = \"y\"\n[template.y]\nextends = \"x\"\n",
)
.unwrap();
let chain = |name: &str| config.extends_chain(&config.templates[name]);
assert_eq!(chain("a").unwrap(), Vec::<String>::new());
assert_eq!(chain("c").unwrap(), ["a", "b", "a"]);
assert!(format!("{:#}", chain("x").unwrap_err()).contains("cyclic"));
}
#[test]
fn sandbox_without_extends() {
let config = Config::parse("[sandbox.solo]\nimage = \"alpine\"").unwrap();
let sandbox = config.resolve_sandbox("solo").unwrap();
assert_eq!(sandbox.source(), "image alpine");
}
#[test]
fn unknown_template_errors() {
let config = Config::parse("[sandbox.bad]\nextends = \"nope\"").unwrap();
let err = config.resolve_sandbox("bad").unwrap_err().to_string();
assert!(err.contains("unknown template `nope`"), "{err}");
}
#[test]
fn non_string_extends_errors() {
let config = Config::parse("[sandbox.bad]\nextends = 3").unwrap();
assert!(config.resolve_sandbox("bad").is_err());
}
#[test]
fn unknown_property_errors() {
let config = Config::parse("[sandbox.bad]\nimag = \"alpine\"").unwrap();
let err = config.resolve_sandbox("bad").unwrap_err().to_string();
assert!(err.contains("imag"), "{err}");
}
#[test]
fn unknown_property_from_template_errors() {
let config = Config::parse(
"[template.t]\nfowardPorts = [3000]\n[sandbox.bad]\nextends = \"t\"",
)
.unwrap();
let err = config.resolve_sandbox("bad").unwrap_err().to_string();
assert!(err.contains("fowardPorts"), "{err}");
}
#[test]
fn unimplemented_properties_are_flagged_ignored() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
appPort = [3000]
runArgs = ["--gpus", "all"]
customizations.vscode.settings = { "editor.formatOnSave" = true }
customizations.jetbrains.plugins = ["x"]
"#,
)
.unwrap();
let sandbox = config.resolve_sandbox("s").unwrap();
assert_eq!(
sandbox.properties.ignored(),
vec![
"appPort",
"runArgs",
"customizations.vscode.settings",
"customizations.jetbrains",
]
);
}
#[test]
fn implemented_properties_are_not_ignored() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
containerEnv = { FOO = "bar" }
postCreateCommand = "npm install"
customizations.vscode.extensions = ["rust-lang.rust-analyzer"]
privileged = true
placement = "home"
"#,
)
.unwrap();
let sandbox = config.resolve_sandbox("s").unwrap();
assert!(sandbox.properties.ignored().is_empty());
assert_eq!(sandbox.properties.privileged, Some(true));
assert_eq!(
sandbox.properties.vscode_extensions(),
Some(&["rust-lang.rust-analyzer".to_string()][..])
);
}
#[test]
fn feature_option_forms_parse() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
[sandbox.s.features]
"ghcr.io/devcontainers/features/node:1" = { version = "lts" }
"ghcr.io/devcontainers/features/go:1" = "1.22"
"ghcr.io/devcontainers/features/git:1" = true
"#,
)
.unwrap();
let features = config.resolve_sandbox("s").unwrap().properties.features.unwrap();
match &features["ghcr.io/devcontainers/features/node:1"] {
FeatureOptions::Options(opts) => {
assert_eq!(opts["version"].as_str(), Some("lts"));
}
other => panic!("expected options table, got {other:?}"),
}
match &features["ghcr.io/devcontainers/features/go:1"] {
FeatureOptions::Version(v) => assert_eq!(v, "1.22"),
other => panic!("expected version string, got {other:?}"),
}
match &features["ghcr.io/devcontainers/features/git:1"] {
FeatureOptions::Enabled(b) => assert!(b),
other => panic!("expected bool, got {other:?}"),
}
}
#[test]
fn features_are_not_ignored() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
features = { "ghcr.io/x/y:1" = true }
"#,
)
.unwrap();
let sandbox = config.resolve_sandbox("s").unwrap();
assert!(sandbox.properties.ignored().is_empty());
assert!(!SandboxProperties::default().ignored().contains(&"features".to_string()));
}
#[test]
fn features_deep_merge_across_template() {
let config = Config::parse(
r#"
[template.feat-base]
[template.feat-base.features]
"ghcr.io/devcontainers/features/common-utils:2" = true
"ghcr.io/devcontainers/features/node:1" = { version = "18" }
[sandbox.s]
extends = "feat-base"
image = "alpine"
[sandbox.s.features]
"ghcr.io/devcontainers/features/go:1" = "1.22"
"ghcr.io/devcontainers/features/node:1" = { version = "lts" }
"#,
)
.unwrap();
let features = config.resolve_sandbox("s").unwrap().properties.features.unwrap();
assert!(matches!(
features["ghcr.io/devcontainers/features/common-utils:2"],
FeatureOptions::Enabled(true)
));
assert!(matches!(
&features["ghcr.io/devcontainers/features/go:1"],
FeatureOptions::Version(v) if v == "1.22"
));
match &features["ghcr.io/devcontainers/features/node:1"] {
FeatureOptions::Options(opts) => assert_eq!(opts["version"].as_str(), Some("lts")),
other => panic!("expected options table, got {other:?}"),
}
}
#[test]
fn lifecycle_command_forms() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
postCreateCommand = "npm install"
postStartCommand = ["node", "server.js"]
onCreateCommand = { b = "make", a = ["cargo", "build"] }
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(
props.post_create_command.unwrap().commands(),
vec![vec!["sh", "-c", "npm install"]]
);
assert_eq!(
props.post_start_command.unwrap().commands(),
vec![vec!["node", "server.js"]]
);
assert_eq!(
props.on_create_command.unwrap().commands(),
vec![vec!["cargo", "build"], vec!["sh", "-c", "make"]]
);
}
fn ctx() -> MountContext<'static> {
MountContext {
config_dir: "/cfg",
workspace_folder: "/home/u/repo",
workspace_folder_basename: "repo",
shared_volumes: "/cfg/shared-volumes",
instance: "repo-2",
container_env: None,
}
}
fn image_env() -> Vec<(String, String)> {
vec![("PATH".into(), "/usr/bin:/bin".into()), ("LANG".into(), "C".into()), ("LANG".into(), "C.UTF-8".into())]
}
#[test]
fn container_env_order_and_home_fallback() {
let sandbox = BTreeMap::from([("LANG".into(), "en_US.UTF-8".into())]);
let env = ContainerEnv { sandbox, image: image_env(), home: "/home/node".into() };
assert_eq!(env.get("LANG").as_deref(), Some("en_US.UTF-8"));
assert_eq!(env.get("PATH").as_deref(), Some("/usr/bin:/bin"));
assert_eq!(env.get("HOME").as_deref(), Some("/home/node"));
assert_eq!(env.get("UNSET"), None);
let mut image = image_env();
image.push(("HOME".into(), "/srv".into()));
let env = ContainerEnv { image, ..env };
assert_eq!(env.get("HOME").as_deref(), Some("/srv"));
assert_eq!(ContainerEnv { sandbox: BTreeMap::new(), ..env }.get("LANG").as_deref(), Some("C.UTF-8"));
}
#[test]
fn container_env_in_mounts_only_with_a_context() {
let m = Mount::Shorthand("type=volume,source=claude-${instance},target=${containerEnv:HOME}/.claude".into());
assert_eq!(m.resolve(&ctx()).unwrap().target, "${containerEnv:HOME}/.claude");
let env = ContainerEnv { home: "/home/vscode".into(), ..Default::default() };
let with = MountContext { container_env: Some(&env), ..ctx() };
assert_eq!(m.resolve(&with).unwrap().target, "/home/vscode/.claude");
}
#[test]
fn container_env_values_resolve_against_the_image_only() {
let raw = BTreeMap::from([
("CLAUDE_CONFIG_DIR".into(), "${containerEnv:HOME}/.claude".into()),
("TOOLS_PATH".into(), "${containerEnv:PATH}:/opt/bin".into()),
("WHERE".into(), "${instance}@${configDir}".into()),
]);
let env = ContainerEnv::resolve(Some(&raw), image_env(), "/home/node".into(), &ctx());
assert_eq!(env.sandbox["CLAUDE_CONFIG_DIR"], "/home/node/.claude");
assert_eq!(env.sandbox["TOOLS_PATH"], "/usr/bin:/bin:/opt/bin");
assert_eq!(env.sandbox["WHERE"], "repo-2@/cfg");
assert_eq!(env.get("TOOLS_PATH").as_deref(), Some("/usr/bin:/bin:/opt/bin"));
let none = ContainerEnv::resolve(None, Vec::new(), "/root".into(), &ctx());
assert!(none.sandbox.is_empty());
}
#[test]
fn container_env_values_read_the_image_not_each_other() {
let path = BTreeMap::from([
("PATH".into(), "${containerEnv:PATH}:/opt/bin".into()),
("HOME".into(), "${containerEnv:HOME}".into()),
]);
let env = ContainerEnv::resolve(Some(&path), image_env(), "/root".into(), &ctx());
assert_eq!(env.sandbox["PATH"], "/usr/bin:/bin:/opt/bin");
assert_eq!(env.sandbox["HOME"], "/root");
let other = BTreeMap::from([("A".into(), "x".into()), ("B".into(), "pre-${containerEnv:A}".into())]);
let env = ContainerEnv::resolve(Some(&other), Vec::new(), "/root".into(), &ctx());
assert_eq!(env.sandbox["B"], "pre-");
}
#[test]
fn substitutes_shared_volumes_and_instance() {
let m = Mount::Shorthand(
"source=${sharedVolumes}/agent/${instance},target=/root/.agent,type=bind".into(),
);
let resolved = m.resolve(&ctx()).unwrap();
assert_eq!(resolved.source.as_deref(), Some("/cfg/shared-volumes/agent/repo-2"));
assert_eq!(resolved.target, "/root/.agent");
assert!(!resolved.per_instance, "binds are never per-instance volumes");
}
#[test]
fn devcontainer_id_is_the_instance_and_marks_volume_per_instance() {
let m = Mount::Object(MountObject {
kind: Some("volume".into()),
source: Some("dind-var-lib-docker-${devcontainerId}".into()),
target: "/var/lib/docker".into(),
readonly: None,
});
let resolved = m.resolve(&ctx()).unwrap();
assert_eq!(resolved.source.as_deref(), Some("dind-var-lib-docker-repo-2"));
assert!(resolved.per_instance);
let m = Mount::Shorthand("type=volume,source=cache-${instance},target=/c".into());
assert!(m.resolve(&ctx()).unwrap().per_instance);
let m = Mount::Shorthand("type=volume,source=pnpm-store,target=/p".into());
assert!(!m.resolve(&ctx()).unwrap().per_instance);
}
#[test]
fn mount_shorthand_resolves_and_substitutes() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
mounts = ["source=${configDir}/shared-volumes/cargo,target=/root/.cargo,type=bind"]
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert!(props.ignored().is_empty());
let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
assert_eq!(resolved.source.as_deref(), Some("/cfg/shared-volumes/cargo"));
assert_eq!(resolved.target, "/root/.cargo");
assert_eq!(resolved.kind, "bind");
assert_eq!(
resolved.to_arg(),
"type=bind,source=/cfg/shared-volumes/cargo,target=/root/.cargo"
);
}
#[test]
fn mount_object_form_with_readonly() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
mounts = [{ source = "${localWorkspaceFolder}/x", target = "/x", readonly = true }]
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
assert_eq!(resolved.source.as_deref(), Some("/home/u/repo/x"));
assert!(resolved.readonly);
assert_eq!(resolved.to_arg(), "type=bind,source=/home/u/repo/x,target=/x,readonly");
}
#[test]
fn mount_localenv_expands_from_host() {
let expected = format!("type=bind,source={}/c,target=/c", std::env::var("PATH").unwrap());
let config = Config::parse(
"[sandbox.s]\nimage = \"alpine\"\nmounts = [\"source=${localEnv:PATH}/c,target=/c\"]",
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
let resolved = props.mounts.as_ref().unwrap()[0].resolve(&ctx()).unwrap();
assert_eq!(resolved.to_arg(), expected);
}
#[test]
fn local_env_default_applies_only_when_unset() {
let env = |name: &str| match name {
"SET" => Some("v".to_string()),
"EMPTY" => Some(String::new()),
_ => None,
};
let allow_all = |_: &str| true;
let r = |expr: &str| resolve_var_with(expr, &ctx(), allow_all, env);
assert_eq!(r("localEnv:SET").as_deref(), Some("v"));
assert_eq!(r("localEnv:SET:d").as_deref(), Some("v"));
assert_eq!(r("localEnv:EMPTY:d").as_deref(), Some(""));
assert_eq!(r("localEnv:UNSET:d").as_deref(), Some("d"));
assert_eq!(r("localEnv:UNSET").as_deref(), Some(""));
assert_eq!(r("localEnv:UNSET:").as_deref(), Some(""));
assert_eq!(r("localEnv:UNSET:http://h:8080/x").as_deref(), Some("http://h:8080/x"));
assert_eq!(
substitute("${localEnv:DEVSANDBOX_TEST_SURELY_UNSET:fall:back}/x", &ctx()),
"fall:back/x"
);
assert_eq!(substitute("${localEnv:PATH:d}", &ctx()), std::env::var("PATH").unwrap());
}
#[test]
fn local_env_gate_sees_the_name_and_refusal_stays_verbatim() {
let env = |_: &str| Some("secret".to_string());
let gate = |name: &str| {
assert!(!name.contains(':'), "gate got `{name}`");
name == "OK"
};
assert_eq!(resolve_var_with("localEnv:OK:d", &ctx(), gate, env).as_deref(), Some("secret"));
assert_eq!(resolve_var_with("localEnv:GH:d", &ctx(), gate, env), None);
assert_eq!(resolve_var_with("localEnv:GH", &ctx(), gate, env), None);
}
#[test]
fn container_env_default_applies_only_when_unset() {
let sandbox = BTreeMap::from([("EMPTY".into(), String::new())]);
let env = ContainerEnv { sandbox, image: image_env(), home: "/home/node".into() };
let with = MountContext { container_env: Some(&env), ..ctx() };
assert_eq!(substitute("${containerEnv:LANG:d}", &with), "C.UTF-8");
assert_eq!(substitute("${containerEnv:EMPTY:d}", &with), "");
assert_eq!(substitute("${containerEnv:HOME:d}", &with), "/home/node");
assert_eq!(substitute("${containerEnv:UNSET:a:b}", &with), "a:b");
assert_eq!(substitute("${containerEnv:UNSET}", &with), "");
assert_eq!(substitute("${containerEnv:UNSET:d}", &ctx()), "${containerEnv:UNSET:d}");
}
#[test]
fn mount_bind_without_source_errors() {
let config =
Config::parse("[sandbox.s]\nimage = \"alpine\"\nmounts = [\"target=/x,type=bind\"]")
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert!(props.mounts.as_ref().unwrap()[0].resolve(&ctx()).is_err());
}
#[test]
fn mount_unknown_variable_left_verbatim() {
assert_eq!(substitute("${nope}/x", &ctx()), "${nope}/x");
assert_eq!(substitute("a/${configDir}/b", &ctx()), "a//cfg/b");
}
#[test]
fn arrays_concatenate_on_merge() {
let config = Config::parse(
r#"
[template.base]
mounts = ["source=/a,target=/a,type=bind"]
customizations.vscode.extensions = ["a.one"]
[sandbox.s]
extends = "base"
image = "alpine"
mounts = ["source=/b,target=/b,type=bind"]
customizations.vscode.extensions = ["b.two"]
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.mounts.as_ref().unwrap().len(), 2);
assert_eq!(
props.vscode_extensions(),
Some(&["a.one".to_string(), "b.two".to_string()][..])
);
}
#[test]
fn persist_shell_history_parses_and_merges() {
let config = Config::parse(
r#"
[template.base]
persist-shell-history = true
[sandbox.s]
extends = "base"
image = "alpine"
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.persist_shell_history, Some(true));
assert!(props.ignored().is_empty());
}
#[test]
fn worktree_branch_parses_and_is_not_ignored() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
worktree-branch = "feat/${instance}"
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.worktree_branch.as_deref(), Some("feat/${instance}"));
assert!(props.ignored().is_empty());
}
#[test]
fn worktree_branch_merges_through_template() {
let config = Config::parse(
r#"
[template.base]
worktree-branch = "team/${instance}"
[sandbox.s]
extends = "base"
image = "alpine"
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.worktree_branch.as_deref(), Some("team/${instance}"));
}
#[test]
fn worktree_base_parses_and_is_not_ignored() {
let config = Config::parse(
r#"
[sandbox.s]
image = "alpine"
worktree-base = "origin/develop"
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.worktree_base.as_deref(), Some("origin/develop"));
assert!(props.ignored().is_empty());
}
#[test]
fn worktree_include_and_link_concatenate_through_template() {
let config = Config::parse(
r#"
[template.base]
worktree-include = [".vscode/tasks.json"]
worktree-link = [".env"]
[sandbox.s]
extends = "base"
image = "alpine"
worktree-include = ["!.vscode/tasks.json"]
worktree-link = [".env.local"]
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(
props.worktree_include.as_deref(),
Some(&[".vscode/tasks.json".to_string(), "!.vscode/tasks.json".to_string()][..])
);
assert_eq!(
props.worktree_link.as_deref(),
Some(&[".env".to_string(), ".env.local".to_string()][..])
);
assert!(props.ignored().is_empty());
}
#[test]
fn shell_rc_concatenates_through_template() {
let config = Config::parse(
r#"
[template.base]
shell-rc = ["${configDir}/shell/aliases.sh"]
[sandbox.s]
extends = "base"
image = "alpine"
shell-rc = ["./env.sh"]
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(
props.shell_rc.as_deref(),
Some(&["${configDir}/shell/aliases.sh".to_string(), "./env.sh".to_string()][..])
);
assert!(props.ignored().is_empty());
}
#[test]
fn extends_list_merges_left_to_right() {
let config = Config::parse(
r#"
[template.node]
image = "node"
containerEnv = { A = "1" }
customizations.vscode.extensions = ["node.ext"]
[template.rust]
containerEnv = { B = "2" }
customizations.vscode.extensions = ["rust.ext"]
[sandbox.s]
extends = ["node", "rust"]
folder = "."
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.image.as_deref(), Some("node"));
let env = props.container_env.as_ref().unwrap();
assert_eq!(env["A"], "1");
assert_eq!(env["B"], "2");
assert_eq!(
props.vscode_extensions(),
Some(&["node.ext".to_string(), "rust.ext".to_string()][..])
);
}
#[test]
fn extends_resolves_recursively() {
let config = Config::parse(
r#"
[template.base]
image = "alpine"
containerEnv = { BASE = "1" }
[template.mid]
extends = "base"
containerEnv = { MID = "2" }
[sandbox.s]
extends = "mid"
folder = "."
"#,
)
.unwrap();
let props = config.resolve_sandbox("s").unwrap().properties;
assert_eq!(props.image.as_deref(), Some("alpine"));
let env = props.container_env.as_ref().unwrap();
assert_eq!(env["BASE"], "1");
assert_eq!(env["MID"], "2");
}
#[test]
fn extends_cycle_errors() {
let config = Config::parse(
r#"
[template.a]
extends = "b"
[template.b]
extends = "a"
[sandbox.s]
extends = "a"
"#,
)
.unwrap();
let err = config.resolve_sandbox("s").unwrap_err().to_string();
assert!(err.contains("cyclic"), "{err}");
}
#[test]
fn caches_expand_to_known_specs() {
let (source, target, env) = known_cache("cargo").unwrap();
assert_eq!(source, "cargo");
assert_eq!(target, "/var/cache/devsandbox/cargo");
assert_eq!(env, &["CARGO_HOME"]);
assert!(known_cache("nope").is_none());
}
#[test]
fn cache_targets_avoid_home_dirs() {
for name in SUPPORTED_CACHES {
let (_, target, _) = known_cache(name).unwrap();
assert!(target.starts_with("/var/cache/devsandbox/"), "{name}: {target}");
}
}
#[test]
fn service_scope_defaults_to_isolated() {
let config = Config::parse("[services.db]\nimage = \"postgres:16\"").unwrap();
let svc = config.resolve_service("db").unwrap();
assert_eq!(svc.spec.scope, ServiceScope::Isolated);
}
#[test]
fn service_scope_global_parses() {
let config =
Config::parse("[services.db]\nimage = \"postgres:16\"\nscope = \"global\"").unwrap();
let svc = config.resolve_service("db").unwrap();
assert_eq!(svc.spec.scope, ServiceScope::Global);
}
#[test]
fn service_requires_image_xor_build() {
let neither = Config::parse("[services.db]\nenv = { X = \"1\" }").unwrap();
assert!(neither.resolve_service("db").unwrap_err().to_string().contains("image"));
let both = Config::parse(
"[services.db]\nimage = \"postgres:16\"\nbuild = { dockerfile = \"Dockerfile\" }",
)
.unwrap();
assert!(both.resolve_service("db").unwrap_err().to_string().contains("only one"));
}
}