Skip to content

Add array(), first(), indexOf() functions #1041

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
382 changes: 225 additions & 157 deletions dsc/tests/dsc_functions.tests.ps1

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions dsc_lib/locales/en-us.toml
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@ invoked = "add function"
description = "Evaluates if all arguments are true"
invoked = "and function"

[functions.array]
description = "Creates an array from the given elements of mixed types"
invoked = "array function"
invalidArgType = "Invalid argument type, only int, string, array, or object are accepted"

[functions.base64]
description = "Encodes a string to Base64 format"

Expand Down Expand Up @@ -280,6 +285,13 @@ description = "Evaluates if the two values are the same"
description = "Returns the boolean value false"
invoked = "false function"

[functions.first]
description = "Returns the first element of an array or first character of a string"
invoked = "first function"
emptyArray = "Cannot get first element of empty array"
emptyString = "Cannot get first character of empty string"
invalidArgType = "Invalid argument type, argument must be an array or string"

[functions.greater]
description = "Evaluates if the first value is greater than the second value"
invoked = "greater function"
Expand Down Expand Up @@ -307,6 +319,11 @@ parseStringError = "unable to parse string to int"
castError = "unable to cast to int"
parseNumError = "unable to parse number to int"

[functions.indexOf]
description = "Returns the index of the first occurrence of an item in an array"
invoked = "indexOf function"
invalidArrayArg = "First argument must be an array"

[functions.length]
description = "Returns the length of a string, array, or object"
invoked = "length function"
Expand Down
103 changes: 103 additions & 0 deletions dsc_lib/src/functions/array.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct Array {}

impl Function for Array {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "array".to_string(),
description: t!("functions.array.description").to_string(),
category: FunctionCategory::Array,
min_args: 1,
max_args: usize::MAX,
accepted_arg_ordered_types: vec![],
remaining_arg_accepted_types: Some(vec![
FunctionArgKind::String,
FunctionArgKind::Number,
FunctionArgKind::Object,
FunctionArgKind::Array,
]),
return_types: vec![FunctionArgKind::Array],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.array.invoked"));
let mut array_result = Vec::<Value>::new();

for value in args {
// Only accept int, string, array, or object as specified
if value.is_number() || value.is_string() || value.is_array() || value.is_object() {
array_result.push(value.clone());
} else {
return Err(DscError::Parser(t!("functions.array.invalidArgType").to_string()));
}
}

Ok(Value::Array(array_result))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn mixed_types() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array('hello', 42)]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"["hello",42]"#);
}

#[test]
fn strings_only() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array('a', 'b', 'c')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"["a","b","c"]"#);
}

#[test]
fn numbers_only() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(1, 2, 3)]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "[1,2,3]");
}

#[test]
fn arrays_and_objects() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(createArray('a','b'), createObject('key', 'value'))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), r#"[["a","b"],{"key":"value"}]"#);
}

#[test]
fn empty_array_not_allowed() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array()]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_boolean() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(true)]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_null() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[array(null())]", &Context::new());
assert!(result.is_err());
}
}
116 changes: 116 additions & 0 deletions dsc_lib/src/functions/first.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct First {}

impl Function for First {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "first".to_string(),
description: t!("functions.first.description").to_string(),
category: FunctionCategory::Array,
min_args: 1,
max_args: 1,
accepted_arg_ordered_types: vec![vec![FunctionArgKind::Array, FunctionArgKind::String]],
remaining_arg_accepted_types: None,
return_types: vec![FunctionArgKind::String, FunctionArgKind::Number, FunctionArgKind::Array, FunctionArgKind::Object],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.first.invoked"));

if let Some(array) = args[0].as_array() {
if array.is_empty() {
return Err(DscError::Parser(t!("functions.first.emptyArray").to_string()));
}
return Ok(array[0].clone());
}

if let Some(string) = args[0].as_str() {
if string.is_empty() {
return Err(DscError::Parser(t!("functions.first.emptyString").to_string()));
}
return Ok(Value::String(string.chars().next().unwrap().to_string()));
}

Err(DscError::Parser(t!("functions.first.invalidArgType").to_string()))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn array_of_strings() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray('hello', 'world'))]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("hello"));
}

#[test]
fn array_of_numbers() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray(1, 2, 3))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn array_of_mixed() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(array('hello', 42))]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("hello"));
}

#[test]
fn string_input() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('hello')]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("h"));
}

#[test]
fn single_character_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('a')]", &Context::new()).unwrap();
assert_eq!(result.as_str(), Some("a"));
}

#[test]
fn empty_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createArray())]", &Context::new());
assert!(result.is_err());
}

#[test]
fn empty_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first('')]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_object() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(createObject('key', 'value'))]", &Context::new());
assert!(result.is_err());
}

#[test]
fn invalid_type_number() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[first(42)]", &Context::new());
assert!(result.is_err());
}
}
121 changes: 121 additions & 0 deletions dsc_lib/src/functions/index_of.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use crate::DscError;
use crate::configure::context::Context;
use crate::functions::{FunctionArgKind, Function, FunctionCategory, FunctionMetadata};
use rust_i18n::t;
use serde_json::Value;
use tracing::debug;

#[derive(Debug, Default)]
pub struct IndexOf {}

impl Function for IndexOf {
fn get_metadata(&self) -> FunctionMetadata {
FunctionMetadata {
name: "indexOf".to_string(),
description: t!("functions.indexOf.description").to_string(),
category: FunctionCategory::Array,
min_args: 2,
max_args: 2,
accepted_arg_ordered_types: vec![
vec![FunctionArgKind::Array],
vec![FunctionArgKind::String, FunctionArgKind::Number, FunctionArgKind::Array, FunctionArgKind::Object],
],
remaining_arg_accepted_types: None,
return_types: vec![FunctionArgKind::Number],
}
}

fn invoke(&self, args: &[Value], _context: &Context) -> Result<Value, DscError> {
debug!("{}", t!("functions.indexOf.invoked"));

let Some(array) = args[0].as_array() else {
return Err(DscError::Parser(t!("functions.indexOf.invalidArrayArg").to_string()));
};

let item_to_find = &args[1];

for (index, item) in array.iter().enumerate() {
if item == item_to_find {
let index_i64 = i64::try_from(index).map_err(|_| {
DscError::Parser("Array index too large to represent as integer".to_string())
})?;
return Ok(Value::Number(index_i64.into()));
}
}

// Not found is -1
Ok(Value::Number((-1i64).into()))
}
}

#[cfg(test)]
mod tests {
use crate::configure::context::Context;
use crate::parser::Statement;

#[test]
fn find_string_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('apple', 'banana', 'cherry'), 'banana')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn find_number_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(10, 20, 30), 20)]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn find_first_occurrence() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('a', 'b', 'a', 'c'), 'a')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "0");
}

#[test]
fn item_not_found() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('apple', 'banana'), 'orange')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "-1");
}

#[test]
fn case_sensitive_string() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray('Apple', 'Banana'), 'apple')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "-1");
}

#[test]
fn find_array_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(array(createArray('a', 'b'), createArray('c', 'd')), createArray('c', 'd'))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn find_object_in_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(array(createObject('name', 'John'), createObject('name', 'Jane')), createObject('name', 'Jane'))]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "1");
}

#[test]
fn empty_array() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf(createArray(), 'test')]", &Context::new()).unwrap();
assert_eq!(result.to_string(), "-1");
}

#[test]
fn invalid_array_arg() {
let mut parser = Statement::new().unwrap();
let result = parser.parse_and_execute("[indexOf('not_an_array', 'test')]", &Context::new());
assert!(result.is_err());
}
}
Loading
Loading