rsomics-annotation 0.1.0

Typed GFF3 and GTF validation, selection, conversion, and sequence extraction
Documentation
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;

use rsomics_common::{Context, Result, RsomicsError};
use tempfile::Builder;

pub(crate) fn open_input(path: Option<&Path>) -> Result<Box<dyn BufRead>> {
    match path {
        None => Ok(Box::new(BufReader::new(io::stdin()))),
        Some(path) if path == Path::new("-") => Ok(Box::new(BufReader::new(io::stdin()))),
        Some(path) => File::open(path)
            .rs_with_context(|| format!("opening input {}", path.display()))
            .map(|file| Box::new(BufReader::new(file)) as Box<dyn BufRead>),
    }
}

pub(crate) fn with_output(
    path: Option<&Path>,
    operation: impl FnOnce(&mut dyn Write) -> Result<()>,
) -> Result<()> {
    rsomics_common::write_output(path, operation)
}

pub(crate) struct StagedOutput {
    path: std::path::PathBuf,
    temporary: tempfile::NamedTempFile,
}

impl Write for StagedOutput {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        self.temporary.write(buffer)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.temporary.flush()
    }
}

pub(crate) fn with_named_outputs(
    paths: &[&Path],
    operation: impl FnOnce(&mut [StagedOutput]) -> Result<()>,
) -> Result<()> {
    let mut outputs = paths
        .iter()
        .map(|path| StagedOutput::new(path))
        .collect::<Result<Vec<_>>>()?;
    operation(&mut outputs)?;

    for output in &mut outputs {
        output
            .temporary
            .as_file_mut()
            .flush()
            .rs_context("flushing annotation output")?;
        output
            .temporary
            .as_file_mut()
            .sync_all()
            .rs_context("syncing annotation output")?;
    }
    for output in outputs {
        output.temporary.persist(&output.path).map_err(|error| {
            RsomicsError::Io(io::Error::new(
                error.error.kind(),
                format!(
                    "persisting output {}: {}",
                    output.path.display(),
                    error.error
                ),
            ))
        })?;
    }
    Ok(())
}

impl StagedOutput {
    fn new(path: &Path) -> Result<Self> {
        let permissions = match fs::metadata(path) {
            Ok(metadata) => Some(metadata.permissions()),
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => return Err(RsomicsError::Io(error)),
        };
        let parent = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        let mut builder = Builder::new();
        builder.prefix(".rsomics-annotation-");
        #[cfg(unix)]
        if permissions.is_none() {
            builder.permissions(fs::Permissions::from_mode(0o666));
        }
        if let Some(existing) = permissions.as_ref() {
            builder.permissions(existing.clone());
        }
        let temporary = builder
            .tempfile_in(parent)
            .rs_with_context(|| format!("creating output beside {}", path.display()))?;
        Ok(Self {
            path: path.to_owned(),
            temporary,
        })
    }
}