chore: Clap parser to parse Either type

Signed-off-by: Awiteb <a@4rs.nl>
This commit is contained in:
Awiteb 2024-08-20 11:33:14 +00:00
parent 00412f6f98
commit 2fc357bfb7
Signed by: awiteb
GPG key ID: 3F6B55640AA6682F

View file

@ -14,9 +14,14 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>. // along with this program. If not, see <https://gnu.org/licenses/gpl-3.0.html>.
use std::{fmt::Display, str::FromStr};
use either::Either::{self, Left, Right};
use crate::{LprsError, LprsResult}; use crate::{LprsError, LprsResult};
/// Parse the key & value arguments. /// Parse the key & value arguments.
///
/// ## Errors /// ## Errors
/// - If the argument value syntax not `key=value` /// - If the argument value syntax not `key=value`
pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> { pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> {
@ -30,3 +35,27 @@ pub fn kv_parser(value: &str) -> LprsResult<(String, Option<String>)> {
Ok((value.trim().to_owned(), None)) Ok((value.trim().to_owned(), None))
} }
} }
/// Parse `Either` type arguments.
///
/// ## Errors
/// - If the argument value can't be parsed to `L` or `R`
pub fn either_parser<L, R>(value: &str) -> LprsResult<Either<L, R>>
where
L: FromStr,
R: FromStr,
<L as FromStr>::Err: Display,
<R as FromStr>::Err: Display,
{
value
.trim()
.parse::<L>()
.map_err(|err| LprsError::ArgParse(err.to_string()))
.map(Left)
.or_else(|_| {
value
.parse::<R>()
.map_err(|err| LprsError::ArgParse(err.to_string()))
.map(Right)
})
}