use crate::{
annotations,
cmd_plan::resolve_all,
context::{CmdError, resolve, root, with_blocking},
find_response::{self, FindResponse},
lines::{Address, address, merge_lines},
};
use griz_core::{FindQuery, content_hash};
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 {
with_blocking(move || read(&ctx.args.path, ctx.options))
.await
.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.")
.examples(crate::usage::example("\"src one.rs\" --root /path/to/repo --format json", "Read a path containing spaces."))
.hint("CLI: the file path is positional. Read-only commands do not take --purpose or --verbosity.")
.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 = false)]
files_only: bool,
#[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 {
let mut command = CommandDef::typed::<(), FindOptions, (), FindResponse, _, _>(
"find",
|ctx: TypedContext<(), FindOptions, ()>| async move {
with_blocking(move || run_find(ctx.options))
.await
.unwrap_or_else(CmdError::result)
},
)
.description("Find literal, regex, or structural matches with byte ranges and file fingerprints. Use files-only for per-file counts and fingerprints instead of individual matches.")
.examples(crate::usage::example("--root /path/to/repo --paths \"src one.rs\" --paths \"src two.rs\" --literal oldName --expect-matches 2 --format json", "Find an expected number of matches."))
.hint(crate::usage::PATHS)
.mcp(annotations::read_only())
.done();
command.output_schema = serde_json::to_value(schemars::schema_for!(Value)).ok();
command
}
fn validate_search_paths(root: &Path, paths: &[String]) -> Result<(), CmdError> {
for path in paths {
if path.contains(['*', '?', '[', '{']) && matches!(root.join(path).try_exists(), Ok(false))
{
return Err(CmdError::invalid(format!(
"search path does not exist: {}. --paths takes literal files or directories; use --glob for filename patterns (MCP: glob).",
root.join(path).display()
)));
}
}
Ok(())
}
fn run_find(options: FindOptions) -> Result<TypedResult<FindResponse>, CmdError> {
let root = root(options.root.as_deref())?;
validate_search_paths(&root, options.paths.as_deref().unwrap_or_default())?;
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 (body, total) = find_response::search(&query, options.files_only)?;
let Some(expected) = options.expect_matches else {
return Ok(TypedResult::ok(body));
};
let (body, failed) = find_response::with_expectation(body, expected, total);
if failed {
return Ok(TypedResult::ok_with_exit_code(body, 1));
}
Ok(TypedResult::ok(body))
}