use std::path::Path;
use anyhow::Context;
use super::upgrade_2x::{Severity, Upgraded};
use crate::config_writer::write_bytes_atomically;
const NOTE_FILE: &str = "config-2x-upgrade-note.txt";
const UPGRADE_GUIDE: &str = "https://matthewyjiang.github.io/rho/upgrading-to-3#configuration";
pub(super) fn leave(rho_dir: &Path, config_path: &Path, upgraded: &Upgraded) -> anyhow::Result<()> {
let path = rho_dir.join(NOTE_FILE);
let mut note = match std::fs::read_to_string(&path) {
Ok(earlier) => earlier + "\n\n",
Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(error) => {
return Err(error).with_context(|| format!("failed to read {}", path.display()))
}
};
note.push_str(&text(config_path, upgraded));
write_bytes_atomically(&path, note.as_bytes())
.with_context(|| format!("failed to write {}", path.display()))
}
pub(crate) fn take_upgrade_note(rho_dir: &Path) -> Option<String> {
let path = rho_dir.join(NOTE_FILE);
let note = match std::fs::read_to_string(&path) {
Ok(note) => note,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return None,
Err(error) => {
tracing::warn!(%error, path = %path.display(), "could not read the config upgrade note");
return None;
}
};
match std::fs::remove_file(&path) {
Ok(()) => Some(note),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => {
tracing::warn!(%error, path = %path.display(), "could not remove the config upgrade note");
None
}
}
}
fn text(config_path: &Path, upgraded: &Upgraded) -> String {
let header = format!(
"rho 3 updated your config from the 2.x layout: {}",
crate::paths::display(config_path)
);
let changes = upgraded
.changes()
.into_iter()
.map(|(severity, line)| match severity {
Severity::Note => format!("- {line}"),
Severity::Warning => format!("- warning: {line}"),
});
let footer = [
format!(
"the original is saved at {}",
crate::paths::display(&upgraded.backup)
),
format!("what changed in rho 3: {UPGRADE_GUIDE}"),
];
std::iter::once(header)
.chain(changes)
.chain(footer)
.collect::<Vec<_>>()
.join("\n")
}