Struct bash_builtins::Args

source ·
pub struct Args { /* private fields */ }
Expand description

This structure provides access to the command-line arguments passed to the builtin.

An instance for this type is sent as an argument of Builtin::call.

§Options

The options method parses the arguments with the internal_getopt function provided by bash, like most builtins, and extract them as values of a type implementing BuiltinOptions.

If the builtin does not expect any option, call to no_options before doing anything else.

§Free Arguments

The iterators returned by raw_arguments, string_arguments, and path_arguments yield the argument values.

If you use options before any of the <type>_arguments methods, the first item of the iteration is the first argument after the last parsed option.

The example below shows how to extract options and then process free arguments.

If the builtin accepts options, but no free arguments, call to finished after options.

If the builtin does not expect any option or free argument, call to finished after no_options.

§Example

use std::io::{stdout, BufWriter, Write};
use bash_builtins::{Args, Builtin, BuiltinOptions, Result};

struct SomeName;

#[derive(BuiltinOptions)]
enum Opt {
    #[opt = 'f']
    Foo,

    #[opt = 'b']
    Bar(i64),
}

impl Builtin for SomeName {
    fn call(&mut self, args: &mut Args) -> Result<()> {
        let mut foo = false;
        let mut bar = 0;

        for option in args.options() {
            match option? {
                Opt::Foo => foo = true,
                Opt::Bar(b) => bar = b,
            }
        }

        let stdout_handle = stdout();
        let mut output = BufWriter::new(stdout_handle.lock());

        writeln!(&mut output, "{}, {}", foo, bar)?;

        for path in args.path_arguments() {
            writeln!(&mut output, "{}", path.display())?;
        }

        Ok(())
    }
}

Implementations§

source§

impl Args

source

pub fn is_empty(&self) -> bool

Returns true if there are no more arguments.

source

pub fn options<'a, T>(&'a mut self) -> impl Iterator<Item = Result<T>> + 'a
where T: BuiltinOptions<'a> + 'a,

Returns an iterator to parse the command-line arguments with the getops function provided by bash.

The generic type T implements the BuiltinOptions trait. See its documentation for details on how to create the parser.

§Example

See the example in the Args documentation.

source

pub fn raw_arguments(&mut self) -> impl Iterator<Item = &CStr>

Returns an iterator to get the arguments passed to the builtin.

Each item is an instance of CStr, and its lifetime is bound to the Args instance.

If this method is called after options, the first item of the iteration is the first argument after the last parsed option.

It is recommended to use path_arguments if the builtin expects file names as arguments, or string_arguments if it expects valid UTF-8 strings.

§Example

See path_arguments for an example.

source

pub fn path_arguments(&mut self) -> impl Iterator<Item = &Path>

Available on Unix only.

Like raw_arguments, but items are Path instances.

Use this iterator if the builtin arguments are file names.

§Example
use std::path::Path;
use bash_builtins::{Args, Builtin, Result};

struct SomeName;

impl Builtin for SomeName {
    fn call(&mut self, args: &mut Args) -> Result<()> {
        args.no_options()?;

        for path in args.path_arguments() {
            process(path)?;
        }

        Ok(())
    }
}

fn process(path: &Path) -> Result<()> {
    // …
    Ok(())
}
source

pub fn string_arguments( &mut self ) -> impl Iterator<Item = Result<&str, Utf8Error>>

Like raw_arguments, but each item is a string reference if the argument contains valid UTF-8 data, or a Utf8Error otherwise.

source

pub fn finished(&mut self) -> Result<()>

Returns an error if there are more arguments to be processed.

If the builtin accepts options but no free arguments, then this method should be called after options.

§Example
#[derive(BuiltinOptions)]
enum Opt {
    // Builtin options.
}

impl Builtin for SomeName {
    fn call(&mut self, args: &mut Args) -> Result<()> {
        for option in args.options() {
            match option? {
                // Parse options.
            }
        }

        // This builtin does not accept free arguments.
        args.finished()?;

        run_builtin_with_options()?;

        Ok(())
    }
}
source

pub fn no_options(&mut self) -> Result<()>

Returns an error if any option is passed as the first argument.

If the builtin expects no options, then call this method before doing anything else.

It uses the no_options function provided by bash. The special option --help is handled properly.

§Example
// Builtin to convert to uppercase its arguments.

impl Builtin for Upcase {
    fn call(&mut self, args: &mut Args) -> Result<()> {
        args.no_options()?;

        let stdout_handle = io::stdout();
        let mut output = BufWriter::new(stdout_handle.lock());

        for argument in args.string_arguments() {
            writeln!(&mut output, "{}", argument?.to_uppercase())?;
        }

        Ok(())
    }
}

Auto Trait Implementations§

§

impl Freeze for Args

§

impl RefUnwindSafe for Args

§

impl !Send for Args

§

impl !Sync for Args

§

impl Unpin for Args

§

impl UnwindSafe for Args

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.

source§

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

§

type Error = Infallible

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>,

§

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.