Skip to content

Commit

Permalink
start moving toward anyhow for errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Rob Patro committed May 7, 2022
1 parent 65584f4 commit 5f27a53
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 28 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ categories = ["command-line-utilities", "science"]
# libradicl = "0.4.4"
# for local development
libradicl = { path = "libradicl", version = "0.4.5" }
anyhow = "1.0.57"
arrayvec = "0.7.2"
ahash = "0.7.6"
bincode = "1.3.3"
Expand Down
62 changes: 37 additions & 25 deletions src/cellfilter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
*/

use anyhow::{anyhow, Context};
use slog::crit;
use slog::info;

Expand Down Expand Up @@ -226,9 +227,10 @@ fn process_unfiltered(
velo_mode: bool,
cmdline: &str,
log: &slog::Logger,
) -> u64 {
) -> anyhow::Result<u64> {
let parent = std::path::Path::new(&output_dir);
std::fs::create_dir_all(&parent).unwrap();
std::fs::create_dir_all(&parent)
.with_context(|| format!("couldn't create directory path {}", parent.display()))?;

// the smallest number of reads we'll allow per barcode
let min_freq = match filter_meth {
Expand Down Expand Up @@ -367,7 +369,12 @@ fn process_unfiltered(
);

let parent = std::path::Path::new(&output_dir);
std::fs::create_dir_all(&parent).unwrap();
std::fs::create_dir_all(&parent).with_context(|| {
format!(
"couldn't create path to output directory {}",
parent.display()
)
})?;
let o_path = parent.join("permit_freq.bin");

match afutils::write_permit_list_freq(&o_path, ft_vals.bclen, &hm) {
Expand Down Expand Up @@ -424,7 +431,7 @@ fn process_unfiltered(
num_corrected.to_formatted_string(&Locale::en)
);

num_corrected
Ok(num_corrected)
}

#[allow(clippy::unnecessary_unwrap, clippy::too_many_arguments)]
Expand All @@ -439,7 +446,7 @@ fn process_filtered(
velo_mode: bool,
cmdline: &str,
log: &slog::Logger,
) -> u64 {
) -> anyhow::Result<u64> {
let valid_bc: Vec<u64>;
let mut freq: Vec<u64> = hm.values().cloned().collect();
freq.sort_unstable();
Expand Down Expand Up @@ -509,7 +516,12 @@ fn process_filtered(
}

let parent = std::path::Path::new(&output_dir);
std::fs::create_dir_all(&parent).unwrap();
std::fs::create_dir_all(&parent).with_context(|| {
format!(
"failed to create path to output location {}",
parent.display()
)
})?;
let o_path = parent.join("permit_freq.bin");

match afutils::write_permit_list_freq(&o_path, ft_vals.bclen, &permitted_map) {
Expand All @@ -529,7 +541,7 @@ fn process_filtered(
};

let s_path = parent.join("permit_map.bin");
let s_file = std::fs::File::create(&s_path).expect("could not create serialization file.");
let s_file = std::fs::File::create(&s_path).context("could not create serialization file.")?;
let mut s_writer = BufWriter::new(&s_file);
bincode::serialize_into(&mut s_writer, &full_permit_list)
.expect("couldn't serialize permit list.");
Expand All @@ -544,21 +556,21 @@ fn process_filtered(
});

let m_path = parent.join("generate_permit_list.json");
let mut m_file = std::fs::File::create(&m_path).expect("could not create metadata file.");
let mut m_file = std::fs::File::create(&m_path).context("could not create metadata file.")?;

let meta_info_string =
serde_json::to_string_pretty(&meta_info).expect("could not format json.");
serde_json::to_string_pretty(&meta_info).context("could not format json.")?;
m_file
.write_all(meta_info_string.as_bytes())
.expect("cannot write to generate_permit_list.json file");
.context("cannot write to generate_permit_list.json file")?;

info!(
log,
"total number of distinct corrected barcodes : {}",
num_corrected.to_formatted_string(&Locale::en)
);

num_corrected
Ok(num_corrected)
}

/// Given the input RAD file `input_file`, compute
Expand All @@ -579,19 +591,19 @@ pub fn generate_permit_list(
//valid_bc_file: Option<String>,
//use_knee_distance: bool,
log: &slog::Logger,
) -> Result<u64, Box<dyn std::error::Error>> {
) -> anyhow::Result<u64> {
let i_dir = std::path::Path::new(&rad_dir);

if !i_dir.exists() {
crit!(log, "the input RAD path {} does not exist", rad_dir);
// std::process::exit(1);
return Err("execution terminated unexpectedly".into());
return Err(anyhow!("execution terminated unexpectedly"));
}

let mut first_bclen = 0usize;
let mut unfiltered_bc_counts = None;
if let CellFilterMethod::UnfilteredExternalList(fname, _) = &filter_meth {
let i_file = File::open(&fname).expect("could not open input file");
let i_file = File::open(&fname).context("could not open input file")?;
let br = BufReader::new(i_file);
unfiltered_bc_counts = Some(populate_unfiltered_barcode_map(br, &mut first_bclen));
info!(
Expand Down Expand Up @@ -690,14 +702,14 @@ pub fn generate_permit_list(
num_reads += c.reads.len();
}
info!(
log,
"observed {} reads ({} orientation consistent) in {} chunks --- max ambiguity read occurs in {} refs",
num_reads.to_formatted_string(&Locale::en),
num_orientation_compat_reads.to_formatted_string(&Locale::en),
hdr.num_chunks.to_formatted_string(&Locale::en),
max_ambiguity_read.to_formatted_string(&Locale::en)
);
Ok(process_unfiltered(
log,
"observed {} reads ({} orientation consistent) in {} chunks --- max ambiguity read occurs in {} refs",
num_reads.to_formatted_string(&Locale::en),
num_orientation_compat_reads.to_formatted_string(&Locale::en),
hdr.num_chunks.to_formatted_string(&Locale::en),
max_ambiguity_read.to_formatted_string(&Locale::en)
);
process_unfiltered(
hmu,
unmatched_bc,
&ft_vals,
Expand All @@ -709,7 +721,7 @@ pub fn generate_permit_list(
velo_mode,
cmdline,
log,
))
)
} else {
Ok(0)
}
Expand All @@ -727,7 +739,7 @@ pub fn generate_permit_list(
hdr.num_chunks.to_formatted_string(&Locale::en),
max_ambiguity_read.to_formatted_string(&Locale::en)
);
Ok(process_filtered(
process_filtered(
&hm,
&ft_vals,
&filter_meth,
Expand All @@ -738,7 +750,7 @@ pub fn generate_permit_list(
velo_mode,
cmdline,
log,
))
)
}
}

Expand Down
8 changes: 5 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
*/

use anyhow::anyhow;
use bio_types::strand::Strand;
use clap::{arg, crate_authors, crate_version, Command};
use csv::Error as CSVError;
Expand Down Expand Up @@ -38,7 +39,8 @@ fn gen_random_kmer(k: usize) -> String {
s
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
fn main() -> anyhow::Result<()> {
//}, Box<dyn std::error::Error>> {
let num_hardware_threads = num_cpus::get() as u32;
let max_num_threads: String = (num_cpus::get() as u32).to_string();
let max_num_collate_threads: String = (16_u32.min(num_hardware_threads).max(2_u32)).to_string();
Expand Down Expand Up @@ -428,7 +430,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
match *error.kind() {
// if a deserialize error, we already complained about it
ErrorKind::Deserialize { .. } => {
return Err("execution terminated unexpectedly".into())
return Err(anyhow!("execution terminated unexpectedly"));
}
// if another type of error, just panic for now
_ => {
Expand Down Expand Up @@ -470,7 +472,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
match *error.kind() {
// if a deserialize error, we already complained about it
ErrorKind::Deserialize { .. } => {
return Err("execution terminated unexpectedly".into())
return Err(anyhow!("execution terminated unexpectedly"));
}
// if another type of error, just panic for now
_ => {
Expand Down

0 comments on commit 5f27a53

Please sign in to comment.