Commit 409bae33 authored by Vahid Kazempour's avatar Vahid Kazempour

Copy from original

parent 6831fdbd
Pipeline #46875 failed with stages
in 7 minutes and 8 seconds
target
Cargo.lock
[package]
name = "dialoguer"
description = "A command line prompting library."
version = "0.4.0"
authors = ["Armin Ronacher <armin.ronacher@active-4.com>"]
keywords = ["cli", "menu", "prompt"]
license = "MIT"
homepage = "https://github.com/mitsuhiko/dialoguer"
documentation = "https://docs.rs/dialoguer"
readme = "README.md"
[dependencies]
console = "0.8.0"
lazy_static = "1"
tempfile = "3"
regex = "1"
The MIT License (MIT)
Copyright (c) 2017 Armin Ronacher <armin.ronacher@active-4.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# dialoguer
A rust library for command line prompts and similar things.
extern crate dialoguer;
use dialoguer::{theme::ColorfulTheme, Checkboxes};
fn main() {
let checkboxes = &[
"Ice Cream",
"Vanilla Cupcake",
"Chocolate Muffin",
"A Pile of sweet, sweet mustard",
];
let selections = Checkboxes::with_theme(&ColorfulTheme::default())
.with_prompt("Pick your food")
.items(&checkboxes[..])
.interact()
.unwrap();
if selections.is_empty() {
println!("You did not select anything :(");
} else {
println!("You selected these things:");
for selection in selections {
println!(" {}", checkboxes[selection]);
}
}
}
extern crate dialoguer;
use dialoguer::{Confirmation, Input};
fn main() {
if Confirmation::new()
.with_text("Do you want to continue?")
.interact()
.unwrap()
{
println!("Looks like you want to continue");
} else {
println!("nevermind then :(");
return;
}
let input: String = Input::new().with_prompt("Your name").interact().unwrap();
println!("Hello {}!", input);
}
extern crate dialoguer;
use dialoguer::Editor;
fn main() {
if let Some(rv) = Editor::new().edit("Enter a commit message").unwrap() {
println!("Your message:");
println!("{}", rv);
} else {
println!("Abort!");
}
}
extern crate dialoguer;
use dialoguer::{theme::ColorfulTheme, FuzzySelect};
fn main() {
let selections = &[
"Ice Cream",
"Vanilla Cupcake",
"Chocolate Muffin",
"A Pile of sweet, sweet mustard",
];
let selection = FuzzySelect::with_theme(&ColorfulTheme::default())
.with_prompt("Pick your flavor")
.default(0)
.items(&selections[..])
.interact()
.unwrap();
println!("Enjoy your {}!", selection);
}
extern crate dialoguer;
use dialoguer::{theme::ColorfulTheme, PasswordInput};
fn main() {
let password = PasswordInput::with_theme(&ColorfulTheme::default())
.with_prompt("Password")
.with_confirmation("Repeat password", "Error: the passwords don't match.")
.interact()
.unwrap();
println!("Your password is {} characters long", password.len());
}
extern crate dialoguer;
use dialoguer::{theme::CustomPromptCharacterTheme, Input};
fn main() {
let theme = CustomPromptCharacterTheme::new('>');
let input: String = Input::with_theme(&theme)
.with_prompt("Your name")
.interact()
.unwrap();
println!("Hello {}!", input);
}
extern crate dialoguer;
use dialoguer::{theme::ColorfulTheme, Select};
fn main() {
let selections = &[
"Ice Cream",
"Vanilla Cupcake",
"Chocolate Muffin",
"A Pile of sweet, sweet mustard",
];
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Pick your flavor")
.default(0)
.items(&selections[..])
.interact()
.unwrap();
println!("Enjoy your {}!", selections[selection]);
}
extern crate dialoguer;
use dialoguer::{theme::ColorfulTheme, Select};
fn main() {
let selections = &[
"Ice Cream",
"Vanilla Cupcake",
"Chocolate Muffin",
"A Pile of sweet, sweet mustard",
];
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Pick your flavor")
.default(0)
.items(&selections[..])
.interact_opt()
.unwrap();
if let Some(selection) = selection {
println!("Enjoy your {}!", selections[selection]);
} else {
println!("You didn't select anything!");
}
}
extern crate console;
extern crate dialoguer;
use std::error::Error;
use std::net::IpAddr;
use console::Style;
use dialoguer::{theme::ColorfulTheme, Confirmation, Input, Select};
#[derive(Debug)]
struct Config {
interface: IpAddr,
hostname: String,
use_acme: bool,
private_key: Option<String>,
cert: Option<String>,
}
fn init_config() -> Result<Option<Config>, Box<Error>> {
let theme = ColorfulTheme {
values_style: Style::new().yellow().dim(),
indicator_style: Style::new().yellow().bold(),
yes_style: Style::new().yellow().dim(),
no_style: Style::new().yellow().dim(),
..ColorfulTheme::default()
};
println!("Welcome to the setup wizard");
if !Confirmation::with_theme(&theme)
.with_text("Do you want to continue?")
.interact()?
{
return Ok(None);
}
let interface = Input::with_theme(&theme)
.with_prompt("Interface")
.default("127.0.0.1".parse().unwrap())
.interact()?;
let hostname = Input::with_theme(&theme)
.with_prompt("Hostname")
.interact()?;
let tls = Select::with_theme(&theme)
.with_prompt("Configure TLS")
.default(0)
.item("automatic with ACME")
.item("manual")
.item("no")
.interact()?;
let (private_key, cert, use_acme) = match tls {
0 => (Some("acme.pkey".into()), Some("acme.cert".into()), true),
1 => (
Some(
Input::with_theme(&theme)
.with_prompt(" Path to private key")
.interact()?,
),
Some(
Input::with_theme(&theme)
.with_prompt(" Path to certificate")
.interact()?,
),
false,
),
_ => (None, None, false),
};
Ok(Some(Config {
hostname,
interface,
private_key,
cert,
use_acme,
}))
}
fn main() {
match init_config() {
Ok(None) => println!("Aborted."),
Ok(Some(config)) => println!("{:#?}", config),
Err(err) => println!("error: {}", err),
}
}
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs;
use std::io;
use std::io::{Read, Write};
use std::process;
/// Launches the default editor edit a string.
///
/// Example:
///
/// ```rust,no_run
/// # fn test() -> Result<(), Box<std::error::Error>> {
/// use dialoguer::Editor;
///
/// if let Some(rv) = Editor::new().edit("Enter a commit message").unwrap() {
/// println!("Your message:");
/// println!("{}", rv);
/// } else {
/// println!("Abort!");
/// }
/// # Ok(()) } fn main() { test().unwrap(); }
/// ```
pub struct Editor {
editor: OsString,
extension: String,
require_save: bool,
trim_newlines: bool,
}
fn get_default_editor() -> OsString {
if let Some(prog) = env::var_os("VISUAL") {
return prog.into();
}
if let Some(prog) = env::var_os("EDITOR") {
return prog.into();
}
if cfg!(windows) {
"notepad.exe".into()
} else {
"vi".into()
}
}
impl Editor {
/// Creates a new editor.
pub fn new() -> Editor {
Editor {
editor: get_default_editor(),
extension: ".txt".into(),
require_save: true,
trim_newlines: true,
}
}
/// Sets a specific editor executable.
pub fn executable<S: AsRef<OsStr>>(&mut self, val: S) -> &mut Editor {
self.editor = val.as_ref().into();
self
}
/// Sets a specific extension
pub fn extension(&mut self, val: &str) -> &mut Editor {
self.extension = val.into();
self
}
/// Enables or disables the save requirement.
pub fn require_save(&mut self, val: bool) -> &mut Editor {
self.require_save = val;
self
}
/// Enables or disables trailing newline stripping.
///
/// This is on by default.
pub fn trim_newlines(&mut self, val: bool) -> &mut Editor {
self.trim_newlines = val;
self
}
/// Launches the editor to edit a string.
///
/// Returns `None` if the file was not saved or otherwise the
/// entered text.
pub fn edit(&self, s: &str) -> io::Result<Option<String>> {
let mut f = tempfile::Builder::new()
.prefix("edit-")
.suffix(&self.extension)
.rand_bytes(12)
.tempfile()?;
f.write_all(s.as_bytes())?;
f.flush()?;
let ts = fs::metadata(f.path())?.modified()?;
let rv = process::Command::new(&self.editor)
.arg(f.path())
.spawn()?
.wait()?;
if rv.success() {
if self.require_save && ts >= fs::metadata(f.path())?.modified()? {
return Ok(None);
}
}
let mut new_f = fs::File::open(f.path())?;
let mut rv = String::new();
new_f.read_to_string(&mut rv)?;
if self.trim_newlines {
let len = rv.trim_end_matches(&['\n', '\r'][..]).len();
rv.truncate(len);
}
Ok(Some(rv))
}
}
//! dialoguer is a library for Rust that helps you build useful small
//! interactive user inputs for the command line. It provides utilities
//! to render various simple dialogs like confirmation prompts, text
//! inputs and more.
//!
//! Best paired with other libraries in the family:
//!
//! * [indicatif](https://docs.rs/indicatif)
//! * [console](https://docs.rs/console)
//!
//! # Crate Contents
//!
//! * Confirmation prompts
//! * Input prompts (regular and password)
//! * Input validation
//! * Menu selections
//! * Checkboxes
//! * Editor launching
//! * Menu fuzzy match selections
extern crate console;
extern crate tempfile;
extern crate regex;
pub use edit::Editor;
pub use prompts::{Confirmation, Input, PasswordInput};
pub use select::{Checkboxes, FuzzySelect, Select};
pub use validate::Validator;
mod edit;
mod prompts;
mod select;
pub mod theme;
mod validate;
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
//! Provides validation for text inputs
use std::fmt::{Debug, Display};
pub trait Validator {
type Err: Debug + Display;
/// Invoked with the value to validate.
///
/// If this produces `Ok(())` then the value is used and parsed, if
/// an error is returned validation fails with that error.
fn validate(&self, text: &str) -> Result<(), Self::Err>;
}
impl<T: Fn(&str) -> Result<(), E>, E: Debug + Display> Validator for T {
type Err = E;
fn validate(&self, text: &str) -> Result<(), Self::Err> {
self(text)
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment