From 2366c36462d7bc77c8179d0beb48111e76d0fb7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=B4=80=E1=B4=8D=E1=B4=9B=E1=B4=8F=E1=B4=80=E1=B4=87?= =?UTF-8?q?=CA=80?= Date: Tue, 23 Apr 2024 23:21:29 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=9C=A8=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E4=B8=AD=E5=AF=B9=E6=96=87=E6=9C=AC=E8=BF=9B=E8=A1=8C?= =?UTF-8?q?=E6=88=AA=E6=96=AD=EF=BC=8C=E9=81=BF=E5=85=8D=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E8=BF=87=E9=95=BF=E9=94=99=E8=AF=AF=20(#73)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/command.rs | 27 +++++++++++++++++++++++++-- src/core/utils.rs | 10 ++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/core/command.rs b/src/core/command.rs index a7de541..c135265 100644 --- a/src/core/command.rs +++ b/src/core/command.rs @@ -643,15 +643,38 @@ async fn generate_nfo(serializer: NFOSerializer<'_>, nfo_path: PathBuf) -> Resul #[cfg(test)] mod tests { + use handlebars::handlebars_helper; + use super::*; #[test] fn test_template_usage() { let mut template = handlebars::Handlebars::new(); - let _ = template.register_template_string("video", "{{bvid}}"); + handlebars_helper!(truncate: |s: String, len: usize| { + if s.chars().count() > len { + s.chars().take(len).collect::() + } else { + s.to_string() + } + }); + template.register_helper("truncate", Box::new(truncate)); + let _ = template.register_template_string("video", "test{{bvid}}test"); + let _ = template.register_template_string("test_truncate", "哈哈,{{ truncate title 30 }}"); assert_eq!( template.render("video", &json!({"bvid": "BV1b5411h7g7"})).unwrap(), - "BV1b5411h7g7" + "testBV1b5411h7g7test" + ); + assert_eq!( + template + .render( + "test_truncate", + &json!({"title": "你说得对,但是 Rust 是由 Mozilla 自主研发的一款全新的编译期格斗游戏。\ + 编译将发生在一个被称作「Cargo」的构建系统中。在这里,被引用的指针将被授予「生命周期」之力,导引对象安全。\ + 你将扮演一位名为「Rustacean」的神秘角色, 在与「Rustc」的搏斗中邂逅各种骨骼惊奇的傲娇报错。\ + 征服她们、通过编译同时,逐步发掘「C++」程序崩溃的真相。"}) + ) + .unwrap(), + "哈哈,你说得对,但是 Rust 是由 Mozilla 自主研发的一" ); } } diff --git a/src/core/utils.rs b/src/core/utils.rs index dcf71f8..c6a5663 100644 --- a/src/core/utils.rs +++ b/src/core/utils.rs @@ -4,6 +4,7 @@ use std::path::Path; use anyhow::Result; use entity::*; use filenamify::filenamify; +use handlebars::handlebars_helper; use migration::OnConflict; use once_cell::sync::Lazy; use quick_xml::events::{BytesCData, BytesText}; @@ -21,6 +22,14 @@ use crate::config::CONFIG; pub static TEMPLATE: Lazy = Lazy::new(|| { let mut handlebars = handlebars::Handlebars::new(); + handlebars_helper!(truncate: |s: String, len: usize| { + if s.chars().count() > len { + s.chars().take(len).collect::() + } else { + s.to_string() + } + }); + handlebars.register_helper("truncate", Box::new(truncate)); handlebars .register_template_string("video", &CONFIG.video_name) .unwrap(); @@ -468,6 +477,7 @@ impl<'a> NFOSerializer<'a> { #[cfg(test)] mod tests { use super::*; + #[tokio::test] async fn test_generate_nfo() { let video = video::Model {