mod alignment;
mod fasta;
mod intervals;
mod reads;
mod variants;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use flate2::bufread::MultiGzDecoder;
pub use alignment::alignment;
pub use fasta::reference;
pub use intervals::{IntervalFormat, intervals};
pub use reads::{reads, samples};
pub use variants::variants;
#[derive(Clone, Debug, Default)]
pub struct Declared {
pub organism: Option<String>,
pub build: Option<String>,
pub samples: Option<Vec<String>>,
}
#[derive(Debug)]
pub enum LoadError {
Io {
path: PathBuf,
source: io::Error,
},
Pairing {
detail: String,
},
Format {
path: PathBuf,
detail: String,
},
}
impl LoadError {
pub(crate) fn io(path: &Path, source: io::Error) -> Self {
Self::Io {
path: path.to_path_buf(),
source,
}
}
pub(crate) fn format(path: &Path, detail: impl Into<String>) -> Self {
Self::Format {
path: path.to_path_buf(),
detail: detail.into(),
}
}
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io { path, source } => write!(f, "cannot read {}: {source}", path.display()),
Self::Format { path, detail } => {
write!(f, "cannot parse {}: {detail}", path.display())
}
Self::Pairing { detail } => {
write!(f, "cannot group reads into samples: {detail}")
}
}
}
}
impl Error for LoadError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::Format { .. } | Self::Pairing { .. } => None,
}
}
}
pub(crate) fn open(path: &Path) -> Result<Box<dyn BufRead>, LoadError> {
let file = File::open(path).map_err(|error| LoadError::io(path, error))?;
let buffered = BufReader::new(file);
if path.extension().is_some_and(|extension| extension == "gz") {
Ok(Box::new(BufReader::new(MultiGzDecoder::new(buffered))))
} else {
Ok(Box::new(buffered))
}
}
pub(crate) fn stem(path: &Path) -> String {
let mut name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
for suffix in [".gz", ".bgz"] {
if let Some(trimmed) = name.strip_suffix(suffix) {
name = trimmed.to_owned();
}
}
match name.rsplit_once('.') {
Some((base, _)) => base.to_owned(),
None => name,
}
}