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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// 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 DNF.
//!
//! DNF is the default package manager on RHEL-based Linux distributions. It works here roughly
//! like this:
//!
//! - Query the system package for what provides "command"
//! - Try to update the system cache if it doesn't exist
//! - Fall back to searching as regular user for "command"
//!
//! This way, as long as `dnf` is installed, it should always perform a lookup, although it may
//! come up empty.
use crate::provider::prelude::*;

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

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

impl Dnf {
    /// Create a new instance.
    pub fn new() -> Self {
        Default::default()
    }

    /// Get a list of candidates from the raw stdout of `dnf provides`.
    fn get_candidates_from_provides_output(&self, output: String) -> Vec<Candidate> {
        let lines = output
            .lines()
            .map(|s| s.to_string())
            .collect::<Vec<String>>();

        let mut results = vec![];
        let mut found_empty = true;
        let mut candidate = Candidate::default();

        for line in lines {
            if line.is_empty() {
                // Block processed
                found_empty = true;
                continue;
            }

            let (before, after) = match line.split_once(':') {
                Some((a, b)) => (a.trim(), b.trim()),
                None => {
                    log::warn!("ignoring unexpected output from dnf: '{}'", line);
                    found_empty = true;
                    continue;
                }
            };

            if found_empty {
                if !candidate.package.is_empty() {
                    results.push(candidate);
                }
                candidate = Candidate::default();
                candidate.package = before.to_string();
                candidate.description = after.to_string();
                candidate.actions.install = Some(cmd!("dnf", "install", "-y", before).privileged());
                found_empty = false;
            }
            if before == "Repo" {
                candidate.origin = after.to_string();
            }
            if before == "Provide" {
                // There might be more in here
                if let Some((package, version)) = after.split_once(" = ") {
                    candidate.actions.execute = cmd!(package);
                    candidate.version = version.to_string();
                } else {
                    candidate.actions.execute = cmd!(after);
                }
            }
        }
        results.push(candidate);

        results
    }

    /// Check whether the given candidates are installed.
    ///
    /// Consumes the vector in the process and generates a new one with updated contents.
    async fn check_installed(
        &self,
        target_env: &Arc<Environment>,
        mut candidates: Vec<Candidate>,
    ) -> Vec<Candidate> {
        let mut futures = vec![];
        for mut candidate in candidates.drain(0..) {
            let cloned_env = target_env.clone();
            let future = async_std::task::spawn(async move {
                // We could have this run with `dnf list --installed ...`, too, but that's
                // significantly slower.
                let is_installed = cloned_env
                    .output_of(cmd!("rpm", "-q", "--quiet", &candidate.package))
                    .await
                    .map(|_| true)
                    .unwrap_or(false);

                if is_installed {
                    candidate.actions.install = None;
                }
                candidate
            });
            futures.push(future);
        }

        futures::future::join_all(futures).await
    }

    /// Search for the package providing the given command.
    async fn search(
        &self,
        target_env: &Arc<Environment>,
        command: &str,
        user_only: bool,
    ) -> Result<String, Error> {
        let mut cmd = cmd!("dnf", "-q", "--color", "never", "provides", command);
        if !user_only {
            cmd.append(&["-C"]);
        }

        target_env.output_of(cmd).await.map_err(Error::from)
    }

    /// Try to update the system package cache.
    async fn update_cache(&self, target_env: &Arc<Environment>) -> Result<(), CacheError> {
        target_env
            .output_of(cmd!("dnf", "makecache", "-q", "--color", "never").privileged())
            .await
            .map(|_| ())
            .map_err(CacheError::from)
    }
}

#[async_trait]
impl IsProvider for Dnf {
    async fn search_internal(
        &self,
        command: &str,
        target_env: Arc<Environment>,
    ) -> ProviderResult<Vec<Candidate>> {
        let stdout = match self.search(&target_env, command, false).await {
            Ok(val) => val,
            Err(Error::NoCache) => async_std::task::block_on(async {
                log::info!("dnf cache is outdated, trying to update");
                let success = self.update_cache(&target_env).await.is_ok();
                self.search(&target_env, command, !success).await
            })
            .map_err(|err| err.into_provider(command))?,
            Err(err) => return Err(err.into_provider(command)),
        };

        let candidates = self.get_candidates_from_provides_output(stdout);
        let mut candidates = self.check_installed(&target_env, candidates).await;
        candidates.iter_mut().for_each(|candidate| {
            if candidate.actions.execute.is_empty() {
                candidate.actions.execute = cmd!(command.to_string());
            }
        });

        Ok(candidates)
    }
}

#[derive(Debug, ThisError)]
pub enum Error {
    #[error("command not found")]
    NotFound,

    #[error("cannot query packages, please update system (root) cache")]
    Cache(#[from] CacheError),

    #[error("no package cache present, please update system cache (as root user)")]
    NoCache,

    #[error("'{0}' must be installed to use this provider")]
    Requirements(String),

    #[error(transparent)]
    Execution(ExecutionError),
}

#[derive(Debug, ThisError)]
#[error("failed to update dnf system cache")]
pub struct CacheError(#[from] ExecutionError);

impl Error {
    pub fn into_provider(self, command: &str) -> ProviderError {
        match self {
            Self::NotFound => ProviderError::NotFound(command.to_string()),
            Self::Requirements(what) => ProviderError::Requirements(what),
            _ => ProviderError::ApplicationError(anyhow::Error::new(self)),
        }
    }
}

impl From<ExecutionError> for Error {
    fn from(value: ExecutionError) -> Self {
        if let ExecutionError::NonZero { ref output, .. } = value {
            let matcher = OutputMatcher::from(output);

            if matcher.starts_with("Error: No matches found") {
                Error::NotFound
            } else if matcher.starts_with("Error: Cache-only enabled but no cache") {
                Error::NoCache
            } else {
                Error::Execution(value)
            }
        // FIXME(hartan): This relies entirely on the fact that all commands this provider executes
        // call into `dnf`. This is needed because we cannot match against a `String` in the
        // pattern, because there's no `String` literal syntax for patterns.
        } else if matches!(value, ExecutionError::NotFound(_)) {
            Error::Requirements("dnf".to_string())
        } else {
            Error::Execution(value)
        }
    }
}

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

    #[test]
    fn initialize() {
        let _dnf = Dnf::new();
    }

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

    /// Searching without system cache
    ///
    /// - Searched with: dnf 4.14.0
    /// - Search command: "dnf -q -C --color never provides asdwasda"
    /// - Remaining outputs taken from `matches_htop` test
    #[test]
    fn cache_empty() {
        let query = quick_test!(
            Dnf::new(),
            Err(ExecutionError::NonZero {
                command: "dnf".to_string(),
                output: std::process::Output {
                    stdout: r"".into(),
                    stderr: r#"Error: Cache-only enabled but no cache for 'fedora'"#.into(),
                    status: ExitStatus::from_raw(1),
                },
            }),
            Err(ExecutionError::NotFound("dnf".to_string())),
            Ok("
htop-3.2.1-2.fc37.x86_64 : Interactive process viewer
Repo        : fedora
Matched from:
Provide    : htop = 3.2.1-2.fc37

htop-3.2.2-2.fc37.x86_64 : Interactive process viewer
Repo        : updates
Matched from:
Provide    : htop = 3.2.2-2.fc37
"
            .to_string()),
            // Already installed
            Ok("".to_string()),
            // Already installed
            Ok("".to_string())
        );

        let result = query.results.expect("expected successful results");
        assert_eq!(result.len(), 2);
        assert!(result[0].package.starts_with("htop-3.2.1-2"));
    }

    /// Searching nonexistent package
    ///
    /// - Searched with: dnf 4.14.0
    /// - Search command: "dnf -q -C --color never provides asdwasda"
    #[test]
    fn search_nonexistent() {
        let query = quick_test!(Dnf::new(), Err(ExecutionError::NonZero {
            command: "dnf".to_string(),
            output: std::process::Output {
                stdout: r"".into(),
                stderr: r#"Error: No matches found. If searching for a file, try specifying the full path or using a wildcard prefix ("*/") at the beginning."#.into(),
                status: ExitStatus::from_raw(1),
            },
        }));

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

    /// Searching existing package htop
    ///
    /// - Searched with: dnf 4.14.0
    /// - Search command: "dnf -q -C --color never provides htop"
    #[test]
    fn matches_htop() {
        let query = quick_test!(
            Dnf::new(),
            Ok("
htop-3.2.1-2.fc37.x86_64 : Interactive process viewer
Repo        : fedora
Matched from:
Provide    : htop = 3.2.1-2.fc37

htop-3.2.2-2.fc37.x86_64 : Interactive process viewer
Repo        : updates
Matched from:
Provide    : htop = 3.2.2-2.fc37
"
            .to_string()),
            // This result is not installable (already installed)
            Ok("".to_string()),
            // This result *is* installable
            Err(ExecutionError::NonZero {
                command: "rpm".to_string(),
                output: std::process::Output {
                    stdout: r"".into(),
                    stderr: r"".into(),
                    status: ExitStatus::from_raw(1),
                },
            })
        );

        let result = query.results.unwrap();

        assert_eq!(result.len(), 2);
        assert!(result[0].package.starts_with("htop-3.2.1-2"));
        assert_eq!(result[0].version, "3.2.1-2.fc37");
        assert_eq!(result[0].origin, "fedora");
        assert_eq!(result[0].description, "Interactive process viewer");
        assert_eq!(result[0].actions.execute, vec!["htop"].into());
        assert_eq!(result[1].description, "Interactive process viewer");

        let num_installable = result
            .iter()
            .fold(0, |acc, c| acc + (c.actions.install.is_some() as usize));
        assert_eq!(num_installable, 1);
    }

    /// Searching existing binary 'ping'
    ///
    /// - Searched with: dnf 4.14.0
    /// - Search command: "dnf -q -C --color never provides ping"
    #[test]
    fn matches_ping() {
        let query = quick_test!(
            Dnf::new(),
            Ok("
iputils-20211215-3.fc37.x86_64 : Network monitoring tools including ping
Repo        : fedora
Matched from:
Filename    : /usr/bin/ping
Provide    : /bin/ping
Filename    : /usr/sbin/ping

iputils-20221126-1.fc37.x86_64 : Network monitoring tools including ping
Repo        : @System
Matched from:
Filename    : /usr/bin/ping
Provide    : /bin/ping
Filename    : /usr/sbin/ping

iputils-20221126-1.fc37.x86_64 : Network monitoring tools including ping
Repo        : updates
Matched from:
Filename    : /usr/bin/ping
Provide    : /bin/ping
Filename    : /usr/sbin/ping
"
            .to_string()),
            // First one is installed
            Ok("".to_string()),
            // Second isn't
            Err(ExecutionError::NonZero {
                command: "rpm".to_string(),
                output: std::process::Output {
                    stdout: r"".into(),
                    stderr: r"".into(),
                    status: ExitStatus::from_raw(1),
                },
            }),
            // Third one throws confusing error (not installed)
            Err(ExecutionError::NotFound("rpm".to_string()))
        );

        let result = query.results.unwrap();

        assert!(result.len() == 3);
        assert!(result[0].package.starts_with("iputils"));
        assert!(result[0].version.is_empty());
        assert!(result[0].origin == "fedora");
        assert!(result[1].origin == "@System");
        assert!(result[0].description == "Network monitoring tools including ping");
        assert!(result[0].actions.execute == vec!["/bin/ping"].into());
        assert!(result[1].description == "Network monitoring tools including ping");

        let num_installable = result
            .iter()
            .fold(0, |acc, c| acc + (c.actions.install.is_some() as usize));
        assert_eq!(num_installable, 2);
    }
}