Skip to main content

xbp_cli/utils/
mod.rs

1//! utility functions for xbp cli
2//!
3//! provides utility modules for common operations
4//! includes version api integration and other helper functions
5
6pub mod version;
7
8pub use version::{fetch_version, increment_version};
9
10use serde::de::DeserializeOwned;
11use serde_json::{Map, Value};
12use std::collections::{BTreeMap, HashMap, HashSet};
13use std::fs;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16use sysinfo::{Pid, System};
17
18use crate::profile::find_all_xbp_projects;
19
20#[derive(Debug, Clone)]
21pub struct FoundXbpConfig {
22    pub project_root: PathBuf,
23    pub config_path: PathBuf,
24    pub kind: &'static str,
25    pub location: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct KnownXbpProject {
30    pub root: PathBuf,
31    pub name: String,
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Eq)]
35pub struct ListeningPortOwnership {
36    pub pids: Vec<u32>,
37    pub xbp_projects: Vec<String>,
38}
39
40pub fn default_project_yaml_config_path(project_root: &Path) -> PathBuf {
41    project_root.join(".xbp").join("xbp.yaml")
42}
43
44pub fn find_existing_yaml_xbp_config(project_root: &Path) -> Option<PathBuf> {
45    let candidates = [
46        project_root.join(".xbp").join("xbp.yaml"),
47        project_root.join(".xbp").join("xbp.yml"),
48        project_root.join("xbp.yaml"),
49        project_root.join("xbp.yml"),
50    ];
51
52    candidates.into_iter().find(|candidate| candidate.exists())
53}
54
55pub fn maybe_auto_convert_legacy_xbp_json_to_yaml(
56    project_root: &Path,
57    config_path: &Path,
58) -> Result<Option<PathBuf>, String> {
59    if config_path.file_name() != Some(std::ffi::OsStr::new("xbp.json")) {
60        return Ok(None);
61    }
62
63    if !config_path.exists() {
64        return Ok(None);
65    }
66
67    if let Some(existing_yaml) = find_existing_yaml_xbp_config(project_root) {
68        return Ok(Some(existing_yaml));
69    }
70
71    let content = fs::read_to_string(config_path).map_err(|e| {
72        format!(
73            "Failed to read legacy JSON config {}: {}",
74            config_path.display(),
75            e
76        )
77    })?;
78    let value: Value = serde_json::from_str(&content)
79        .map_err(|e| format!("Failed to parse legacy JSON config: {}", e))?;
80
81    let yaml_path = default_project_yaml_config_path(project_root);
82    if let Some(parent) = yaml_path.parent() {
83        fs::create_dir_all(parent).map_err(|e| {
84            format!(
85                "Failed to create config directory {}: {}",
86                parent.display(),
87                e
88            )
89        })?;
90    }
91
92    let yaml = serde_yaml::to_string(&value)
93        .map_err(|e| format!("Failed to serialize YAML config: {}", e))?;
94    fs::write(&yaml_path, yaml)
95        .map_err(|e| format!("Failed to write YAML config {}: {}", yaml_path.display(), e))?;
96
97    Ok(Some(yaml_path))
98}
99
100pub fn write_json_config_from_any_xbp_config(
101    config_path: &Path,
102    output_json_path: &Path,
103) -> Result<(), String> {
104    let content = fs::read_to_string(config_path)
105        .map_err(|e| format!("Failed to read config {}: {}", config_path.display(), e))?;
106
107    let kind = if config_path
108        .extension()
109        .and_then(|ext| ext.to_str())
110        .map(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
111        .unwrap_or(false)
112    {
113        "yaml"
114    } else {
115        "json"
116    };
117
118    let value = if kind == "yaml" {
119        let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content)
120            .map_err(|e| format!("Failed to parse YAML config: {}", e))?;
121        serde_json::to_value(yaml_value)
122            .map_err(|e| format!("Failed to convert YAML config to JSON value: {}", e))?
123    } else {
124        serde_json::from_str::<Value>(&content)
125            .map_err(|e| format!("Failed to parse JSON config: {}", e))?
126    };
127
128    if let Some(parent) = output_json_path.parent() {
129        fs::create_dir_all(parent).map_err(|e| {
130            format!(
131                "Failed to create config directory {}: {}",
132                parent.display(),
133                e
134            )
135        })?;
136    }
137
138    let rendered = serde_json::to_string_pretty(&value)
139        .map_err(|e| format!("Failed to serialize JSON config: {}", e))?;
140    fs::write(output_json_path, rendered).map_err(|e| {
141        format!(
142            "Failed to write JSON config {}: {}",
143            output_json_path.display(),
144            e
145        )
146    })?;
147
148    Ok(())
149}
150
151pub fn find_xbp_config_upwards(start_dir: &Path) -> Option<FoundXbpConfig> {
152    for dir in start_dir.ancestors() {
153        let candidates: [(PathBuf, &'static str); 6] = [
154            (dir.join(".xbp").join("xbp.yaml"), "yaml"),
155            (dir.join(".xbp").join("xbp.yml"), "yaml"),
156            (dir.join(".xbp").join("xbp.json"), "json"),
157            (dir.join("xbp.yaml"), "yaml"),
158            (dir.join("xbp.yml"), "yaml"),
159            (dir.join("xbp.json"), "json"),
160        ];
161
162        for (path, kind) in candidates {
163            if !path.exists() {
164                continue;
165            }
166
167            let project_root = path
168                .parent()
169                .and_then(|p| {
170                    if p.file_name() == Some(std::ffi::OsStr::new(".xbp")) {
171                        p.parent().map(|pp| pp.to_path_buf())
172                    } else {
173                        Some(p.to_path_buf())
174                    }
175                })
176                .unwrap_or_else(|| dir.to_path_buf());
177
178            let location = path
179                .strip_prefix(&project_root)
180                .ok()
181                .map(|p| p.to_string_lossy().replace('\\', "/"))
182                .unwrap_or_else(|| path.to_string_lossy().replace('\\', "/"));
183
184            return Some(FoundXbpConfig {
185                project_root,
186                config_path: path,
187                kind,
188                location,
189            });
190        }
191    }
192
193    None
194}
195
196pub fn collect_known_xbp_projects() -> Vec<KnownXbpProject> {
197    let mut projects = Vec::new();
198    let mut seen_roots = HashSet::new();
199
200    for project in find_all_xbp_projects() {
201        let root = canonicalize_or_fallback(&project.path);
202        if seen_roots.insert(root.clone()) {
203            projects.push(KnownXbpProject {
204                root,
205                name: project.name,
206            });
207        }
208    }
209
210    if let Ok(current_dir) = std::env::current_dir() {
211        if let Some(found) = find_xbp_config_upwards(&current_dir) {
212            let root = canonicalize_or_fallback(&found.project_root);
213            if seen_roots.insert(root.clone()) {
214                let name = root
215                    .file_name()
216                    .and_then(|value| value.to_str())
217                    .unwrap_or("current")
218                    .to_string();
219                projects.push(KnownXbpProject { root, name });
220            }
221        }
222    }
223
224    projects.sort_by(|left, right| {
225        right
226            .root
227            .components()
228            .count()
229            .cmp(&left.root.components().count())
230            .then_with(|| left.name.cmp(&right.name))
231    });
232    projects
233}
234
235pub fn resolve_xbp_project_for_path(
236    candidate: &Path,
237    known_projects: &[KnownXbpProject],
238) -> Option<String> {
239    if candidate.as_os_str().is_empty() {
240        return None;
241    }
242
243    if let Some(found) = find_xbp_config_upwards(candidate) {
244        let found_root = canonicalize_or_fallback(&found.project_root);
245        if let Some(project) = known_projects
246            .iter()
247            .find(|project| canonicalize_or_fallback(&project.root) == found_root)
248        {
249            return Some(project.name.clone());
250        }
251
252        return found_root
253            .file_name()
254            .and_then(|value| value.to_str())
255            .map(|value| value.to_string());
256    }
257
258    let candidate_path = canonicalize_or_fallback(candidate);
259    known_projects
260        .iter()
261        .find(|project| candidate_path.starts_with(canonicalize_or_fallback(&project.root)))
262        .map(|project| project.name.clone())
263}
264
265pub fn collect_listening_port_ownership() -> Result<BTreeMap<u16, ListeningPortOwnership>, String> {
266    use netstat2::{get_sockets_info, AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo};
267
268    let af_flags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6;
269    let proto_flags = ProtocolFlags::TCP;
270    let sockets = get_sockets_info(af_flags, proto_flags)
271        .map_err(|e| format!("Failed to get sockets info: {}", e))?;
272
273    let mut system = System::new_all();
274    system.refresh_all();
275    let known_projects = collect_known_xbp_projects();
276    let mut pid_project_cache: HashMap<u32, Option<String>> = HashMap::new();
277    let mut ports: BTreeMap<u16, ListeningPortOwnership> = BTreeMap::new();
278
279    for socket in sockets {
280        if let ProtocolSocketInfo::Tcp(tcp) = socket.protocol_socket_info {
281            let state = format!("{:?}", tcp.state);
282            if state != "Listen" && state != "LISTEN" {
283                continue;
284            }
285
286            let row = ports.entry(tcp.local_port).or_default();
287            for pid in socket.associated_pids {
288                row.pids.push(pid);
289                if let Some(project) = pid_project_cache
290                    .entry(pid)
291                    .or_insert_with(|| resolve_xbp_project_for_pid(pid, &system, &known_projects))
292                    .clone()
293                {
294                    row.xbp_projects.push(project);
295                }
296            }
297        }
298    }
299
300    for row in ports.values_mut() {
301        row.pids.sort_unstable();
302        row.pids.dedup();
303        row.xbp_projects.sort();
304        row.xbp_projects.dedup();
305    }
306
307    Ok(ports)
308}
309
310fn resolve_xbp_project_for_pid(
311    pid: u32,
312    system: &System,
313    known_projects: &[KnownXbpProject],
314) -> Option<String> {
315    let process = system.process(Pid::from_u32(pid))?;
316
317    if let Some(project) = process
318        .cwd()
319        .and_then(|path| resolve_xbp_project_for_path(path, known_projects))
320    {
321        return Some(project);
322    }
323
324    process
325        .exe()
326        .and_then(|path| path.parent())
327        .and_then(|path| resolve_xbp_project_for_path(path, known_projects))
328}
329
330fn canonicalize_or_fallback(path: &Path) -> PathBuf {
331    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
332}
333
334pub fn expand_home_in_string(input: &str) -> String {
335    let home = dirs::home_dir()
336        .unwrap_or_else(|| std::path::PathBuf::from("."))
337        .to_string_lossy()
338        .to_string();
339
340    if input == "~" {
341        return home;
342    }
343
344    if let Some(rest) = input
345        .strip_prefix("~/")
346        .or_else(|| input.strip_prefix("~\\"))
347    {
348        return format!("{}{}{}", home, std::path::MAIN_SEPARATOR, rest);
349    }
350
351    if let Some(rest) = input
352        .strip_prefix("$HOME/")
353        .or_else(|| input.strip_prefix("$HOME\\"))
354    {
355        return format!("{}{}{}", home, std::path::MAIN_SEPARATOR, rest);
356    }
357
358    if let Some(rest) = input
359        .strip_prefix("${HOME}/")
360        .or_else(|| input.strip_prefix("${HOME}\\"))
361    {
362        return format!("{}{}{}", home, std::path::MAIN_SEPARATOR, rest);
363    }
364
365    input.to_string()
366}
367
368pub fn collapse_home_to_env(input: &str) -> String {
369    let home = dirs::home_dir()
370        .unwrap_or_else(|| std::path::PathBuf::from("."))
371        .to_string_lossy()
372        .to_string();
373
374    if input == home {
375        return "$HOME".to_string();
376    }
377
378    if let Some(rest) = input.strip_prefix(&(home.clone() + "/")) {
379        return format!("$HOME/{}", rest);
380    }
381
382    if let Some(rest) = input.strip_prefix(&(home.clone() + "\\")) {
383        return format!("$HOME\\{}", rest);
384    }
385
386    input.to_string()
387}
388
389pub fn command_exists(program: &str) -> bool {
390    let Some(path_var) = std::env::var_os("PATH") else {
391        return false;
392    };
393
394    for dir in std::env::split_paths(&path_var) {
395        let candidate = dir.join(program);
396        if candidate.is_file() {
397            return true;
398        }
399
400        #[cfg(windows)]
401        for ext in ["exe", "cmd", "bat"] {
402            let candidate = dir.join(format!("{}.{}", program, ext));
403            if candidate.is_file() {
404                return true;
405            }
406        }
407    }
408
409    false
410}
411
412pub fn git_remote_url_from_metadata(
413    project_root: &Path,
414    remote: &str,
415) -> Result<Option<String>, String> {
416    let Some(git_dir) = resolve_git_dir(project_root)? else {
417        return Ok(None);
418    };
419
420    let config_path = git_dir.join("config");
421    if !config_path.exists() {
422        return Ok(None);
423    }
424
425    let content = fs::read_to_string(&config_path)
426        .map_err(|e| format!("Failed to read git config {}: {}", config_path.display(), e))?;
427
428    Ok(parse_git_remote_url_from_config(&content, remote))
429}
430
431pub fn parse_github_repo_from_remote_url(url: &str) -> Option<(String, String)> {
432    let normalized: &str = url.trim();
433
434    let repo_path: String = if let Some(path) = normalized.strip_prefix("git@github.com:") {
435        path.to_string()
436    } else if let Some(path) = parse_github_https_repo_path(normalized) {
437        path
438    } else if let Some(path) = normalized.strip_prefix("ssh://git@github.com/") {
439        path.to_string()
440    } else {
441        return None;
442    };
443
444    let cleaned: &str = repo_path.trim_end_matches('/').trim_end_matches(".git");
445    let mut segments: std::str::Split<'_, char> = cleaned.split('/');
446    let owner: &str = segments.next()?.trim();
447    let repo: &str = segments.next()?.trim();
448    if owner.is_empty() || repo.is_empty() || segments.next().is_some() {
449        return None;
450    }
451
452    Some((owner.to_string(), repo.to_string()))
453}
454
455pub fn redact_remote_url_credentials(url: &str) -> String {
456    if !url.contains('@') || !url.contains("://") {
457        return url.to_string();
458    }
459    let mut parsed: reqwest::Url = match reqwest::Url::parse(url) {
460        Ok(value) => value,
461        Err(_) => return url.to_string(),
462    };
463    if parsed.password().is_some() {
464        let _ = parsed.set_password(Some("REDACTED"));
465    }
466    if !parsed.username().is_empty() {
467        let _ = parsed.set_username("REDACTED");
468    }
469    parsed.to_string()
470}
471
472fn resolve_git_dir(project_root: &Path) -> Result<Option<PathBuf>, String> {
473    let dot_git = project_root.join(".git");
474    if dot_git.is_dir() {
475        return Ok(Some(dot_git));
476    }
477
478    if !dot_git.exists() {
479        return Ok(None);
480    }
481
482    let content = fs::read_to_string(&dot_git)
483        .map_err(|e| format!("Failed to read git metadata {}: {}", dot_git.display(), e))?;
484    let git_dir = content
485        .lines()
486        .find_map(|line| line.trim().strip_prefix("gitdir:").map(str::trim))
487        .filter(|value| !value.is_empty())
488        .ok_or_else(|| format!("Failed to parse gitdir pointer from {}", dot_git.display()))?;
489
490    let git_dir_path = PathBuf::from(git_dir);
491    let resolved = if git_dir_path.is_absolute() {
492        git_dir_path
493    } else {
494        dot_git.parent().unwrap_or(project_root).join(git_dir_path)
495    };
496
497    Ok(Some(resolved))
498}
499
500fn parse_git_remote_url_from_config(content: &str, remote: &str) -> Option<String> {
501    let expected_quoted = format!(r#"remote "{}""#, remote);
502    let expected_dotted = format!("remote.{}", remote);
503    let mut in_target_section = false;
504
505    for line in content.lines() {
506        let trimmed = line.trim();
507        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
508            continue;
509        }
510
511        if trimmed.starts_with('[') && trimmed.ends_with(']') {
512            let section = trimmed.trim_start_matches('[').trim_end_matches(']').trim();
513            in_target_section = section.eq_ignore_ascii_case(&expected_quoted)
514                || section.eq_ignore_ascii_case(&expected_dotted);
515            continue;
516        }
517
518        if !in_target_section {
519            continue;
520        }
521
522        let Some((key, value)) = trimmed.split_once('=') else {
523            continue;
524        };
525        if key.trim().eq_ignore_ascii_case("url") {
526            let value = value.trim();
527            if !value.is_empty() {
528                return Some(value.to_string());
529            }
530        }
531    }
532
533    None
534}
535
536fn parse_github_https_repo_path(url: &str) -> Option<String> {
537    let parsed: reqwest::Url = reqwest::Url::parse(url).ok()?;
538    if !matches!(parsed.scheme(), "http" | "https") {
539        return None;
540    }
541    if parsed.host_str()?.eq_ignore_ascii_case("github.com") {
542        return Some(parsed.path().trim_start_matches('/').to_string());
543    }
544    None
545}
546
547pub fn first_available_command(candidates: &[&str]) -> Option<String> {
548    candidates
549        .iter()
550        .find(|candidate| command_exists(candidate))
551        .map(|candidate| (*candidate).to_string())
552}
553
554pub fn preferred_python_command() -> String {
555    first_available_command(&["python3", "python"]).unwrap_or_else(|| {
556        if cfg!(target_os = "windows") {
557            "python".to_string()
558        } else {
559            "python3".to_string()
560        }
561    })
562}
563
564pub fn preferred_pip_command() -> String {
565    first_available_command(&["pip3", "pip"]).unwrap_or_else(|| {
566        if cfg!(target_os = "windows") {
567            "pip".to_string()
568        } else {
569            "pip3".to_string()
570        }
571    })
572}
573
574pub fn open_with_default_handler(target: &str) -> Result<(), String> {
575    let mut command = if cfg!(target_os = "windows") {
576        let mut cmd = Command::new("cmd");
577        cmd.arg("/C").arg("start").arg("").arg(target);
578        cmd
579    } else if cfg!(target_os = "macos") {
580        let mut cmd = Command::new("open");
581        cmd.arg(target);
582        cmd
583    } else {
584        let mut cmd = Command::new("xdg-open");
585        cmd.arg(target);
586        cmd
587    };
588
589    command
590        .spawn()
591        .map_err(|e| format!("Failed to open '{}': {}", target, e))?;
592    Ok(())
593}
594
595pub fn open_path_with_editor(path: &Path) -> Result<(), String> {
596    if let Ok(editor) = std::env::var("EDITOR") {
597        let mut parts = editor.split_whitespace();
598        let binary = parts
599            .next()
600            .ok_or_else(|| "EDITOR is set but empty".to_string())?;
601        let mut command = Command::new(binary);
602        for part in parts {
603            command.arg(part);
604        }
605        command
606            .arg(path)
607            .spawn()
608            .map_err(|e| format!("Failed to launch editor '{}': {}", editor, e))?;
609        return Ok(());
610    }
611
612    open_with_default_handler(&path.display().to_string())
613}
614
615pub fn parse_config_with_auto_heal<T: DeserializeOwned>(
616    content: &str,
617    kind: &str,
618) -> Result<(T, Option<String>), String> {
619    let mut value = match kind {
620        "yaml" => {
621            let yaml_value: serde_yaml::Value =
622                serde_yaml::from_str(content).map_err(|e| e.to_string())?;
623            serde_json::to_value(yaml_value).map_err(|e| e.to_string())?
624        }
625        "json" => serde_json::from_str::<Value>(content).map_err(|e| e.to_string())?,
626        _ => return Err(format!("Unsupported config kind: {}", kind)),
627    };
628
629    let healed = auto_heal_xbp_config_value(&mut value);
630    let parsed = serde_json::from_value::<T>(value.clone()).map_err(|e| e.to_string())?;
631
632    let healed_content = if healed {
633        Some(match kind {
634            "yaml" => serde_yaml::to_string(&value).map_err(|e| e.to_string())?,
635            "json" => serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?,
636            _ => unreachable!(),
637        })
638    } else {
639        None
640    };
641
642    Ok((parsed, healed_content))
643}
644
645pub fn heal_config_file(path: &Path, kind: &str) -> Result<bool, String> {
646    let content = fs::read_to_string(path)
647        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
648    let (_, healed_content) = parse_config_with_auto_heal::<Value>(&content, kind)?;
649
650    if let Some(healed_content) = healed_content {
651        fs::write(path, healed_content)
652            .map_err(|e| format!("Failed to write healed config {}: {}", path.display(), e))?;
653        return Ok(true);
654    }
655
656    Ok(false)
657}
658
659fn auto_heal_xbp_config_value(value: &mut Value) -> bool {
660    let Some(root) = value.as_object_mut() else {
661        return false;
662    };
663
664    let mut changed = false;
665
666    if let Some(environment) = root.get_mut("environment") {
667        changed |= normalize_environment_value(environment);
668    }
669
670    if let Some(services) = root.get_mut("services").and_then(Value::as_array_mut) {
671        for service in services {
672            if let Some(environment) = service
673                .as_object_mut()
674                .and_then(|service| service.get_mut("environment"))
675            {
676                changed |= normalize_environment_value(environment);
677            }
678        }
679    }
680
681    changed
682}
683
684fn normalize_environment_value(value: &mut Value) -> bool {
685    let Value::Object(map) = value else {
686        return false;
687    };
688
689    let original = map.clone();
690    let mut normalized = Map::new();
691    let mut changed = false;
692
693    flatten_environment_entries(&original, &mut normalized, &mut changed);
694
695    if normalized != original {
696        *map = normalized;
697        changed = true;
698    }
699
700    changed
701}
702
703fn flatten_environment_entries(
704    source: &Map<String, Value>,
705    target: &mut Map<String, Value>,
706    changed: &mut bool,
707) {
708    for (key, value) in source {
709        match value {
710            Value::String(string) => {
711                target.insert(key.clone(), Value::String(string.clone()));
712            }
713            Value::Number(number) => {
714                *changed = true;
715                target.insert(key.clone(), Value::String(number.to_string()));
716            }
717            Value::Bool(boolean) => {
718                *changed = true;
719                target.insert(key.clone(), Value::String(boolean.to_string()));
720            }
721            Value::Null => {
722                *changed = true;
723                target.insert(key.clone(), Value::String(String::new()));
724            }
725            Value::Array(items) => {
726                *changed = true;
727                let serialized = serde_json::to_string(items).unwrap_or_else(|_| "[]".to_string());
728                target.insert(key.clone(), Value::String(serialized));
729            }
730            Value::Object(nested) => {
731                *changed = true;
732                flatten_environment_entries(nested, target, changed);
733            }
734        }
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use super::{
741        command_exists, first_available_command, git_remote_url_from_metadata,
742        maybe_auto_convert_legacy_xbp_json_to_yaml, parse_config_with_auto_heal,
743        parse_github_repo_from_remote_url, preferred_pip_command, preferred_python_command,
744        redact_remote_url_credentials, resolve_xbp_project_for_path,
745        write_json_config_from_any_xbp_config, KnownXbpProject,
746    };
747    use crate::strategies::XbpConfig;
748    use std::fs;
749    use std::path::PathBuf;
750    use std::sync::{Mutex, OnceLock};
751
752    fn path_lock() -> &'static Mutex<()> {
753        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
754        LOCK.get_or_init(|| Mutex::new(()))
755    }
756
757    fn make_temp_path(name: &str) -> PathBuf {
758        let mut path = std::env::temp_dir();
759        path.push(format!("xbp-test-{}-{}", name, std::process::id()));
760        path
761    }
762
763    fn with_path<F>(entries: &[PathBuf], test: F)
764    where
765        F: FnOnce(),
766    {
767        let _guard = path_lock().lock().expect("path lock should be available");
768        let original = std::env::var_os("PATH");
769        let joined = std::env::join_paths(entries).expect("PATH entries should join");
770        std::env::set_var("PATH", joined);
771        test();
772        match original {
773            Some(path) => std::env::set_var("PATH", path),
774            None => std::env::remove_var("PATH"),
775        }
776    }
777
778    #[test]
779    fn heals_nested_yaml_environment_blocks() {
780        let yaml = r#"
781project_name: demo
782port: 3000
783build_dir: $HOME/demo
784environment:
785  production:
786    DATABASE_URL: postgres://localhost/demo
787    LOG_LEVEL: info
788services:
789  - name: api
790    target: rust
791    branch: main
792    port: 3001
793    environment:
794      production:
795        SERVICE_TOKEN: abc123
796"#;
797
798        let (config, healed_content) =
799            parse_config_with_auto_heal::<XbpConfig>(yaml, "yaml").expect("config should heal");
800
801        let environment = config.environment.expect("top-level env should exist");
802        assert_eq!(
803            environment.get("DATABASE_URL"),
804            Some(&"postgres://localhost/demo".to_string())
805        );
806        assert_eq!(environment.get("LOG_LEVEL"), Some(&"info".to_string()));
807
808        let service_environment = config.services.expect("services should exist")[0]
809            .environment
810            .clone()
811            .expect("service env should exist");
812        assert_eq!(
813            service_environment.get("SERVICE_TOKEN"),
814            Some(&"abc123".to_string())
815        );
816        assert!(healed_content.is_some());
817    }
818
819    #[test]
820    fn heals_non_string_environment_values_in_json() {
821        let json = r#"{
822  "project_name": "demo",
823  "port": 3000,
824  "build_dir": "$HOME/demo",
825  "environment": {
826    "PORT": 3000,
827    "DEBUG": true,
828    "EMPTY": null
829  }
830}"#;
831
832        let (config, healed_content) =
833            parse_config_with_auto_heal::<XbpConfig>(json, "json").expect("config should heal");
834
835        let environment = config.environment.expect("top-level env should exist");
836        assert_eq!(environment.get("PORT"), Some(&"3000".to_string()));
837        assert_eq!(environment.get("DEBUG"), Some(&"true".to_string()));
838        assert_eq!(environment.get("EMPTY"), Some(&String::new()));
839        assert!(healed_content.is_some());
840    }
841
842    #[test]
843    fn command_helpers_respect_path_order() {
844        let bin_dir = make_temp_path("bin");
845        fs::create_dir_all(&bin_dir).expect("temp dir should be created");
846        fs::write(bin_dir.join("python"), b"").expect("python file should be created");
847        fs::write(bin_dir.join("pip"), b"").expect("pip file should be created");
848
849        with_path(std::slice::from_ref(&bin_dir), || {
850            assert!(command_exists("python"));
851            assert_eq!(
852                first_available_command(&["python3", "python"]),
853                Some("python".to_string())
854            );
855            assert_eq!(preferred_python_command(), "python".to_string());
856            assert_eq!(preferred_pip_command(), "pip".to_string());
857        });
858
859        fs::remove_dir_all(&bin_dir).expect("temp dir should be removed");
860    }
861
862    #[test]
863    fn resolves_xbp_project_for_nested_paths() {
864        let project_root = make_temp_path("ownership");
865        let service_dir = project_root.join("services").join("api");
866        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir should be created");
867        fs::create_dir_all(&service_dir).expect("service dir should be created");
868        fs::write(
869            project_root.join(".xbp").join("xbp.json"),
870            br#"{"project_name":"demo"}"#,
871        )
872        .expect("xbp config should be written");
873
874        let known_projects = vec![KnownXbpProject {
875            root: project_root.clone(),
876            name: "demo".to_string(),
877        }];
878
879        assert_eq!(
880            resolve_xbp_project_for_path(&service_dir, &known_projects),
881            Some("demo".to_string())
882        );
883
884        fs::remove_dir_all(&project_root).expect("temp project should be removed");
885    }
886
887    #[test]
888    fn ignores_non_xbp_paths_for_project_resolution() {
889        let project_root = make_temp_path("ownership-miss");
890        let other_dir = make_temp_path("ownership-other");
891        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir should be created");
892        fs::create_dir_all(&other_dir).expect("other dir should be created");
893        fs::write(
894            project_root.join(".xbp").join("xbp.json"),
895            br#"{"project_name":"demo"}"#,
896        )
897        .expect("xbp config should be written");
898
899        let known_projects = vec![KnownXbpProject {
900            root: project_root.clone(),
901            name: "demo".to_string(),
902        }];
903
904        assert_eq!(
905            resolve_xbp_project_for_path(&other_dir, &known_projects),
906            None
907        );
908
909        fs::remove_dir_all(&project_root).expect("temp project should be removed");
910        fs::remove_dir_all(&other_dir).expect("temp other dir should be removed");
911    }
912
913    #[test]
914    fn auto_converts_legacy_json_to_yaml() {
915        let project_root = make_temp_path("json-to-yaml");
916        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir should be created");
917        let json_path = project_root.join(".xbp").join("xbp.json");
918        fs::write(
919            &json_path,
920            br#"{"project_name":"demo","port":3000,"build_dir":"$HOME/demo"}"#,
921        )
922        .expect("json should be written");
923
924        let output = maybe_auto_convert_legacy_xbp_json_to_yaml(&project_root, &json_path)
925            .expect("conversion should succeed")
926            .expect("yaml path should be returned");
927        assert!(output.exists(), "converted yaml should exist");
928
929        let yaml = fs::read_to_string(output).expect("yaml should be readable");
930        assert!(yaml.contains("project_name: demo"));
931
932        fs::remove_dir_all(project_root).expect("temp project should be removed");
933    }
934
935    #[test]
936    fn writes_json_from_yaml_config() {
937        let project_root = make_temp_path("yaml-to-json");
938        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir should be created");
939        let yaml_path = project_root.join(".xbp").join("xbp.yaml");
940        let json_out = project_root.join("xbp.json");
941        fs::write(
942            &yaml_path,
943            "project_name: demo\nport: 3000\nbuild_dir: $HOME/demo\n",
944        )
945        .expect("yaml should be written");
946
947        write_json_config_from_any_xbp_config(&yaml_path, &json_out)
948            .expect("json should be generated from yaml");
949
950        let json = fs::read_to_string(json_out).expect("json should be readable");
951        assert!(json.contains("\"project_name\": \"demo\""));
952
953        fs::remove_dir_all(project_root).expect("temp project should be removed");
954    }
955
956    #[test]
957    fn parses_github_repo_from_supported_remote_urls() {
958        assert_eq!(
959            parse_github_repo_from_remote_url("https://github.com/xylex-group/xbp.git"),
960            Some(("xylex-group".to_string(), "xbp".to_string()))
961        );
962        assert_eq!(
963            parse_github_repo_from_remote_url("git@github.com:xylex-group/xbp.git"),
964            Some(("xylex-group".to_string(), "xbp".to_string()))
965        );
966        assert_eq!(
967            parse_github_repo_from_remote_url("ssh://git@github.com/xylex-group/xbp"),
968            Some(("xylex-group".to_string(), "xbp".to_string()))
969        );
970        assert_eq!(
971            parse_github_repo_from_remote_url("https://gitlab.com/xylex-group/xbp.git"),
972            None
973        );
974        assert_eq!(
975            parse_github_repo_from_remote_url("https://github.com/xylex-group/xbp/extra.git"),
976            None
977        );
978    }
979
980    #[test]
981    fn redacts_credentials_in_remote_urls() {
982        let redacted = redact_remote_url_credentials("https://token@example.com/xylex-group/xbp");
983        assert!(redacted.contains("REDACTED"));
984        assert!(!redacted.contains("token@example.com"));
985    }
986
987    #[test]
988    fn reads_origin_remote_url_from_git_config_directory() {
989        let project_root = make_temp_path("git-config-dir");
990        let git_dir = project_root.join(".git");
991        fs::create_dir_all(&git_dir).expect("git dir should be created");
992        fs::write(
993            git_dir.join("config"),
994            "[remote \"origin\"]\n\turl = https://github.com/xylex-group/xbp.git\n",
995        )
996        .expect("git config should be written");
997
998        let remote = git_remote_url_from_metadata(&project_root, "origin")
999            .expect("git metadata should parse")
1000            .expect("origin remote should exist");
1001        assert_eq!(remote, "https://github.com/xylex-group/xbp.git");
1002
1003        fs::remove_dir_all(project_root).expect("temp project should be removed");
1004    }
1005
1006    #[test]
1007    fn reads_origin_remote_url_from_gitdir_pointer() {
1008        let project_root = make_temp_path("git-config-file");
1009        let nested_git_dir = project_root.join(".git-real");
1010        fs::create_dir_all(&nested_git_dir).expect("gitdir target should be created");
1011        fs::write(project_root.join(".git"), "gitdir: .git-real\n")
1012            .expect("gitdir pointer should be written");
1013        fs::write(
1014            nested_git_dir.join("config"),
1015            "[remote \"origin\"]\n\turl = git@github.com:xylex-group/xbp.git\n",
1016        )
1017        .expect("git config should be written");
1018
1019        let remote = git_remote_url_from_metadata(&project_root, "origin")
1020            .expect("git metadata should parse")
1021            .expect("origin remote should exist");
1022        assert_eq!(remote, "git@github.com:xylex-group/xbp.git");
1023
1024        fs::remove_dir_all(project_root).expect("temp project should be removed");
1025    }
1026}