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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// 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

//! Search packages with pacman
use crate::provider::prelude::*;
use std::str::FromStr;

#[derive(Debug, ThisError)]
pub enum Error {
    #[error("pacman database files don't exist, please update database files")]
    NoDatabase,
    #[error("failed to parse stderr from pacman: '{0}'")]
    ParseError(String),
}

/// Shorthand to get error type from stderr
impl FromStr for Error {
    type Err = Self;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.contains("warning: database file") & s.contains("not exist (use '-Fy' to download)") {
            Ok(Self::NoDatabase)
        } else {
            Err(Self::ParseError(s.to_string()))
        }
    }
}

#[derive(Default, Debug, PartialEq)]
pub struct Pacman;

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

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

    fn get_candidates_from_files_output(&self, output: String) -> ProviderResult<Vec<Candidate>> {
        let mut results = vec![];

        for line in output.lines() {
            let mut candidate = Candidate::default();
            for (index, piece) in line.splitn(4, '\0').enumerate() {
                let piece = piece.to_string();
                match index {
                    0 => candidate.origin = piece,
                    1 => candidate.package = piece,
                    2 => candidate.version = piece,
                    3 => candidate.actions.execute = cmd!(piece),
                    _ => panic!("line contained superfluous piece {}", piece),
                }
            }
            if !candidate.package.is_empty() {
                results.push(candidate);
            }
        }

        Ok(results)
    }
}

#[async_trait]
impl IsProvider for Pacman {
    async fn search_internal(
        &self,
        command: &str,
        target_env: Arc<Environment>,
    ) -> ProviderResult<Vec<Candidate>> {
        let stdout = match target_env
            .output_of(cmd!(
                "pacman",
                "-F",
                "--noconfirm",
                "--machinereadable",
                command
            ))
            .await
        {
            Ok(val) => val,
            Err(ExecutionError::NonZero { ref output, .. })
                if (output.stdout.is_empty() && output.stderr.is_empty()) =>
            {
                return Err(ProviderError::NotFound(command.to_string()))
            }
            Err(e) => return Err(ProviderError::from(e)),
        };

        let mut candidates = self.get_candidates_from_files_output(stdout)?;
        candidates.iter_mut().for_each(|candidate| {
            if candidate.actions.execute.is_empty() {
                candidate.actions.execute = cmd!(command);
            }
        });

        Ok(candidates)
    }
}

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

    #[test]
    fn initialize() {
        let _pacman = Pacman::new();
    }

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

    /// Searching without system cache
    ///
    /// - Searched with: pacman 6.0.2
    /// - Search command: "pacman -F --noconfirm --machinereadable asdwasda"
    #[test]
    fn cache_empty() {
        let query =
            quick_test!(Pacman::new(), Err(ExecutionError::NonZero {
            command: "pacman".to_string(),
            output: std::process::Output {
                stdout: r"".into(),
                stderr: r"warning: database file for 'core' does not exist (use '-Fy' to download)
warning: database file for 'extra' does not exist (use '-Fy' to download)
warning: database file for 'community' does not exist (use '-Fy' to download)
".into(),
                status: ExitStatus::from_raw(1),
            }
        }));

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

    /// Searching nonexistent package
    ///
    /// - Searched with: pacman 6.0.2
    /// - Search command: "pacman -F --noconfirm --machinereadable asdwasda"
    #[test]
    fn search_nonexistent() {
        let query = quick_test!(
            Pacman::new(),
            Err(ExecutionError::NonZero {
                command: "pacman".to_string(),
                output: std::process::Output {
                    stdout: r"".into(),
                    stderr: r"".into(),
                    status: ExitStatus::from_raw(1),
                }
            })
        );

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

    /// Searching existent package
    ///
    /// - Searched with: pacman 6.0.2
    /// - Search command: "pacman -F --noconfirm --machinereadable htop"
    #[test]
    fn matches_htop() {
        let query = quick_test!(
            Pacman::new(),
            Ok("
extra\0bash-completion\02.11-3\0usr/share/bash-completion/completions/htop
extra\0htop\03.2.2-1\0usr/bin/htop
community\0pcp\06.0.3-1\0etc/pcp/pmlogconf/tools/htop
community\0pcp\06.0.3-1\0var/lib/pcp/config/pmlogconf/tools/htop
"
            .to_string())
        );

        let result = query.results.unwrap();

        assert_eq!(result.len(), 4);
        assert!(result[0].package.starts_with("bash-completion"));
        assert_eq!(result[0].version, "2.11-3");
        assert_eq!(result[0].origin, "extra");
        assert!(result[0].description.is_empty());
        assert_eq!(
            result[0].actions.execute,
            vec!["usr/share/bash-completion/completions/htop"].into()
        );
        assert!(result[1].package.starts_with("htop"))
    }
}