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
// Copyright (C) 2023 Andreas Hartmann <hartan@7x.de>
// GNU General Public License v3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt)
// SPDX-License-Identifier: GPL-3.0-or-later

//! # Path provider.
//!
//! Searches for an executable in the `$PATH`. Since this provider runs on all environments, it is
//! useful to e.g. discover executables available in a toolbx container.
use crate::provider::prelude::*;

#[derive(Debug, Default, PartialEq)]
pub struct Path {}

impl fmt::Display for Path {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "$PATH")
    }
}

impl Path {
    pub fn new() -> Path {
        Default::default()
    }
}

#[async_trait]
impl IsProvider for Path {
    async fn search_internal(
        &self,
        command: &str,
        target_env: Arc<Environment>,
    ) -> ProviderResult<Vec<Candidate>> {
        let result_success = |package: String| {
            Ok(vec![Candidate {
                package: package.clone(),
                actions: Actions {
                    install: None,
                    execute: cmd!(package),
                },
                ..Candidate::default()
            }])
        };

        if &crate::environment::current() == target_env.as_ref() {
            match which::which(command) {
                Ok(path) => result_success(path.display().to_string()),
                Err(_) => Err(ProviderError::NotFound(command.to_string())),
            }
        } else {
            let stdout = target_env
                .output_of(cmd!("command", "-v", command))
                .await
                .map_err(|e| {
                    if let ExecutionError::NonZero { .. } = e {
                        ProviderError::NotFound(command.to_string())
                    } else {
                        ProviderError::from(e)
                    }
                })?;

            result_success(stdout.trim_end().to_string())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test::prelude::*;

    test::default_tests!(Path::new());

    #[test]
    fn search_nonexistent() {
        let query = quick_test!(
            Path::new(),
            Err(ExecutionError::NonZero {
                command: "command".to_string(),
                output: std::process::Output {
                    stdout: "".into(),
                    stderr: "".into(),
                    status: ExitStatus::from_raw(1),
                }
            })
        );

        assert::is_err!(query);
        assert::err::not_found!(query);
    }

    #[test]
    fn search_existent() {
        let query = quick_test!(Path::new(), Ok("/usr/bin/top".to_string()));

        let result = query.results.unwrap();

        assert_eq!(result.len(), 1);
        assert_eq!(result[0].package, "/usr/bin/top".to_string());
        assert_eq!(result[0].actions.execute, vec!["/usr/bin/top"].into());
    }
}