Skip to content

Commit

Permalink
adds "prompt" method
Browse files Browse the repository at this point in the history
  • Loading branch information
conradkleinespel committed Sep 3, 2016
1 parent 2140b7a commit fab06b6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@ extern crate rpassword;
use rpassword::read_password;

fn main() {
println!("Type a password: ");
let password = read_password().unwrap();
println!("The password is: '{}'", password);
let pass = rpassword::prompt_password_stdout("Password: ").unwrap();
println!("Your password is {}", pass);
}
```

Check [examples/example.rs](examples/example.rs) for a few more examples.

## Contributors

* [@conradkleinespel](https://github.com/conradkleinespel)
Expand Down
6 changes: 6 additions & 0 deletions examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,10 @@ fn main() {
stdout.flush().unwrap();
let pass = rpassword::read_password().unwrap();
println!("Your password is {}", pass);

let pass = rpassword::prompt_password_stdout("Password: ").unwrap();
println!("Your password is {}", pass);

let pass = rpassword::prompt_password_stderr("Password: ").unwrap();
println!("Your password is {}", pass);
}
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::io::Write;

#[cfg(not(windows))]
mod unix {
extern crate termios;
Expand Down Expand Up @@ -67,6 +69,7 @@ mod unix {
stdin()
}

/// Reads a password from STDIN.
pub fn read_password() -> IoResult<String> {
// Make two copies of the terminal settings. The first one will be modified
// and the second one will act as a backup for when we want to set the
Expand Down Expand Up @@ -137,6 +140,7 @@ mod windows {
use std::io::Result as IoResult;
use std::ptr::null_mut;

/// Reads a password from STDIN.
pub fn read_password() -> IoResult<String> {
// Get the stdin handle
let handle = unsafe { kernel32::GetStdHandle(winapi::STD_INPUT_HANDLE) };
Expand Down Expand Up @@ -185,3 +189,21 @@ mod windows {
pub use unix::read_password;
#[cfg(windows)]
pub use windows::read_password;

/// Prompts for a password on STDOUT and reads it from STDIN.
pub fn prompt_password_stdout(prompt: &str) -> std::io::Result<String> {
let mut stdout = std::io::stdout();

try!(write!(stdout, "{}", prompt));
try!(stdout.flush());
read_password()
}

/// Prompts for a password on STDERR and reads it from STDIN.
pub fn prompt_password_stderr(prompt: &str) -> std::io::Result<String> {
let mut stderr = std::io::stderr();

try!(write!(stderr, "{}", prompt));
try!(stderr.flush());
read_password()
}

0 comments on commit fab06b6

Please sign in to comment.