anchor_coverage/util/
mod.rs

1use anyhow::{bail, Result};
2use std::{
3    env::current_dir,
4    ffi::OsStr,
5    fs::read_dir,
6    path::{Path, PathBuf},
7};
8
9pub mod var_guard;
10
11pub fn files_with_extension(dir: impl AsRef<Path>, extension: &str) -> Result<Vec<PathBuf>> {
12    let mut pcs_paths = Vec::new();
13    for result in read_dir(dir)? {
14        let entry = result?;
15        let path = entry.path();
16        if path.is_file() && path.extension() == Some(OsStr::new(extension)) {
17            pcs_paths.push(path);
18        }
19    }
20    Ok(pcs_paths)
21}
22
23pub fn patched_agave_tools(path: impl AsRef<Path>) -> Result<Option<PathBuf>> {
24    let mut path_bufs = Vec::new();
25    for result in read_dir(path)? {
26        let entry = result?;
27        let path = entry.path();
28        let Some(file_name) = path.file_name() else {
29            continue;
30        };
31        if file_name
32            .to_str()
33            .is_none_or(|s| !s.starts_with("patched-agave-tools-"))
34        {
35            continue;
36        }
37        if !path.is_dir() {
38            eprintln!(
39                "Warning: Found `{}` but it is not a directory. If it contains patched Agave \
40                 tools that you want to use, please unzip and untar it.",
41                path.display()
42            );
43            continue;
44        }
45        path_bufs.push(path);
46    }
47    let mut iter = path_bufs.into_iter();
48    let Some(path_buf) = iter.next() else {
49        return Ok(None);
50    };
51    if iter.next().is_some() {
52        bail!("Found multiple patched Agave tools directories");
53    }
54    Ok(Some(path_buf))
55}
56
57pub trait StripCurrentDir {
58    fn strip_current_dir(&self) -> &Self;
59}
60
61impl StripCurrentDir for Path {
62    fn strip_current_dir(&self) -> &Self {
63        let Ok(current_dir) = current_dir() else {
64            return self;
65        };
66        self.strip_prefix(current_dir).unwrap_or(self)
67    }
68}