1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-08-09 04:22:45 +03:00

Upgrade minijinja to 2.0.1

This commit is contained in:
Quentin Gliech
2024-05-02 12:23:01 +02:00
parent 4d2ad999d7
commit 3567f7c445
11 changed files with 95 additions and 35 deletions

4
Cargo.lock generated
View File

@@ -3710,9 +3710,9 @@ dependencies = [
[[package]] [[package]]
name = "minijinja" name = "minijinja"
version = "1.0.13" version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562e7acc6adf9a8359061ea3e0634560a3f636dc0539d36cd300c82fd703f528" checksum = "7165d0e94806d52ad5295e4b54a95176d831814840bc067298ca647e1c956338"
dependencies = [ dependencies = [
"memo-map", "memo-map",
"self_cell", "self_cell",

View File

@@ -108,7 +108,7 @@ default-features = false
# Templates # Templates
[workspace.dependencies.minijinja] [workspace.dependencies.minijinja]
version = "1.0.13" version = "2.0.1"
# Random values # Random values
[workspace.dependencies.rand] [workspace.dependencies.rand]

View File

@@ -242,7 +242,7 @@ pub(crate) async fn get(
let env = { let env = {
let mut env = minijinja::Environment::new(); let mut env = minijinja::Environment::new();
env.add_global("user", minijinja::Value::from_serializable(&id_token)); env.add_global("user", minijinja::Value::from_serialize(&id_token));
env env
}; };

View File

@@ -43,7 +43,7 @@ fn b64encode(bytes: &[u8]) -> String {
} }
/// Decode a Tag-Length-Value encoded byte array into a map of tag to value. /// Decode a Tag-Length-Value encoded byte array into a map of tag to value.
fn tlvdecode(bytes: &[u8]) -> Result<HashMap<u8, Value>, Error> { fn tlvdecode(bytes: &[u8]) -> Result<HashMap<Value, Value>, Error> {
let mut iter = bytes.iter().copied(); let mut iter = bytes.iter().copied();
let mut ret = HashMap::new(); let mut ret = HashMap::new();
loop { loop {
@@ -67,7 +67,7 @@ fn tlvdecode(bytes: &[u8]) -> Result<HashMap<u8, Value>, Error> {
); );
} }
ret.insert(tag, Value::from(Arc::new(bytes))); ret.insert(tag.into(), Value::from(Arc::new(bytes)));
} }
Ok(ret) Ok(ret)

View File

@@ -12,8 +12,13 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Without the custom_syntax feature, the `SyntaxConfig` is a unit struct
// which is annoying with this clippy lint
#![allow(clippy::default_constructed_unit_structs)]
use std::fs::File; use std::fs::File;
use ::minijinja::{machinery::WhitespaceConfig, syntax::SyntaxConfig};
use camino::Utf8PathBuf; use camino::Utf8PathBuf;
use clap::Parser; use clap::Parser;
use key::Context; use key::Context;
@@ -77,7 +82,12 @@ fn main() {
if options.extensions.split(',').any(|e| e == extension) { if options.extensions.split(',').any(|e| e == extension) {
tracing::debug!("Parsing {relative}"); tracing::debug!("Parsing {relative}");
let template = std::fs::read_to_string(&path).expect("Failed to read template"); let template = std::fs::read_to_string(&path).expect("Failed to read template");
match minijinja::parse(&template, relative.as_str()) { match minijinja::parse(
&template,
relative.as_str(),
SyntaxConfig::default(),
WhitespaceConfig::default(),
) {
Ok(ast) => { Ok(ast) => {
context.set_current_file(relative.as_str()); context.set_current_file(relative.as_str());
minijinja::find_in_stmt(&mut context, &ast).unwrap(); minijinja::find_in_stmt(&mut context, &ast).unwrap();

View File

@@ -247,6 +247,8 @@ fn find_in_optional_expr<'a>(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use minijinja::{machinery::WhitespaceConfig, syntax::SyntaxConfig};
use super::*; use super::*;
#[test] #[test]
@@ -288,7 +290,13 @@ mod tests {
]; ];
for (name, content) in templates { for (name, content) in templates {
let ast = parse(content, name).unwrap(); let ast = parse(
content,
name,
SyntaxConfig::default(),
WhitespaceConfig::default(),
)
.unwrap();
find_in_stmt(&mut context, &ast).unwrap(); find_in_stmt(&mut context, &ast).unwrap();
} }
@@ -323,7 +331,13 @@ mod tests {
fn test_invalid_key_not_string() { fn test_invalid_key_not_string() {
// This is invalid because the key is not a string // This is invalid because the key is not a string
let mut context = Context::new("t".to_owned()); let mut context = Context::new("t".to_owned());
let ast = parse(r"{{ t(5) }}", "invalid.txt").unwrap(); let ast = parse(
r"{{ t(5) }}",
"invalid.txt",
SyntaxConfig::default(),
WhitespaceConfig::default(),
)
.unwrap();
let res = find_in_stmt(&mut context, &ast); let res = find_in_stmt(&mut context, &ast);
assert!(res.is_err()); assert!(res.is_err());
@@ -333,7 +347,13 @@ mod tests {
fn test_invalid_key_filtered() { fn test_invalid_key_filtered() {
// This is invalid because the key argument has a filter // This is invalid because the key argument has a filter
let mut context = Context::new("t".to_owned()); let mut context = Context::new("t".to_owned());
let ast = parse(r#"{{ t("foo" | bar) }}"#, "invalid.txt").unwrap(); let ast = parse(
r#"{{ t("foo" | bar) }}"#,
"invalid.txt",
SyntaxConfig::default(),
WhitespaceConfig::default(),
)
.unwrap();
let res = find_in_stmt(&mut context, &ast); let res = find_in_stmt(&mut context, &ast);
assert!(res.is_err()); assert!(res.is_err());
@@ -343,7 +363,13 @@ mod tests {
fn test_invalid_key_missing() { fn test_invalid_key_missing() {
// This is invalid because the key argument is missing // This is invalid because the key argument is missing
let mut context = Context::new("t".to_owned()); let mut context = Context::new("t".to_owned());
let ast = parse(r"{{ t() }}", "invalid.txt").unwrap(); let ast = parse(
r"{{ t() }}",
"invalid.txt",
SyntaxConfig::default(),
WhitespaceConfig::default(),
)
.unwrap();
let res = find_in_stmt(&mut context, &ast); let res = find_in_stmt(&mut context, &ast);
assert!(res.is_err()); assert!(res.is_err());
@@ -353,7 +379,13 @@ mod tests {
fn test_invalid_key_negated() { fn test_invalid_key_negated() {
// This is invalid because the key argument is missing // This is invalid because the key argument is missing
let mut context = Context::new("t".to_owned()); let mut context = Context::new("t".to_owned());
let ast = parse(r#"{{ t(not "foo") }}"#, "invalid.txt").unwrap(); let ast = parse(
r#"{{ t(not "foo") }}"#,
"invalid.txt",
SyntaxConfig::default(),
WhitespaceConfig::default(),
)
.unwrap();
let res = find_in_stmt(&mut context, &ast); let res = find_in_stmt(&mut context, &ast);
assert!(res.is_err()); assert!(res.is_err());

View File

@@ -14,7 +14,10 @@
use std::sync::Arc; use std::sync::Arc;
use minijinja::{value::StructObject, Value}; use minijinja::{
value::{Enumerator, Object},
Value,
};
/// Site branding information. /// Site branding information.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@@ -59,9 +62,9 @@ impl SiteBranding {
} }
} }
impl StructObject for SiteBranding { impl Object for SiteBranding {
fn get_field(&self, name: &str) -> Option<Value> { fn get_value(self: &Arc<Self>, name: &Value) -> Option<Value> {
match name { match name.as_str()? {
"server_name" => Some(self.server_name.clone().into()), "server_name" => Some(self.server_name.clone().into()),
"policy_uri" => self.policy_uri.clone().map(Value::from), "policy_uri" => self.policy_uri.clone().map(Value::from),
"tos_uri" => self.tos_uri.clone().map(Value::from), "tos_uri" => self.tos_uri.clone().map(Value::from),
@@ -70,7 +73,7 @@ impl StructObject for SiteBranding {
} }
} }
fn static_fields(&self) -> Option<&'static [&'static str]> { fn enumerate(self: &Arc<Self>) -> Enumerator {
Some(&["server_name", "policy_uri", "tos_uri", "imprint"]) Enumerator::Str(&["server_name", "policy_uri", "tos_uri", "imprint"])
} }
} }

View File

@@ -12,7 +12,12 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
use minijinja::{value::StructObject, Value}; use std::sync::Arc;
use minijinja::{
value::{Enumerator, Object},
Value,
};
/// Site features information. /// Site features information.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -24,16 +29,16 @@ pub struct SiteFeatures {
pub password_login: bool, pub password_login: bool,
} }
impl StructObject for SiteFeatures { impl Object for SiteFeatures {
fn get_field(&self, field: &str) -> Option<Value> { fn get_value(self: &Arc<Self>, field: &Value) -> Option<Value> {
match field { match field.as_str()? {
"password_registration" => Some(Value::from(self.password_registration)), "password_registration" => Some(Value::from(self.password_registration)),
"password_login" => Some(Value::from(self.password_login)), "password_login" => Some(Value::from(self.password_login)),
_ => None, _ => None,
} }
} }
fn static_fields(&self) -> Option<&'static [&'static str]> { fn enumerate(self: &Arc<Self>) -> Enumerator {
Some(&["password_registration", "password_login"]) Enumerator::Str(&["password_registration", "password_login"])
} }
} }

View File

@@ -31,7 +31,7 @@ use mas_spa::ViteManifest;
use minijinja::{ use minijinja::{
escape_formatter, escape_formatter,
machinery::make_string_output, machinery::make_string_output,
value::{from_args, Kwargs, Object, SeqObject, ViaDeserialize}, value::{from_args, Kwargs, Object, ViaDeserialize},
Error, ErrorKind, State, Value, Error, ErrorKind, State, Value,
}; };
use url::Url; use url::Url;
@@ -76,8 +76,8 @@ pub fn register(
}); });
} }
fn tester_empty(seq: &dyn SeqObject) -> bool { fn tester_empty(seq: Value) -> bool {
seq.item_count() == 0 seq.len() == Some(0)
} }
fn tester_starting_with(value: &str, prefix: &str) -> bool { fn tester_starting_with(value: &str, prefix: &str) -> bool {
@@ -236,7 +236,7 @@ impl std::fmt::Display for TranslatorFunc {
} }
impl Object for TranslatorFunc { impl Object for TranslatorFunc {
fn call(&self, _state: &State, args: &[Value]) -> Result<Value, Error> { fn call(self: &Arc<Self>, _state: &State, args: &[Value]) -> Result<Value, Error> {
let (lang,): (&str,) = from_args(args)?; let (lang,): (&str,) = from_args(args)?;
let lang: DataLocale = lang.parse().map_err(|e| { let lang: DataLocale = lang.parse().map_err(|e| {
@@ -271,7 +271,7 @@ impl std::fmt::Display for TranslateFunc {
} }
impl Object for TranslateFunc { impl Object for TranslateFunc {
fn call(&self, state: &State, args: &[Value]) -> Result<Value, Error> { fn call(self: &Arc<Self>, state: &State, args: &[Value]) -> Result<Value, Error> {
let (key, kwargs): (&str, Kwargs) = from_args(args)?; let (key, kwargs): (&str, Kwargs) = from_args(args)?;
let (message, _locale) = if let Some(count) = kwargs.get("count")? { let (message, _locale) = if let Some(count) = kwargs.get("count")? {
@@ -326,7 +326,12 @@ impl Object for TranslateFunc {
Ok(Value::from_safe_string(buf)) Ok(Value::from_safe_string(buf))
} }
fn call_method(&self, _state: &State, name: &str, args: &[Value]) -> Result<Value, Error> { fn call_method(
self: &Arc<Self>,
_state: &State,
name: &str,
args: &[Value],
) -> Result<Value, Error> {
match name { match name {
"relative_date" => { "relative_date" => {
let (date,): (String,) = from_args(args)?; let (date,): (String,) = from_args(args)?;
@@ -435,7 +440,7 @@ impl std::fmt::Display for IncludeAsset {
} }
impl Object for IncludeAsset { impl Object for IncludeAsset {
fn call(&self, _state: &State, args: &[Value]) -> Result<Value, Error> { fn call(self: &Arc<Self>, _state: &State, args: &[Value]) -> Result<Value, Error> {
let (path, kwargs): (&str, Kwargs) = from_args(args)?; let (path, kwargs): (&str, Kwargs) = from_args(args)?;
let preload = kwargs.get("preload").unwrap_or(false); let preload = kwargs.get("preload").unwrap_or(false);
@@ -493,7 +498,12 @@ impl std::fmt::Display for Counter {
} }
impl Object for Counter { impl Object for Counter {
fn call_method(&self, _state: &State, name: &str, args: &[Value]) -> Result<Value, Error> { fn call_method(
self: &Arc<Self>,
_state: &State,
name: &str,
args: &[Value],
) -> Result<Value, Error> {
// None of the methods take any arguments // None of the methods take any arguments
from_args::<()>(args)?; from_args::<()>(args)?;

View File

@@ -234,8 +234,8 @@ impl Templates {
}) })
.await??; .await??;
env.add_global("branding", Value::from_struct_object(branding)); env.add_global("branding", Value::from_object(branding));
env.add_global("features", Value::from_struct_object(features)); env.add_global("features", Value::from_object(features));
self::functions::register( self::functions::register(
&mut env, &mut env,

View File

@@ -62,7 +62,7 @@ macro_rules! register_templates {
$(< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)? $(< $( $lt $( : $clt $(+ $dlt )* )? ),+ >)?
(&self, context: &$param) (&self, context: &$param)
-> Result<String, TemplateError> { -> Result<String, TemplateError> {
let ctx = ::minijinja::value::Value::from_serializable(context); let ctx = ::minijinja::value::Value::from_serialize(context);
let env = self.environment.load(); let env = self.environment.load();
let tmpl = env.get_template($template) let tmpl = env.get_template($template)