Struct Jargon

Source
pub struct Jargon(/* private fields */);
Expand description

§Jargon

This is the main struct in this crate. This is what is used to handle arguments, and get arguments’ values.

§Example

use jargon_args::Jargon;
let mut jargon: Jargon = Jargon::from_env();

if jargon.contains(["-h", "--help"]) {
    println!("help text");
    std::process::exit(0);
}

// ...

Implementations§

Source§

impl Jargon

Source

pub fn from_env() -> Self

Extracts a program’s arguments from the environment.

Examples found in repository?
examples/subcontinued.rs (line 4)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5    j.on_subcommand("go", go);
6}
More examples
Hide additional examples
examples/subcommand.rs (line 4)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5
6    j.on_subcommand("list", list);
7    j.on_subcommand("backwards", list_backwards);
8}
examples/name.rs (line 4)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5    let name_key: Key = "--name".into();
6
7    match j.option_arg::<String, Key>(name_key.clone()) {
8        Some(n) => println!("Your name: {}", n),
9        None => eprintln!("Missing argument: {}", name_key),
10    }
11}
examples/basename.rs (line 12)
11fn main() {
12    let mut j: Jargon = Jargon::from_env(); // Get an instance of Jargon using `std::env::args()`
13
14    if j.contains(["-h", "--help"]) { // check for help argument
15        print!("{}", HELP);
16        return;
17    }
18
19    if j.contains(["-v", "--version"]) { // check for version argument
20        println!(
21            "basename example for Jargon crate {}",
22            env!("CARGO_PKG_VERSION")
23        );
24        return;
25    }
26
27    let args = Args { // fill helper struct
28        multiple: j.contains(["-a", "--multiple"]), // multiple
29        suffix: j.option_arg(["-s", "--suffix"]), // suffix to remove
30        zero: j.contains(["-z", "--zero"]), // terminate lines with null
31        names: j.finish(), // get names
32    };
33
34    if args.names.is_empty() { // check if there are names
35        println!("Missing NAMES");
36        return;
37    }
38
39    let mut v: Vec<String> = vec![print(&args, &args.names[0])]; // initiate vector of names
40
41    if args.multiple { // fill the rest if `-a` or `--multiple` was passed
42        args.names.iter().skip(1).for_each(|name| v.append(&mut vec![print(&args, name)]));
43    }
44
45    if args.zero { // terminate with null if `-z` or `--zero` was passed
46        v.iter().for_each(|name| print!("{}", name));
47    } else { // terminate each name with space or new line
48        v.iter().for_each(|name| println!("{} ", name));
49    }
50}
Source

pub fn from_vec<T: ToString>(v: Vec<T>) -> Self

Places provided vector into Jargon. Please have the program’s name or subcommand’s name at index 0. 0 is always ignored.

Examples found in repository?
examples/subcontinued.rs (line 10)
8fn go(v: Vec<String>) {
9    println!("go!");
10    let mut j: Jargon = Jargon::from_vec(v);
11    j.on_subcommand("goo", goo)
12}
13
14fn goo(v: Vec<String>) {
15    println!("goo!");
16    let mut j: Jargon = Jargon::from_vec(v);
17    j.on_subcommand("gooo", gooo)
18}
Source

pub fn contains<K: Into<Key>>(&mut self, key: K) -> bool

Checks if provided key is given in arguments. Removes it.

Examples found in repository?
examples/basename.rs (line 14)
11fn main() {
12    let mut j: Jargon = Jargon::from_env(); // Get an instance of Jargon using `std::env::args()`
13
14    if j.contains(["-h", "--help"]) { // check for help argument
15        print!("{}", HELP);
16        return;
17    }
18
19    if j.contains(["-v", "--version"]) { // check for version argument
20        println!(
21            "basename example for Jargon crate {}",
22            env!("CARGO_PKG_VERSION")
23        );
24        return;
25    }
26
27    let args = Args { // fill helper struct
28        multiple: j.contains(["-a", "--multiple"]), // multiple
29        suffix: j.option_arg(["-s", "--suffix"]), // suffix to remove
30        zero: j.contains(["-z", "--zero"]), // terminate lines with null
31        names: j.finish(), // get names
32    };
33
34    if args.names.is_empty() { // check if there are names
35        println!("Missing NAMES");
36        return;
37    }
38
39    let mut v: Vec<String> = vec![print(&args, &args.names[0])]; // initiate vector of names
40
41    if args.multiple { // fill the rest if `-a` or `--multiple` was passed
42        args.names.iter().skip(1).for_each(|name| v.append(&mut vec![print(&args, name)]));
43    }
44
45    if args.zero { // terminate with null if `-z` or `--zero` was passed
46        v.iter().for_each(|name| print!("{}", name));
47    } else { // terminate each name with space or new line
48        v.iter().for_each(|name| println!("{} ", name));
49    }
50}
Source

pub fn on_subcommand<K: Into<Key>, F: FnMut(Vec<String>)>( &mut self, key: K, f: F, )

Runs function that does not return a value if specified key exists. Removes the program’s name from provided vector.

Examples found in repository?
examples/subcontinued.rs (line 5)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5    j.on_subcommand("go", go);
6}
7
8fn go(v: Vec<String>) {
9    println!("go!");
10    let mut j: Jargon = Jargon::from_vec(v);
11    j.on_subcommand("goo", goo)
12}
13
14fn goo(v: Vec<String>) {
15    println!("goo!");
16    let mut j: Jargon = Jargon::from_vec(v);
17    j.on_subcommand("gooo", gooo)
18}
More examples
Hide additional examples
examples/subcommand.rs (line 6)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5
6    j.on_subcommand("list", list);
7    j.on_subcommand("backwards", list_backwards);
8}
Source

pub fn opt_on_subcommand<K: Into<Key>, F: FnMut(Vec<String>) -> Option<T>, T>( &mut self, key: K, f: F, ) -> Option<T>

Runs function that returns Option if specified key exists. Removes the program’s name from provided vector.

Source

pub fn res_on_subcommand<K: Into<Key>, F: FnMut(Vec<String>) -> Result<T, Error>, T>( &mut self, key: K, f: F, ) -> Result<T, Error>

Runs function that returns Result<T, jargon_args::Error> if specified key exists. Removes the program’s name from provided vector.

Source

pub fn subcommand<K: Into<Key>>(&mut self, key: K) -> Option<Vec<String>>

Checks if key exists, removes it, and returns it and all remaining arguments in Some(Vec). None if key isn’t in arguments.

Source

pub fn option_arg<T: FromStr, K: Into<Key>>(&mut self, key: K) -> Option<T>

Checks for provided key in arguments, removes it, returns Some(String) with the value after it if there is one. None is there is no value.

Examples found in repository?
examples/name.rs (line 7)
3fn main() {
4    let mut j: Jargon = Jargon::from_env();
5    let name_key: Key = "--name".into();
6
7    match j.option_arg::<String, Key>(name_key.clone()) {
8        Some(n) => println!("Your name: {}", n),
9        None => eprintln!("Missing argument: {}", name_key),
10    }
11}
More examples
Hide additional examples
examples/basename.rs (line 29)
11fn main() {
12    let mut j: Jargon = Jargon::from_env(); // Get an instance of Jargon using `std::env::args()`
13
14    if j.contains(["-h", "--help"]) { // check for help argument
15        print!("{}", HELP);
16        return;
17    }
18
19    if j.contains(["-v", "--version"]) { // check for version argument
20        println!(
21            "basename example for Jargon crate {}",
22            env!("CARGO_PKG_VERSION")
23        );
24        return;
25    }
26
27    let args = Args { // fill helper struct
28        multiple: j.contains(["-a", "--multiple"]), // multiple
29        suffix: j.option_arg(["-s", "--suffix"]), // suffix to remove
30        zero: j.contains(["-z", "--zero"]), // terminate lines with null
31        names: j.finish(), // get names
32    };
33
34    if args.names.is_empty() { // check if there are names
35        println!("Missing NAMES");
36        return;
37    }
38
39    let mut v: Vec<String> = vec![print(&args, &args.names[0])]; // initiate vector of names
40
41    if args.multiple { // fill the rest if `-a` or `--multiple` was passed
42        args.names.iter().skip(1).for_each(|name| v.append(&mut vec![print(&args, name)]));
43    }
44
45    if args.zero { // terminate with null if `-z` or `--zero` was passed
46        v.iter().for_each(|name| print!("{}", name));
47    } else { // terminate each name with space or new line
48        v.iter().for_each(|name| println!("{} ", name));
49    }
50}
Source

pub fn result_arg<T: FromStr, K: Into<Key>>( &mut self, key: K, ) -> Result<T, Error>

Checks for provided key in arguments, removes it, returns Ok(String) with the value after it if there is one. Err(jargon_args::Error) is there is no value.

Source

pub fn opt_next<T: FromStr>(&mut self) -> Option<T>

Returns the next argument as Some(T) or ‘None’ if there is no more arguments.

Source

pub fn finish(self) -> Vec<String>

Drops your jargon instance and returns all remaining arguments.

Examples found in repository?
examples/basename.rs (line 31)
11fn main() {
12    let mut j: Jargon = Jargon::from_env(); // Get an instance of Jargon using `std::env::args()`
13
14    if j.contains(["-h", "--help"]) { // check for help argument
15        print!("{}", HELP);
16        return;
17    }
18
19    if j.contains(["-v", "--version"]) { // check for version argument
20        println!(
21            "basename example for Jargon crate {}",
22            env!("CARGO_PKG_VERSION")
23        );
24        return;
25    }
26
27    let args = Args { // fill helper struct
28        multiple: j.contains(["-a", "--multiple"]), // multiple
29        suffix: j.option_arg(["-s", "--suffix"]), // suffix to remove
30        zero: j.contains(["-z", "--zero"]), // terminate lines with null
31        names: j.finish(), // get names
32    };
33
34    if args.names.is_empty() { // check if there are names
35        println!("Missing NAMES");
36        return;
37    }
38
39    let mut v: Vec<String> = vec![print(&args, &args.names[0])]; // initiate vector of names
40
41    if args.multiple { // fill the rest if `-a` or `--multiple` was passed
42        args.names.iter().skip(1).for_each(|name| v.append(&mut vec![print(&args, name)]));
43    }
44
45    if args.zero { // terminate with null if `-z` or `--zero` was passed
46        v.iter().for_each(|name| print!("{}", name));
47    } else { // terminate each name with space or new line
48        v.iter().for_each(|name| println!("{} ", name));
49    }
50}

Trait Implementations§

Source§

impl Clone for Jargon

Source§

fn clone(&self) -> Jargon

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Jargon

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Ord for Jargon

Source§

fn cmp(&self, other: &Jargon) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Jargon

Source§

fn eq(&self, other: &Jargon) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

const fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Jargon

Source§

fn partial_cmp(&self, other: &Jargon) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Eq for Jargon

Source§

impl StructuralPartialEq for Jargon

Auto Trait Implementations§

§

impl Freeze for Jargon

§

impl RefUnwindSafe for Jargon

§

impl Send for Jargon

§

impl Sync for Jargon

§

impl Unpin for Jargon

§

impl UnwindSafe for Jargon

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

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

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.