Skip to content

Commit

Permalink
add AsRef<Path> and Into<PathBuf> where it makes sense
Browse files Browse the repository at this point in the history
  • Loading branch information
Rob Patro committed Jul 14, 2022
1 parent 347c342 commit 8ea680f
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 49 deletions.
13 changes: 8 additions & 5 deletions src/cellfilter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Instant;

#[derive(Debug)]
Expand All @@ -43,11 +43,11 @@ pub enum CellFilterMethod {
// correct all cells in an
// edit distance of 1 of these
// barcodes
ExplicitList(String),
ExplicitList(PathBuf),
// barcodes will be provided in the
// form of an *unfiltered* external
// permit list
UnfilteredExternalList(String, usize),
UnfilteredExternalList(PathBuf, usize),
// use the distance method to
// automatically find the knee
// in the curve
Expand Down Expand Up @@ -610,7 +610,7 @@ pub fn generate_permit_list(gpl_opts: GenPermitListOpts) -> anyhow::Result<u64>
let mut first_bclen = 0usize;
let mut unfiltered_bc_counts = None;
if let CellFilterMethod::UnfilteredExternalList(fname, _) = &filter_meth {
let i_file = File::open(&fname).context("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 @@ -998,7 +998,10 @@ pub fn permit_list_from_threshold(
valid_bc
}

pub fn permit_list_from_file(ifile: &str, bclen: u16) -> Vec<u64> {
pub fn permit_list_from_file<P>(ifile: P, bclen: u16) -> Vec<u64>
where
P: AsRef<Path>,
{
let f = File::open(ifile).expect("couldn't open input barcode file.");
let br = BufReader::new(f);
let mut bc = Vec::<u64>::with_capacity(10_000);
Expand Down
40 changes: 25 additions & 15 deletions src/collate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,30 @@ use std::fs::File;
use std::io::BufReader;
use std::io::{BufWriter, Cursor, Read, Seek, SeekFrom, Write};
use std::iter::FromIterator;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;

#[allow(clippy::too_many_arguments)]
pub fn collate(
input_dir: &PathBuf,
rad_dir: &PathBuf,
pub fn collate<P1, P2>(
input_dir: P1,
rad_dir: P2,
num_threads: u32,
max_records: u32,
compress_out: bool,
cmdline: &str,
version_str: &str,
//expected_ori: Strand,
log: &slog::Logger,
) -> anyhow::Result<()> {
let parent = std::path::Path::new(input_dir);
) -> anyhow::Result<()>
where
P1: Into<PathBuf>,
P2: AsRef<Path>,
{
let input_dir = input_dir.into();
let parent = std::path::Path::new(input_dir.as_path());

// open the metadata file and read the json
let gpl_path = parent.join("generate_permit_list.json");
Expand Down Expand Up @@ -246,9 +251,9 @@ fn correct_unmapped_counts(
}

#[allow(clippy::too_many_arguments)]
pub fn collate_with_temp(
input_dir: &PathBuf,
rad_dir: &PathBuf,
pub fn collate_with_temp<P1, P2>(
input_dir: P1,
rad_dir: P2,
num_threads: u32,
max_records: u32,
tsv_map: Vec<(u64, u64)>,
Expand All @@ -257,11 +262,16 @@ pub fn collate_with_temp(
cmdline: &str,
version: &str,
log: &slog::Logger,
) -> anyhow::Result<()> {
) -> anyhow::Result<()>
where
P1: Into<PathBuf>,
P2: AsRef<Path>,
{
// the number of corrected cells we'll write
let expected_output_chunks = tsv_map.len() as u64;
// the parent input directory
let parent = std::path::Path::new(input_dir);
let input_dir = input_dir.into();
let parent = std::path::Path::new(input_dir.as_path());

let n_workers = if num_threads > 1 {
(num_threads - 1) as usize
Expand Down Expand Up @@ -340,13 +350,13 @@ pub fn collate_with_temp(
.with_context(|| format!("couldn't create directory {}", cfname))?;
let owriter = Arc::new(Mutex::new(BufWriter::with_capacity(1048576, ofile)));

let i_dir = std::path::Path::new(rad_dir);
let i_dir = std::path::Path::new(rad_dir.as_ref());

if !i_dir.exists() {
crit!(
log,
"the input RAD path {} does not exist",
rad_dir.display()
"the input RAD path {:?} does not exist",
rad_dir.as_ref()
);
return Err(anyhow!("invalid input"));
}
Expand Down Expand Up @@ -708,7 +718,7 @@ pub fn collate_with_temp(
let umi_type =
rad_types::decode_int_type_tag(cc.umi_type).context("unknown barcode type id.")?;
// have access to the input directory
let input_dir = input_dir.clone();
let input_dir: PathBuf = input_dir.clone();
// the output file
let owriter = owriter.clone();
// and the progress bar
Expand Down
28 changes: 19 additions & 9 deletions src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use rust_htslib::bam::HeaderView;
use rust_htslib::{bam, bam::record::Aux, bam::Read};
use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::str;

// pub fn reset_signal_pipe_handler() -> Result<()> {
Expand Down Expand Up @@ -92,15 +92,19 @@ pub fn tid_2_contig(h: &HeaderView) -> HashMap<u32, String> {
dict
}

pub fn bam2rad(input_file: &PathBuf, rad_file: &PathBuf, num_threads: u32, log: &slog::Logger) {
let oname = Path::new(rad_file);
pub fn bam2rad<P1, P2>(input_file: P1, rad_file: P2, num_threads: u32, log: &slog::Logger)
where
P1: AsRef<Path>,
P2: AsRef<Path>,
{
let oname = Path::new(rad_file.as_ref());
let parent = oname.parent().unwrap();
std::fs::create_dir_all(&parent).unwrap();

if oname.exists() {
std::fs::remove_file(oname).expect("could not be deleted");
}
let ofile = File::create(rad_file).unwrap();
let ofile = File::create(rad_file.as_ref()).unwrap();

let mut bam = bam::Reader::from_path(&input_file).unwrap();
let bam_bytes = fs::metadata(&input_file).unwrap().len();
Expand Down Expand Up @@ -484,18 +488,24 @@ pub fn bam2rad(input_file: &PathBuf, rad_file: &PathBuf, num_threads: u32, log:
.write_all(&num_output_chunks.to_le_bytes())
.expect("couldn't write to output file.");

info!(log, "finished writing to {:?}.", rad_file);
info!(log, "finished writing to {:?}.", rad_file.as_ref());
}

pub fn view(rad_file: &PathBuf, print_header: bool, out_file: String, log: &slog::Logger) {
pub fn view<P>(rad_file: P, print_header: bool, out_file: String, log: &slog::Logger)
where
P: AsRef<Path>,
{
let _read_num = view2(rad_file, print_header, out_file, log).unwrap();
}
pub fn view2(
rad_file: &PathBuf,
pub fn view2<P>(
rad_file: P,
print_header: bool,
_out_file: String,
log: &slog::Logger,
) -> anyhow::Result<u64> {
) -> anyhow::Result<u64>
where
P: AsRef<Path>,
{
let i_file = File::open(rad_file).unwrap();
let mut br = BufReader::new(i_file);
let hdr = rad_types::RadHeader::from_bytes(&mut br);
Expand Down
24 changes: 4 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,6 @@ fn gen_random_kmer(k: usize) -> String {
s
}

/// Checks if the path pointed to by v exists. It can be
/// any valid entity (e.g. disk file, FIFO, directory, etc.).
/// If there is any issue with permissions or failure to properly
/// resolve symlinks, or if the path is wrong, it returns
/// an Err(String), else Ok(String).
fn file_exists_validator(v: &str) -> Result<String, String> {
// NOTE: we explicitly *do not* check `is_file()` here
// since we want to return true even if the path is to
// a FIFO/named pipe.
if !Path::new(v).exists() {
Err(String::from("No valid file was found at this path."))
} else {
Ok(v.to_string())
}
}

/// Checks if the path pointed to by v exists. It can be
/// any valid entity (e.g. disk file, FIFO, directory, etc.).
/// If there is any issue with permissions or failure to properly
Expand Down Expand Up @@ -147,13 +131,13 @@ fn main() -> anyhow::Result<()> {
.arg(
arg!(-b --"valid-bc" <VALIDBC> "uses true barcode collected from a provided file")
.conflicts_with_all(&["force-cells", "expect-cells", "knee-distance", "unfiltered-pl"])
.value_parser(file_exists_validator)
.value_parser(pathbuf_file_exists_validator)
)
.arg(
arg!(-u --"unfiltered-pl" <UNFILTEREDPL> "uses an unfiltered external permit list")
.conflicts_with_all(&["force-cells", "expect-cells", "knee-distance", "valid-bc"])
.requires("min-reads")
.value_parser(file_exists_validator)
.value_parser(pathbuf_file_exists_validator)
)
.arg(
arg!(-m --"min-reads" <MINREADS> "minimum read count threshold; only used with --unfiltered-pl")
Expand Down Expand Up @@ -343,7 +327,7 @@ fn main() -> anyhow::Result<()> {
None => None,
};

let _valid_bc = match t.get_one::<String>("valid-bc") {
let _valid_bc = match t.get_one::<PathBuf>("valid-bc") {
Some(v) => {
fmeth = CellFilterMethod::ExplicitList(v.clone());
Some(v)
Expand All @@ -352,7 +336,7 @@ fn main() -> anyhow::Result<()> {
};

//let _unfiltered_pl = match t.get_one::<String>("unfiltered-pl") {
if let Some(v) = t.get_one::<String>("unfiltered-pl") {
if let Some(v) = t.get_one::<PathBuf>("unfiltered-pl") {
let min_reads: usize = *t
.get_one("min-reads")
.expect("min-reads must be a valid integer");
Expand Down

0 comments on commit 8ea680f

Please sign in to comment.