1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
//! The core functionality
//!
//! See [crate-level documentation](../index.html) for more information on this module.

use {
    crate::{
        util::{is_executable, is_executable_path, split_path_env},
        IchwhError, IchwhResult,
    },
    async_std::{
        fs::read_dir,
        path::{Path, PathBuf},
    },
    futures::stream::StreamExt,
};

#[cfg(windows)]
use {
    crate::util::{filename_matches, pathext},
    std::collections::HashMap,
};

/// Searches `PATH` for an executable with the name `bin`. The core functionality of the `which`
/// command
///
/// # Errors
///
/// * Binary is not found
/// * PATH is not defined as an environment variable
/// * An IO error occurs
pub async fn which(bin: &str) -> IchwhResult<PathBuf> {
    #[cfg(unix)]
    let is_path = bin.contains('/');
    #[cfg(windows)]
    let is_path = bin.contains('\\');

    if is_path {
        // It's an absolute or relative path, so see if it points to an executable file
        let path = Path::new(bin);
        if let Some(actual_path) = is_executable_path(&path).await? {
            return Ok(actual_path);
        } else {
            return Err(IchwhError::BinaryNotFound(bin.to_string()));
        }
    }

    let dirs = split_path_env()?;

    for dir in dirs {
        let res = which_in_dir(&bin, &dir).await?;
        if let Some(res) = res {
            return Ok(res);
        }
    }

    Err(IchwhError::BinaryNotFound(bin.to_string()))
}

/// Searches `PATH` for all executables with the name `bin`. Returns a list of paths, in the order
/// of which they were found.
pub async fn which_all(bin: &str) -> IchwhResult<Vec<PathBuf>> {
    if bin.contains('/') {
        // It's an absolute or relative path, so see if it points to an executable file
        let path = Path::new(bin);
        if let Some(actual_path) = is_executable_path(&path).await? {
            return Ok(vec![actual_path]);
        } else {
            return Err(IchwhError::BinaryNotFound(bin.to_string()));
        }
    }

    let dirs = split_path_env()?;

    let mut rtn = Vec::new();

    for dir in dirs {
        #[cfg(unix)]
        {
            let res = which_in_dir(&bin, &dir).await?;
            if let Some(res) = res {
                rtn.push(res);
            }
        }
        #[cfg(windows)]
        {
            let res = which_all_in_dir(&bin, &dir).await?;
            rtn.extend(res);
        }
    }

    Ok(rtn)
}

/// Searches a directory for an exexcutable with the name `bin`.
///
/// # Errors
///
/// * An IO error occurs
pub async fn which_in_dir<P: AsRef<Path>>(bin: &str, path: P) -> IchwhResult<Option<PathBuf>> {
    #[cfg(windows)]
    {
        let matching_entries = which_all_in_dir(bin, path).await?;

        Ok(matching_entries.get(0).cloned())
    }

    #[cfg(unix)]
    {
        let mut entries = read_dir(path).await?;

        while let Some(entry) = entries.next().await {
            let entry = entry?;

            if is_executable(&entry).await? && entry.file_name() == bin {
                return Ok(Some(entry.path()));
            }
        }

        Ok(None)
    }
}

/// Find all executable files that could possibly match in a given directory,
/// sorted by their extensions' appearance in %PATHEXT%
#[cfg(windows)]
pub(crate) async fn which_all_in_dir<P: AsRef<Path>>(
    bin: &str,
    path: P,
) -> IchwhResult<Vec<PathBuf>> {
    let mut matches = read_dir(path)
        .await?
        .filter_map(|entry| {
            async {
                if let Ok(entry) = entry {
                    let is_exec = is_executable(&entry).await;
                    if is_exec.is_ok() && is_exec.unwrap() && filename_matches(&bin, &entry) {
                        return Some(entry.path());
                    }
                }
                None
            }
        })
        .collect::<Vec<_>>()
        .await;

    // Create a lookup table for executable extensions (extension --maps-> index)
    let exts = pathext()?; // need this for lifetime reasons
    let exts = exts
        .iter()
        .enumerate()
        .map(|(a, b)| (b, a))
        .collect::<HashMap<_, _>>();

    // Sort the matches by their extensions' appearance in PATHEXT
    matches.sort_by(|a, b| {
        let a_ext = a
            .extension()
            .unwrap()
            .to_string_lossy()
            .to_ascii_uppercase();
        let b_ext = b
            .extension()
            .unwrap()
            .to_string_lossy()
            .to_ascii_uppercase();

        exts[&a_ext].cmp(&exts[&b_ext])
    });

    Ok(matches)
}