use crate::{
annotations,
cmd_plan::resolve_all,
context::{CmdError, resolve, root},
lines::{Address, address, merge_lines},
verdict::{Outcome, unmet},
};
use griz_core::{FindQuery, content_hash, find};
use incurs::command::{CommandDef, TypedContext, TypedResult};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;
#[derive(Deserialize, incurs::Args)]
struct PathArgs {
path: String,
}
#[derive(Deserialize, incurs::Options)]
struct ReadOptions {
grep: Option<String>,
#[incurs(default = 0)]
context: usize,
lines: Option<String>,
root: Option<String>,
}
pub fn read_command() -> CommandDef {
CommandDef::typed::<PathArgs, ReadOptions, (), Value, _, _>(
"read",
|ctx: TypedContext<PathArgs, ReadOptions, ()>| async move {
read(&ctx.args.path, ctx.options).unwrap_or_else(CmdError::result)
},
)
.description("Read a file as numbered lines with its fingerprint. Pass the fingerprint as expect_hash to make an edit refuse a changed file.")
.mcp(annotations::read_only())
.done()
}
fn read(path: &str, options: ReadOptions) -> Result<TypedResult<Value>, CmdError> {
let path = resolve(&root(options.root.as_deref())?, Path::new(path))?;
let text = std::fs::read_to_string(&path).map_err(|e| CmdError {
code: "NOT_FOUND",
message: format!("{}: {e}", path.display()),
})?;
let selected = address(
&text,
&Address {
grep: options.grep,
context: options.context,
lines: options.lines,
},
)
.map_err(CmdError::invalid)?;
let mut body = json!({ "path": path, "hash": content_hash(&text) });
merge_lines(&mut body, selected);
Ok(TypedResult::ok(body))
}
#[derive(Deserialize, incurs::Options)]
struct FindOptions {
paths: Option<Vec<String>>,
glob: Option<Vec<String>>,
literal: Option<String>,
regex: Option<String>,
pattern: Option<String>,
language: Option<String>,
#[incurs(default = 0)]
offset: usize,
#[incurs(default = 200)]
limit: usize,
expect_matches: Option<usize>,
root: Option<String>,
within: Option<Vec<String>>,
}
pub fn find_command() -> CommandDef {
CommandDef::typed::<(), FindOptions, (), Value, _, _>(
"find",
|ctx: TypedContext<(), FindOptions, ()>| async move {
run_find(ctx.options).unwrap_or_else(CmdError::result)
},
)
.description("Find literal or regex matches across files. Each match carries its byte range and file fingerprint, so a program can edit exactly what it found.")
.mcp(annotations::read_only())
.done()
}
fn run_find(options: FindOptions) -> Result<TypedResult<Value>, CmdError> {
let root = root(options.root.as_deref())?;
let mut paths = resolve_all(&root, options.paths)?;
if paths.is_empty() {
paths.push(root);
}
let query = FindQuery {
paths,
globs: options.glob.unwrap_or_default(),
literal: options.literal,
regex: options.regex,
pattern: options.pattern,
language: options.language,
offset: options.offset,
limit: options.limit,
within: options.within.unwrap_or_default(),
};
let page = find(&query).map_err(CmdError::invalid)?;
let mut body = serde_json::to_value(&page).map_err(|e| CmdError::invalid(e.to_string()))?;
let Some(expected) = options.expect_matches else {
return Ok(TypedResult::ok(body));
};
let miss = unmet("matches", Some(expected), page.total);
let outcome = if miss.is_some() {
Outcome::Failed
} else {
Outcome::Passed
};
body["outcome"] = json!(outcome);
if let Some(reason) = miss {
body["reason"] = json!(reason);
return Ok(TypedResult::ok_with_exit_code(body, 1));
}
Ok(TypedResult::ok(body))
}