feat: implementing parse_many

This commit is contained in:
kevin zhao
2025-11-13 16:58:32 -05:00
parent 8cbb5378f3
commit 43db77a97b
4 changed files with 119 additions and 24 deletions

View File

@@ -1,5 +1,4 @@
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context;
@@ -13,8 +12,8 @@ use codex_execpolicy2::PolicyParser;
enum Cli {
/// Evaluate a command against a policy.
Check {
#[arg(short, long, value_name = "PATH")]
policy: PathBuf,
#[arg(short, long, value_name = "PATH", required = true)]
policies: Vec<PathBuf>,
/// Command tokens to check.
#[arg(
@@ -30,12 +29,12 @@ enum Cli {
fn main() -> Result<()> {
let cli = Cli::parse();
match cli {
Cli::Check { policy, command } => cmd_check(policy, command),
Cli::Check { policies, command } => cmd_check(policies, command),
}
}
fn cmd_check(policy_path: PathBuf, args: Vec<String>) -> Result<()> {
let policy = load_policy(&policy_path)?;
fn cmd_check(policies: Vec<PathBuf>, args: Vec<String>) -> Result<()> {
let policy = load_policies(&policies)?;
let eval = policy.check(&args);
let json = serde_json::to_string_pretty(&eval)?;
@@ -43,12 +42,20 @@ fn cmd_check(policy_path: PathBuf, args: Vec<String>) -> Result<()> {
Ok(())
}
fn load_policy(policy_path: &Path) -> Result<codex_execpolicy2::Policy> {
let policy_file_contents = fs::read_to_string(policy_path)
.with_context(|| format!("failed to read policy at {}", policy_path.display()))?;
let policy_identifier = policy_path.to_string_lossy();
Ok(PolicyParser::parse(
policy_identifier.as_ref(),
&policy_file_contents,
)?)
fn load_policies(policy_paths: &[PathBuf]) -> Result<codex_execpolicy2::Policy> {
let loaded_policies: Vec<(String, String)> = policy_paths
.iter()
.map(|policy_path| {
let policy_file_contents = fs::read_to_string(policy_path)
.with_context(|| format!("failed to read policy at {}", policy_path.display()))?;
let policy_identifier = policy_path.to_string_lossy().to_string();
Ok((policy_identifier, policy_file_contents))
})
.collect::<Result<_>>()
.context("failed to load policy files")?;
Ok(PolicyParser::parse_many(loaded_policies.iter().map(
|(policy_identifier, policy_file_contents)| {
(policy_identifier.as_str(), policy_file_contents.as_str())
},
))?)
}