Struct Context

Source
pub struct Context {
    pub raw_args: Vec<String>,
    pub args: VecDeque<String>,
    pub common_flags: Vector<Vector<Flag>>,
    pub routes: Vector<String>,
    pub exe_path: String,
    pub common_flags_values: Vector<(String, FlagValue)>,
    pub local_flags_values: Vector<(String, FlagValue)>,
    pub parsing_args: Option<VecDeque<MiddleArg>>,
    pub error_info_list: Vector<ErrorInfo>,
}
Expand description

Storage information for command execution. This storage raw args, non-flag args, flag values, and etc. コマンドからrunを通ってactionにたどり着くまでの情報およびパース結果を格納する構造体。 フラグの値、たどってきたルートなどを保管しています。

Fields§

§raw_args: Vec<String>

raw args

§args: VecDeque<String>

non-flag args

§common_flags: Vector<Vector<Flag>>

common_flags of its own and inherited

§routes: Vector<String>

routes of from root to end

§exe_path: String

exe_path (String, not PathBuf)

§common_flags_values: Vector<(String, FlagValue)>

storage of result of parsing common flags values

§local_flags_values: Vector<(String, FlagValue)>

storage of result of parsing local flags values

§parsing_args: Option<VecDeque<MiddleArg>>

On parsing, storage of parsing args. In edge(action), storage of error args

§error_info_list: Vector<ErrorInfo>

error inforamation list of parsing

Implementations§

Source§

impl Context

Source

pub fn new( raw_args: Vec<String>, args: VecDeque<String>, common_flags: Vector<Flag>, routes: Vector<String>, exe_path: String, ) -> Context

Creates a new instance of Context

Source

pub fn with_all_field( raw_args: Vec<String>, args: VecDeque<String>, common_flags: Vector<Vector<Flag>>, exe_path: String, routes: Vector<String>, common_flags_values: Vector<(String, FlagValue)>, local_flags_values: Vector<(String, FlagValue)>, parsing_args: Option<VecDeque<MiddleArg>>, error_info_list: Vector<ErrorInfo>, ) -> Context

Creates a new instance of Context with all options.

Source

pub fn args(self, args: VecDeque<String>) -> Self

Set args

Source

pub fn exe_path(&self) -> &str

Get exe_path as &str

Source

pub fn change_exe_path(self, path: String)

Change exe_path’s value

Source

pub fn push_back_to_parsing_args(&mut self, middle_arg: MiddleArg)

Add(Push back) middle_arg to this context’s parsing_args

Source

pub fn push_front_to_parsing_args(&mut self, middle_arg: MiddleArg)

Shift(Push front) middle_arg to this context’s parsing_args

Source

pub fn take_flag_value_of( &mut self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Takes flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからフラグ値を取得する。Getとは違い、参照ではなくcontextに格納されているもの(格納されていない場合はデフォルト値のコピー)そのものを返す

Source

pub fn take_inputted_flag_value_of( &mut self, flag_name: &str, ) -> Option<FlagValue>

Takes inputted flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからフラグ値を(ユーザによりargに指定(入力)されている場合)取得する。Getとは違い、参照ではなくcontextに格納されているもの(格納されていない場合はNoneを)そのものを返す

Source

pub fn take_local_flag_value_of( &mut self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Takes flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからローカルフラグの値を取得する。Getとは違い、参照ではなくcontextに格納されているもの(格納されていない場合はデフォルト値のコピー)そのものを返す

Source

pub fn take_common_flag_value_of( &mut self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Takes inputted flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからコモンフラグの値を取得する。Getとは違い、参照ではなくcontextに格納されているもの(格納されていない場合はデフォルト値のコピー)そのものを返す

Source

pub fn take_inputted_local_flag_value_of( &mut self, flag_name: &str, ) -> Option<FlagValue>

Takes inputted local flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからローカルフラグ値を(ユーザによりargに指定(入力)されている場合)取得する。Getとは違い、参照ではなくcontextに格納されているものそのもの(格納されていない場合はNone)を返す

Source

pub fn take_inputted_common_flag_value_of( &mut self, flag_name: &str, ) -> Option<FlagValue>

Takes inputted local flag value from context. Different from get, returns flag_value instance own (not reference) that has context. contextからコモンフラグ値を(ユーザによりargに指定(入力)されている場合)取得する。Getとは違い、参照ではなくcontextに格納されているものそのもの(格納されていない場合はNone)を返す

Source

pub fn get_flag_value_of( &self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Gets FlagValue’s clone of the flag matches flag_name from context. contextからフラグ値のcloneを取得する。フラグが設定されていない場合はNoneを返す なお明示的に値が指定されない場合、Bool型のフラグであればFlagValue::Bool(true)とし、String型のフラグであればFlagValue::String(String::new())、それ以外の型のフラグではFlagValue::NoneをSomeで包んで返す

Examples found in repository?
examples/single.rs (line 23)
22fn act(cmd: Command, c: Context) -> Result<ActionResult, ActionError> {
23	let r = c.get_flag_value_of("reverse", &cmd).unwrap();
24
25	println!(
26		"{}",
27		match r {
28			FlagValue::Bool(true) => {
29				c.args
30					.iter()
31					.rev()
32					.fold(String::new(), |concated, arg| concated + arg)
33			}
34			_ => {
35				c.args
36					.iter()
37					.fold(String::new(), |concated, arg| concated + arg)
38			}
39		}
40	);
41	Ok(ActionResult::Done)
42}
More examples
Hide additional examples
examples/multi.rs (line 40)
35fn print_args(current_command: Command, context: Context) -> Result<ActionResult, ActionError> {
36	if called_help(&context, &current_command) {
37		return call_help(&context, &current_command);
38	}
39	let r: bool =
40		context.get_flag_value_of("reverse", &current_command) == Some(FlagValue::Bool(true));
41	let c: bool =
42		context.get_flag_value_of("by-char", &current_command) == Some(FlagValue::Bool(true));
43	let str = {
44		let str = if r && !c {
45			context
46				.args
47				.iter()
48				.rev()
49				.fold(String::new(), |c, arg| c + arg)
50		} else {
51			context.args.iter().fold(String::new(), |c, arg| c + arg)
52		};
53		if c {
54			str.chars().rev().collect::<String>()
55		} else {
56			str
57		}
58	};
59
60	println!("{str}");
61
62	Ok(ActionResult::Done)
63}
64
65fn called_help(c: &Context, cc: &Command) -> bool {
66	Some(FlagValue::Bool(true)) == c.get_flag_value_of("help", cc)
67}
68
69fn add_command() -> Command {
70	Command::new()
71		.name("add")
72		.alias("a")
73		.action(add_action)
74		.local_flag(Flag::new_bool("detail").short_alias('d'))
75}
76
77fn add_action(cmd: Command, c: Context) -> Result<ActionResult, ActionError> {
78	if called_help(&c, &cmd) {
79		return call_help(&c, &cmd);
80	}
81	let f = |(str, sum), num: f64| (format!("{str} {num} +"), sum + num);
82	let (mut str, sum): (String, f64) =
83		if c.get_flag_value_of("reverse", &cmd) == Some(FlagValue::Bool(true)) {
84			c.args
85				.iter()
86				.rev()
87				.filter_map(|arg| arg.parse().ok())
88				.fold((String::new(), 0.0), f)
89		} else {
90			c.args
91				.iter()
92				.filter_map(|arg| arg.parse().ok())
93				.fold((String::new(), 0.0), f)
94		};
95	str.pop();
96	str.pop();
97
98	if c.get_flag_value_of("detail", &cmd).unwrap().is_bool_true() {
99		println!("{str} = {sum}");
100	} else {
101		println!("{sum}");
102	}
103	Ok(ActionResult::Done)
104}
105
106fn sub_command() -> Command {
107	Command::new()
108		.name("sub")
109		.alias("s")
110		.action(sub_action)
111		.local_flag(Flag::new_bool("sort").short_alias('s'))
112}
113
114fn sub_action(cmd: Command, c: Context) -> Result<ActionResult, ActionError> {
115	if called_help(&c, &cmd) {
116		return call_help(&c, &cmd);
117	}
118	let f = |(str, sum), (index, num): (usize, f64)| {
119		(
120			format!("{str} {num} -"),
121			if index < 1 { num } else { sum - num },
122		)
123	};
124	let filter_map_f = |arg: &String| arg.parse().ok();
125	let (mut str, result): (String, f64) =
126		if c.get_flag_value_of("reverse", &cmd) == Some(FlagValue::Bool(true)) {
127			c.args
128				.iter()
129				.rev()
130				.filter_map(filter_map_f)
131				.enumerate()
132				.fold((String::new(), 0.0), f)
133		} else if c.get_flag_value_of("sort", &cmd).unwrap().is_bool_true() {
134			let mut fvec = c.args.iter().filter_map(filter_map_f).collect::<Vec<f64>>();
135			fvec.sort_by(|a, b| a.partial_cmp(b).unwrap());
136			fvec
137				.iter_mut()
138				.enumerate()
139				.fold((String::new(), 0.0), |s, (index, fl)| f(s, (index, *fl)))
140		} else {
141			c.args
142				.iter()
143				.filter_map(filter_map_f)
144				.enumerate()
145				.fold((String::new(), 0.0), f)
146		};
147	str.pop();
148	str.pop();
149
150	println!("{str} = {result}");
151
152	Ok(ActionResult::Done)
153}
Source

pub fn get_inputted_flag_value_of(&self, flag_name: &str) -> Option<FlagValue>

Gets FlagValue’s clone of the inputted flag matches flag_name from context. contextからユーザから指定された場合のフラグ値のcloneを取得する。ユーザから入力されていない場合はNoneを返す。

Source

pub fn get_common_flag_value_of( &self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Gets FlagValue’s clone of the common flag matches flag_name from context. If it is not defined, Returns None. contextからユーザから指定された場合のコモンフラグ値のcloneを取得する。ユーザから入力されていないが定義されている場合はデフォルト値のクローンを返す。定義もされていない場合はNoneを返す。 なお明示的に値が指定されない場合、Bool型のフラグであればFlagValue::Bool(true)とし、String型のフラグであればFlagValue::String(String::new())、それ以外の型のフラグではFlagValue::NoneをSomeで包んで返す

Source

pub fn get_local_flag_value_of( &self, flag_name: &str, current_command: &Command, ) -> Option<FlagValue>

Gets FlagValue’s clone of the common flag matches flag_name from context. If it is not defined, Returns None. contextからユーザから指定された場合のローカルフラグ値のcloneを取得する。ユーザから入力されていないが定義されている場合はデフォルト値のクローンを返す。定義もされていない場合はNoneを返す。 なお明示的に値が指定されない場合、Bool型のフラグであればFlagValue::Bool(true)とし、String型のフラグであればFlagValue::String(String::new())、それ以外の型のフラグではFlagValue::NoneをSomeで包んで返す

Source

pub fn get_inputted_local_flag_value_of( &self, flag_name: &str, ) -> Option<FlagValue>

Gets the flag value of the local flag matches flag_name if inputted. If it is not defined or not inputted, returns None. flag_nameとnameが一致するローカルフラグがあり、それがユーザからコマンド引数で指定されていた場合、その値のクローンをSomeで包んで返す。flag_nameと一致するnameを持たない場合はローカルフラグ値として保存されていないためNoneを返し、ユーザがコマンド引数で指定していない場合もNoneを返す。

Source

pub fn get_inputted_common_flag_value_of( &self, flag_name: &str, ) -> Option<FlagValue>

Gets the flag value of the common flag whose name matches flag_name. If it is not defined or not inputted, returns None. flag_nameとnameが一致するコモンフラグがあり、それがユーザからコマンド引数で指定されていた場合、その値のクローンをSomeで包んで返す。flag_nameと一致するnameをどのコモンフラグも持たない場合はコモンフラグ値としてそのフラグ値は保存されないためNoneを返し、ユーザがコマンド引数で指定していない場合もNoneを返す。

Source

pub fn is_flag_true(&self, name: &str, current_command: &Command) -> bool

Returns flag has specified name is true flag.

Source

pub fn depth(&self) -> usize

Returns depth of command - root:0

Source

pub fn has_no_error(&self) -> bool

Returns true is self has no error in error_info_list

Source

pub fn num_of_error(&self) -> usize

Returns error info list’s length

Source

pub fn has_error(&self) -> bool

Returns true if error info list’s length is more than one.

Source

pub fn first_error(&self) -> Option<&ErrorInfo>

Returns info of first parse error, or None if it does not exist.

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Context

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Context

Source§

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

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

impl From<Vec<String>> for Context

Source§

fn from(raw_args: Vec<String>) -> Context

Converts to this type from the input type.
Source§

impl Run<Context> for Command

Source§

fn run(self, c: Context) -> Result<ActionResult, ActionError>

run function

Auto Trait Implementations§

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.