git_prompt/
unix.rs

1/// The path to the default TTY on linux
2pub const TTY_PATH: &str = "/dev/tty";
3
4#[cfg(unix)]
5pub(crate) mod imp {
6    use std::{
7        io::{BufRead, Write},
8        os::unix::io::{AsRawFd, RawFd},
9    };
10
11    use nix::sys::{termios, termios::Termios};
12    use parking_lot::{const_mutex, lock_api::MutexGuard, Mutex, RawMutex};
13
14    use crate::{unix::TTY_PATH, Error, Mode, Options};
15
16    static TERM_STATE: Mutex<Option<Termios>> = const_mutex(None);
17
18    /// Ask the user given a `prompt`, returning the result.
19    pub(crate) fn ask(prompt: &str, Options { mode, .. }: &Options<'_>) -> Result<String, Error> {
20        match mode {
21            Mode::Disable => Err(Error::Disabled),
22            Mode::Hidden => {
23                let state = TERM_STATE.lock();
24                let mut in_out = std::fs::OpenOptions::new().write(true).read(true).open(TTY_PATH)?;
25                let restore = save_term_state_and_disable_echo(state, in_out.as_raw_fd())?;
26                in_out.write_all(prompt.as_bytes())?;
27
28                let mut buf_read = std::io::BufReader::with_capacity(64, in_out);
29                let mut out = String::with_capacity(64);
30                buf_read.read_line(&mut out)?;
31
32                out.pop();
33                if out.ends_with('\r') {
34                    out.pop();
35                }
36                restore.now()?;
37                Ok(out)
38            }
39            Mode::Visible => {
40                let mut in_out = std::fs::OpenOptions::new().write(true).read(true).open(TTY_PATH)?;
41                in_out.write_all(prompt.as_bytes())?;
42
43                let mut buf_read = std::io::BufReader::with_capacity(64, in_out);
44                let mut out = String::with_capacity(64);
45                buf_read.read_line(&mut out)?;
46                Ok(out.trim_end().to_owned())
47            }
48        }
49    }
50
51    type TermiosGuard<'a> = MutexGuard<'a, RawMutex, Option<Termios>>;
52
53    struct RestoreTerminalStateOnDrop<'a> {
54        state: TermiosGuard<'a>,
55        fd: RawFd,
56    }
57
58    impl<'a> RestoreTerminalStateOnDrop<'a> {
59        fn now(mut self) -> Result<(), Error> {
60            let state = self.state.take().expect("BUG: we exist only if something is saved");
61            termios::tcsetattr(self.fd, termios::SetArg::TCSAFLUSH, &state)?;
62            Ok(())
63        }
64    }
65
66    impl<'a> Drop for RestoreTerminalStateOnDrop<'a> {
67        fn drop(&mut self) {
68            if let Some(state) = self.state.take() {
69                termios::tcsetattr(self.fd, termios::SetArg::TCSAFLUSH, &state).ok();
70            }
71        }
72    }
73
74    fn save_term_state_and_disable_echo(
75        mut state: TermiosGuard<'_>,
76        fd: RawFd,
77    ) -> Result<RestoreTerminalStateOnDrop<'_>, Error> {
78        assert!(
79            state.is_none(),
80            "BUG: recursive calls are not possible and we restore afterwards"
81        );
82
83        let prev = termios::tcgetattr(fd)?;
84        let mut new = prev.clone();
85        *state = prev.into();
86
87        new.local_flags &= !termios::LocalFlags::ECHO;
88        new.local_flags |= termios::LocalFlags::ECHONL;
89        termios::tcsetattr(fd, termios::SetArg::TCSAFLUSH, &new)?;
90
91        Ok(RestoreTerminalStateOnDrop { fd, state })
92    }
93}