Skip to content

Commit

Permalink
Fix --format CLI flag (#248)
Browse files Browse the repository at this point in the history
* Fix --format CLI flag

Previously, the CLI used clap's PossibleValueParser, which only supports
parsing strings. However, hayagriva was expecting to parse Format
directly. This caused a panic in clap, when trying to convert the String
to Format.

With this patch, Format implements ValueEnum, so we can use
clap::value_parser to create an EnumValueParser to parse the Format.

* remove from_str from format

---------

Co-authored-by: PgBiel <9021226+PgBiel@users.noreply.github.com>
  • Loading branch information
m-haug and PgBiel authored Nov 20, 2024
1 parent 67f4f88 commit 20b1d74
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use std::fs::{self, read_to_string};
use std::io::ErrorKind as IoErrorKind;
use std::path::Path;
use std::process::exit;
use std::str::FromStr;

use citationberg::taxonomy::Locator;
use citationberg::{
IndependentStyle, Locale, LocaleCode, LocaleFile, LongShortForm, Style,
};
use clap::{crate_version, Arg, ArgAction, Command};
use clap::builder::PossibleValue;
use clap::{crate_version, Arg, ArgAction, Command, ValueEnum};
use strum::VariantNames;

use hayagriva::archive::{locales, ArchivedStyle};
Expand All @@ -29,18 +29,25 @@ pub enum Format {
Yaml,
}

impl FromStr for Format {
type Err = &'static str;
impl ValueEnum for Format {
fn value_variants<'a>() -> &'a [Self] {
if cfg!(feature = "biblatex") {
&[Self::Bibtex, Self::Biblatex, Self::Yaml]
} else {
&[Self::Yaml]
}
}

fn from_str(s: &str) -> Result<Self, &'static str> {
match s.to_ascii_lowercase().as_ref() {
fn to_possible_value(&self) -> Option<PossibleValue> {
let value = match self {
#[cfg(feature = "biblatex")]
"bibtex" => Ok(Format::Bibtex),
Format::Bibtex => "bibtex",
#[cfg(feature = "biblatex")]
"biblatex" => Ok(Format::Biblatex),
"yaml" => Ok(Format::Yaml),
_ => Err("unknown format"),
}
Format::Biblatex => "biblatex",
Format::Yaml => "yaml",
};

Some(PossibleValue::new(value))
}
}

Expand All @@ -59,7 +66,7 @@ fn main() {
Arg::new("format")
.long("format")
.help("What input file format to expect")
.value_parser(clap::builder::PossibleValuesParser::new(Format::VARIANTS))
.value_parser(clap::value_parser!(Format))
.ignore_case(true)
.num_args(1)
.global(true),
Expand Down

0 comments on commit 20b1d74

Please sign in to comment.