Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Tiny library for prompting sensitive or non-sensitive data on the terminal.
2 //!
3 //! The only dependency is `libc` on Unix and `winapi` on Windows.
4 //!
5 //! See [`Terminal`] for the API documentation.
6 //!
7 //! # Example
8 //! Read a username and password from the terminal:
9 //! ```no_run
10 //! # fn main() -> std::io::Result<()> {
11 //! use terminal_prompt::Terminal;
12 //! let mut terminal = Terminal::open()?;
13 //! let username = terminal.prompt("Username: ")?;
14 //! let password = terminal.prompt_sensitive("Password: ")?;
15 //! # Ok(())
16 //! # }
17 //! ```
18
19 #![warn(missing_docs)]
20
21 use std::io::{BufReader, BufRead, Read, Write};
22
23 mod sys;
24
25 /// A handle to the terminal associated with the current process.
26 ///
27 /// Once opened, you can use [`Self::prompt()`] to read non-sensitive data from the terminal,
28 /// and [`Self::prompt_sensitive()`] to read sensitive data like passwords.
29 ///
30 /// Alternatively, you can manually call [`Self::enable_echo()`] and [`Self::disable_echo()`], and read/write from the terminal directly.
31 /// The terminal handle implements the standard [`Read`], [`Write`] and [`BufRead`] traits,
32 /// and it has a [`Self::read_line()`] convenience function that returns a new string.
33 ///
34 /// # Terminal modes
35 /// When opened, the terminal will be put in line editing mode.
36 /// When dropped, the original mode of the terminal will be restored.
37 /// Note that the terminal is inherently a global resource,
38 /// so creating multiple terminal objects and dropping them in a different order can cause the terminal to be left in a different mode.
39 pub struct Terminal {
40 /// The underlying terminal.
41 terminal: BufReader<sys::Terminal>,
42
43 /// The mode of the terminal when we opened it.
44 initial_mode: sys::TerminalMode,
45 }
46
47 impl Terminal {
48 /// Open the terminal associated with the current process.
49 ///
50 /// The exact behavior is platform dependent.
51 ///
52 /// On Unix platforms, if one of standard I/O streams is a terminal, that terminal is used.
53 /// First standard error is tried, then standard input and finally standard output.
54 /// If none of those work, the function tries to open `/dev/tty`.
55 /// This means that on Unix platforms, the terminal prompt can still work, even when both standard input and standard output are connected to pipes instead of the terminal.
56 ///
57 /// On Windows, if both standard input and standard error are connected to a terminal, those streams are used.
58 ///
59 /// In all cases, if the function fails to find a terminal for the process, an error is returned.
60 pub fn open() -> std::io::Result<Self> {
61 // Open the terminal and retrieve the initial mode.
62 let terminal = sys::Terminal::open()?;
63 let initial_mode = terminal.get_terminal_mode()?;
64
65 // Enable line editing mode.
66 let mut mode = initial_mode;
67 mode.enable_line_editing();
68 terminal.set_terminal_mode(&mode)?;
69
70 Ok(Self {
71 terminal: BufReader::new(terminal),
72 initial_mode,
73 })
74 }
75
76 /// Check if the terminal is echoing input.
77 ///
78 /// If enabled, any text typed on the terminal will be visible.
79 pub fn is_echo_enabled(&self) -> std::io::Result<bool> {
80 let mode = self.terminal.get_ref().get_terminal_mode()?;
81 Ok(mode.is_echo_enabled())
82 }
83
84 /// Disable echoing of terminal input.
85 ///
86 /// This will prevent text typed on the terminal from being visible.
87 /// This can be used to hide passwords while they are being typed.
88 pub fn disable_echo(&self) -> std::io::Result<()> {
89 let mut mode = self.terminal.get_ref().get_terminal_mode()?;
90 mode.disable_echo();
91 self.terminal.get_ref().set_terminal_mode(&mode)?;
92 Ok(())
93 }
94
95 /// Enable echoing of terminal input.
96 ///
97 /// This will cause any text typed on the terminal to be visible.
98 pub fn enable_echo(&mut self) -> std::io::Result<()> {
99 let mut mode = self.terminal.get_ref().get_terminal_mode()?;
100 mode.enable_echo();
101 self.terminal.get_ref().set_terminal_mode(&mode)?;
102 Ok(())
103 }
104
105 /// Read a line of input from the terminal.
106 ///
107 /// If echoing is disabled, this will also print a newline character to visually indicate to the user.
108 /// If this is not desired, use the [`BufRead::read_line()`] function instead.
109 pub fn read_input_line(&mut self) -> std::io::Result<String> {
110 let mut buffer = String::new();
111 self.terminal.read_line(&mut buffer)?;
112
113 if self.is_echo_enabled().ok() == Some(false) {
114 writeln!(self).ok();
115 }
116 if buffer.ends_with('\n') {
117 buffer.pop();
118 }
119 Ok(buffer)
120 }
121
122 /// Prompt the user on the terminal.
123 ///
124 /// This function does not enable or disable echoing and should not normally be used for reading sensitive data like passwords.
125 /// Consider [`Self::prompt_sensitive()`] instead.
126 pub fn prompt(&mut self, prompt: impl std::fmt::Display) -> std::io::Result<String> {
127 write!(self, "{prompt}")?;
128 self.read_input_line()
129 }
130
131 /// Prompt the user for sensitive data (like passwords) on the terminal.
132 ///
133 /// This function makes sure that echoing is disabled before the prompt is shown.
134 /// If echoing was enabled, it is re-enabled after the response is read.
135 ///
136 /// Use [`Self::prompt()`] to read non-sensitive data.
137 pub fn prompt_sensitive(&mut self, prompt: impl std::fmt::Display) -> std::io::Result<String> {
138 let old_mode = self.terminal.get_ref().get_terminal_mode()?;
139 if old_mode.is_echo_enabled() {
140 let mut new_mode = old_mode;
141 new_mode.disable_echo();
142 self.terminal.get_ref().set_terminal_mode(&new_mode)?;
143 }
144 write!(self, "{prompt}")?;
145 let line = self.read_input_line();
146 if old_mode.is_echo_enabled() {
147 self.terminal.get_ref().set_terminal_mode(&old_mode).ok();
148 }
149 line
150 }
151 }
152
153 impl Drop for Terminal {
154 fn drop(&mut self) {
155 self.terminal.get_ref().set_terminal_mode(&self.initial_mode).ok();
156 }
157 }
158
159 impl Read for Terminal {
160 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
161 self.terminal.read(buf)
162 }
163
164 fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result<usize> {
165 self.terminal.read_vectored(bufs)
166 }
167 }
168
169 impl BufRead for Terminal {
170 fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
171 self.terminal.fill_buf()
172 }
173
174 fn consume(&mut self, amt: usize) {
175 self.terminal.consume(amt)
176 }
177 }
178
179 impl Write for Terminal {
180 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
181 self.terminal.get_mut().write(buf)
182 }
183
184 fn flush(&mut self) -> std::io::Result<()> {
185 self.terminal.get_mut().flush()
186 }
187
188 fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
189 self.terminal.get_mut().write_vectored(bufs)
190 }
191 }