git_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 git_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!("Cannot run askpass program: {askpass:?} with error: {err}"),
47        }
48    }
49    imp::ask(prompt, opts)
50}
51
52/// Ask for information typed by the user into the terminal after showing the prompt`, like `"Username: `.
53///
54/// Use [`ask()`] for more control.
55pub fn openly(prompt: impl AsRef<str>) -> Result<String, Error> {
56    imp::ask(
57        prompt.as_ref(),
58        &Options {
59            mode: Mode::Visible,
60            askpass: None,
61        },
62    )
63}
64
65/// Ask for information _securely_ after showing the `prompt` (like `"password: "`) by not showing what's typed.
66///
67/// Use [`ask()`] for more control.
68pub fn securely(prompt: impl AsRef<str>) -> Result<String, Error> {
69    imp::ask(
70        prompt.as_ref(),
71        &Options {
72            mode: Mode::Hidden,
73            askpass: None,
74        },
75    )
76}