use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::{Map, Value, json};
use crate::dap::session::AdapterKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestKind {
Launch,
Attach,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DebugConfig {
pub name: String,
pub type_name: String,
pub request: RequestKind,
pub source: &'static str,
pub presentation: Option<Presentation>,
raw: Map<String, Value>,
}
pub fn discover_compounds(root: &Path) -> Vec<Compound> {
let mut out: Vec<Compound> = Vec::new();
for rel in [".croft/launch.json", ".vscode/launch.json"] {
let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
continue;
};
for c in parse_compounds(&text, rel) {
if !out.iter().any(|existing| existing.name == c.name) {
out.push(c);
}
}
}
out
}
pub fn discover_configs_all(root: &Path) -> Vec<DebugConfig> {
let mut out: Vec<DebugConfig> = Vec::new();
for (rel, source) in [
(".croft/launch.json", ".croft/launch.json"),
(".vscode/launch.json", ".vscode/launch.json"),
] {
let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
continue;
};
out.extend(parse_launch_json(&text, source));
}
out
}
pub fn discover_configs(root: &Path) -> Vec<DebugConfig> {
let mut out: Vec<DebugConfig> = Vec::new();
for (rel, source) in [
(".croft/launch.json", ".croft/launch.json"),
(".vscode/launch.json", ".vscode/launch.json"),
] {
let Ok(text) = std::fs::read_to_string(root.join(rel)) else {
continue;
};
for cfg in parse_launch_json(&text, source) {
if !out.iter().any(|c| c.name == cfg.name) {
out.push(cfg);
}
}
}
out
}
pub fn parse_launch_json(text: &str, source: &'static str) -> Vec<DebugConfig> {
let Ok(v) = serde_json::from_str::<Value>(&crate::tasks::strip_jsonc(text)) else {
return Vec::new();
};
let list = match (&v, v.get("configurations")) {
(_, Some(Value::Array(a))) => a.clone(),
(Value::Array(a), _) => a.clone(),
_ => return Vec::new(),
};
list.into_iter()
.filter_map(|c| {
let obj = c.as_object()?;
let name = obj.get("name")?.as_str()?.to_string();
let type_name = obj.get("type")?.as_str()?.to_string();
let request = match obj.get("request").and_then(Value::as_str) {
Some("attach") => RequestKind::Attach,
_ => RequestKind::Launch,
};
Some(DebugConfig {
name,
type_name,
request,
source,
presentation: parse_presentation(obj),
raw: obj.clone(),
})
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Presentation {
pub hidden: bool,
pub group: Option<String>,
pub order: Option<f64>,
}
pub fn parse_presentation(obj: &Map<String, Value>) -> Option<Presentation> {
let p = obj.get("presentation")?.as_object()?;
let hidden = p.get("hidden").and_then(Value::as_bool).unwrap_or(false);
let group = p
.get("group")
.and_then(Value::as_str)
.filter(|g| !g.is_empty())
.map(str::to_string);
let order = p.get("order").and_then(Value::as_f64);
Some(Presentation {
hidden,
group,
order,
})
}
pub fn malformed_presentation_keys(obj: &Map<String, Value>) -> Vec<&'static str> {
let Some(value) = obj.get("presentation") else {
return Vec::new();
};
if value.is_null() || value == &Value::Bool(false) || value.as_str().is_some_and(str::is_empty)
{
return Vec::new();
}
let Some(p) = value.as_object() else {
return vec!["presentation"];
};
let mut out = Vec::new();
for (key, path, well_formed) in [
(
"hidden",
"presentation.hidden",
Value::is_boolean as fn(&Value) -> bool,
),
(
"group",
"presentation.group",
Value::is_string as fn(&Value) -> bool,
),
(
"order",
"presentation.order",
Value::is_number as fn(&Value) -> bool,
),
] {
if p.get(key).is_some_and(|v| !v.is_null() && !well_formed(v)) {
out.push(path);
}
}
out
}
pub fn visible_and_sorted<T>(
items: Vec<T>,
presentation: impl Fn(&T) -> Option<&Presentation>,
) -> Vec<T> {
let mut kept: Vec<T> = items
.into_iter()
.filter(|i| !presentation(i).is_some_and(|p| p.hidden))
.collect();
kept.sort_by(|a, b| {
use std::cmp::Ordering;
let (Some(first), Some(second)) = (presentation(a), presentation(b)) else {
return match (presentation(a), presentation(b)) {
(None, None) => Ordering::Equal,
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
_ => unreachable!("both-Some is handled by the outer let-else"),
};
};
match (&first.group, &second.group) {
(None, None) => compare_orders(first.order, second.order),
(None, Some(_)) => Ordering::Greater,
(Some(_), None) => Ordering::Less,
(Some(g1), Some(g2)) if g1 != g2 => g1.cmp(g2),
_ => compare_orders(first.order, second.order),
}
});
kept
}
fn compare_orders(first: Option<f64>, second: Option<f64>) -> std::cmp::Ordering {
match (first, second) {
(None, None) => std::cmp::Ordering::Equal,
(None, Some(_)) => std::cmp::Ordering::Greater,
(Some(_), None) => std::cmp::Ordering::Less,
(Some(a), Some(b)) => a.total_cmp(&b),
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Compound {
pub name: String,
pub configurations: Vec<String>,
pub pre_launch_task: Option<String>,
pub presentation: Option<Presentation>,
pub unsupported_keys: Vec<&'static str>,
pub source: &'static str,
}
impl Compound {
pub fn hidden(&self) -> bool {
self.presentation.as_ref().is_some_and(|p| p.hidden)
}
}
impl DebugConfig {
pub fn hidden(&self) -> bool {
self.presentation.as_ref().is_some_and(|p| p.hidden)
}
}
pub fn parse_compounds(text: &str, source: &'static str) -> Vec<Compound> {
let Ok(v) = serde_json::from_str::<Value>(&crate::tasks::strip_jsonc(text)) else {
return Vec::new();
};
let Some(Value::Array(list)) = v.get("compounds") else {
return Vec::new();
};
list.iter()
.filter_map(|c| {
let obj = c.as_object()?;
let name = obj.get("name")?.as_str()?.to_string();
let configurations: Vec<String> = obj
.get("configurations")?
.as_array()?
.iter()
.map(|m| match m {
Value::String(s) => Some(s.clone()),
Value::Object(o) => o.get("name")?.as_str().map(str::to_string),
_ => None,
})
.collect::<Option<Vec<String>>>()?;
if configurations.is_empty() {
return None;
}
let asks_for_something = |k: &str| match obj.get(k) {
None | Some(Value::Null) => false,
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Bool(b)) => *b,
Some(Value::Object(o)) => !o.is_empty(),
Some(_) => true,
};
let presentation = parse_presentation(obj);
let unsupported_keys: Vec<&'static str> = malformed_presentation_keys(obj);
let pre_launch_task = asks_for_something("preLaunchTask")
.then(|| obj.get("preLaunchTask").and_then(|v| v.as_str()))
.flatten()
.map(str::to_string);
Some(Compound {
name,
configurations,
source,
pre_launch_task,
presentation,
unsupported_keys,
})
})
.collect()
}
pub fn resolve_compound<'a>(
compound: &Compound,
configs: &'a [DebugConfig],
) -> Result<Vec<&'a DebugConfig>, String> {
compound
.configurations
.iter()
.map(|want| {
configs
.iter()
.find(|c| &c.name == want && c.source == compound.source)
.or_else(|| configs.iter().find(|c| &c.name == want))
.ok_or_else(|| {
format!(
"compound \"{}\" names configuration \"{}\", which no launch.json declares",
compound.name, want
)
})
})
.collect()
}
pub fn adapter_for_type(type_name: &str) -> Option<AdapterKind> {
match type_name {
"python" | "debugpy" => Some(AdapterKind::Debugpy),
"lldb" | "lldb-dap" | "cppdbg" | "codelldb" => Some(AdapterKind::LldbDap),
"node" | "pwa-node" | "node-terminal" | "javascript" => Some(AdapterKind::JsDebug),
_ => None,
}
}
#[derive(Debug, Clone)]
pub struct SubstCtx {
pub workspace_folder: PathBuf,
pub file: Option<PathBuf>,
}
pub fn substitute(input: &str, ctx: &SubstCtx) -> Result<String, String> {
let mut out = String::with_capacity(input.len());
let mut rest = input;
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 Ok(out);
};
let var = &after[..end];
out.push_str(&expand_variable(var, ctx)?);
rest = &after[end + 1..];
}
out.push_str(rest);
Ok(out)
}
fn expand_variable(var: &str, ctx: &SubstCtx) -> Result<String, String> {
let file = || {
ctx.file
.as_deref()
.ok_or_else(|| format!("${{{var}}}: no active file"))
};
match var {
"workspaceFolder" | "workspaceRoot" => {
Ok(ctx.workspace_folder.to_string_lossy().into_owned())
}
"workspaceFolderBasename" => Ok(ctx
.workspace_folder
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()),
"file" => Ok(file()?.to_string_lossy().into_owned()),
"fileBasename" => Ok(file()?
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()),
"fileBasenameNoExtension" => Ok(file()?
.file_stem()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()),
"fileDirname" => Ok(file()?
.parent()
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_default()),
"fileExtname" => Ok(file()?
.extension()
.map(|e| format!(".{}", e.to_string_lossy()))
.unwrap_or_default()),
"cwd" => Ok(ctx.workspace_folder.to_string_lossy().into_owned()),
"pathSeparator" => Ok(String::from(std::path::MAIN_SEPARATOR_STR)),
_ => {
if let Some(name) = var.strip_prefix("env:") {
return std::env::var(name)
.map_err(|_| format!("${{env:{name}}}: environment variable not set"));
}
Err(format!("${{{var}}}: unsupported substitution variable"))
}
}
}
fn substitute_value(v: &Value, ctx: &SubstCtx) -> Result<Value, String> {
Ok(match v {
Value::String(s) => Value::String(substitute(s, ctx)?),
Value::Array(a) => Value::Array(
a.iter()
.map(|x| substitute_value(x, ctx))
.collect::<Result<_, _>>()?,
),
Value::Object(o) => Value::Object(
o.iter()
.map(|(k, x)| Ok((k.clone(), substitute_value(x, ctx)?)))
.collect::<Result<_, String>>()?,
),
other => other.clone(),
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedConfig {
pub name: String,
pub kind: AdapterKind,
pub request: RequestKind,
pub program: Option<String>,
pub module: Option<String>,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
pub cwd: Option<PathBuf>,
pub pre_launch_task: Option<String>,
pub stop_on_entry: bool,
pub port: Option<u16>,
pub process_id: Option<i64>,
pub extra: Map<String, Value>,
}
const MAPPED_KEYS: &[&str] = &[
"name",
"type",
"request",
"program",
"module",
"args",
"env",
"envFile",
"cwd",
"preLaunchTask",
"stopOnEntry",
"port",
"processId",
"console",
];
pub fn resolve(cfg: &DebugConfig, ctx: &SubstCtx) -> Result<ResolvedConfig, String> {
let kind = adapter_for_type(&cfg.type_name).ok_or_else(|| {
format!(
"config \"{}\": unsupported type \"{}\" (python, lldb, and node families are supported)",
cfg.name, cfg.type_name
)
})?;
let raw = Value::Object(cfg.raw.clone());
let raw = substitute_value(&raw, ctx).map_err(|e| format!("config \"{}\": {e}", cfg.name))?;
let obj = raw.as_object().expect("substitution preserves the object");
let get_str = |key: &str| obj.get(key).and_then(Value::as_str).map(str::to_string);
let mut env: BTreeMap<String, String> = BTreeMap::new();
if let Some(env_file) = get_str("envFile") {
let path = absolute_in(&env_file, &ctx.workspace_folder);
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("config \"{}\": envFile {}: {e}", cfg.name, path.display()))?;
env.extend(parse_env_file(&text));
}
if let Some(map) = obj.get("env").and_then(Value::as_object) {
for (k, v) in map {
let val = match v {
Value::String(s) => s.clone(),
other => other.to_string(),
};
env.insert(k.clone(), val);
}
}
let args = obj
.get("args")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.map(|x| match x {
Value::String(s) => s.clone(),
other => other.to_string(),
})
.collect()
})
.unwrap_or_default();
let port = obj
.get("port")
.and_then(Value::as_u64)
.and_then(|p| u16::try_from(p).ok());
let process_id = match obj.get("processId") {
Some(Value::Number(n)) => n.as_i64(),
Some(Value::String(s)) => s.trim().parse::<i64>().ok(),
_ => None,
};
let extra: Map<String, Value> = obj
.iter()
.filter(|(k, _)| !MAPPED_KEYS.contains(&k.as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
Ok(ResolvedConfig {
name: cfg.name.clone(),
kind,
request: cfg.request,
program: get_str("program"),
module: get_str("module"),
args,
env,
cwd: get_str("cwd").map(|c| absolute_in(&c, &ctx.workspace_folder)),
pre_launch_task: get_str("preLaunchTask"),
stop_on_entry: obj
.get("stopOnEntry")
.and_then(Value::as_bool)
.unwrap_or(false),
port,
process_id,
extra,
})
}
pub fn absolute_in(path: &str, workspace_folder: &Path) -> PathBuf {
let p = PathBuf::from(path);
if p.is_absolute() {
p
} else {
workspace_folder.join(p)
}
}
pub fn parse_env_file(text: &str) -> BTreeMap<String, String> {
let mut out = BTreeMap::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim_start();
let Some((key, value)) = line.split_once('=') else {
continue;
};
let key = key.trim();
if key.is_empty() || key.contains(char::is_whitespace) {
continue;
}
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value);
out.insert(key.to_string(), value.to_string());
}
out
}
fn base_arguments(rc: &ResolvedConfig) -> Map<String, Value> {
let mut args = rc.extra.clone();
if let Some(p) = &rc.program {
args.insert("program".into(), json!(p));
}
if !rc.args.is_empty() {
args.insert("args".into(), json!(rc.args));
}
if let Some(c) = &rc.cwd {
args.insert("cwd".into(), json!(c.to_string_lossy()));
}
args.insert("stopOnEntry".into(), json!(rc.stop_on_entry));
args
}
fn request_value(command: &str, arguments: Map<String, Value>) -> Value {
json!({
"type": "request",
"command": command,
"arguments": Value::Object(arguments),
})
}
pub fn debugpy_request(rc: &ResolvedConfig, debug_venv_python: &Path) -> Value {
let mut args = base_arguments(rc);
match rc.request {
RequestKind::Launch => {
args.insert("request".into(), json!("launch"));
if let Some(m) = &rc.module {
args.insert("module".into(), json!(m));
args.remove("program");
}
if !rc.env.is_empty() {
args.insert("env".into(), json!(rc.env));
}
if !args.contains_key("python") {
args.insert(
"python".into(),
json!([debug_venv_python.to_string_lossy()]),
);
}
args.insert("console".into(), json!("internalConsole"));
if !args.contains_key("justMyCode") {
args.insert("justMyCode".into(), json!(false));
}
request_value("launch", args)
}
RequestKind::Attach => {
args.insert("request".into(), json!("attach"));
if let Some(port) = rc.port
&& !args.contains_key("connect")
{
let host = args.remove("host").unwrap_or_else(|| json!("127.0.0.1"));
args.insert("connect".into(), json!({ "host": host, "port": port }));
}
request_value("attach", args)
}
}
}
pub fn lldb_request(rc: &ResolvedConfig) -> Value {
let mut args = base_arguments(rc);
if !rc.env.is_empty() {
let pairs: Vec<String> = rc.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
args.insert("env".into(), json!(pairs));
}
match rc.request {
RequestKind::Launch => request_value("launch", args),
RequestKind::Attach => {
if let Some(pid) = rc.process_id {
args.insert("pid".into(), json!(pid));
}
args.remove("stopOnEntry");
request_value("attach", args)
}
}
}
pub fn js_request(rc: &ResolvedConfig) -> Value {
let mut args = base_arguments(rc);
args.insert("type".into(), json!("pwa-node"));
if !rc.env.is_empty() {
args.insert("env".into(), json!(rc.env));
}
match rc.request {
RequestKind::Launch => {
args.insert("request".into(), json!("launch"));
args.insert("console".into(), json!("internalConsole"));
if !args.contains_key("sourceMaps") {
args.insert("sourceMaps".into(), json!(true));
}
request_value("launch", args)
}
RequestKind::Attach => {
args.insert("request".into(), json!("attach"));
if let Some(port) = rc.port {
args.insert("port".into(), json!(port));
}
if !args.contains_key("address") {
args.insert("address".into(), json!("127.0.0.1"));
}
args.remove("stopOnEntry");
request_value("attach", args)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ctx() -> SubstCtx {
SubstCtx {
workspace_folder: PathBuf::from("/work/proj"),
file: Some(PathBuf::from("/work/proj/src/main.py")),
}
}
fn config(json_text: &str) -> DebugConfig {
parse_launch_json(json_text, ".vscode/launch.json")
.into_iter()
.next()
.expect("one config")
}
#[test]
fn parses_vscode_shape_bare_arrays_and_jsonc() {
let vscode = r#"{
// launch.json allows comments
"version": "0.2.0",
"configurations": [
{ "name": "Run API", "type": "python", "request": "launch", "program": "api.py", },
],
}"#;
let cfgs = parse_launch_json(vscode, ".vscode/launch.json");
assert_eq!(cfgs.len(), 1);
assert_eq!(cfgs[0].name, "Run API");
assert_eq!(cfgs[0].request, RequestKind::Launch);
let bare = r#"[ { "name": "A", "type": "lldb", "request": "attach", "pid": 1 } ]"#;
let cfgs = parse_launch_json(bare, ".croft/launch.json");
assert_eq!(cfgs.len(), 1);
assert_eq!(cfgs[0].request, RequestKind::Attach);
}
#[test]
fn entries_without_name_or_type_are_skipped_and_request_defaults_to_launch() {
let text = r#"{ "configurations": [
{ "type": "python", "program": "a.py" },
{ "name": "no type" },
{ "name": "ok", "type": "node", "program": "s.js" }
]}"#;
let cfgs = parse_launch_json(text, ".vscode/launch.json");
assert_eq!(cfgs.len(), 1);
assert_eq!(cfgs[0].name, "ok");
assert_eq!(cfgs[0].request, RequestKind::Launch);
}
#[test]
fn croft_file_wins_duplicate_names_and_both_files_are_read() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(
tmp.path().join(".croft/launch.json"),
r#"[ { "name": "Serve", "type": "python", "program": "croft.py" } ]"#,
)
.unwrap();
std::fs::write(
tmp.path().join(".vscode/launch.json"),
r#"{ "configurations": [
{ "name": "Serve", "type": "python", "program": "vscode.py" },
{ "name": "Worker", "type": "node", "program": "w.js" }
]}"#,
)
.unwrap();
let cfgs = discover_configs(tmp.path());
assert_eq!(cfgs.len(), 2);
assert_eq!(cfgs[0].name, "Serve");
assert_eq!(cfgs[0].source, ".croft/launch.json");
assert_eq!(cfgs[0].raw["program"], "croft.py");
assert_eq!(cfgs[1].name, "Worker");
}
#[test]
fn maps_the_three_adapter_families_and_rejects_unknown_types() {
use AdapterKind::*;
for (t, k) in [
("python", Debugpy),
("debugpy", Debugpy),
("lldb", LldbDap),
("cppdbg", LldbDap),
("node", JsDebug),
("pwa-node", JsDebug),
] {
assert_eq!(adapter_for_type(t), Some(k), "{t}");
}
assert_eq!(adapter_for_type("go"), None);
let cfg = config(r#"[{ "name": "Go", "type": "go", "program": "main.go" }]"#);
let err = resolve(&cfg, &ctx()).unwrap_err();
assert!(err.contains("unsupported type \"go\""), "{err}");
}
#[test]
fn substitutes_workspace_and_file_variables() {
let c = ctx();
assert_eq!(
substitute("${workspaceFolder}/bin", &c).unwrap(),
"/work/proj/bin"
);
assert_eq!(
substitute("${workspaceFolderBasename}", &c).unwrap(),
"proj"
);
assert_eq!(substitute("${file}", &c).unwrap(), "/work/proj/src/main.py");
assert_eq!(substitute("${fileBasename}", &c).unwrap(), "main.py");
assert_eq!(
substitute("${fileBasenameNoExtension}", &c).unwrap(),
"main"
);
assert_eq!(substitute("${fileDirname}", &c).unwrap(), "/work/proj/src");
assert_eq!(substitute("${fileExtname}", &c).unwrap(), ".py");
assert_eq!(
substitute("a ${fileBasename} b ${fileBasename}", &c).unwrap(),
"a main.py b main.py"
);
assert_eq!(substitute("plain", &c).unwrap(), "plain");
assert_eq!(substitute("odd ${file", &c).unwrap(), "odd ${file");
}
#[test]
fn env_variable_expands_and_unknowns_error_loudly() {
let c = ctx();
unsafe { std::env::set_var("CROFT_TEST_SUBST_VAR", "xyz") };
assert_eq!(
substitute("${env:CROFT_TEST_SUBST_VAR}", &c).unwrap(),
"xyz"
);
let err = substitute("${env:CROFT_TEST_UNSET_VAR}", &c).unwrap_err();
assert!(err.contains("CROFT_TEST_UNSET_VAR"), "{err}");
let err = substitute("${command:pickProcess}", &c).unwrap_err();
assert!(err.contains("command:pickProcess"), "{err}");
let no_file = SubstCtx {
workspace_folder: PathBuf::from("/w"),
file: None,
};
assert!(substitute("${fileBasename}", &no_file).is_err());
}
#[test]
fn resolve_splits_mapped_fields_and_passes_the_rest_through() {
let cfg = config(
r#"[{
"name": "API",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/api.py",
"args": ["--port", 8080],
"env": { "MODE": "dev", "RETRIES": 3 },
"cwd": "${workspaceFolder}",
"preLaunchTask": "build",
"stopOnEntry": true,
"justMyCode": true,
"subProcess": "${workspaceFolderBasename}"
}]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
assert_eq!(rc.program.as_deref(), Some("/work/proj/api.py"));
assert_eq!(rc.args, vec!["--port", "8080"]);
assert_eq!(rc.env["MODE"], "dev");
assert_eq!(rc.env["RETRIES"], "3");
assert_eq!(rc.cwd.as_deref(), Some(Path::new("/work/proj")));
assert_eq!(rc.pre_launch_task.as_deref(), Some("build"));
assert!(rc.stop_on_entry);
assert_eq!(rc.extra["justMyCode"], json!(true));
assert_eq!(rc.extra["subProcess"], json!("proj"));
assert!(!rc.extra.contains_key("program"));
}
#[test]
fn a_relative_cwd_resolves_against_the_workspace_folder() {
let cfg =
config(r#"[{ "name": "R", "type": "python", "program": "a.py", "cwd": "backend" }]"#);
let rc = resolve(&cfg, &ctx()).unwrap();
assert_eq!(rc.cwd.as_deref(), Some(Path::new("/work/proj/backend")));
let cfg =
config(r#"[{ "name": "R", "type": "python", "program": "a.py", "cwd": "/srv/app" }]"#);
let rc = resolve(&cfg, &ctx()).unwrap();
assert_eq!(rc.cwd.as_deref(), Some(Path::new("/srv/app")));
}
#[test]
fn env_file_merges_under_explicit_env() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join(".env"),
"# comment\nexport FROM_FILE=1\nSHARED=file\nQUOTED=\"a b\"\n",
)
.unwrap();
let cfg = config(
r#"[{
"name": "E", "type": "python", "program": "a.py",
"envFile": "${workspaceFolder}/.env",
"env": { "SHARED": "config" }
}]"#,
);
let c = SubstCtx {
workspace_folder: tmp.path().to_path_buf(),
file: None,
};
let rc = resolve(&cfg, &c).unwrap();
assert_eq!(rc.env["FROM_FILE"], "1");
assert_eq!(rc.env["QUOTED"], "a b");
assert_eq!(rc.env["SHARED"], "config", "explicit env wins per key");
let cfg = config(
r#"[{ "name": "E", "type": "python", "program": "a.py", "envFile": "/nope/.env" }]"#,
);
let err = resolve(&cfg, &c).unwrap_err();
assert!(err.contains("/nope/.env"), "{err}");
}
#[test]
fn debugpy_launch_request_carries_env_args_and_forces_internal_console() {
let cfg = config(
r#"[{
"name": "API", "type": "python", "program": "/p/api.py",
"args": ["--serve"], "env": { "MODE": "dev" },
"console": "integratedTerminal"
}]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["program"], "/p/api.py");
assert_eq!(req["arguments"]["args"][0], "--serve");
assert_eq!(req["arguments"]["env"]["MODE"], "dev");
assert_eq!(req["arguments"]["python"][0], "/venv/bin/python");
assert_eq!(req["arguments"]["justMyCode"], false);
assert_eq!(req["arguments"]["console"], "internalConsole");
}
#[test]
fn debugpy_module_launch_drops_program_and_attach_builds_connect() {
let cfg = config(
r#"[{ "name": "T", "type": "python", "module": "pytest", "args": ["-k", "x"] }]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
assert_eq!(req["arguments"]["module"], "pytest");
assert!(req["arguments"].get("program").is_none());
let cfg =
config(r#"[{ "name": "A", "type": "python", "request": "attach", "port": 5678 }]"#);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = debugpy_request(&rc, Path::new("/venv/bin/python"));
assert_eq!(req["command"], "attach");
assert_eq!(req["arguments"]["connect"]["port"], 5678);
assert_eq!(req["arguments"]["connect"]["host"], "127.0.0.1");
}
#[test]
fn lldb_requests_use_kv_env_and_attach_by_pid() {
let cfg = config(
r#"[{
"name": "Bin", "type": "lldb", "program": "/t/debug/app",
"args": ["--flag"], "env": { "RUST_LOG": "debug" }
}]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = lldb_request(&rc);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["program"], "/t/debug/app");
assert_eq!(req["arguments"]["env"][0], "RUST_LOG=debug");
let cfg = config(
r#"[{ "name": "At", "type": "lldb", "request": "attach", "processId": "4242" }]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
assert_eq!(rc.process_id, Some(4242), "numeric string processId parses");
let req = lldb_request(&rc);
assert_eq!(req["command"], "attach");
assert_eq!(req["arguments"]["pid"], 4242);
assert!(req["arguments"].get("stopOnEntry").is_none());
}
#[test]
fn js_requests_are_pwa_node_and_attach_by_port() {
let cfg = config(
r#"[{ "name": "S", "type": "node", "program": "/p/server.js", "sourceMaps": false }]"#,
);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = js_request(&rc);
assert_eq!(req["command"], "launch");
assert_eq!(req["arguments"]["type"], "pwa-node");
assert_eq!(
req["arguments"]["sourceMaps"], false,
"user value respected"
);
assert_eq!(req["arguments"]["console"], "internalConsole");
let cfg = config(r#"[{ "name": "A", "type": "node", "request": "attach", "port": 9229 }]"#);
let rc = resolve(&cfg, &ctx()).unwrap();
let req = js_request(&rc);
assert_eq!(req["command"], "attach");
assert_eq!(req["arguments"]["port"], 9229);
assert_eq!(req["arguments"]["address"], "127.0.0.1");
}
#[test]
fn parse_env_file_handles_comments_export_and_quotes() {
let env = parse_env_file(
"# a comment\n\nexport A=1\nB = spaced \nC='sq'\nnot a pair\nBAD KEY=x\n",
);
assert_eq!(env["A"], "1");
assert_eq!(env["B"], "spaced");
assert_eq!(env["C"], "sq");
assert!(!env.contains_key("not a pair"));
assert!(!env.contains_key("BAD KEY"));
}
#[test]
fn compound_members_may_be_folder_name_objects_as_well_as_bare_strings() {
let text = r#"{"configurations":[
{"name":"Server","type":"lldb","request":"launch"},
{"name":"Client","type":"lldb","request":"launch"}],
"compounds":[{"name":"Mixed","configurations":[
"Server",
{"folder":"web","name":"Client"}]}]}"#;
let compounds = parse_compounds(text, ".vscode/launch.json");
assert_eq!(compounds.len(), 1, "precondition: the compound parsed");
assert_eq!(
compounds[0].configurations,
vec!["Server", "Client"],
"an object member contributes its name, exactly as a bare string does"
);
}
#[test]
fn a_compound_binds_to_its_own_files_configuration_not_a_same_named_one() {
let croft = r#"{"configurations":[
{"name":"Server","type":"python","request":"launch","program":"croft.py"}]}"#;
let vscode = r#"{"configurations":[
{"name":"Server","type":"node","request":"launch","program":"vscode.js"}],
"compounds":[{"name":"VsCompound","configurations":["Server"]}]}"#;
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join(".croft")).unwrap();
std::fs::create_dir_all(tmp.path().join(".vscode")).unwrap();
std::fs::write(tmp.path().join(".croft/launch.json"), croft).unwrap();
std::fs::write(tmp.path().join(".vscode/launch.json"), vscode).unwrap();
let configs = discover_configs_all(tmp.path());
let compounds = discover_compounds(tmp.path());
assert_eq!(compounds.len(), 1, "precondition: the compound parsed");
assert_eq!(
compounds[0].source, ".vscode/launch.json",
"precondition: the compound remembers which file declared it"
);
assert_eq!(
configs.iter().filter(|c| c.name == "Server").count(),
2,
"precondition: the list resolve_compound receives still holds BOTH \
Servers — `discover_configs` would have dropped one, leaving the \
source preference nothing to prefer"
);
assert_eq!(
discover_configs(tmp.path())
.iter()
.filter(|c| c.name == "Server")
.count(),
1,
"and the picker's list drops it, which is why the two lists differ"
);
let members = resolve_compound(&compounds[0], &configs).expect("resolves");
assert_eq!(
members[0].source, ".vscode/launch.json",
"the .vscode compound binds .vscode's Server, not .croft's same-named one"
);
assert_eq!(
members[0].type_name, "node",
"which is a different adapter — binding .croft's python config here \
would debug a different program than the compound declares"
);
}
#[test]
fn a_compound_with_one_unusable_member_is_dropped_rather_than_silently_shrunk() {
let text = r#"{"configurations":[
{"name":"A","type":"lldb","request":"launch"},
{"name":"B","type":"lldb","request":"launch"}],
"compounds":[
{"name":"Partial","configurations":["A", 7, "B"]},
{"name":"Whole","configurations":["A","B"]}]}"#;
let names: Vec<String> = parse_compounds(text, ".vscode/launch.json")
.into_iter()
.map(|c| c.name)
.collect();
assert_eq!(
names,
vec!["Whole"],
"the compound with a malformed member is dropped entirely — shrinking \
it to [\"A\", \"B\"] would launch two of the three the user wrote"
);
}
#[test]
fn a_compound_with_no_usable_members_is_skipped_rather_than_listed_empty() {
let text = r#"{"configurations":[{"name":"A","type":"lldb","request":"launch"}],
"compounds":[
{"name":"Empty","configurations":[]},
{"name":"Unusable","configurations":[7, true]},
{"name":"Real","configurations":["A"]}]}"#;
let names: Vec<String> = parse_compounds(text, ".vscode/launch.json")
.into_iter()
.map(|c| c.name)
.collect();
assert_eq!(
names,
vec!["Real"],
"an empty compound and one whose members are all unusable are both dropped"
);
}
#[test]
fn discover_compounds_prefers_croft_over_vscode_for_a_duplicate_name() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
std::fs::create_dir_all(root.join(".croft")).unwrap();
std::fs::create_dir_all(root.join(".vscode")).unwrap();
std::fs::write(
root.join(".croft/launch.json"),
r#"{"configurations":[{"name":"A","type":"lldb","request":"launch"}],
"compounds":[{"name":"Both","configurations":["A"]}]}"#,
)
.unwrap();
std::fs::write(
root.join(".vscode/launch.json"),
r#"{"configurations":[{"name":"B","type":"lldb","request":"launch"}],
"compounds":[{"name":"Both","configurations":["B"]},
{"name":"VsOnly","configurations":["B"]}]}"#,
)
.unwrap();
let found = discover_compounds(root);
let names: Vec<&str> = found.iter().map(|c| c.name.as_str()).collect();
assert_eq!(
names,
vec!["Both", "VsOnly"],
"both files contribute, .croft first"
);
assert_eq!(
found[0].configurations,
vec!["A"],
"the .croft definition of a duplicate name wins, not .vscode's"
);
}
#[test]
fn compounds_are_parsed_alongside_the_configurations_they_name() {
let text = r#"{
"configurations": [
{ "name": "Server", "type": "node", "program": "s.js" },
{ "name": "Client", "type": "node", "program": "c.js" }
],
"compounds": [
{ "name": "Full Stack", "configurations": ["Server", "Client"] }
]
}"#;
let cfgs = parse_launch_json(text, ".vscode/launch.json");
assert_eq!(cfgs.len(), 2, "precondition: both configurations parsed");
let compounds = parse_compounds(text, ".vscode/launch.json");
assert_eq!(compounds.len(), 1, "the compound is found");
assert_eq!(compounds[0].name, "Full Stack");
assert_eq!(compounds[0].configurations, vec!["Server", "Client"]);
}
#[test]
fn a_compound_naming_a_missing_configuration_errors_rather_than_launching_a_subset() {
let text = r#"{
"configurations": [ { "name": "Server", "type": "node", "program": "s.js" } ],
"compounds": [ { "name": "Both", "configurations": ["Server", "Ghost"] } ]
}"#;
let cfgs = parse_launch_json(text, ".vscode/launch.json");
let compounds = parse_compounds(text, ".vscode/launch.json");
assert_eq!(compounds.len(), 1, "precondition: the compound parsed");
let err = resolve_compound(&compounds[0], &cfgs)
.expect_err("a missing member is an error, not a shorter list");
assert!(
err.contains("Ghost"),
"the error names the missing configuration, got: {err}"
);
}
#[test]
fn a_compound_key_that_requests_nothing_is_not_recorded_as_unsupported() {
let text = r#"{
"configurations": [ { "name": "A", "type": "node", "program": "a.js" } ],
"compounds": [
{ "name": "DefaultStopAll", "configurations": ["A"], "stopAll": false },
{ "name": "TrueStopAll", "configurations": ["A"], "stopAll": true },
{ "name": "NulledTask", "configurations": ["A"], "preLaunchTask": null },
{ "name": "EmptyTask", "configurations": ["A"], "preLaunchTask": "" },
{ "name": "EmptyPresentation", "configurations": ["A"], "presentation": {} },
{ "name": "RealPresentation", "configurations": ["A"], "presentation": { "order": 1 } },
{ "name": "Malformed", "configurations": ["A"], "presentation": 7 }
]
}"#;
let cs = parse_compounds(text, ".vscode/launch.json");
assert_eq!(cs.len(), 7, "precondition: every compound parsed");
let by = |n: &str| {
cs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
};
assert!(
by("DefaultStopAll").unsupported_keys.is_empty(),
"stopAll:false is VS Code's default and cannot change a one-member \
outcome: {:?}",
by("DefaultStopAll").unsupported_keys
);
assert!(
by("TrueStopAll").unsupported_keys.is_empty(),
"nor can stopAll:true — with one session there are no others to \
stop: {:?}",
by("TrueStopAll").unsupported_keys
);
assert!(
by("NulledTask").unsupported_keys.is_empty(),
"a null preLaunchTask asks for nothing: {:?}",
by("NulledTask").unsupported_keys
);
assert!(
by("EmptyTask").unsupported_keys.is_empty(),
"nor does an empty one: {:?}",
by("EmptyTask").unsupported_keys
);
assert!(
by("EmptyPresentation").unsupported_keys.is_empty(),
"nor an empty presentation object: {:?}",
by("EmptyPresentation").unsupported_keys
);
assert_eq!(
by("Malformed").unsupported_keys,
vec!["presentation"],
"and a shape croft cannot act on is still recorded"
);
assert_eq!(
by("RealPresentation").unsupported_keys,
Vec::<&str>::new(),
"while a well-formed order is honoured rather than refused"
);
}
#[test]
fn a_compounds_pre_launch_task_is_captured_and_no_longer_unsupported() {
let text = r#"{
"configurations": [ { "name": "A", "type": "node", "program": "a.js" } ],
"compounds": [
{ "name": "Builds", "configurations": ["A"], "preLaunchTask": "build" },
{ "name": "Nulled", "configurations": ["A"], "preLaunchTask": null },
{ "name": "Empty", "configurations": ["A"], "preLaunchTask": "" },
{ "name": "Presents", "configurations": ["A"], "presentation": { "order": 1 } }
]
}"#;
let cs = parse_compounds(text, ".vscode/launch.json");
let by = |n: &str| {
cs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
};
assert_eq!(
by("Builds").pre_launch_task.as_deref(),
Some("build"),
"the task's NAME is what running it needs; the key alone cannot"
);
assert!(
by("Builds").unsupported_keys.is_empty(),
"preLaunchTask is honoured now, so it must stop being a refusal reason: {:?}",
by("Builds").unsupported_keys
);
assert_eq!(by("Nulled").pre_launch_task, None);
assert_eq!(by("Empty").pre_launch_task, None);
assert!(
by("Presents").unsupported_keys.is_empty(),
"order is honoured now and must stop refusing: {:?}",
by("Presents").unsupported_keys
);
assert_eq!(
by("Presents").presentation.as_ref().and_then(|p| p.order),
Some(1.0),
"the order's VALUE is what sorting needs; tolerating the key cannot"
);
assert_eq!(by("Presents").pre_launch_task, None);
}
#[test]
fn presentation_keys_are_honoured_and_only_unreadable_values_refuse() {
let text = r#"{
"compounds": [
{ "name": "Hid", "configurations": ["A"], "presentation": { "hidden": true } },
{ "name": "Shown", "configurations": ["A"], "presentation": { "hidden": false } },
{ "name": "Grouped", "configurations": ["A"], "presentation": { "group": "g" } },
{ "name": "Ordered", "configurations": ["A"], "presentation": { "order": 2 } },
{ "name": "Both", "configurations": ["A"],
"presentation": { "hidden": true, "order": 1 } },
{ "name": "Empty", "configurations": ["A"], "presentation": {} }
]
}"#;
let cs = parse_compounds(text, "test");
let by = |n: &str| cs.iter().find(|c| c.name == n).expect("compound present");
assert!(by("Hid").hidden(), "hidden: true asks not to be listed");
assert!(
!by("Shown").hidden(),
"hidden: false is the default, spelled out"
);
assert!(
!by("Empty").hidden(),
"an empty presentation asks for nothing"
);
assert!(
by("Hid").unsupported_keys.is_empty(),
"hidden alone is honoured, so nothing is unsupported: {:?}",
by("Hid").unsupported_keys
);
assert!(
by("Empty").unsupported_keys.is_empty(),
"an empty presentation refuses nothing"
);
assert!(
by("Grouped").unsupported_keys.is_empty(),
"group no longer refuses: {:?}",
by("Grouped").unsupported_keys
);
assert_eq!(
by("Grouped")
.presentation
.as_ref()
.and_then(|p| p.group.clone()),
Some(String::from("g")),
"and its VALUE is what places the row"
);
assert!(by("Ordered").unsupported_keys.is_empty());
assert_eq!(
by("Ordered").presentation.as_ref().and_then(|p| p.order),
Some(2.0)
);
let bad = parse_compounds(
r#"{
"compounds": [
{ "name": "QuotedBool", "configurations": ["A"],
"presentation": { "hidden": "true" } },
{ "name": "NotAnObject", "configurations": ["A"],
"presentation": "grouped" }
]
}"#,
"test",
);
let bad_by = |n: &str| bad.iter().find(|c| c.name == n).expect("present");
assert!(
!bad_by("QuotedBool").hidden(),
"a quoted bool is not a bool"
);
assert_eq!(
bad_by("QuotedBool").unsupported_keys,
vec!["presentation.hidden"],
"and it refuses rather than launching unhidden in silence"
);
assert_eq!(
bad_by("NotAnObject").unsupported_keys,
vec!["presentation"],
"a non-object presentation refuses under its own name"
);
assert!(by("Both").hidden(), "Both asks to be hidden");
assert!(
by("Both").unsupported_keys.is_empty(),
"and both halves are honoured now, so nothing refuses: {:?}",
by("Both").unsupported_keys
);
}
#[test]
fn a_malformed_presentation_value_refuses_whichever_key_it_is_on() {
let cs = parse_compounds(
r#"{
"compounds": [
{ "name": "QuotedOrder", "configurations": ["A"],
"presentation": { "order": "1" } },
{ "name": "NumberGroup", "configurations": ["A"],
"presentation": { "group": 7 } },
{ "name": "FractionalOrder", "configurations": ["A"],
"presentation": { "order": 1.5 } },
{ "name": "NulledKeys", "configurations": ["A"],
"presentation": { "group": null, "order": null } }
]
}"#,
".vscode/launch.json",
);
assert_eq!(cs.len(), 4, "precondition: every compound parsed");
let by = |n: &str| {
cs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
};
assert_eq!(
by("QuotedOrder").unsupported_keys,
vec!["presentation.order"]
);
assert_eq!(
by("NumberGroup").unsupported_keys,
vec!["presentation.group"]
);
assert!(
by("FractionalOrder").unsupported_keys.is_empty(),
"a fractional order is a position, not a mistake: {:?}",
by("FractionalOrder").unsupported_keys
);
assert_eq!(
by("FractionalOrder")
.presentation
.as_ref()
.and_then(|p| p.order),
Some(1.5)
);
assert!(
by("NulledKeys").unsupported_keys.is_empty(),
"null asks for nothing: {:?}",
by("NulledKeys").unsupported_keys
);
}
#[test]
fn presentation_sorts_the_picker_the_way_vs_code_does() {
fn p(group: Option<&str>, order: Option<f64>) -> Option<Presentation> {
Some(Presentation {
hidden: false,
group: group.map(str::to_string),
order,
})
}
let items: Vec<(&str, Option<Presentation>)> = vec![
("plain-first", None),
("b-group", p(Some("b"), None)),
("no-group-ord-2", p(None, Some(2.0))),
(
"hidden",
Some(Presentation {
hidden: true,
group: None,
order: None,
}),
),
("a-group-ord-9", p(Some("a"), Some(9.0))),
("plain-second", None),
("a-group-ord-1", p(Some("a"), Some(1.0))),
("a-group-no-ord", p(Some("a"), None)),
("no-group-ord-1", p(None, Some(1.0))),
];
let sorted: Vec<&str> = visible_and_sorted(items, |(_, p)| p.as_ref())
.into_iter()
.map(|(n, _)| n)
.collect();
assert_eq!(
sorted,
vec![
"a-group-ord-1",
"a-group-ord-9",
"a-group-no-ord",
"b-group",
"no-group-ord-1",
"no-group-ord-2",
"plain-first",
"plain-second",
],
"hidden is dropped, and every other rule is VS Code's"
);
}
#[test]
fn an_empty_presentation_block_still_outranks_no_block() {
let cfgs = parse_launch_json(
r#"{ "configurations": [
{ "name": "Bare", "type": "node", "program": "a.js" },
{ "name": "EmptyBlock", "type": "node", "program": "b.js",
"presentation": {} },
{ "name": "OnlyShown", "type": "node", "program": "c.js",
"presentation": { "hidden": false } }
] }"#,
".vscode/launch.json",
);
let by = |n: &str| {
cfgs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
.clone()
};
assert_eq!(by("Bare").presentation, None, "no block is no block");
assert_eq!(
by("EmptyBlock").presentation,
Some(Presentation::default()),
"an empty block asks for nothing but is still declared"
);
assert_eq!(by("OnlyShown").presentation, Some(Presentation::default()));
let sorted: Vec<String> = visible_and_sorted(cfgs, |c| c.presentation.as_ref())
.into_iter()
.map(|c| c.name)
.collect();
assert_eq!(
sorted,
vec!["EmptyBlock", "OnlyShown", "Bare"],
"both declared blocks sort ahead of the bare entry, in file order"
);
}
#[test]
fn a_presentation_that_requests_nothing_is_not_a_refusal() {
let cs = parse_compounds(
r#"{
"compounds": [
{ "name": "FalseBlock", "configurations": ["A"], "presentation": false },
{ "name": "EmptyString", "configurations": ["A"], "presentation": "" },
{ "name": "NulledBlock", "configurations": ["A"], "presentation": null },
{ "name": "Truthy", "configurations": ["A"], "presentation": true }
]
}"#,
".vscode/launch.json",
);
assert_eq!(cs.len(), 4, "precondition: every compound parsed");
let by = |n: &str| {
cs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
};
for name in ["FalseBlock", "EmptyString", "NulledBlock"] {
assert!(
by(name).unsupported_keys.is_empty(),
"{name} asks for nothing and must launch: {:?}",
by(name).unsupported_keys
);
}
assert_eq!(
by("Truthy").unsupported_keys,
vec!["presentation"],
"a non-object that asks for something is unreadable"
);
}
#[test]
fn a_workspace_with_no_presentation_keeps_its_file_order() {
let items: Vec<(&str, Option<Presentation>)> = vec![("z", None), ("a", None), ("m", None)];
let sorted: Vec<&str> = visible_and_sorted(items, |(_, p)| p.as_ref())
.into_iter()
.map(|(n, _)| n)
.collect();
assert_eq!(
sorted,
vec!["z", "a", "m"],
"sorting must be stable, or introducing the feature would silently \
reorder every existing workspace's picker"
);
}
#[test]
fn a_configuration_reads_presentation_like_a_compound_does() {
let cfgs = parse_launch_json(
r#"{ "configurations": [
{ "name": "Plain", "type": "node", "program": "a.js" },
{ "name": "Grouped", "type": "node", "program": "b.js",
"presentation": { "group": "servers", "order": 3 } },
{ "name": "Hid", "type": "node", "program": "c.js",
"presentation": { "hidden": true } }
] }"#,
".vscode/launch.json",
);
let by = |n: &str| {
cfgs.iter()
.find(|c| c.name == n)
.unwrap_or_else(|| panic!("{n} parsed"))
.clone()
};
assert_eq!(by("Plain").presentation, None, "no block asks for nothing");
assert_eq!(
by("Grouped").presentation,
Some(Presentation {
hidden: false,
group: Some(String::from("servers")),
order: Some(3.0),
})
);
assert!(by("Hid").presentation.is_some_and(|p| p.hidden));
}
#[test]
fn a_resolved_compound_yields_its_members_in_declaration_order() {
let text = r#"{
"configurations": [
{ "name": "Client", "type": "node", "program": "c.js" },
{ "name": "Server", "type": "node", "program": "s.js" }
],
"compounds": [ { "name": "Both", "configurations": ["Server", "Client"] } ]
}"#;
let cfgs = parse_launch_json(text, ".vscode/launch.json");
let compounds = parse_compounds(text, ".vscode/launch.json");
let members = resolve_compound(&compounds[0], &cfgs).unwrap();
assert_eq!(
members.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(),
vec!["Server", "Client"],
"compound order wins over the order in `configurations`"
);
}
}