pub(super) fn reformat_for_pnpm_parity(yaml: &str) -> String {
let lines: Vec<&str> = yaml.lines().collect();
let mut compact: Vec<String> = Vec::with_capacity(lines.len());
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let stripped = line.trim_start();
let indent = line.len() - stripped.len();
let key = stripped.strip_suffix(':');
let is_flow_candidate = matches!(key, Some("resolution") | Some("engines"));
if is_flow_candidate && i + 1 < lines.len() {
let inner_indent = indent + 2;
let mut entries: Vec<String> = Vec::new();
let mut all_scalar = true;
let mut j = i + 1;
while j < lines.len() {
let next = lines[j];
let n_stripped = next.trim_start();
let n_indent = next.len() - n_stripped.len();
if n_stripped.is_empty() || n_indent < inner_indent {
break;
}
if n_indent > inner_indent {
all_scalar = false;
break;
}
match n_stripped.split_once(": ") {
Some((k, v)) => entries.push(format!("{k}: {v}")),
None => {
all_scalar = false;
break;
}
}
j += 1;
}
let block_form_type = entries
.iter()
.any(|e| e == "type: binary" || e == "type: variations");
if all_scalar && !block_form_type && !entries.is_empty() {
compact.push(format!(
"{}{}: {{{}}}",
" ".repeat(indent),
key.unwrap(),
entries.join(", ")
));
i = j;
continue;
}
}
compact.push(line.to_string());
i += 1;
}
const ENTRY_SECTIONS: &[&str] = &["importers:", "packages:", "snapshots:", "catalogs:"];
let mut out = String::with_capacity(yaml.len() + 512);
let mut in_entries = false;
for (idx, line) in compact.iter().enumerate() {
let stripped = line.trim_start();
let indent = line.len() - stripped.len();
let is_top = indent == 0 && !stripped.is_empty();
let is_entry_header =
in_entries && indent == 2 && !stripped.starts_with('-') && stripped.contains(':');
if (is_top && idx > 0) || is_entry_header {
out.push('\n');
}
out.push_str(line);
out.push('\n');
if is_top {
in_entries = ENTRY_SECTIONS.contains(&stripped);
}
}
out
}