aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart/src/commands/config_helpers.rs
blob: f0aacbbeb65f829b6cd2cb95f6258b9e3066e1fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use anyhow::anyhow;
use std::path::{Path, PathBuf};

pub(crate) use mozart_core::composer::composer_home;

/// Read TLS-related options (`config.cafile`, `config.capath`) from the merged
/// global + local config. Local values override global. Relative paths are
/// resolved against the directory of the config file that defined them.
pub(crate) fn load_tls_options(cli: &super::Cli) -> mozart_core::http::TlsOptions {
    let mut opts = mozart_core::http::TlsOptions::default();

    let home = composer_home();
    apply_tls_from_file(&home.join("config.json"), &home, &mut opts);

    if let Ok(wd) = cli.working_dir() {
        apply_tls_from_file(&wd.join("composer.json"), &wd, &mut opts);
    }

    opts
}

fn apply_tls_from_file(path: &Path, base_dir: &Path, opts: &mut mozart_core::http::TlsOptions) {
    let Ok(content) = std::fs::read_to_string(path) else {
        return;
    };
    let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) else {
        return;
    };
    let Some(cfg) = json.get("config").and_then(|v| v.as_object()) else {
        return;
    };
    if let Some(s) = cfg.get("cafile").and_then(|v| v.as_str())
        && !s.is_empty()
    {
        opts.cafile = Some(resolve_relative(s, base_dir));
    }
    if let Some(s) = cfg.get("capath").and_then(|v| v.as_str())
        && !s.is_empty()
    {
        opts.capath = Some(resolve_relative(s, base_dir));
    }
}

fn resolve_relative(path: &str, base: &Path) -> PathBuf {
    let p = Path::new(path);
    if p.is_absolute() {
        p.to_path_buf()
    } else {
        base.join(p)
    }
}

/// Read a JSON file as `serde_json::Value`.
/// If the file does not exist, return a default skeleton:
/// `{"config": {}}` for global files, `{}` for local.
pub(crate) fn read_json_file(path: &Path, is_global: bool) -> anyhow::Result<serde_json::Value> {
    if !path.exists() {
        if is_global {
            return Ok(serde_json::json!({"config": {}}));
        }
        return Ok(serde_json::json!({}));
    }
    let content = std::fs::read_to_string(path)?;
    let value: serde_json::Value = serde_json::from_str(&content)
        .map_err(|e| anyhow!("Failed to parse JSON from {}: {}", path.display(), e))?;
    Ok(value)
}

/// Write a `serde_json::Value` back to a file with 4-space indentation + trailing newline.
pub(crate) fn write_json_file(path: &Path, value: &serde_json::Value) -> anyhow::Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    mozart_core::package::write_to_file(value, path)?;
    Ok(())
}

/// Normalize a `repositories` value into a `Vec<serde_json::Value>`.
///
/// Composer stores repositories as an associative object:
///   `{"foo": {"type": "vcs", "url": "..."}}`
/// Mozart stores them as an array of objects with a `"name"` field:
///   `[{"name": "foo", "type": "vcs", "url": "..."}]`
///
/// This function accepts either format and always returns the array-of-objects
/// representation so callers can treat them uniformly.
pub(crate) fn normalize_repositories(value: &serde_json::Value) -> Vec<serde_json::Value> {
    match value {
        serde_json::Value::Array(arr) => arr.clone(),
        serde_json::Value::Object(obj) => obj
            .iter()
            .map(|(key, val)| {
                if let serde_json::Value::Object(inner) = val {
                    // Regular repo entry: inject "name" from the key if absent.
                    let mut entry = serde_json::Map::new();
                    entry.insert("name".to_string(), serde_json::json!(key));
                    for (k, v) in inner {
                        if k != "name" {
                            entry.insert(k.clone(), v.clone());
                        }
                    }
                    serde_json::Value::Object(entry)
                } else {
                    // Boolean / scalar entry (e.g. `"packagist.org": false`).
                    serde_json::json!({key: val})
                }
            })
            .collect(),
        _ => vec![],
    }
}

/// Add a repository entry to the `repositories` array in json.
/// If `append` is true, push to end; otherwise insert at beginning.
/// Removes any existing entry with the same name first.
pub(crate) fn add_repository(
    json: &mut serde_json::Value,
    name: &str,
    config: serde_json::Value,
    append: bool,
) {
    if !json["repositories"].is_array() {
        json["repositories"] = serde_json::json!([]);
    }

    remove_repository(json, name);

    let repos = json["repositories"].as_array_mut().unwrap();
    if append {
        repos.push(config);
    } else {
        repos.insert(0, config);
    }
}

/// Remove a repository entry by name from the `repositories` array.
pub(crate) fn remove_repository(json: &mut serde_json::Value, name: &str) {
    if let Some(repos) = json["repositories"].as_array_mut() {
        repos.retain(|entry| {
            if let Some(entry_name) = entry.get("name").and_then(|n| n.as_str()) {
                entry_name != name
            } else {
                let disabled_key_matches = entry
                    .as_object()
                    .map(|obj| obj.contains_key(name))
                    .unwrap_or(false);
                !disabled_key_matches
            }
        });
    }
}

/// Render a `serde_json::Value` as a human-readable string suitable for
/// single-line display (matching Composer's behaviour).
pub(crate) fn render_value(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(_) => {
            serde_json::to_string(v).unwrap_or_else(|_| "[]".to_string())
        }
        serde_json::Value::Object(obj) => {
            if obj.is_empty() {
                "{}".to_string()
            } else {
                serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string())
            }
        }
    }
}