Skip to main content

PromptBuilder

Struct PromptBuilder 

Source
pub struct PromptBuilder<TOutput, TCancel: PromptCancelConfig, TValidate: FnMut(&mut String) -> Result<bool>> { /* private fields */ }
Available on crate features print and prompt only.
Expand description

Implementations§

Source§

impl<TCancel: PromptCancelConfig, TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<ZString, TCancel, TValidate>

Source

pub fn password(self) -> Self

Prompt for password. The input will be hidden.

§Example
match cu::prompt("enter your password:").password().run()? {
    Some(password) => cu::info!("user entered: {password}"),
    None => cu::error!("cancelled"),
}
Source

pub fn trim_trailing_whitespace(self, trim: bool) -> Self

Configure whether to trim trailing whitespace from the input.

By default, trailing whitespace is trimmed from user input. Set this to false to preserve trailing whitespace. Note that CRLF/LF line endings are always removed.

§Example
let input = cu::prompt("enter text:").trim_trailing_whitespace(false).run()?;
// trailing spaces will be preserved
Source

pub fn validate_with<F>( self, validator: F, ) -> PromptBuilder<ZString, TCancel, F>
where F: FnMut(&mut String) -> Result<bool>,

Add a validation function to the prompt. The prompt will be looped until a validation function passes.

The validation function takes a &mut String, and returns cu::Result<bool>, where:

  • Ok(true) means the validation passed.
  • Ok(false) means the validation failed. The function can optionally print some kind of error or hint message
  • Err means there is an error, the error will be propagated to the prompt call.

The validation function can be a FnMut closure, which means it can double as a result parsing function if needed

let mut index: i32 = 0;
cu::prompt("select a number between 0 and 5")
    .validate_with(
        |answer| {
            let number = match cu::parse::<i32>(answer) {
                Err(e) => {
                    cu::error!("{e}");
                    cu::hint!("please ensure you are entering a number");
                    return Ok(false);
                }
                Ok(x) => x
            };
            if number < 0 {
                cu::error!("the number you entered is too small");
                return Ok(false);
            }
            if number > 5 {
                cu::error!("the number you entered is too big");
                return Ok(false);
            }
            index = number;
            Ok(true)
        }
    ).run()?;
cu::info!("index is {index:?}");
Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<ZString, Cancellable, TValidate>

Source

pub fn yesno(self) -> PromptBuilder<bool, Cancellable, TValidate>

Convert to a yes/no confirmation prompt. The prompt will accept “yes”, “y”, “no”, or “n” (case-insensitive) as valid input.

Unlike cu::yesno, .prompt().yesno() will let you detect cancellations by pressing Ctrl-C.

§Example
match cu::prompt("delete all files?").yesno().run()? {
    None => cu::error!("cancelled"),
    Some(true) => cu::info!("all files are deleted!"),
    Some(false) => cu::error!("user explicitly answered no"),
}
Source

pub fn if_cancel( self, default: impl Into<String>, ) -> PromptBuilder<ZString, DefaultIfCancel, TValidate>

Set a default value to return if the user cancels the prompt (e.g., Ctrl+C).

Without if_cancel, the prompt returns Option<ZString> where None indicates cancellation. With if_cancel, the prompt returns ZString directly, using the provided default value on cancellation.

§Example
let name: cu::ZString = cu::prompt("enter your name:")
    .if_cancel("anonymous")
    .run()?;
cu::info!("Hello, {name}!");

This has the same effect as calling unwrap_or() on the resulting Option<ZString> - Just that the prompt creator has control over the outcome of the prompt, rather than the prompt consumer accessing the outcome.

Source

pub fn or_cancel(self) -> PromptBuilder<ZString, BailIfCancel, TValidate>

Return an error if the user cancels the prompt (e.g., Ctrl+C).

This appends “(Ctrl-C to cancel)” to the prompt message and returns an error with message “operation cancelled by user” if the user presses Ctrl+C.

§Example
let name: cu::ZString = cu::prompt("enter your name:").or_cancel().run()?;
cu::info!("Hello, {name}!");
Source

pub fn run(self) -> Result<Option<ZString>>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, None will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<Option<ZString>>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, None will be returned.

Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<ZString, DefaultIfCancel, TValidate>

Source

pub fn run(self) -> Result<ZString>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, the default value set by if_cancel will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<ZString>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, the default value set by if_cancel will be returned.

Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<ZString, BailIfCancel, TValidate>

Source

pub fn run(self) -> Result<ZString>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, an error with message “operation cancelled by user” will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<ZString>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, an error with message “operation cancelled by user” will be returned.

Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<bool, Cancellable, TValidate>

Source

pub fn if_cancel( self, default: bool, ) -> PromptBuilder<bool, DefaultIfCancel, TValidate>

Set a default value to return if the user cancels the prompt (e.g., Ctrl+C).

Without if_cancel, the prompt returns Option<bool> where None indicates cancellation. With if_cancel, the prompt returns bool directly, using the provided default value on cancellation.

Note that cu::yesno already calls .if_cancel(false) internally.

§Example
if cu::prompt("proceed?").yesno().if_cancel(false).run()? {
    cu::info!("user answered yes!");
}

This has the same effect as calling unwrap_or() on the resulting Option<bool> - Just that the prompt creator has control over the outcome of the prompt, rather than the prompt consumer accessing the outcome.

Source

pub fn or_cancel(self) -> PromptBuilder<bool, BailIfCancel, TValidate>

Return an error if the user cancels the prompt (e.g., Ctrl+C).

This appends “(Ctrl-C to cancel)” to the prompt message and returns an error with message “operation cancelled by user” if the user presses Ctrl+C.

§Example
match cu::prompt("proceed?").yesno().or_cancel().run() {
    // user answered yes
    Ok(true) => cu::info!("proceeding..."),
    // user answered no
    Ok(false) => cu::warn!("user declined"),
    // user pressed Ctrl-C, or prompt not allowed
    Err(e) => cu::error!("{e}"),
}
Source

pub fn run(self) -> Result<Option<bool>>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, None will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<Option<bool>>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, None will be returned.

Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<bool, BailIfCancel, TValidate>

Source

pub fn run(self) -> Result<bool>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, an error with message “operation cancelled by user” will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<bool>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, an error with message “operation cancelled by user” will be returned.

Source§

impl<TValidate: FnMut(&mut String) -> Result<bool>> PromptBuilder<bool, DefaultIfCancel, TValidate>

Source

pub fn run(self) -> Result<bool>

Show the prompt and block the current thread to wait for input.

If the user presses Ctrl-C, the default value set by if_cancel will be returned.

§Blocking

Do not use this in an async context, since it will block the runtime, and will panic if the thread is currently driving IO. Use co_run().await? instead.

Source

pub async fn co_run(self) -> Result<bool>

Available on crate feature coroutine only.

Show the prompt and use the async runtime to wait for input.

If the user presses Ctrl-C, the default value set by if_cancel will be returned.

Auto Trait Implementations§

§

impl<TOutput, TCancel, TValidate> Freeze for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: Freeze, TCancel: Freeze, Option<TOutput>: Freeze,

§

impl<TOutput, TCancel, TValidate> RefUnwindSafe for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: RefUnwindSafe, TCancel: RefUnwindSafe, Option<TOutput>: RefUnwindSafe,

§

impl<TOutput, TCancel, TValidate> Send for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: Send, TCancel: Send, Option<TOutput>: Send,

§

impl<TOutput, TCancel, TValidate> Sync for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: Sync, TCancel: Sync, Option<TOutput>: Sync,

§

impl<TOutput, TCancel, TValidate> Unpin for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: Unpin, TCancel: Unpin, Option<TOutput>: Unpin,

§

impl<TOutput, TCancel, TValidate> UnsafeUnpin for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: UnsafeUnpin, TCancel: UnsafeUnpin, Option<TOutput>: UnsafeUnpin,

§

impl<TOutput, TCancel, TValidate> UnwindSafe for PromptBuilder<TOutput, TCancel, TValidate>
where TValidate: UnwindSafe, TCancel: UnwindSafe, Option<TOutput>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.