Files
zesdex/src/tool/fs/helpers.rs
T
asepharyana 29a9fae3f6 ci: add GitHub Actions workflows with semantic-release auto-versioning
chore: fix all 702 clippy warnings across codebase
- auto-fix 475 via cargo clippy --fix
- fix remaining 227 manually: uninlined_format_args, redundant_closure, match_same_arms,
  underscore_binding, format_push_string, items_after_statements, needless_pass_by_value,
  clone_on_copy, case_sensitive_extension, single_match/let-else, write_with_newline,
  and other clippy lints
2026-07-13 08:12:12 +07:00

77 lines
2.4 KiB
Rust

//! Shared helpers for filesystem tools: extracting string arguments from JSON
//! and producing user-friendly "not found" diagnostics.
use std::path::Path;
use serde_json::Value;
use anyhow::{Result, anyhow};
/// Extract a required string argument from a JSON args map.
///
/// Return: the value as `String` if present and a string type; `Err` if missing
/// or of a different JSON type (null, number, boolean, array, object).
pub fn arg_str(args: &Value, name: &str) -> Result<String> {
args.get(name)
.and_then(|v| v.as_str())
.map(std::string::ToString::to_string)
.ok_or_else(|| anyhow!("missing required argument: {name}"))
}
/// Produce a user-friendly diagnostic string when a path doesn't resolve or exist.
///
/// Checks whether the resolved path canonically falls inside any workspace root
/// and reports either "path outside workspaces" or "path does not exist" accordingly.
///
/// Return: a one-line description of the resolution failure.
pub fn not_found_help(ctx: &super::super::ToolCtx, path: &Path, rel: &str) -> String {
let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let in_ws = ctx.workspaces.iter().any(|w| {
let wc = w.canonicalize().unwrap_or_else(|_| w.clone());
canon.starts_with(&wc)
});
if in_ws {
format!("path '{}' does not exist (resolved to {})", rel, canon.display())
} else {
format!(
"path '{}' is outside all workspace roots. Workspace roots: {}",
rel,
ctx.workspaces.iter().map(|w| w.display().to_string()).collect::<Vec<_>>().join(", ")
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_arg_str_found() {
let args = json!({"key": "value"});
assert_eq!(arg_str(&args, "key").unwrap(), "value");
}
#[test]
fn test_arg_str_missing() {
let args = json!({"other": "value"});
assert!(arg_str(&args, "key").is_err());
}
#[test]
fn test_arg_str_empty_string() {
let args = json!({"key": ""});
assert_eq!(arg_str(&args, "key").unwrap(), "");
}
#[test]
fn test_arg_str_wrong_type() {
let args = json!({"key": 42});
assert!(arg_str(&args, "key").is_err());
}
#[test]
fn test_arg_str_null() {
let args = json!({"key": null});
assert!(arg_str(&args, "key").is_err());
}
}