writers.rs 790 B

12345678910111213141516171819202122232425262728
  1. use std::{
  2. fs::{self, File, OpenOptions},
  3. path::Path,
  4. };
  5. use anyhow::Context;
  6. use bgzip::{BGZFWriter, Compression};
  7. use log::info;
  8. pub fn get_gz_writer(path: &str, force: bool) -> anyhow::Result<BGZFWriter<File>> {
  9. if !path.ends_with(".gz") {
  10. anyhow::bail!("The file should end with gz");
  11. }
  12. if force && Path::new(path).exists() {
  13. fs::remove_file(path).with_context(|| anyhow::anyhow!("Failed to remove file: {path}"))?;
  14. }
  15. let file = OpenOptions::new()
  16. .write(true) // Open the file for writing
  17. .create_new(true)
  18. .truncate(true)
  19. .open(path)
  20. .with_context(|| anyhow::anyhow!("failed to open the file: {path}"))?;
  21. info!("Writing into {path}");
  22. Ok(BGZFWriter::new(file, Compression::default()))
  23. }