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
|
use anyhow::anyhow;
use std::path::{Path, PathBuf};
/// Return the Composer home directory, respecting `COMPOSER_HOME` and
/// falling back to the platform default (`~/.config/composer` on Unix,
/// `%APPDATA%/Composer` on Windows).
pub(crate) fn composer_home() -> String {
if let Ok(home) = std::env::var("COMPOSER_HOME") {
return home;
}
#[cfg(target_os = "windows")]
{
std::env::var("APPDATA")
.map(|p| format!("{p}/Composer"))
.unwrap_or_else(|_| "C:/ProgramData/ComposerSetup/bin".to_string())
}
#[cfg(not(target_os = "windows"))]
{
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
format!("{xdg}/composer")
} else {
std::env::var("HOME")
.map(|h| format!("{h}/.config/composer"))
.unwrap_or_else(|_| "/tmp/composer".to_string())
}
}
}
/// Build the working directory path, preferring `--working-dir` over `cwd`.
pub(crate) fn working_dir(cli: &super::Cli) -> anyhow::Result<PathBuf> {
match &cli.working_dir {
Some(d) => Ok(PathBuf::from(d)),
None => Ok(std::env::current_dir()?),
}
}
/// 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(())
}
/// 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
}
});
}
}
/// Insert a repository entry before or after a named repository.
/// Returns an error if the target repository is not found.
pub(crate) fn insert_repository(
json: &mut serde_json::Value,
name: &str,
config: serde_json::Value,
target: &str,
before: bool,
) -> anyhow::Result<()> {
if !json["repositories"].is_array() {
json["repositories"] = serde_json::json!([]);
}
remove_repository(json, name);
let repos = json["repositories"].as_array_mut().unwrap();
let pos = repos
.iter()
.position(|entry| {
entry.get("name").and_then(|n| n.as_str()) == Some(target)
|| entry
.as_object()
.map(|obj| obj.contains_key(target))
.unwrap_or(false)
})
.ok_or_else(|| anyhow!("Repository \"{target}\" not found"))?;
let insert_pos = if before { pos } else { pos + 1 };
repos.insert(insert_pos, config);
Ok(())
}
/// 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(arr) => {
arr.iter().map(render_value).collect::<Vec<_>>().join(", ")
}
serde_json::Value::Object(obj) => {
if obj.is_empty() {
"{}".to_string()
} else {
serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string())
}
}
}
}
|