Skip to content

Commit

Permalink
editoast: units: define an unit_type when annotating
Browse files Browse the repository at this point in the history
Signed-off-by: Tristram Gräbener <tristram+git@tristramg.eu>
  • Loading branch information
Tristramg committed Jan 15, 2025
1 parent 30394fb commit a898d03
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions editoast/editoast_derive/src/annotate_units.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,32 @@ use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse_quote, DeriveInput, LitStr};

pub fn get_abbreviation(value: String) -> Option<&'static str> {
const OPTIONAL_SUFFIX: &str = "::option";
struct UnitType {
unit_path: String,
optional: bool,
}

impl UnitType {
fn new(path: LitStr) -> Self {
let path = path.value();
if path.ends_with(OPTIONAL_SUFFIX) {
Self {
unit_path: path.replace(OPTIONAL_SUFFIX, ""),
optional: true,
}
} else {
Self {
unit_path: path.to_string(),
optional: false,
}
}
}
}

fn get_abbreviation(value: &UnitType) -> Option<&'static str> {
// Any new value here must also be added in editoast_common/src/units.rs
match value.replace("::option", "").as_str() {
match value.unit_path.as_str() {
"second" => Some("Duration in s"),
"millisecond" => Some("Duration in ms"),
"meter" => Some("Length in m"),
Expand Down Expand Up @@ -34,8 +57,9 @@ pub fn annotate_units(input: &mut DeriveInput) -> Result<TokenStream> {
if meta.path.is_ident("with") {
let value = meta.value()?;
let s: LitStr = value.parse()?;
if let Some(abbreviation) = get_abbreviation(s.value()) {
if s.value().ends_with("::option") {
let unit = UnitType::new(s);
if let Some(abbreviation) = get_abbreviation(&unit) {
if unit.optional {
f.attrs
.push(parse_quote! {#[schema(value_type = Option<f64>)]});
} else {
Expand Down

0 comments on commit a898d03

Please sign in to comment.