//! The project's `.devcontainer/devcontainer.json` (or `.devcontainer.json`) as a //! remote host reads it: `remoteEnv` for every child process of the IDE backend and //! `postStartCommand` once per backend start. No container is built. The desktop reads //! `forwardPorts`, `hostRequirements`, `runArgs` and Compose `deploy.resources.limits` //! of a dev container it opens — always read-only, never rewriting the files. use serde::{Deserialize, Serialize}; use serde_json::Value; use specta::Type; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; /// Where the configuration may be, first match wins. const LOCATIONS: [&str; 2] = [".devcontainer/devcontainer.json", ".devcontainer.json"]; /// Minimum host / Docker VM resources declared by `hostRequirements` in `devcontainer.json`. #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct HostRequirements { /// Minimum CPU cores (`hostRequirements.cpus`). pub cpus: Option, /// Minimum memory in bytes (`hostRequirements.memory`, e.g. `"8gb"`). pub memory_bytes: Option, /// Minimum free storage in bytes (`hostRequirements.storage`, e.g. `"32gb"`). pub storage_bytes: Option, } impl HostRequirements { pub fn is_empty(&self) -> bool { self.cpus.is_none() && self.memory_bytes.is_none() && self.storage_bytes.is_none() } } /// Where a dev container's CPU / memory limit is configured. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub enum ResourceLimitSource { #[default] None, /// `runArgs` in `devcontainer.json` (`--cpus`, `--memory`, `-m`, `--cpu-quota`). DevcontainerRunArgs, /// `deploy.resources.limits` (or `cpus` / `mem_limit`) in a Docker Compose file. ComposeDeployLimits, /// The Docker daemon / VM ceiling (no per-container cap was configured). DockerVm, } /// Read-only CPU / memory limits read from `devcontainer.json` (`runArgs`) or Compose. #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct ConfiguredResourceLimits { pub cpus: Option, pub memory_bytes: Option, pub source: ResourceLimitSource, /// Path to the config file declaring the limits (`devcontainer.json` or Compose file). pub config_path: Option, } #[derive(Debug, Default, Clone, PartialEq)] pub struct DevContainer { pub path: PathBuf, /// Values as written (`None`: unset the variable), substitutions not applied. pub remote_env: BTreeMap>, pub post_start: Option, /// `forwardPorts` of the container itself (a number, `localhost:` or /// `127.0.0.1:`), in order, without duplicates. pub forward_ports: Vec, /// `forwardPorts` of another host the container reaches, such as a Compose service /// (`:`), in order, without duplicates. pub forward_host_ports: Vec<(String, u16)>, /// Minimum machine / Docker VM resources declared under `hostRequirements`. pub host_requirements: Option, /// Raw `runArgs` entries from `devcontainer.json`. pub run_args: Vec, /// Compose files declared via `dockerComposeFile` (relative to `devcontainer.json`'s folder). pub docker_compose_files: Vec, /// Compose service name declared via `service`. pub service: Option, /// Configured CPU / memory limits parsed read-only from `runArgs` or Compose. pub resource_limits: Option, } /// A lifecycle command in its three forms. #[derive(Debug, Clone, PartialEq)] pub enum LifecycleCommand { /// Run through `/bin/sh -c`. Shell(String), /// Run directly: program and arguments, no shell. Exec(Vec), /// Named commands (each a `Shell` or an `Exec`) run in parallel; all must succeed. Parallel(Vec<(String, LifecycleCommand)>), } impl LifecycleCommand { fn parse(v: &Value) -> Result, String> { Ok(match v { Value::Null => None, Value::String(s) if s.trim().is_empty() => None, Value::String(s) => Some(Self::Shell(s.clone())), Value::Array(items) => { let args: Vec = items .iter() .map(|i| i.as_str().map(str::to_owned).ok_or("array items must be strings")) .collect::>()?; (!args.is_empty()).then_some(Self::Exec(args)) } Value::Object(map) => { let mut named = Vec::new(); for (name, v) in map { match Self::parse(v)? { Some(Self::Parallel(_)) => return Err(format!("{name}: expected a string or an array")), Some(c) => named.push((name.clone(), c)), None => {} } } (!named.is_empty()).then_some(Self::Parallel(named)) } _ => return Err("expected a string, an array or an object".into()), }) } /// The single commands to run (one, or each of a `Parallel`), with their names. pub fn commands(&self) -> Vec<(Option<&str>, &LifecycleCommand)> { match self { Self::Parallel(named) => named.iter().map(|(n, c)| (Some(n.as_str()), c)).collect(), c => vec![(None, c)], } } /// Program and arguments of a `Shell` or `Exec` command (`Parallel`: `None`). pub fn argv(&self) -> Option> { match self { Self::Shell(s) => Some(vec!["/bin/sh".into(), "-c".into(), s.clone()]), Self::Exec(args) => Some(args.clone()), Self::Parallel(_) => None, } } } /// The configuration file of the project at `root`, if it has one. pub fn find(root: &Path) -> Option { LOCATIONS.iter().map(|l| root.join(l)).find(|p| p.is_file()) } /// Reads the project's configuration: `Ok(None)` without one, `Err` with a message when /// it can't be read or parsed. pub fn load(root: &Path) -> Result, String> { let Some(path) = find(root) else { return Ok(None) }; load_file(&path).map(Some) } /// Reads an explicit `config` (relative to `root` or absolute), or the project's default /// configuration when `config` is blank. pub fn load_with_config(root: &Path, config: &str) -> Result, String> { let trimmed = config.trim(); if trimmed.is_empty() { return load(root); } let candidate = Path::new(trimmed); let full = if candidate.is_absolute() { candidate.to_path_buf() } else { root.join(candidate) }; if !full.is_file() { return Ok(None); } load_file(&full).map(Some) } /// Reads the configuration at `path`, resolving any Compose resource limits read-only. pub fn load_file(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let mut config = parse(&text)?; config.path = path.to_owned(); let config_path_str = ide_core::ipc_path::to_ipc(path); if let Some(ref mut limits) = config.resource_limits && limits.config_path.is_none() { limits.config_path = Some(config_path_str.clone()); } if let Some(service) = config.service.as_deref() && !config.docker_compose_files.is_empty() { let base_dir = path.parent().unwrap_or_else(|| Path::new(".")); let mut cpus = None; let mut memory_bytes = None; let mut source_file: Option = None; for rel in &config.docker_compose_files { let compose_path = if Path::new(rel).is_absolute() { PathBuf::from(rel) } else { base_dir.join(rel) }; let Ok(yaml) = std::fs::read_to_string(&compose_path) else { continue }; let (file_cpus, file_mem) = parse_compose_service_limits(&yaml, service); if file_cpus.is_some() || file_mem.is_some() { if file_cpus.is_some() { cpus = file_cpus; } if file_mem.is_some() { memory_bytes = file_mem; } source_file = Some(ide_core::ipc_path::to_ipc(&compose_path)); } } if cpus.is_some() || memory_bytes.is_some() { config.resource_limits = Some(ConfiguredResourceLimits { cpus, memory_bytes, source: ResourceLimitSource::ComposeDeployLimits, config_path: source_file.or(Some(config_path_str)), }); } } Ok(config) } /// Parses `devcontainer.json` text (JSON with comments and trailing commas). pub fn parse(text: &str) -> Result { let json: Value = serde_json::from_str(&ide_core::jsonc::strip(text)).map_err(|e| e.to_string())?; let Value::Object(top) = json else { return Err("expected an object".into()) }; let mut config = DevContainer::default(); if let Some(env) = top.get("remoteEnv") { let Value::Object(env) = env else { return Err("remoteEnv: expected an object".into()) }; for (k, v) in env { let value = match v { Value::Null => None, Value::String(s) => Some(s.clone()), Value::Number(n) => Some(n.to_string()), Value::Bool(b) => Some(b.to_string()), _ => return Err(format!("remoteEnv.{k}: expected a string")), }; config.remote_env.insert(k.clone(), value); } } if let Some(cmd) = top.get("postStartCommand") { config.post_start = LifecycleCommand::parse(cmd).map_err(|e| format!("postStartCommand: {e}"))?; } // Only the desktop uses these: an entry it can't forward never makes the file unreadable. if let Some(Value::Array(ports)) = top.get("forwardPorts") { for entry in ports.iter().filter_map(forward_port) { match entry { (None, port) if !config.forward_ports.contains(&port) => config.forward_ports.push(port), (Some(host), port) if !config.forward_host_ports.iter().any(|(h, p)| *h == host && *p == port) => { config.forward_host_ports.push((host, port)); } _ => {} } } } if let Some(req) = top.get("hostRequirements").and_then(parse_host_requirements) { config.host_requirements = Some(req); } if let Some(Value::Array(args)) = top.get("runArgs") { config.run_args = args.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(); let (cpus, memory_bytes) = parse_run_args_limits(&config.run_args); if cpus.is_some() || memory_bytes.is_some() { config.resource_limits = Some(ConfiguredResourceLimits { cpus, memory_bytes, source: ResourceLimitSource::DevcontainerRunArgs, config_path: None, }); } } if let Some(compose) = top.get("dockerComposeFile") { match compose { Value::String(s) if !s.trim().is_empty() => config.docker_compose_files.push(s.trim().to_owned()), Value::Array(items) => { for item in items { if let Some(s) = item.as_str().map(str::trim).filter(|s| !s.is_empty()) { config.docker_compose_files.push(s.to_owned()); } } } _ => {} } } if let Some(service) = top.get("service").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) { config.service = Some(service.to_owned()); } Ok(config) } fn parse_positive_f64(v: &Value) -> Option { let n = match v { Value::Number(n) => n.as_f64()?, Value::String(s) => s.trim().parse::().ok()?, _ => return None, }; (n.is_finite() && n > 0.0).then_some(n) } fn parse_byte_value(v: &Value) -> Option { match v { Value::Number(n) => n.as_u64().filter(|&b| b > 0), Value::String(s) => parse_byte_size(s), _ => None, } } fn parse_host_requirements(v: &Value) -> Option { let obj = v.as_object()?; let req = HostRequirements { cpus: obj.get("cpus").and_then(parse_positive_f64), memory_bytes: obj.get("memory").and_then(parse_byte_value), storage_bytes: obj.get("storage").and_then(parse_byte_value), }; (!req.is_empty()).then_some(req) } /// Parses a Docker / Dev Container byte size (`"4gb"`, `"4g"`, `"512m"`, `"8GiB"`, `"1.5 GB"`, /// or a positive byte integer) using Docker's binary units (1024-based KiB/MiB/GiB/TiB). pub fn parse_byte_size(raw: &str) -> Option { let s = raw.trim(); if s.is_empty() { return None; } let split = s.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(s.len()); let (num_str, unit_raw) = s.split_at(split); if num_str.is_empty() { return None; } let num: f64 = num_str.parse().ok()?; if !num.is_finite() || num <= 0.0 { return None; } let unit = unit_raw.trim().to_ascii_lowercase(); let mult: f64 = match unit.as_str() { "" | "b" => 1.0, "k" | "kb" | "ki" | "kib" => 1024.0, "m" | "mb" | "mi" | "mib" => 1024.0 * 1024.0, "g" | "gb" | "gi" | "gib" => 1024.0 * 1024.0 * 1024.0, "t" | "tb" | "ti" | "tib" => 1024.0 * 1024.0 * 1024.0 * 1024.0, _ => return None, }; let bytes = (num * mult).round(); if !bytes.is_finite() || bytes <= 0.0 || bytes > u64::MAX as f64 { return None; } Some(bytes as u64) } /// Formats bytes for plain-language limits and messages (`4 GB`, `1.5 GB`, `512 MB`, `256 KB`). pub fn format_memory_bytes(bytes: u64) -> String { const KIB: f64 = 1024.0; const MIB: f64 = KIB * 1024.0; const GIB: f64 = MIB * 1024.0; const TIB: f64 = GIB * 1024.0; let b = bytes as f64; let (value, unit) = if b >= TIB { (b / TIB, "TB") } else if b >= GIB { (b / GIB, "GB") } else if b >= MIB { (b / MIB, "MB") } else if b >= KIB { (b / KIB, "KB") } else { return format!("{bytes} B"); }; let rounded = (value * 10.0).round() / 10.0; if (rounded.fract()).abs() < f64::EPSILON { format!("{:.0} {unit}", rounded) } else { format!("{rounded:.1} {unit}") } } /// Formats a CPU core count cleanly (`1 CPU`, `2 CPUs`, `2.5 CPUs`). pub fn format_cpus(cpus: f64) -> String { let rounded = (cpus * 100.0).round() / 100.0; let num = if (rounded - rounded.round()).abs() < 1e-6 { format!("{:.0}", rounded.round()) } else { let s = format!("{rounded:.2}"); s.trim_end_matches('0').trim_end_matches('.').to_owned() }; if (rounded - 1.0).abs() < 1e-6 { format!("{num} CPU") } else { format!("{num} CPUs") } } /// Reads `--cpus`, `--cpu-quota`/`--cpu-period`, `--memory` / `-m` from `devcontainer.json` `runArgs`. pub fn parse_run_args_limits(args: &[String]) -> (Option, Option) { let mut explicit_cpus: Option = None; let mut cpu_quota: Option = None; let mut cpu_period: Option = None; let mut memory_bytes: Option = None; let mut i = 0; while i < args.len() { let arg = args[i].trim(); let next = |idx: &mut usize| -> Option<&str> { if *idx + 1 < args.len() { *idx += 1; Some(args[*idx].trim()) } else { None } }; if let Some(val) = arg.strip_prefix("--cpus=") { if let Ok(n) = val.trim().parse::() && n.is_finite() && n > 0.0 { explicit_cpus = Some(n); } } else if arg == "--cpus" { if let Some(val) = next(&mut i) && let Ok(n) = val.parse::() && n.is_finite() && n > 0.0 { explicit_cpus = Some(n); } } else if let Some(val) = arg.strip_prefix("--cpu-quota=") { if let Ok(n) = val.trim().parse::() && n > 0 { cpu_quota = Some(n); } } else if arg == "--cpu-quota" { if let Some(val) = next(&mut i) && let Ok(n) = val.parse::() && n > 0 { cpu_quota = Some(n); } } else if let Some(val) = arg.strip_prefix("--cpu-period=") { if let Ok(n) = val.trim().parse::() && n > 0 { cpu_period = Some(n); } } else if arg == "--cpu-period" { if let Some(val) = next(&mut i) && let Ok(n) = val.parse::() && n > 0 { cpu_period = Some(n); } } else if let Some(val) = arg.strip_prefix("--memory=") { if let Some(b) = parse_byte_size(val) { memory_bytes = Some(b); } } else if arg == "--memory" || arg == "-m" { if let Some(val) = next(&mut i) && let Some(b) = parse_byte_size(val) { memory_bytes = Some(b); } } else if let Some(val) = arg.strip_prefix("-m=") { if let Some(b) = parse_byte_size(val) { memory_bytes = Some(b); } } else if let Some(val) = arg.strip_prefix("-m") && !val.is_empty() && val.as_bytes()[0].is_ascii_digit() && let Some(b) = parse_byte_size(val) { memory_bytes = Some(b); } i += 1; } let cpus = explicit_cpus.or_else(|| { let quota = cpu_quota?; let period = cpu_period.unwrap_or(100_000); (period > 0).then(|| quota as f64 / period as f64) }); (cpus, memory_bytes) } fn strip_yaml_comment(line: &str) -> &str { let mut quote: Option = None; let bytes = line.as_bytes(); let mut i = 0; while i < bytes.len() { let ch = bytes[i] as char; if let Some(q) = quote { if ch == '\\' && q == '"' { i += 2; continue; } if ch == q { quote = None; } } else if ch == '"' || ch == '\'' { quote = Some(ch); } else if ch == '#' && (i == 0 || bytes[i - 1].is_ascii_whitespace()) { return &line[..i]; } i += 1; } line } fn unquote_yaml(raw: &str) -> &str { let s = raw.trim(); s.strip_prefix('"') .and_then(|v| v.strip_suffix('"')) .or_else(|| s.strip_prefix('\'').and_then(|v| v.strip_suffix('\''))) .unwrap_or(s) } fn parse_yaml_kv(trimmed: &str) -> Option<(&str, &str)> { let colon = trimmed.find(':')?; let after = &trimmed[colon + 1..]; if !after.is_empty() && !after.starts_with(char::is_whitespace) { return None; } let key = unquote_yaml(trimmed[..colon].trim_end()); (!key.is_empty()).then_some((key, unquote_yaml(after))) } /// Reads `services..deploy.resources.limits.{cpus, memory}` (with `cpus` / `mem_limit` /// fallbacks) from a Docker Compose YAML file. Read-only. pub fn parse_compose_service_limits(yaml: &str, service: &str) -> (Option, Option) { let mut stack: Vec<(usize, String)> = Vec::new(); let mut deploy_cpus: Option = None; let mut deploy_mem: Option = None; let mut top_cpus: Option = None; let mut top_mem: Option = None; for raw_line in yaml.lines() { let code = strip_yaml_comment(raw_line.trim_end_matches('\r')); let trimmed = code.trim_start(); if trimmed.is_empty() || trimmed.starts_with('-') { continue; } let indent = code.len() - trimmed.len(); let Some((key, val)) = parse_yaml_kv(trimmed) else { continue }; while stack.last().is_some_and(|(prev_indent, _)| *prev_indent >= indent) { stack.pop(); } let path: Vec<&str> = stack.iter().map(|(_, k)| k.as_str()).chain(std::iter::once(key)).collect(); if path == ["services", service, "deploy", "resources", "limits", "cpus"] { if let Ok(n) = val.parse::() && n.is_finite() && n > 0.0 { deploy_cpus = Some(n); } } else if path == ["services", service, "deploy", "resources", "limits", "memory"] { if let Some(b) = parse_byte_size(val) { deploy_mem = Some(b); } } else if path == ["services", service, "cpus"] { if let Ok(n) = val.parse::() && n.is_finite() && n > 0.0 { top_cpus = Some(n); } } else if path == ["services", service, "mem_limit"] && let Some(b) = parse_byte_size(val) { top_mem = Some(b); } if val.is_empty() { stack.push((indent, key.to_owned())); } } (deploy_cpus.or(top_cpus), deploy_mem.or(top_mem)) } /// A `forwardPorts` entry: a port of the container itself (`None`), or of another host it /// reaches by name, such as a Compose service. fn forward_port(v: &Value) -> Option<(Option, u16)> { let (host, port) = match v { Value::Number(n) => (None, n.as_u64()?), Value::String(s) => match s.trim().split_once(':') { Some(("localhost" | "127.0.0.1", port)) => (None, port.parse().ok()?), Some((host, port)) if is_host_name(host) => (Some(host.to_owned()), port.parse().ok()?), Some(_) => return None, None => (None, s.trim().parse().ok()?), }, _ => return None, }; Some((host, u16::try_from(port).ok().filter(|p| *p != 0)?)) } /// A DNS name such as a Compose service or container name (letters, digits, `.`, `-`, `_`). fn is_host_name(host: &str) -> bool { !host.is_empty() && host.len() <= 253 && !host.starts_with(['-', '.']) && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) } /// Expands `${localEnv:NAME}`, `${containerEnv:NAME}` and `${env:NAME}` (all the remote /// host's environment, through `env`; `${…:NAME:default}` when unset), and /// `${localWorkspaceFolder}` / `${containerWorkspaceFolder}` (and their `…Basename`) to /// the project root. Unknown references stay as written. pub fn substitute(value: &str, root: &Path, env: &dyn Fn(&str) -> Option) -> String { let mut out = String::with_capacity(value.len()); let mut rest = value; while let Some(start) = rest.find("${") { out.push_str(&rest[..start]); let after = &rest[start + 2..]; let Some(end) = after.find('}') else { out.push_str(&rest[start..]); return out; }; let inner = &after[..end]; match resolve(inner, root, env) { Some(v) => out.push_str(&v), None => out.push_str(&rest[start..start + 2 + end + 1]), } rest = &after[end + 1..]; } out.push_str(rest); out } fn resolve(inner: &str, root: &Path, env: &dyn Fn(&str) -> Option) -> Option { let basename = || root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); match inner { "localWorkspaceFolder" | "containerWorkspaceFolder" => return Some(root.to_string_lossy().into_owned()), "localWorkspaceFolderBasename" | "containerWorkspaceFolderBasename" => return Some(basename()), _ => {} } let (scope, spec) = inner.split_once(':')?; if !matches!(scope, "localEnv" | "containerEnv" | "env") { return None; } let (name, default) = match spec.split_once(':') { Some((name, default)) => (name, Some(default)), None => (spec, None), }; Some(env(name).or_else(|| default.map(str::to_owned)).unwrap_or_default()) } /// `remoteEnv` with substitutions applied against `env` (the environment before it), in /// order: `None` unsets the variable. pub fn resolve_env( config: &DevContainer, root: &Path, env: &dyn Fn(&str) -> Option, ) -> Vec<(String, Option)> { config.remote_env.iter().map(|(k, v)| (k.clone(), v.as_deref().map(|v| substitute(v, root, env)))).collect() } #[cfg(test)] mod tests { use super::*; fn env(name: &str) -> Option { match name { "PATH" => Some("/usr/bin:/bin".into()), "HOME" => Some("/home/me".into()), _ => None, } } #[test] fn parses_jsonc_with_remote_env_and_post_start() { let c = parse( r#"{ // A comment "name": "demo", "remoteEnv": { "PATH": "${containerEnv:PATH}:/opt/tools/bin", "EMPTY": null, "PORT": 8080, /* numbers are text */ }, "postStartCommand": "make dev", }"#, ) .unwrap(); assert_eq!(c.remote_env.get("PATH").unwrap().as_deref(), Some("${containerEnv:PATH}:/opt/tools/bin")); assert_eq!(c.remote_env.get("EMPTY"), Some(&None)); assert_eq!(c.remote_env.get("PORT").unwrap().as_deref(), Some("8080")); assert_eq!(c.post_start, Some(LifecycleCommand::Shell("make dev".into()))); } #[test] fn forward_ports_of_the_container_only() { let c = parse( r#"{ "forwardPorts": [8000, "5173", "localhost:3000", "127.0.0.1:8000", "db:5432", 0, 70000, "x", null] }"#, ) .unwrap(); assert_eq!(c.forward_ports, [8000, 5173, 3000]); assert_eq!(c.forward_host_ports, [("db".to_owned(), 5432)]); assert!(parse(r#"{ "forwardPorts": "8000" }"#).unwrap().forward_ports.is_empty()); } #[test] fn forward_ports_of_compose_services() { let c = parse( r#"{ "forwardPorts": [8000, "selenium:4444", "selenium:7900", "selenium:4444", "my-db.local:5432", "db:0", "db:x", "-db:1", ".db:1", "d b:1", "db/x:1", "db:1:2", ":5432"] }"#, ) .unwrap(); assert_eq!(c.forward_ports, [8000]); let hosts: Vec<_> = c.forward_host_ports.iter().map(|(h, p)| format!("{h}:{p}")).collect(); assert_eq!(hosts, ["selenium:4444", "selenium:7900", "my-db.local:5432"]); } #[test] fn forward_ports_skip_malformed_entries_and_keep_valid_bounds() { let config = parse( r#"{ "remoteEnv": {"PORT": "8000"}, "forwardPorts": [1, 65535, " 8000 ", "localhost:8000", "127.0.0.1:8000", -1, 1.5, 65536, 18446744073709551616, true, false, {}, [], null, "", " ", ":80", "db:5432", "localhost:", "localhost:0", "localhost:65536", "localhost:80:90", "localhost: 80", "http://localhost:80", "::1:80"] }"#, ) .unwrap(); assert_eq!(config.forward_ports, [1, 65535, 8000]); assert_eq!(config.forward_host_ports, [("db".to_owned(), 5432)]); assert_eq!(config.remote_env["PORT"].as_deref(), Some("8000")); } #[test] fn post_start_command_forms() { let parse_cmd = |json: &str| parse(&format!(r#"{{ "postStartCommand": {json} }}"#)).map(|c| c.post_start); assert_eq!(parse_cmd(r#""echo hi""#).unwrap().unwrap().argv().unwrap(), ["/bin/sh", "-c", "echo hi"]); let exec = parse_cmd(r#"["npm", "run", "watch"]"#).unwrap().unwrap(); assert_eq!(exec, LifecycleCommand::Exec(vec!["npm".into(), "run".into(), "watch".into()])); assert_eq!(exec.argv().unwrap(), ["npm", "run", "watch"]); let parallel = parse_cmd(r#"{ "server": "npm start", "db": ["pg_ctl", "start"], "none": "" }"#).unwrap().unwrap(); let names: Vec<_> = parallel.commands().into_iter().map(|(n, _)| n.unwrap()).collect(); assert_eq!(names, ["db", "server"]); assert!(parallel.argv().is_none()); assert_eq!(parse_cmd(r#""""#).unwrap(), None); assert_eq!(parse_cmd("[]").unwrap(), None); assert!(parse_cmd("42").unwrap_err().contains("postStartCommand")); assert!(parse_cmd("[1]").is_err()); assert!(parse_cmd(r#"{ "nested": { "a": "b" } }"#).is_err()); } #[test] fn invalid_files_are_errors() { assert!(parse("{ \"remoteEnv\": [] }").unwrap_err().contains("remoteEnv")); assert!(parse("{ not json").is_err()); assert!(parse("[]").is_err()); } #[test] fn substitutes_remote_env_references() { let root = Path::new("/work/demo"); let s = |v: &str| substitute(v, root, &env); assert_eq!(s("${containerEnv:PATH}:/opt/bin"), "/usr/bin:/bin:/opt/bin"); assert_eq!(s("${localEnv:HOME}/.cache"), "/home/me/.cache"); assert_eq!(s("${env:HOME}"), "/home/me"); assert_eq!(s("${localEnv:MISSING}"), ""); assert_eq!(s("${localEnv:MISSING:fallback}"), "fallback"); assert_eq!(s("${containerWorkspaceFolder}/bin:${localWorkspaceFolderBasename}"), "/work/demo/bin:demo"); assert_eq!(s("${unknown} ${other:X} $HOME ${open"), "${unknown} ${other:X} $HOME ${open"); } #[test] fn resolves_against_the_environment_before_it() { let c = parse(r#"{ "remoteEnv": { "PATH": "/opt/bin:${containerEnv:PATH}", "GONE": null } }"#).unwrap(); let resolved = resolve_env(&c, Path::new("/p"), &env); assert_eq!( resolved, [("GONE".to_owned(), None), ("PATH".to_owned(), Some("/opt/bin:/usr/bin:/bin".to_owned()))] ); } #[test] fn finds_either_location() { let tmp = tempfile::tempdir().unwrap(); assert_eq!(load(tmp.path()).unwrap(), None); std::fs::write(tmp.path().join(".devcontainer.json"), r#"{ "postStartCommand": "a" }"#).unwrap(); assert_eq!(load(tmp.path()).unwrap().unwrap().post_start, Some(LifecycleCommand::Shell("a".into()))); std::fs::create_dir(tmp.path().join(".devcontainer")).unwrap(); std::fs::write(tmp.path().join(".devcontainer/devcontainer.json"), r#"{ "postStartCommand": "b" }"#).unwrap(); let c = load(tmp.path()).unwrap().unwrap(); assert_eq!(c.post_start, Some(LifecycleCommand::Shell("b".into()))); assert!(c.path.ends_with(".devcontainer/devcontainer.json")); } #[test] fn parses_host_requirements_and_byte_sizes() { let c = parse( r#"{ "hostRequirements": { "cpus": 4, "memory": "8gb", "storage": "32GB" } }"#, ) .unwrap(); assert_eq!( c.host_requirements, Some(HostRequirements { cpus: Some(4.0), memory_bytes: Some(8 * 1024 * 1024 * 1024), storage_bytes: Some(32 * 1024 * 1024 * 1024), }) ); assert_eq!(parse_byte_size("512m"), Some(512 * 1024 * 1024)); assert_eq!(parse_byte_size("1.5 GiB"), Some(1536 * 1024 * 1024)); assert_eq!(parse_byte_size("2048"), Some(2048)); assert_eq!(parse_byte_size("0gb"), None); assert_eq!(parse_byte_size("-4g"), None); assert_eq!(parse_byte_size("abc"), None); assert_eq!(format_memory_bytes(4 * 1024 * 1024 * 1024), "4 GB"); assert_eq!(format_memory_bytes(1536 * 1024 * 1024), "1.5 GB"); assert_eq!(format_memory_bytes(512 * 1024 * 1024), "512 MB"); assert_eq!(format_cpus(1.0), "1 CPU"); assert_eq!(format_cpus(2.0), "2 CPUs"); assert_eq!(format_cpus(2.5), "2.5 CPUs"); } #[test] fn parses_run_args_cpu_and_memory_limits() { let c = parse(r#"{ "runArgs": ["--cpus=2.5", "--memory", "4g", "--init"] }"#).unwrap(); assert_eq!( c.resource_limits, Some(ConfiguredResourceLimits { cpus: Some(2.5), memory_bytes: Some(4 * 1024 * 1024 * 1024), source: ResourceLimitSource::DevcontainerRunArgs, config_path: None, }) ); // Short `-m` flag and `--cpu-quota`/`--cpu-period` fallback, with later flags overriding earlier ones. let (cpus, mem) = parse_run_args_limits(&[ "--cpu-quota=150000".into(), "--cpu-period=100000".into(), "-m2g".into(), "-m".into(), "6gb".into(), ]); assert_eq!(cpus, Some(1.5)); assert_eq!(mem, Some(6 * 1024 * 1024 * 1024)); } #[test] fn reads_compose_deploy_resource_limits_without_modifying_files() { let tmp = tempfile::tempdir().unwrap(); let dev_dir = tmp.path().join(".devcontainer"); std::fs::create_dir(&dev_dir).unwrap(); let devcontainer_raw = r#"{ "dockerComposeFile": ["../compose.yml", "compose.override.yml"], "service": "app", "hostRequirements": { "cpus": 2, "memory": "4gb" } }"#; let base_compose = "\ services: db: image: postgres:16 deploy: resources: limits: cpus: '1' memory: 1G app: image: rust:1.80 deploy: resources: limits: cpus: '2' memory: 4G "; let override_compose = "\ services: app: deploy: resources: limits: memory: '8G' # bumped for builds "; let dc_path = dev_dir.join("devcontainer.json"); let base_path = tmp.path().join("compose.yml"); let override_path = dev_dir.join("compose.override.yml"); std::fs::write(&dc_path, devcontainer_raw).unwrap(); std::fs::write(&base_path, base_compose).unwrap(); std::fs::write(&override_path, override_compose).unwrap(); let loaded = load(tmp.path()).unwrap().unwrap(); let limits = loaded.resource_limits.expect("compose limits"); assert_eq!(limits.source, ResourceLimitSource::ComposeDeployLimits); assert_eq!(limits.cpus, Some(2.0)); assert_eq!(limits.memory_bytes, Some(8 * 1024 * 1024 * 1024)); assert!(limits.config_path.as_deref().unwrap().ends_with("compose.override.yml")); // Read-only invariant: none of the files were modified. assert_eq!(std::fs::read_to_string(&dc_path).unwrap(), devcontainer_raw); assert_eq!(std::fs::read_to_string(&base_path).unwrap(), base_compose); assert_eq!(std::fs::read_to_string(&override_path).unwrap(), override_compose); } }