From 9661684ca32082d5a7338fac607dd35da09b6c1d Mon Sep 17 00:00:00 2001 From: Arthur Milchior Date: Sat, 13 Mar 2021 07:16:11 +0100 Subject: [PATCH] If a template name contains only quote, show relevant error message This is for the sake of the consistency with the last commit --- rslib/src/notetype/mod.rs | 11 +++-------- rslib/src/notetype/templates.rs | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/rslib/src/notetype/mod.rs b/rslib/src/notetype/mod.rs index 9c87f14f7..089ae52e5 100644 --- a/rslib/src/notetype/mod.rs +++ b/rslib/src/notetype/mod.rs @@ -333,14 +333,9 @@ impl NoteType { } fn fix_template_names(&mut self) -> Result<()> { - for mut t in &mut self.templates { - CardTemplate::fix_name(&mut t); - if t.name.is_empty() { - return Err(AnkiError::invalid_input("Empty template name")); - } - } - - Ok(()) + self.templates + .iter_mut() + .try_for_each(CardTemplate::fix_name) } /// Find the field index of the provided field name. diff --git a/rslib/src/notetype/templates.rs b/rslib/src/notetype/templates.rs index 781dc2aae..1da7c81d0 100644 --- a/rslib/src/notetype/templates.rs +++ b/rslib/src/notetype/templates.rs @@ -4,6 +4,7 @@ use crate::{ backend_proto::{CardTemplate as CardTemplateProto, CardTemplateConfig, OptionalUInt32}, decks::DeckID, + err::{AnkiError, Result}, template::ParsedTemplate, timestamp::TimestampSecs, types::Usn, @@ -89,10 +90,21 @@ impl CardTemplate { } } - pub(crate) fn fix_name(&mut self) { + /// Return whether the name is valid. Remove quote characters if it leads to a valid name. + pub(crate) fn fix_name(&mut self) -> Result<()> { let bad_chars = |c| c == '"'; - if self.name.contains(bad_chars) { - self.name = self.name.replace(bad_chars, ""); + if self.name.is_empty() { + return Err(AnkiError::invalid_input("Empty template name")); } + let trimmed = self.name.replace(bad_chars, ""); + if trimmed.is_empty() { + return Err(AnkiError::invalid_input( + "Template name contain only quotes", + )); + } + if self.name.len() != trimmed.len() { + self.name = trimmed; + } + Ok(()) } }