gix_prompt/
lib.rs

1//! Git style prompting with support for `GIT_ASKPASS` and `askpass` program configuration.
2//!
3//! ### Compatibility
4//!
5//! This is a unix-only crate which will return with an error when trying to obtain any prompt on other platforms.
6//! On those platforms it is common to have helpers which perform this task so it shouldn't be a problem.
7#![deny(rust_2018_idioms, missing_docs)]
8#![forbid(unsafe_code)]
9
10mod types;
11pub use types::{Error, Mode, Options};
12
13///
14pub mod unix;
15#[cfg(unix)]
16use unix::imp;
17
18#[cfg(not(unix))]
19mod imp {
20    use crate::{Error, Options};
21
22    pub(crate) fn ask(_prompt: &str, _opts: &Options<'_>) -> Result<String, Error> {
23        Err(Error::UnsupportedPlatform)
24    }
25}
26
27/// Ask the user given a `prompt`, returning the result.
28pub fn ask(prompt: &str, opts: &Options<'_>) -> Result<String, Error> {
29    if let Some(askpass) = opts.askpass.as_deref() {
30        match gix_command::prepare(askpass).arg(prompt).spawn() {
31            Ok(cmd) => {
32                if let Some(mut stdout) = cmd
33                    .wait_with_output()
34                    .ok()
35                    .and_then(|out| String::from_utf8(out.stdout).ok())
36                {
37                    if stdout.ends_with('\n') {
38                        stdout.pop();
39                    }
40                    if stdout.ends_with('\r') {
41                        stdout.pop();
42                    }
43                    return Ok(stdout);
44                }
45            }
46            Err(err) => eprintln!(
47                "Cannot run askpass program: '{askpass}' with error: {err}",
48                askpass = askpass.display()
49            ),
50        }
51    }
52    imp::ask(prompt, opts)
53}
54
55/// Ask for information typed by the user into the terminal after showing the prompt, like `"Username: `.
56///
57/// Use [`ask()`] for more control.
58pub fn openly(prompt: impl AsRef<str>) -> Result<String, Error> {
59    imp::ask(
60        prompt.as_ref(),
61        &Options {
62            mode: Mode::Visible,
63            askpass: None,
64        },
65    )
66}
67
68/// Ask for information _securely_ after showing the `prompt` (like `"password: "`) by not showing what's typed.
69///
70/// Use [`ask()`] for more control.
71pub fn securely(prompt: impl AsRef<str>) -> Result<String, Error> {
72    imp::ask(
73        prompt.as_ref(),
74        &Options {
75            mode: Mode::Hidden,
76            askpass: None,
77        },
78    )
79}