formatting

This commit is contained in:
2026-03-04 22:42:23 -06:00
parent 67a1c02543
commit 95765f50a8
30 changed files with 5172 additions and 336 deletions

2
.gitignore vendored
View File

@@ -70,8 +70,6 @@ ENV/
# Node (if used for tooling)
node_modules/
package-lock.json
yarn.lock
tests/pids/*
# Docker

View File

@@ -1,8 +1,8 @@
//! Webhook security helpers for HMAC verification and validation
use hmac::{Hmac, Mac};
use sha2::{Sha256, Sha512};
use sha1::Sha1;
use sha2::{Sha256, Sha512};
/// Verify HMAC signature for webhook payload
pub fn verify_hmac_signature(
@@ -33,8 +33,8 @@ pub fn verify_hmac_signature(
}
// Decode hex signature
let expected_signature = hex::decode(hex_signature)
.map_err(|e| format!("Invalid hex signature: {}", e))?;
let expected_signature =
hex::decode(hex_signature).map_err(|e| format!("Invalid hex signature: {}", e))?;
// Compute HMAC based on algorithm
let is_valid = match algorithm {
@@ -91,7 +91,11 @@ fn verify_hmac_sha1(payload: &[u8], expected: &[u8], secret: &str) -> bool {
}
/// Generate HMAC signature for testing
pub fn generate_hmac_signature(payload: &[u8], secret: &str, algorithm: &str) -> Result<String, String> {
pub fn generate_hmac_signature(
payload: &[u8],
secret: &str,
algorithm: &str,
) -> Result<String, String> {
let signature = match algorithm {
"sha256" => {
type HmacSha256 = Hmac<Sha256>;
@@ -127,12 +131,14 @@ pub fn generate_hmac_signature(payload: &[u8], secret: &str, algorithm: &str) ->
pub fn check_ip_in_cidr(ip: &str, cidr: &str) -> Result<bool, String> {
use std::net::IpAddr;
let ip_addr: IpAddr = ip.parse()
let ip_addr: IpAddr = ip
.parse()
.map_err(|e| format!("Invalid IP address: {}", e))?;
// If CIDR doesn't contain '/', treat it as a single IP
if !cidr.contains('/') {
let cidr_addr: IpAddr = cidr.parse()
let cidr_addr: IpAddr = cidr
.parse()
.map_err(|e| format!("Invalid CIDR notation: {}", e))?;
return Ok(ip_addr == cidr_addr);
}
@@ -143,9 +149,11 @@ pub fn check_ip_in_cidr(ip: &str, cidr: &str) -> Result<bool, String> {
return Err("Invalid CIDR format".to_string());
}
let network_addr: IpAddr = parts[0].parse()
let network_addr: IpAddr = parts[0]
.parse()
.map_err(|e| format!("Invalid network address: {}", e))?;
let prefix_len: u8 = parts[1].parse()
let prefix_len: u8 = parts[1]
.parse()
.map_err(|e| format!("Invalid prefix length: {}", e))?;
// Convert to bytes for comparison
@@ -156,7 +164,11 @@ pub fn check_ip_in_cidr(ip: &str, cidr: &str) -> Result<bool, String> {
}
let ip_bits = u32::from(ip);
let network_bits = u32::from(network);
let mask = if prefix_len == 0 { 0 } else { !0u32 << (32 - prefix_len) };
let mask = if prefix_len == 0 {
0
} else {
!0u32 << (32 - prefix_len)
};
Ok((ip_bits & mask) == (network_bits & mask))
}
(IpAddr::V6(ip), IpAddr::V6(network)) => {
@@ -165,7 +177,11 @@ pub fn check_ip_in_cidr(ip: &str, cidr: &str) -> Result<bool, String> {
}
let ip_bits = u128::from(ip);
let network_bits = u128::from(network);
let mask = if prefix_len == 0 { 0 } else { !0u128 << (128 - prefix_len) };
let mask = if prefix_len == 0 {
0
} else {
!0u128 << (128 - prefix_len)
};
Ok((ip_bits & mask) == (network_bits & mask))
}
_ => Err("IP address and CIDR must be same version (IPv4 or IPv6)".to_string()),

View File

@@ -101,7 +101,9 @@ async fn handle_login(
// If a URL was provided and the target profile doesn't exist yet, create it.
if !config.profiles.contains_key(&target_profile_name) {
let url = api_url.clone().unwrap_or_else(|| "http://localhost:8080".to_string());
let url = api_url
.clone()
.unwrap_or_else(|| "http://localhost:8080".to_string());
use crate::config::Profile;
config.set_profile(
target_profile_name.clone(),
@@ -155,7 +157,10 @@ async fn handle_login(
config.save()?;
} else {
// Fallback: set_auth writes to the current profile.
config.set_auth(response.access_token.clone(), response.refresh_token.clone())?;
config.set_auth(
response.access_token.clone(),
response.refresh_token.clone(),
)?;
}
match output_format {

View File

@@ -554,9 +554,7 @@ async fn handle_create(
("Label", label.clone()),
(
"Description",
description
.clone()
.unwrap_or_else(|| "(none)".to_string()),
description.clone().unwrap_or_else(|| "(none)".to_string()),
),
("Version", version.clone()),
(
@@ -873,8 +871,8 @@ async fn handle_upload(
}
// Read pack ref from pack.yaml so we can display it
let pack_yaml_content = std::fs::read_to_string(&pack_yaml_path)
.context("Failed to read pack.yaml")?;
let pack_yaml_content =
std::fs::read_to_string(&pack_yaml_path).context("Failed to read pack.yaml")?;
let pack_yaml: serde_yaml_ng::Value =
serde_yaml_ng::from_str(&pack_yaml_content).context("Failed to parse pack.yaml")?;
let pack_ref = pack_yaml
@@ -884,10 +882,7 @@ async fn handle_upload(
match output_format {
OutputFormat::Table => {
output::print_info(&format!(
"Uploading pack '{}' from: {}",
pack_ref, path
));
output::print_info(&format!("Uploading pack '{}' from: {}", pack_ref, path));
output::print_info("Creating archive...");
}
_ => {}
@@ -995,9 +990,7 @@ fn append_dir_to_tar<W: std::io::Write>(
append_dir_to_tar(tar, base, &entry_path)?;
} else if entry_path.is_file() {
tar.append_path_with_name(&entry_path, relative_path)
.with_context(|| {
format!("Failed to add {} to archive", entry_path.display())
})?;
.with_context(|| format!("Failed to add {} to archive", entry_path.display()))?;
}
// symlinks are intentionally skipped
}

View File

@@ -219,10 +219,7 @@ async fn handle_upload(
(resolved from workflow_file: '{}' relative to '{}')",
workflow_path.display(),
workflow_file_rel,
action_path
.parent()
.unwrap_or(Path::new("."))
.display()
action_path.parent().unwrap_or(Path::new(".")).display()
);
}
@@ -230,8 +227,8 @@ async fn handle_upload(
let workflow_yaml_content =
std::fs::read_to_string(&workflow_path).context("Failed to read workflow YAML file")?;
let workflow_definition: serde_json::Value =
serde_yaml_ng::from_str(&workflow_yaml_content).context(format!(
let workflow_definition: serde_json::Value = serde_yaml_ng::from_str(&workflow_yaml_content)
.context(format!(
"Failed to parse workflow YAML file: {}",
workflow_path.display()
))?;
@@ -411,7 +408,15 @@ async fn handle_list(
let mut table = output::create_table();
output::add_header(
&mut table,
vec!["ID", "Reference", "Pack", "Label", "Version", "Enabled", "Tags"],
vec![
"ID",
"Reference",
"Pack",
"Label",
"Version",
"Enabled",
"Tags",
],
);
for wf in &workflows {
@@ -512,14 +517,8 @@ async fn handle_show(
output::add_header(&mut table, vec!["#", "Name", "Action", "Transitions"]);
for (i, task) in arr.iter().enumerate() {
let name = task
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("?");
let action = task
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("-");
let name = task.get("name").and_then(|v| v.as_str()).unwrap_or("?");
let action = task.get("action").and_then(|v| v.as_str()).unwrap_or("-");
let transition_count = task
.get("next")
@@ -589,7 +588,8 @@ async fn handle_delete(
match output_format {
OutputFormat::Json | OutputFormat::Yaml => {
let msg = serde_json::json!({"message": format!("Workflow '{}' deleted", workflow_ref)});
let msg =
serde_json::json!({"message": format!("Workflow '{}' deleted", workflow_ref)});
output::print_output(&msg, output_format)?;
}
OutputFormat::Table => {
@@ -635,9 +635,7 @@ fn split_action_ref(action_ref: &str) -> Result<(String, String)> {
/// YAML is typically at `<pack>/actions/<name>.yaml`, the workflow path is
/// resolved relative to the action YAML's parent directory.
fn resolve_workflow_path(action_yaml_path: &Path, workflow_file: &str) -> Result<PathBuf> {
let action_dir = action_yaml_path
.parent()
.unwrap_or(Path::new("."));
let action_dir = action_yaml_path.parent().unwrap_or(Path::new("."));
let resolved = action_dir.join(workflow_file);

View File

@@ -1,7 +1,6 @@
//! Integration tests for CLI action commands
#![allow(deprecated)]
use assert_cmd::Command;
use predicates::prelude::*;
use serde_json::json;

View File

@@ -546,8 +546,7 @@ async fn test_workflow_upload_success() {
let fixture = TestFixture::new().await;
fixture.write_authenticated_config("valid_token", "refresh_token");
let wf_fixture =
WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
let wf_fixture = WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
mock_workflow_save(&fixture.mock_server, "mypack").await;
@@ -571,8 +570,7 @@ async fn test_workflow_upload_json_output() {
let fixture = TestFixture::new().await;
fixture.write_authenticated_config("valid_token", "refresh_token");
let wf_fixture =
WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
let wf_fixture = WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
mock_workflow_save(&fixture.mock_server, "mypack").await;
@@ -597,8 +595,7 @@ async fn test_workflow_upload_conflict_without_force() {
let fixture = TestFixture::new().await;
fixture.write_authenticated_config("valid_token", "refresh_token");
let wf_fixture =
WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
let wf_fixture = WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
mock_workflow_save_conflict(&fixture.mock_server, "mypack").await;
@@ -622,8 +619,7 @@ async fn test_workflow_upload_conflict_with_force() {
let fixture = TestFixture::new().await;
fixture.write_authenticated_config("valid_token", "refresh_token");
let wf_fixture =
WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
let wf_fixture = WorkflowFixture::new("mypack.deploy", "workflows/deploy.workflow.yaml");
mock_workflow_save_conflict(&fixture.mock_server, "mypack").await;
mock_workflow_update(&fixture.mock_server, "mypack.deploy").await;

View File

@@ -56,7 +56,10 @@ impl RegistryClient {
let http_client = reqwest::Client::builder()
.timeout(timeout)
.user_agent(format!("attune-registry-client/{}", env!("CARGO_PKG_VERSION")))
.user_agent(format!(
"attune-registry-client/{}",
env!("CARGO_PKG_VERSION")
))
.build()
.map_err(|e| Error::Internal(format!("Failed to create HTTP client: {}", e)))?;
@@ -69,7 +72,9 @@ impl RegistryClient {
/// Get all enabled registries sorted by priority (lower number = higher priority)
pub fn get_registries(&self) -> Vec<RegistryIndexConfig> {
let mut registries: Vec<_> = self.config.indices
let mut registries: Vec<_> = self
.config
.indices
.iter()
.filter(|r| r.enabled)
.cloned()
@@ -156,7 +161,8 @@ impl RegistryClient {
/// Fetch index from file:// URL
async fn fetch_index_from_file(&self, url: &str) -> Result<PackIndex> {
let path = url.strip_prefix("file://")
let path = url
.strip_prefix("file://")
.ok_or_else(|| Error::Configuration(format!("Invalid file URL: {}", url)))?;
let path = PathBuf::from(path);
@@ -209,11 +215,7 @@ impl RegistryClient {
}
}
Err(e) => {
tracing::warn!(
"Failed to fetch registry {}: {}",
registry.url,
e
);
tracing::warn!("Failed to fetch registry {}: {}", registry.url, e);
continue;
}
}
@@ -236,7 +238,10 @@ impl RegistryClient {
let matches = pack.pack_ref.to_lowercase().contains(&keyword_lower)
|| pack.label.to_lowercase().contains(&keyword_lower)
|| pack.description.to_lowercase().contains(&keyword_lower)
|| pack.keywords.iter().any(|k| k.to_lowercase().contains(&keyword_lower));
|| pack
.keywords
.iter()
.any(|k| k.to_lowercase().contains(&keyword_lower));
if matches {
results.push((pack, registry.url.clone()));
@@ -244,11 +249,7 @@ impl RegistryClient {
}
}
Err(e) => {
tracing::warn!(
"Failed to fetch registry {}: {}",
registry.url,
e
);
tracing::warn!("Failed to fetch registry {}: {}", registry.url, e);
continue;
}
}
@@ -264,7 +265,9 @@ impl RegistryClient {
registry_name: &str,
) -> Result<Option<PackIndexEntry>> {
// Find registry by name
let registry = self.config.indices
let registry = self
.config
.indices
.iter()
.find(|r| r.name.as_deref() == Some(registry_name))
.ok_or_else(|| Error::not_found("registry", "name", registry_name))?;

View File

@@ -23,15 +23,9 @@ pub type ProgressCallback = Arc<dyn Fn(ProgressEvent) + Send + Sync>;
#[derive(Debug, Clone)]
pub enum ProgressEvent {
/// Started a new step
StepStarted {
step: String,
message: String,
},
StepStarted { step: String, message: String },
/// Step completed
StepCompleted {
step: String,
message: String,
},
StepCompleted { step: String, message: String },
/// Download progress
Downloading {
url: String,
@@ -39,21 +33,13 @@ pub enum ProgressEvent {
total_bytes: Option<u64>,
},
/// Extraction progress
Extracting {
file: String,
},
Extracting { file: String },
/// Verification progress
Verifying {
message: String,
},
Verifying { message: String },
/// Warning message
Warning {
message: String,
},
Warning { message: String },
/// Info message
Info {
message: String,
},
Info { message: String },
}
/// Pack installer for handling various installation sources
@@ -151,12 +137,15 @@ impl PackInstaller {
/// Install a pack from the given source
pub async fn install(&self, source: PackSource) -> Result<InstalledPack> {
match source {
PackSource::Git { url, git_ref } => self.install_from_git(&url, git_ref.as_deref()).await,
PackSource::Git { url, git_ref } => {
self.install_from_git(&url, git_ref.as_deref()).await
}
PackSource::Archive { url } => self.install_from_archive_url(&url, None).await,
PackSource::LocalDirectory { path } => self.install_from_local_directory(&path).await,
PackSource::LocalArchive { path } => self.install_from_local_archive(&path).await,
PackSource::Registry { pack_ref, version } => {
self.install_from_registry(&pack_ref, version.as_deref()).await
self.install_from_registry(&pack_ref, version.as_deref())
.await
}
}
}
@@ -267,7 +256,11 @@ impl PackInstaller {
// Verify source exists and is a directory
if !source_path.exists() {
return Err(Error::not_found("directory", "path", source_path.display().to_string()));
return Err(Error::not_found(
"directory",
"path",
source_path.display().to_string(),
));
}
if !source_path.is_dir() {
@@ -301,7 +294,11 @@ impl PackInstaller {
// Verify file exists
if !archive_path.exists() {
return Err(Error::not_found("file", "path", archive_path.display().to_string()));
return Err(Error::not_found(
"file",
"path",
archive_path.display().to_string(),
));
}
if !archive_path.is_file() {
@@ -369,9 +366,7 @@ impl PackInstaller {
git_ref,
checksum,
} => {
let mut installed = self
.install_from_git(&url, git_ref.as_deref())
.await?;
let mut installed = self.install_from_git(&url, git_ref.as_deref()).await?;
installed.checksum = Some(checksum);
Ok(installed)
}
@@ -426,11 +421,7 @@ impl PackInstaller {
}
// Determine filename from URL
let filename = url
.split('/')
.last()
.unwrap_or("archive.zip")
.to_string();
let filename = url.split('/').last().unwrap_or("archive.zip").to_string();
let archive_path = self.temp_dir.join(&filename);
@@ -483,7 +474,10 @@ impl PackInstaller {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(Error::internal(format!("Failed to extract zip: {}", stderr)));
return Err(Error::internal(format!(
"Failed to extract zip: {}",
stderr
)));
}
Ok(())
@@ -502,22 +496,23 @@ impl PackInstaller {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(Error::internal(format!("Failed to extract tar.gz: {}", stderr)));
return Err(Error::internal(format!(
"Failed to extract tar.gz: {}",
stderr
)));
}
Ok(())
}
/// Verify archive checksum
async fn verify_archive_checksum(
&self,
archive_path: &Path,
checksum_str: &str,
) -> Result<()> {
async fn verify_archive_checksum(&self, archive_path: &Path, checksum_str: &str) -> Result<()> {
let checksum = Checksum::parse(checksum_str)
.map_err(|e| Error::validation(format!("Invalid checksum: {}", e)))?;
let computed = self.compute_checksum(archive_path, &checksum.algorithm).await?;
let computed = self
.compute_checksum(archive_path, &checksum.algorithm)
.await?;
if computed != checksum.hash {
return Err(Error::validation(format!(
@@ -553,7 +548,10 @@ impl PackInstaller {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(Error::internal(format!("Checksum computation failed: {}", stderr)));
return Err(Error::internal(format!(
"Checksum computation failed: {}",
stderr
)));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -611,9 +609,9 @@ impl PackInstaller {
use tokio::fs;
// Create destination directory if it doesn't exist
fs::create_dir_all(dst)
.await
.map_err(|e| Error::internal(format!("Failed to create destination directory: {}", e)))?;
fs::create_dir_all(dst).await.map_err(|e| {
Error::internal(format!("Failed to create destination directory: {}", e))
})?;
// Read source directory
let mut entries = fs::read_dir(src)

View File

@@ -145,7 +145,8 @@ impl PackStorage {
})?;
for entry in entries {
let entry = entry.map_err(|e| Error::io(format!("Failed to read directory entry: {}", e)))?;
let entry =
entry.map_err(|e| Error::io(format!("Failed to read directory entry: {}", e)))?;
let path = entry.path();
if path.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
@@ -209,13 +210,21 @@ pub fn calculate_directory_checksum<P: AsRef<Path>>(path: P) -> Result<String> {
// Hash file contents
let mut file = fs::File::open(&file_path).map_err(|e| {
Error::io(format!("Failed to open file {}: {}", file_path.display(), e))
Error::io(format!(
"Failed to open file {}: {}",
file_path.display(),
e
))
})?;
let mut buffer = [0u8; 8192];
loop {
let n = file.read(&mut buffer).map_err(|e| {
Error::io(format!("Failed to read file {}: {}", file_path.display(), e))
Error::io(format!(
"Failed to read file {}: {}",
file_path.display(),
e
))
})?;
if n == 0 {
break;
@@ -255,15 +264,14 @@ pub fn calculate_file_checksum<P: AsRef<Path>>(path: P) -> Result<String> {
}
let mut hasher = Sha256::new();
let mut file = fs::File::open(path).map_err(|e| {
Error::io(format!("Failed to open file {}: {}", path.display(), e))
})?;
let mut file = fs::File::open(path)
.map_err(|e| Error::io(format!("Failed to open file {}: {}", path.display(), e)))?;
let mut buffer = [0u8; 8192];
loop {
let n = file.read(&mut buffer).map_err(|e| {
Error::io(format!("Failed to read file {}: {}", path.display(), e))
})?;
let n = file
.read(&mut buffer)
.map_err(|e| Error::io(format!("Failed to read file {}: {}", path.display(), e)))?;
if n == 0 {
break;
}
@@ -291,7 +299,8 @@ fn copy_dir_all(src: &Path, dst: &Path) -> Result<()> {
e
))
})? {
let entry = entry.map_err(|e| Error::io(format!("Failed to read directory entry: {}", e)))?;
let entry =
entry.map_err(|e| Error::io(format!("Failed to read directory entry: {}", e)))?;
let path = entry.path();
let file_name = entry.file_name();
let dest_path = dst.join(&file_name);

View File

@@ -332,9 +332,8 @@ impl ExecutionRepository {
.collect::<Vec<_>>()
.join(", ");
let select_clause = format!(
"{prefixed_select}, enf.rule_ref AS rule_ref, enf.trigger_ref AS trigger_ref"
);
let select_clause =
format!("{prefixed_select}, enf.rule_ref AS rule_ref, enf.trigger_ref AS trigger_ref");
let from_clause = "FROM execution e LEFT JOIN enforcement enf ON e.enforcement = enf.id";
@@ -425,10 +424,7 @@ impl ExecutionRepository {
}
// ── COUNT query ──────────────────────────────────────────────────
let total: i64 = count_qb
.build_query_scalar()
.fetch_one(db)
.await?;
let total: i64 = count_qb.build_query_scalar().fetch_one(db).await?;
let total = total.max(0) as u64;
// ── Data query with ORDER BY + pagination ────────────────────────
@@ -438,10 +434,7 @@ impl ExecutionRepository {
qb.push(" OFFSET ");
qb.push_bind(filters.offset as i64);
let rows: Vec<ExecutionWithRefs> = qb
.build_query_as()
.fetch_all(db)
.await?;
let rows: Vec<ExecutionWithRefs> = qb.build_query_as().fetch_all(db).await?;
Ok(ExecutionSearchResult { rows, total })
}

View File

@@ -556,11 +556,7 @@ mod tests {
#[test]
fn test_context_without_event_metadata() {
// Context with only a payload — no id, trigger, or created
let context = TemplateContext::new(
json!({"service": "test"}),
json!({}),
json!({}),
);
let context = TemplateContext::new(json!({"service": "test"}), json!({}), json!({}));
let template = json!({
"service": "{{ event.payload.service }}",

View File

@@ -87,26 +87,14 @@ pub enum Expr {
},
/// Unary operation: `op operand`
UnaryOp {
op: UnaryOp,
operand: Box<Expr>,
},
UnaryOp { op: UnaryOp, operand: Box<Expr> },
/// Property access: `expr.field`
DotAccess {
object: Box<Expr>,
field: String,
},
DotAccess { object: Box<Expr>, field: String },
/// Index/bracket access: `expr[index_expr]`
IndexAccess {
object: Box<Expr>,
index: Box<Expr>,
},
IndexAccess { object: Box<Expr>, index: Box<Expr> },
/// Function call: `name(arg1, arg2, ...)`
FunctionCall {
name: String,
args: Vec<Expr>,
},
FunctionCall { name: String, args: Vec<Expr> },
}

View File

@@ -741,7 +741,9 @@ fn to_int(v: &JsonValue) -> EvalResult<JsonValue> {
} else if let Some(f) = n.as_f64() {
Ok(json!(f as i64))
} else {
Err(EvalError::TypeError("Cannot convert number to int".to_string()))
Err(EvalError::TypeError(
"Cannot convert number to int".to_string(),
))
}
}
JsonValue::String(s) => {
@@ -958,9 +960,7 @@ fn fn_join(arr: &JsonValue, sep: &JsonValue) -> EvalResult<JsonValue> {
))
})?;
let sep = require_string("join", sep)?;
let strings: Result<Vec<String>, _> = arr.iter().map(|v| {
Ok(value_to_string(v))
}).collect();
let strings: Result<Vec<String>, _> = arr.iter().map(|v| Ok(value_to_string(v))).collect();
Ok(json!(strings?.join(sep)))
}
@@ -986,8 +986,7 @@ fn fn_ends_with(s: &JsonValue, suffix: &JsonValue) -> EvalResult<JsonValue> {
fn fn_match(pattern: &JsonValue, s: &JsonValue) -> EvalResult<JsonValue> {
let pattern = require_string("match", pattern)?;
let s = require_string("match", s)?;
let re = Regex::new(pattern)
.map_err(|e| EvalError::RegexError(format!("{}", e)))?;
let re = Regex::new(pattern).map_err(|e| EvalError::RegexError(format!("{}", e)))?;
Ok(json!(re.is_match(s)))
}
@@ -1012,9 +1011,7 @@ fn fn_reversed(v: &JsonValue) -> EvalResult<JsonValue> {
rev.reverse();
Ok(JsonValue::Array(rev))
}
JsonValue::String(s) => {
Ok(json!(s.chars().rev().collect::<String>()))
}
JsonValue::String(s) => Ok(json!(s.chars().rev().collect::<String>())),
_ => Err(EvalError::TypeError(format!(
"reversed() requires array or string, got {}",
type_name(v)
@@ -1095,7 +1092,10 @@ fn fn_flat(v: &JsonValue) -> EvalResult<JsonValue> {
fn fn_zip(a: &JsonValue, b: &JsonValue) -> EvalResult<JsonValue> {
let a_arr = a.as_array().ok_or_else(|| {
EvalError::TypeError(format!("zip() first argument must be array, got {}", type_name(a)))
EvalError::TypeError(format!(
"zip() first argument must be array, got {}",
type_name(a)
))
})?;
let b_arr = b.as_array().ok_or_else(|| {
EvalError::TypeError(format!(
@@ -1114,37 +1114,38 @@ fn fn_zip(a: &JsonValue, b: &JsonValue) -> EvalResult<JsonValue> {
}
fn fn_range_1(end: &JsonValue) -> EvalResult<JsonValue> {
let n = end.as_i64().ok_or_else(|| {
EvalError::TypeError("range() requires integer argument".to_string())
})?;
let n = end
.as_i64()
.ok_or_else(|| EvalError::TypeError("range() requires integer argument".to_string()))?;
let arr: Vec<JsonValue> = (0..n).map(|i| json!(i)).collect();
Ok(JsonValue::Array(arr))
}
fn fn_range_2(start: &JsonValue, end: &JsonValue) -> EvalResult<JsonValue> {
let s = start.as_i64().ok_or_else(|| {
EvalError::TypeError("range() requires integer arguments".to_string())
})?;
let e = end.as_i64().ok_or_else(|| {
EvalError::TypeError("range() requires integer arguments".to_string())
})?;
let s = start
.as_i64()
.ok_or_else(|| EvalError::TypeError("range() requires integer arguments".to_string()))?;
let e = end
.as_i64()
.ok_or_else(|| EvalError::TypeError("range() requires integer arguments".to_string()))?;
let arr: Vec<JsonValue> = (s..e).map(|i| json!(i)).collect();
Ok(JsonValue::Array(arr))
}
fn fn_slice(v: &JsonValue, start: &JsonValue, end: &JsonValue) -> EvalResult<JsonValue> {
let s = start.as_i64().ok_or_else(|| {
EvalError::TypeError("slice() start must be integer".to_string())
})? as usize;
let s = start
.as_i64()
.ok_or_else(|| EvalError::TypeError("slice() start must be integer".to_string()))?
as usize;
match v {
JsonValue::Array(arr) => {
let e = if end.is_null() {
arr.len()
} else {
end.as_i64()
.ok_or_else(|| EvalError::TypeError("slice() end must be integer".to_string()))?
as usize
end.as_i64().ok_or_else(|| {
EvalError::TypeError("slice() end must be integer".to_string())
})? as usize
};
let e = e.min(arr.len());
let s = s.min(e);
@@ -1155,9 +1156,9 @@ fn fn_slice(v: &JsonValue, start: &JsonValue, end: &JsonValue) -> EvalResult<Jso
let e = if end.is_null() {
chars.len()
} else {
end.as_i64()
.ok_or_else(|| EvalError::TypeError("slice() end must be integer".to_string()))?
as usize
end.as_i64().ok_or_else(|| {
EvalError::TypeError("slice() end must be integer".to_string())
})? as usize
};
let e = e.min(chars.len());
let s = s.min(e);
@@ -1182,7 +1183,9 @@ fn fn_index_of(haystack: &JsonValue, needle: &JsonValue) -> EvalResult<JsonValue
}
JsonValue::String(s) => {
let needle = needle.as_str().ok_or_else(|| {
EvalError::TypeError("index_of() needle must be string for string search".to_string())
EvalError::TypeError(
"index_of() needle must be string for string search".to_string(),
)
})?;
match s.find(needle) {
Some(pos) => Ok(json!(pos as i64)),
@@ -1292,10 +1295,7 @@ mod tests {
&json!({"a": [1, 2], "b": {"c": 3}}),
&json!({"b": {"c": 3}, "a": [1, 2]})
));
assert!(!json_eq(
&json!({"a": [1, 2]}),
&json!({"a": [1, 3]})
));
assert!(!json_eq(&json!({"a": [1, 2]}), &json!({"a": [1, 3]})));
}
#[test]

View File

@@ -71,12 +71,12 @@ use serde_json::Value as JsonValue;
/// This is the main entry point for the expression engine. It tokenizes the
/// input, parses it into an AST, and evaluates it to produce a `JsonValue`.
pub fn eval_expression(input: &str, ctx: &dyn EvalContext) -> EvalResult<JsonValue> {
let tokens = Tokenizer::new(input).tokenize().map_err(|e| {
EvalError::ParseError(format!("{}", e))
})?;
let ast = Parser::new(&tokens).parse().map_err(|e| {
EvalError::ParseError(format!("{}", e))
})?;
let tokens = Tokenizer::new(input)
.tokenize()
.map_err(|e| EvalError::ParseError(format!("{}", e)))?;
let ast = Parser::new(&tokens)
.parse()
.map_err(|e| EvalError::ParseError(format!("{}", e)))?;
evaluator::eval(&ast, ctx)
}
@@ -84,9 +84,9 @@ pub fn eval_expression(input: &str, ctx: &dyn EvalContext) -> EvalResult<JsonVal
///
/// Useful for validation or inspection.
pub fn parse_expression(input: &str) -> Result<Expr, ParseError> {
let tokens = Tokenizer::new(input).tokenize().map_err(|e| {
ParseError::TokenError(format!("{}", e))
})?;
let tokens = Tokenizer::new(input)
.tokenize()
.map_err(|e| ParseError::TokenError(format!("{}", e)))?;
Parser::new(&tokens).parse()
}
@@ -149,7 +149,10 @@ mod tests {
fn test_float_arithmetic() {
let ctx = TestContext::new();
assert_eq!(eval_expression("2.5 + 1.5", &ctx).unwrap(), json!(4.0));
assert_eq!(eval_expression("10.0 / 3.0", &ctx).unwrap(), json!(10.0 / 3.0));
assert_eq!(
eval_expression("10.0 / 3.0", &ctx).unwrap(),
json!(10.0 / 3.0)
);
}
#[test]
@@ -214,9 +217,18 @@ mod tests {
#[test]
fn test_string_comparison() {
let ctx = TestContext::new();
assert_eq!(eval_expression("\"abc\" == \"abc\"", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("\"abc\" < \"abd\"", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("\"abc\" > \"abb\"", &ctx).unwrap(), json!(true));
assert_eq!(
eval_expression("\"abc\" == \"abc\"", &ctx).unwrap(),
json!(true)
);
assert_eq!(
eval_expression("\"abc\" < \"abd\"", &ctx).unwrap(),
json!(true)
);
assert_eq!(
eval_expression("\"abc\" > \"abb\"", &ctx).unwrap(),
json!(true)
);
}
#[test]
@@ -225,7 +237,10 @@ mod tests {
assert_eq!(eval_expression("null == null", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("null != null", &ctx).unwrap(), json!(false));
assert_eq!(eval_expression("null == 0", &ctx).unwrap(), json!(false));
assert_eq!(eval_expression("null == false", &ctx).unwrap(), json!(false));
assert_eq!(
eval_expression("null == false", &ctx).unwrap(),
json!(false)
);
}
#[test]
@@ -256,9 +271,15 @@ mod tests {
fn test_boolean_operators() {
let ctx = TestContext::new();
assert_eq!(eval_expression("true and true", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("true and false", &ctx).unwrap(), json!(false));
assert_eq!(
eval_expression("true and false", &ctx).unwrap(),
json!(false)
);
assert_eq!(eval_expression("false or true", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("false or false", &ctx).unwrap(), json!(false));
assert_eq!(
eval_expression("false or false", &ctx).unwrap(),
json!(false)
);
assert_eq!(eval_expression("not true", &ctx).unwrap(), json!(false));
assert_eq!(eval_expression("not false", &ctx).unwrap(), json!(true));
}
@@ -283,8 +304,7 @@ mod tests {
#[test]
fn test_dot_access() {
let ctx = TestContext::new()
.with_var("obj", json!({"a": {"b": 42}}));
let ctx = TestContext::new().with_var("obj", json!({"a": {"b": 42}}));
assert_eq!(eval_expression("obj.a.b", &ctx).unwrap(), json!(42));
}
@@ -294,7 +314,10 @@ mod tests {
.with_var("arr", json!([10, 20, 30]))
.with_var("obj", json!({"key": "value"}));
assert_eq!(eval_expression("arr[1]", &ctx).unwrap(), json!(20));
assert_eq!(eval_expression("obj[\"key\"]", &ctx).unwrap(), json!("value"));
assert_eq!(
eval_expression("obj[\"key\"]", &ctx).unwrap(),
json!("value")
);
}
#[test]
@@ -304,9 +327,18 @@ mod tests {
.with_var("obj", json!({"key": "val"}));
assert_eq!(eval_expression("2 in arr", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("5 in arr", &ctx).unwrap(), json!(false));
assert_eq!(eval_expression("\"key\" in obj", &ctx).unwrap(), json!(true));
assert_eq!(eval_expression("\"nope\" in obj", &ctx).unwrap(), json!(false));
assert_eq!(eval_expression("\"ell\" in \"hello\"", &ctx).unwrap(), json!(true));
assert_eq!(
eval_expression("\"key\" in obj", &ctx).unwrap(),
json!(true)
);
assert_eq!(
eval_expression("\"nope\" in obj", &ctx).unwrap(),
json!(false)
);
assert_eq!(
eval_expression("\"ell\" in \"hello\"", &ctx).unwrap(),
json!(true)
);
}
// ---------------------------------------------------------------
@@ -319,7 +351,10 @@ mod tests {
.with_var("arr", json!([1, 2, 3]))
.with_var("obj", json!({"a": 1, "b": 2}));
assert_eq!(eval_expression("length(arr)", &ctx).unwrap(), json!(3));
assert_eq!(eval_expression("length(\"hello\")", &ctx).unwrap(), json!(5));
assert_eq!(
eval_expression("length(\"hello\")", &ctx).unwrap(),
json!(5)
);
assert_eq!(eval_expression("length(obj)", &ctx).unwrap(), json!(2));
}
@@ -327,7 +362,10 @@ mod tests {
fn test_type_conversions() {
let ctx = TestContext::new();
assert_eq!(eval_expression("string(42)", &ctx).unwrap(), json!("42"));
assert_eq!(eval_expression("number(\"3.14\")", &ctx).unwrap(), json!(3.14));
assert_eq!(
eval_expression("number(\"3.14\")", &ctx).unwrap(),
json!(3.14)
);
assert_eq!(eval_expression("int(3.9)", &ctx).unwrap(), json!(3));
assert_eq!(eval_expression("int(\"42\")", &ctx).unwrap(), json!(42));
assert_eq!(eval_expression("bool(1)", &ctx).unwrap(), json!(true));
@@ -341,18 +379,35 @@ mod tests {
let ctx = TestContext::new()
.with_var("arr", json!([1]))
.with_var("obj", json!({}));
assert_eq!(eval_expression("type_of(42)", &ctx).unwrap(), json!("number"));
assert_eq!(eval_expression("type_of(\"hi\")", &ctx).unwrap(), json!("string"));
assert_eq!(eval_expression("type_of(true)", &ctx).unwrap(), json!("bool"));
assert_eq!(eval_expression("type_of(null)", &ctx).unwrap(), json!("null"));
assert_eq!(eval_expression("type_of(arr)", &ctx).unwrap(), json!("array"));
assert_eq!(eval_expression("type_of(obj)", &ctx).unwrap(), json!("object"));
assert_eq!(
eval_expression("type_of(42)", &ctx).unwrap(),
json!("number")
);
assert_eq!(
eval_expression("type_of(\"hi\")", &ctx).unwrap(),
json!("string")
);
assert_eq!(
eval_expression("type_of(true)", &ctx).unwrap(),
json!("bool")
);
assert_eq!(
eval_expression("type_of(null)", &ctx).unwrap(),
json!("null")
);
assert_eq!(
eval_expression("type_of(arr)", &ctx).unwrap(),
json!("array")
);
assert_eq!(
eval_expression("type_of(obj)", &ctx).unwrap(),
json!("object")
);
}
#[test]
fn test_keys_values() {
let ctx = TestContext::new()
.with_var("obj", json!({"b": 2, "a": 1}));
let ctx = TestContext::new().with_var("obj", json!({"b": 2, "a": 1}));
let keys = eval_expression("sort(keys(obj))", &ctx).unwrap();
assert_eq!(keys, json!(["a", "b"]));
let values = eval_expression("sort(values(obj))", &ctx).unwrap();
@@ -368,15 +423,27 @@ mod tests {
assert_eq!(eval_expression("round(3.5)", &ctx).unwrap(), json!(4));
assert_eq!(eval_expression("min(3, 7)", &ctx).unwrap(), json!(3));
assert_eq!(eval_expression("max(3, 7)", &ctx).unwrap(), json!(7));
assert_eq!(eval_expression("sum([1, 2, 3, 4])", &ctx).unwrap(), json!(10));
assert_eq!(
eval_expression("sum([1, 2, 3, 4])", &ctx).unwrap(),
json!(10)
);
}
#[test]
fn test_string_functions() {
let ctx = TestContext::new();
assert_eq!(eval_expression("lower(\"HELLO\")", &ctx).unwrap(), json!("hello"));
assert_eq!(eval_expression("upper(\"hello\")", &ctx).unwrap(), json!("HELLO"));
assert_eq!(eval_expression("trim(\" hi \")", &ctx).unwrap(), json!("hi"));
assert_eq!(
eval_expression("lower(\"HELLO\")", &ctx).unwrap(),
json!("hello")
);
assert_eq!(
eval_expression("upper(\"hello\")", &ctx).unwrap(),
json!("HELLO")
);
assert_eq!(
eval_expression("trim(\" hi \")", &ctx).unwrap(),
json!("hi")
);
assert_eq!(
eval_expression("replace(\"hello world\", \"world\", \"rust\")", &ctx).unwrap(),
json!("hello rust")
@@ -414,10 +481,15 @@ mod tests {
#[test]
fn test_collection_functions() {
let ctx = TestContext::new()
.with_var("arr", json!([3, 1, 2]));
assert_eq!(eval_expression("sort(arr)", &ctx).unwrap(), json!([1, 2, 3]));
assert_eq!(eval_expression("reversed(arr)", &ctx).unwrap(), json!([2, 1, 3]));
let ctx = TestContext::new().with_var("arr", json!([3, 1, 2]));
assert_eq!(
eval_expression("sort(arr)", &ctx).unwrap(),
json!([1, 2, 3])
);
assert_eq!(
eval_expression("reversed(arr)", &ctx).unwrap(),
json!([2, 1, 3])
);
assert_eq!(
eval_expression("unique([1, 2, 2, 3, 1])", &ctx).unwrap(),
json!([1, 2, 3])
@@ -435,14 +507,23 @@ mod tests {
#[test]
fn test_range() {
let ctx = TestContext::new();
assert_eq!(eval_expression("range(5)", &ctx).unwrap(), json!([0, 1, 2, 3, 4]));
assert_eq!(eval_expression("range(2, 5)", &ctx).unwrap(), json!([2, 3, 4]));
assert_eq!(
eval_expression("range(5)", &ctx).unwrap(),
json!([0, 1, 2, 3, 4])
);
assert_eq!(
eval_expression("range(2, 5)", &ctx).unwrap(),
json!([2, 3, 4])
);
}
#[test]
fn test_reversed_string() {
let ctx = TestContext::new();
assert_eq!(eval_expression("reversed(\"abc\")", &ctx).unwrap(), json!("cba"));
assert_eq!(
eval_expression("reversed(\"abc\")", &ctx).unwrap(),
json!("cba")
);
}
#[test]
@@ -464,8 +545,7 @@ mod tests {
#[test]
fn test_complex_expression() {
let ctx = TestContext::new()
.with_var("items", json!([1, 2, 3, 4, 5]));
let ctx = TestContext::new().with_var("items", json!([1, 2, 3, 4, 5]));
assert_eq!(
eval_expression("length(items) > 3 and 5 in items", &ctx).unwrap(),
json!(true)
@@ -474,8 +554,10 @@ mod tests {
#[test]
fn test_chained_access() {
let ctx = TestContext::new()
.with_var("data", json!({"users": [{"name": "Alice"}, {"name": "Bob"}]}));
let ctx = TestContext::new().with_var(
"data",
json!({"users": [{"name": "Alice"}, {"name": "Bob"}]}),
);
assert_eq!(
eval_expression("data.users[1].name", &ctx).unwrap(),
json!("Bob")
@@ -484,8 +566,7 @@ mod tests {
#[test]
fn test_ternary_via_boolean() {
let ctx = TestContext::new()
.with_var("x", json!(10));
let ctx = TestContext::new().with_var("x", json!(10));
// No ternary operator, but boolean expressions work for conditions
assert_eq!(
eval_expression("x > 5 and x < 20", &ctx).unwrap(),

View File

@@ -368,8 +368,8 @@ impl<'a> Parser<'a> {
#[cfg(test)]
mod tests {
use super::*;
use super::super::tokenizer::Tokenizer;
use super::*;
fn parse(input: &str) -> Expr {
let tokens = Tokenizer::new(input).tokenize().unwrap();

View File

@@ -320,14 +320,14 @@ impl Tokenizer {
}
if is_float {
let val: f64 = num_str.parse().map_err(|_| {
TokenError::InvalidNumber(start, num_str.clone())
})?;
let val: f64 = num_str
.parse()
.map_err(|_| TokenError::InvalidNumber(start, num_str.clone()))?;
Ok(Token::new(TokenKind::Float(val), start, self.pos))
} else {
let val: i64 = num_str.parse().map_err(|_| {
TokenError::InvalidNumber(start, num_str.clone())
})?;
let val: i64 = num_str
.parse()
.map_err(|_| TokenError::InvalidNumber(start, num_str.clone()))?;
Ok(Token::new(TokenKind::Integer(val), start, self.pos))
}
}
@@ -365,11 +365,7 @@ mod tests {
fn tokenize(input: &str) -> Vec<TokenKind> {
let mut t = Tokenizer::new(input);
t.tokenize()
.unwrap()
.into_iter()
.map(|t| t.kind)
.collect()
t.tokenize().unwrap().into_iter().map(|t| t.kind).collect()
}
#[test]

View File

@@ -307,9 +307,7 @@ impl WorkflowLoader {
// Strip `.workflow` suffix if present:
// "deploy.workflow.yaml" -> stem "deploy.workflow" -> name "deploy"
// "deploy.yaml" -> stem "deploy" -> name "deploy"
let name = raw_stem
.strip_suffix(".workflow")
.unwrap_or(raw_stem);
let name = raw_stem.strip_suffix(".workflow").unwrap_or(raw_stem);
let ref_name = format!("{}.{}", pack_name, name);
workflow_files.push(WorkflowFile {

View File

@@ -1501,7 +1501,10 @@ tasks:
let failure_transition = &task.next[1];
assert_eq!(failure_transition.publish.len(), 1);
if let PublishDirective::Simple(map) = &failure_transition.publish[0] {
assert_eq!(map.get("validation_passed"), Some(&serde_json::Value::Bool(false)));
assert_eq!(
map.get("validation_passed"),
Some(&serde_json::Value::Bool(false))
);
} else {
panic!("Expected Simple publish directive");
}

View File

@@ -1172,7 +1172,9 @@ async fn test_find_rules_by_trigger() {
.unwrap();
assert_eq!(trigger1_rules.len(), 2);
assert!(trigger1_rules.iter().all(|r| r.trigger == Some(trigger1.id)));
assert!(trigger1_rules
.iter()
.all(|r| r.trigger == Some(trigger1.id)));
let trigger2_rules = RuleRepository::find_by_trigger(&pool, trigger2.id)
.await

View File

@@ -691,7 +691,10 @@ tasks:
assert_eq!(transitions.len(), 1);
assert_eq!(transitions[0].publish.len(), 1);
assert_eq!(transitions[0].publish[0].name, "msg");
assert_eq!(transitions[0].publish[0].value, JsonValue::String("task1 done".to_string()));
assert_eq!(
transitions[0].publish[0].value,
JsonValue::String("task1 done".to_string())
);
}
#[test]

View File

@@ -21,7 +21,12 @@ fn make_python_process_runtime(packs_base_dir: PathBuf) -> ProcessRuntime {
dependencies: None,
env_vars: std::collections::HashMap::new(),
};
ProcessRuntime::new("python".to_string(), config, packs_base_dir.clone(), packs_base_dir.join("../runtime_envs"))
ProcessRuntime::new(
"python".to_string(),
config,
packs_base_dir.clone(),
packs_base_dir.join("../runtime_envs"),
)
}
fn make_python_context(
@@ -269,7 +274,12 @@ async fn test_shell_process_runtime_truncation() {
dependencies: None,
env_vars: std::collections::HashMap::new(),
};
let runtime = ProcessRuntime::new("shell".to_string(), config, tmp.path().to_path_buf(), tmp.path().join("runtime_envs"));
let runtime = ProcessRuntime::new(
"shell".to_string(),
config,
tmp.path().to_path_buf(),
tmp.path().join("runtime_envs"),
);
let context = ExecutionContext {
execution_id: 8,

View File

@@ -22,8 +22,16 @@ fn make_python_process_runtime(packs_base_dir: PathBuf) -> ProcessRuntime {
dependencies: None,
env_vars: std::collections::HashMap::new(),
};
let runtime_envs_dir = packs_base_dir.parent().unwrap_or(&packs_base_dir).join("runtime_envs");
ProcessRuntime::new("python".to_string(), config, packs_base_dir, runtime_envs_dir)
let runtime_envs_dir = packs_base_dir
.parent()
.unwrap_or(&packs_base_dir)
.join("runtime_envs");
ProcessRuntime::new(
"python".to_string(),
config,
packs_base_dir,
runtime_envs_dir,
)
}
#[tokio::test]
@@ -436,7 +444,12 @@ echo "PASS: No secrets in environment"
dependencies: None,
env_vars: std::collections::HashMap::new(),
};
let runtime = ProcessRuntime::new("shell".to_string(), config, tmp.path().to_path_buf(), tmp.path().join("runtime_envs"));
let runtime = ProcessRuntime::new(
"shell".to_string(),
config,
tmp.path().to_path_buf(),
tmp.path().join("runtime_envs"),
);
let context = ExecutionContext {
execution_id: 7,
@@ -508,7 +521,12 @@ print(json.dumps({"leaked": leaked}))
dependencies: None,
env_vars: std::collections::HashMap::new(),
};
let runtime = ProcessRuntime::new("python".to_string(), config, tmp.path().to_path_buf(), tmp.path().join("runtime_envs"));
let runtime = ProcessRuntime::new(
"python".to_string(),
config,
tmp.path().to_path_buf(),
tmp.path().join("runtime_envs"),
);
let context = ExecutionContext {
execution_id: 8,

4733
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff