use std::{ fs::{self, File, OpenOptions}, path::Path, }; use anyhow::Context; use bgzip::{BGZFWriter, Compression}; use log::info; pub fn get_gz_writer(path: &str, force: bool) -> anyhow::Result> { if !path.ends_with(".gz") { anyhow::bail!("The file should end with gz"); } if force && Path::new(path).exists() { fs::remove_file(path).with_context(|| anyhow::anyhow!("Failed to remove file: {path}"))?; } let file = OpenOptions::new() .write(true) // Open the file for writing .create_new(true) .truncate(true) .open(path) .with_context(|| anyhow::anyhow!("failed to open the file: {path}"))?; info!("Writing into {path}"); Ok(BGZFWriter::new(file, Compression::default())) }