use anyhow::{Context, Result};
use std::fs;
use super::super::MigrationContext;
use super::config_refs::update_config_file_references;
use super::rename::{FileMigrationOptions, apply_file_rename_with_options};
pub fn migrate_queue_json_to_jsonc(ctx: &MigrationContext) -> Result<()> {
migrate_json_to_jsonc(ctx, ".ralph/queue.json", ".ralph/queue.jsonc")
.context("migrate queue.json to queue.jsonc")
}
pub fn migrate_done_json_to_jsonc(ctx: &MigrationContext) -> Result<()> {
migrate_json_to_jsonc(ctx, ".ralph/done.json", ".ralph/done.jsonc")
.context("migrate done.json to done.jsonc")
}
pub fn is_queue_json_to_jsonc_applicable(ctx: &MigrationContext) -> bool {
ctx.file_exists(".ralph/queue.json")
}
pub fn is_done_json_to_jsonc_applicable(ctx: &MigrationContext) -> bool {
ctx.file_exists(".ralph/done.json")
}
pub fn migrate_config_json_to_jsonc(ctx: &MigrationContext) -> Result<()> {
migrate_json_to_jsonc(ctx, ".ralph/config.json", ".ralph/config.jsonc")
.context("migrate config.json to config.jsonc")
}
pub fn is_config_json_to_jsonc_applicable(ctx: &MigrationContext) -> bool {
ctx.file_exists(".ralph/config.json")
}
pub(super) fn migrate_json_to_jsonc(
ctx: &MigrationContext,
old_path: &str,
new_path: &str,
) -> Result<()> {
let old_full_path = ctx.resolve_path(old_path);
let new_full_path = ctx.resolve_path(new_path);
if !old_full_path.exists() {
return Ok(());
}
if new_full_path.exists() {
update_config_file_references(ctx, old_path, new_path)
.context("update config references for established jsonc migration")?;
fs::remove_file(&old_full_path)
.with_context(|| format!("remove legacy file {}", old_full_path.display()))?;
log::info!(
"Removed legacy file {} because {} already exists",
old_full_path.display(),
new_full_path.display()
);
return Ok(());
}
let opts = FileMigrationOptions {
keep_backup: false,
update_config: true,
};
apply_file_rename_with_options(ctx, old_path, new_path, &opts)
}