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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! APIs for spawning subprocesses and handling their results.

use std::{
    process::Stdio,
    sync::atomic::{AtomicBool, Ordering},
};

use bytes::{Bytes, BytesMut};
use dialoguer::FuzzySelect;
use futures::prelude::*;
use indoc::indoc;
use itertools::{chain, Itertools};
use regex::{RegexSet, RegexSetBuilder};
use tap::prelude::*;
use tokio::{
    io::{self, AsyncRead, AsyncWrite},
    process::Command as Exec,
    task::JoinHandle,
};
#[allow(clippy::wildcard_imports)]
use tokio_util::{
    codec::{BytesCodec, FramedRead},
    compat::*,
    either::Either,
};
use which::which;

use crate::{
    error::{Error, Result},
    print::{println_quoted, prompt, question_theme},
};

/// Different ways in which a [`Cmd`] shall be dealt with.
#[derive(Copy, Clone, Debug)]
pub enum Mode {
    /// Solely prints out the command that should be executed and stops.
    PrintCmd,

    /// Silently collects all the `stdout`/`stderr` combined. Prints nothing.
    Mute,

    /// Prints out the command which should be executed, runs it and collects
    /// its `stdout`/`stderr` combined.
    ///
    /// This is potentially dangerous as it destroys the colored `stdout`. Use
    /// it only if really necessary.
    CheckAll,

    /// Prints out the command which should be executed, runs it and collects
    /// its `stderr`.
    ///
    /// This will work with a colored `stdout`.
    CheckErr,

    /// A CUSTOM prompt implemented by a `pacaptr` module itself.
    ///
    /// Prints out the command which should be executed, runs it and collects
    /// its `stderr`. Also, this will ask for confirmation before
    /// proceeding.
    Prompt,
}

/// The status code type returned by a [`Cmd`],
pub type StatusCode = i32;

/// Returns a [`Result`] for a [`Cmd`] according to if its exit status code
/// indicates an error.
///
/// # Errors
/// This function might return one of the following errors:
///
/// - [`Error::CmdStatusCodeError`], when `status` is `Some(n)` where `n != 0`.
/// - [`Error::CmdInterruptedError`], when `status` is `None`.
#[allow(clippy::missing_const_for_fn)]
fn exit_result(code: Option<StatusCode>, output: Output) -> Result<Output> {
    match code {
        Some(0) => Ok(output),
        Some(code) => Err(Error::CmdStatusCodeError { code, output }),
        None => Err(Error::CmdInterruptedError),
    }
}

/// The type for captured `stdout`, and if set to [`Mode::CheckAll`], mixed with
/// captured `stderr`.
pub type Output = Vec<u8>;

/// A command to be executed, provided in `command-flags-keywords` form.
#[must_use]
#[derive(Debug, Clone, Default)]
pub struct Cmd {
    /// Flag indicating if a **normal admin** needs to run this command with
    /// `sudo`.
    pub sudo: bool,

    /// The "command" part of the command string, e.g. `brew install`.
    pub cmd: Vec<String>,

    /// The "flags" part of the command string, e.g. `--dry-run`.
    pub flags: Vec<String>,

    /// The "keywords" part of the command string, e.g. `curl fish`.
    pub kws: Vec<String>,
}

impl Cmd {
    /// Makes a new [`Cmd`] instance with the given [`cmd`](Cmd::cmd) part.
    pub(crate) fn new(cmd: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        Self {
            cmd: cmd.into_iter().map(|s| s.as_ref().into()).collect(),
            ..Self::default()
        }
    }

    /// Makes a new [`Cmd`] instance with the given [`cmd`](Cmd::cmd) part,
    /// setting [`sudo`](field@Cmd::sudo) to `true`.
    pub(crate) fn with_sudo(cmd: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        Self::new(cmd).sudo(true)
    }

    /// Overrides the value of [`flags`](field@Cmd::flags).
    pub(crate) fn flags(mut self, flags: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        self.flags = flags.into_iter().map(|s| s.as_ref().into()).collect();
        self
    }

    /// Overrides the value of [`kws`](field@Cmd::kws).
    pub(crate) fn kws(mut self, kws: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        self.kws = kws.into_iter().map(|s| s.as_ref().into()).collect();
        self
    }

    /// Overrides the value of [`sudo`](field@Cmd::sudo).
    pub(crate) const fn sudo(mut self, sudo: bool) -> Self {
        self.sudo = sudo;
        self
    }

    /// Determines if this command actually needs to run with `sudo -S`.
    ///
    /// If a **normal admin** needs to run it with `sudo`, and we are not
    /// `root`, then this is the case.
    #[must_use]
    fn should_sudo(&self) -> bool {
        self.sudo && !is_root()
    }

    /// Converts a [`Cmd`] object into an [`Exec`].
    #[must_use]
    fn build(self) -> Exec {
        // ! Special fix for `zypper`: `zypper install -y curl` is accepted,
        // ! but not `zypper install curl -y`.
        // ! So we place the flags first, and then keywords.
        if self.should_sudo() {
            Exec::new("sudo").tap_mut(|builder| {
                builder
                    .arg("-S")
                    .args(&self.cmd)
                    .args(&self.flags)
                    .args(&self.kws);
            })
        } else {
            let (cmd, subcmd) = self
                .cmd
                .split_first()
                .expect("failed to build Cmd, command is empty");
            Exec::new(cmd).tap_mut(|builder| {
                builder.args(subcmd).args(&self.flags).args(&self.kws);
            })
        }
    }
}

/// Takes contents from an input stream and copy to an output stream (optional)
/// and a [`Vec<u8>`], then returns the [`Vec<u8>`].
///
/// Helper to implement [`Cmd::exec_checkerr`] and [`Cmd::exec_checkall`].
///
/// # Arguments
///
/// * `src` - The input stream to read from.
/// * `out` - The optional output stream to write to.
async fn exec_tee(
    src: impl Stream<Item = io::Result<Bytes>> + Send,
    out: Option<impl AsyncWrite + Send>,
) -> Result<Vec<u8>> {
    let mut buf = Vec::<u8>::new();
    let buf_sink = (&mut buf).into_sink();

    let sink = if let Some(out) = out {
        let out_sink = out.compat_write().into_sink();
        buf_sink.fanout(out_sink).left_sink()
    } else {
        buf_sink.right_sink()
    };

    src.forward(sink).await?;
    Ok(buf)
}

macro_rules! docs_errors_exec {
    () => {
        indoc! {"
            # Errors
            This function might return one of the following errors:

            - [`Error::CmdJoinError`]
            - [`Error::CmdNoHandleError`]
            - [`Error::CmdSpawnError`]
            - [`Error::CmdWaitError`]
            - [`Error::CmdStatusCodeError`]
            - [`Error::CmdInterruptedError`]
        "}
    };
}

impl Cmd {
    /// Executes a [`Cmd`] and returns its output.
    ///
    /// The exact behavior depends on the [`Mode`] passed in (see the definition
    /// of [`Mode`] for more info).
    #[doc = docs_errors_exec!()]
    pub(crate) async fn exec(self, mode: Mode) -> Result<Output> {
        match mode {
            Mode::PrintCmd => {
                println_quoted(&*prompt::CANCELED, &self);
                Ok(Output::default())
            }
            Mode::Mute => self.exec_checkall(true).await,
            Mode::CheckAll => {
                println_quoted(&*prompt::RUNNING, &self);
                self.exec_checkall(false).await
            }
            Mode::CheckErr => {
                println_quoted(&*prompt::RUNNING, &self);
                self.exec_checkerr(false).await
            }
            Mode::Prompt => self.exec_prompt(false).await,
        }
    }

    /// Inner implementation of [`Cmd::exec_checkerr`] (if `merge` is `false`)
    /// and [`Cmd::exec_checkall`] (otherwise).
    #[doc = docs_errors_exec!()]
    async fn exec_check_output(self, mute: bool, merge: bool) -> Result<Output> {
        use tokio_stream::StreamExt;
        use Error::{CmdJoinError, CmdNoHandleError, CmdSpawnError, CmdWaitError};

        fn make_reader(
            src: Option<impl AsyncRead>,
            name: &str,
        ) -> Result<impl Stream<Item = io::Result<Bytes>>> {
            src.map(into_bytes).ok_or_else(|| CmdNoHandleError {
                handle: name.into(),
            })
        }

        let mut child = self
            .build()
            .stderr(Stdio::piped())
            .tap_deref_mut(|cmd| {
                if merge {
                    cmd.stdout(Stdio::piped());
                }
            })
            .spawn()
            .map_err(CmdSpawnError)?;

        let stderr_reader = make_reader(child.stderr.take(), "stderr")?;
        let mut reader = if merge {
            let stdout_reader = make_reader(child.stdout.take(), "stdout")?;
            StreamExt::merge(stdout_reader, stderr_reader).left_stream()
        } else {
            stderr_reader.right_stream()
        };

        let mut out = if merge {
            Either::Left(io::stdout())
        } else {
            Either::Right(io::stderr())
        };

        let code: JoinHandle<Result<Option<i32>>> = tokio::spawn(async move {
            let status = child.wait().await.map_err(CmdWaitError)?;
            Ok(status.code())
        });

        let output = exec_tee(&mut reader, (!mute).then_some(&mut out)).await?;
        let code = code.await.map_err(CmdJoinError)??;
        exit_result(code, output)
    }

    /// Executes a [`Cmd`] and returns its `stdout` and `stderr`.
    ///
    /// If `mute` is `false`, then normal `stdout/stderr` output will be printed
    /// to `stdout` too.
    #[doc = docs_errors_exec!()]
    async fn exec_checkall(self, mute: bool) -> Result<Output> {
        self.exec_check_output(mute, true).await
    }

    /// Executes a [`Cmd`] and collects its `stderr`.
    ///
    /// If `mute` is `false`, then its `stderr` output will be printed to
    /// `stderr` too.
    #[doc = docs_errors_exec!()]
    async fn exec_checkerr(self, mute: bool) -> Result<Output> {
        self.exec_check_output(mute, false).await
    }

    /// Executes a [`Cmd`] and collects its `stderr`.
    ///
    /// If `mute` is `false`, then its `stderr` output will be printed to
    /// `stderr` too.
    ///
    /// This function behaves just like [`exec_checkerr`](Cmd::exec_checkerr),
    /// but in addition, the user will be prompted if (s)he wishes to
    /// continue with the command execution.
    #[doc = docs_errors_exec!()]
    async fn exec_prompt(self, mute: bool) -> Result<Output> {
        /// If the user has skipped all the prompts with `yes`.
        static ALL: AtomicBool = AtomicBool::new(false);

        // The answer obtained from the prompt.
        // The only Atomic* we're dealing with is `ALL`, so `Ordering::Relaxed` is fine.
        // See: <https://marabos.nl/atomics/memory-ordering.html#relaxed>
        let proceed = ALL.load(Ordering::Relaxed) || {
            println_quoted(&*prompt::PENDING, &self);
            let answer = tokio::task::block_in_place(move || {
                prompt(
                    "Proceed",
                    "with the previous command?",
                    &["Yes", "All", "No"],
                )
            })?;
            match answer {
                // The default answer is `Yes`.
                0 => true,
                // You can also say `All` to answer `Yes` to all the other questions that follow.
                1 => {
                    ALL.store(true, Ordering::Relaxed);
                    true
                }
                // Or you can say `No`.
                2 => false,
                // ! I didn't put a `None` option because you can just Ctrl-C it if you want.
                _ => unreachable!(),
            }
        };
        if !proceed {
            return Ok(Output::default());
        }
        println_quoted(&*prompt::RUNNING, &self);
        self.exec_checkerr(mute).await
    }
}

impl std::fmt::Display for Cmd {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sudo: &str = if self.should_sudo() { "sudo -S " } else { "" };
        let cmd = chain!(&self.cmd, &self.flags, &self.kws).join(" ");
        write!(f, "{sudo}{cmd}")
    }
}

/// Gives a prompt and returns the index of the user choice.
fn prompt(prompt: &str, question: &str, expected: &[&str]) -> Result<usize> {
    Ok(FuzzySelect::with_theme(&question_theme(prompt))
        .with_prompt(question)
        .items(expected)
        .default(0)
        .interact()?)
}

macro_rules! docs_errors_grep {
    () => {
        indoc! {"
            # Errors
            Returns an [`Error::OtherError`] when any of the
            regex patterns is ill-formed.
        "}
    };
}

/// Finds all lines in the given `text` that matches all the `patterns`.
///
/// We suppose that all patterns are legal regular expressions.
/// An error message will be returned if this is not the case.
#[doc = docs_errors_grep!()]
pub fn grep<'t>(text: &'t str, patterns: &[&str]) -> Result<Vec<&'t str>> {
    let patterns: RegexSet = RegexSetBuilder::new(patterns)
        .case_insensitive(true)
        .build()
        .map_err(|e| Error::OtherError(format!("ill-formed patterns found: {e:?}")))?;
    Ok(text
        .lines()
        .filter(|line| patterns.matches(line).into_iter().count() == patterns.len())
        .collect())
}

/// Prints the result of [`grep`] line by line.
#[doc = docs_errors_grep!()]
pub fn grep_print(text: &str, patterns: &[&str]) -> Result<()> {
    grep_print_with_header(text, patterns, 0)
}

/// Prints the result of [`grep`] line by line, with `header_lines` of header
/// prepended.
/// If `header_lines >= text.lines().count()`, then `text` is printed without
/// changes.
#[doc = docs_errors_grep!()]
pub fn grep_print_with_header(text: &str, patterns: &[&str], header_lines: usize) -> Result<()> {
    let lns = text.lines().collect_vec();
    let (header, rest) = lns.split_at(header_lines);
    header
        .iter()
        .copied()
        .chain(grep(&rest.join("\n"), patterns)?)
        .for_each(|ln| println!("{ln}"));
    Ok(())
}

/// Checks if an executable exists by name (consult `$PATH`) or by path.
///
/// To check by one parameter only, pass `""` to the other one.
#[must_use]
pub fn is_exe(name: &str, path: &str) -> bool {
    (!path.is_empty() && which(path).is_ok()) || (!name.is_empty() && which(name).is_ok())
}

/// Checks if the current user is root or admin.
#[cfg(windows)]
#[must_use]
pub fn is_root() -> bool {
    is_elevated::is_elevated()
}

/// Checks if the current user is root or admin.
#[cfg(unix)]
#[must_use]
pub fn is_root() -> bool {
    nix::unistd::Uid::current().is_root()
}

/// Turns an [`AsyncRead`] into a [`Stream`].
///
/// _Shamelessly copied from [`StackOverflow`](https://stackoverflow.com/a/59327560)._
fn into_bytes(reader: impl AsyncRead) -> impl Stream<Item = io::Result<Bytes>> {
    FramedRead::new(reader, BytesCodec::new()).map_ok(BytesMut::freeze)
}