forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli2 hours ago363 commits

search.rs397 lines, 12.3 KiBHistoryRawDownload
1use std::path::Path;
2use std::process::Stdio;
3use std::time::Duration;
4
5use tokio::io::{AsyncBufRead, AsyncBufReadExt, BufReader};
6
7use crate::command::GitEnv;
8use crate::error::{Error, Result};
9use crate::history::{git, read_pipe_head, validate_oid};
10
11pub const MAX_QUERY_BYTES: usize = 200;
12const MAX_GLOB_BYTES: usize = 512;
13const MAX_LINE_CHARS: usize = 500;
14const MAX_RECORD_BYTES: usize = 4 * MAX_LINE_CHARS + 4096;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct GrepOptions {
18 pub fixed: bool,
19 pub ignore_case: bool,
20 pub path_glob: Option<String>,
21 pub max_matches: usize,
22 pub timeout: Duration,
23}
24
25impl Default for GrepOptions {
26 fn default() -> Self {
27 Self {
28 fixed: true,
29 ignore_case: false,
30 path_glob: None,
31 max_matches: 200,
32 timeout: Duration::from_secs(10),
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct GrepHit {
39 pub path: String,
40 pub line_no: u32,
41 pub line: String,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct GrepResult {
46 pub hits: Vec<GrepHit>,
47 pub truncated: bool,
48}
49
50fn validate_query(query: &str) -> Result<()> {
51 if query.is_empty() || query.len() > MAX_QUERY_BYTES {
52 return Err(Error::InvalidInput(format!(
53 "query must be 1 to {MAX_QUERY_BYTES} bytes"
54 )));
55 }
56 if query.contains(['\0', '\n', '\r']) {
57 return Err(Error::InvalidInput(
58 "query contains NUL or a newline".into(),
59 ));
60 }
61 Ok(())
62}
63
64fn validate_glob(glob: &str) -> Result<()> {
65 if glob.is_empty() || glob.len() > MAX_GLOB_BYTES {
66 return Err(Error::InvalidInput(format!(
67 "path glob must be 1 to {MAX_GLOB_BYTES} bytes"
68 )));
69 }
70 if glob.starts_with('-') || glob.contains("..") {
71 return Err(Error::InvalidInput(format!("unsafe path glob: {glob:?}")));
72 }
73 if glob.contains(['\0', '\n', '\r']) {
74 return Err(Error::InvalidInput(
75 "path glob contains NUL or a newline".into(),
76 ));
77 }
78 Ok(())
79}
80
81fn parse_record(record: &[u8], commit: &str) -> Option<GrepHit> {
82 let mut parts = record.splitn(3, |&b| b == 0);
83 let header = parts.next()?;
84 let line_bytes = parts.next()?;
85 let text = parts.next().unwrap_or_default();
86
87 let prefix = format!("{commit}:");
88 let path = header.strip_prefix(prefix.as_bytes())?;
89 let line_no = std::str::from_utf8(line_bytes).ok()?.parse::<u32>().ok()?;
90 let text = String::from_utf8_lossy(text);
91 let text = text.strip_suffix('\r').unwrap_or(&text);
92 Some(GrepHit {
93 path: String::from_utf8_lossy(path).into_owned(),
94 line_no,
95 line: text.chars().take(MAX_LINE_CHARS).collect(),
96 })
97}
98
99async fn read_line_capped<R: AsyncBufRead + Unpin>(
100 reader: &mut R,
101 buf: &mut Vec<u8>,
102 keep: usize,
103) -> std::io::Result<bool> {
104 buf.clear();
105 let mut started = false;
106 loop {
107 let available = reader.fill_buf().await?;
108 if available.is_empty() {
109 return Ok(started);
110 }
111 started = true;
112 let newline = available.iter().position(|&b| b == b'\n');
113 let content = newline.unwrap_or(available.len());
114 let take = content.min(keep - buf.len());
115 buf.extend_from_slice(&available[..take]);
116 let consumed = newline.map_or(available.len(), |i| i + 1);
117 reader.consume(consumed);
118 if newline.is_some() {
119 return Ok(true);
120 }
121 }
122}
123
124pub async fn grep(
125 env: &GitEnv,
126 repo: &Path,
127 commit: &str,
128 query: &str,
129 opts: GrepOptions,
130) -> Result<GrepResult> {
131 validate_oid(commit)?;
132 validate_query(query)?;
133 if let Some(glob) = &opts.path_glob {
134 validate_glob(glob)?;
135 }
136 let globs: Vec<&str> = opts.path_glob.as_deref().into_iter().collect();
137
138 let mut cmd = git(env, "grep")
139 .git_dir(repo)
140 .arg("-n")
141 .arg("-I")
142 .arg("--no-color")
143 .arg("--null")
144 .arg("--max-count=20")
145 .arg(if opts.fixed { "-F" } else { "-E" });
146 if opts.ignore_case {
147 cmd = cmd.arg("-i");
148 }
149 let cmd = cmd.user_pattern(query)?.user_arg(commit)?.paths(&globs);
150
151 let mut command = cmd.into_tokio();
152 command.stdout(Stdio::piped()).stderr(Stdio::piped());
153 let mut child = command.spawn()?;
154 let stdout = child
155 .stdout
156 .take()
157 .ok_or_else(|| Error::Failed("git stdout missing".into()))?;
158 let stderr_task = child.stderr.take().map(|e| tokio::spawn(read_pipe_head(e)));
159
160 let max = opts.max_matches;
161 let mut hits = Vec::new();
162 let mut truncated = false;
163 let reading = async {
164 let mut lines = BufReader::new(stdout);
165 let mut buf = Vec::new();
166 while read_line_capped(&mut lines, &mut buf, MAX_RECORD_BYTES).await? {
167 let Some(hit) = parse_record(&buf, commit) else {
168 continue;
169 };
170 if hits.len() == max {
171 truncated = true;
172 break;
173 }
174 hits.push(hit);
175 }
176 Ok::<(), Error>(())
177 };
178
179 match tokio::time::timeout(opts.timeout, reading).await {
180 Ok(read) => read?,
181 Err(_) => {
182 let _ = child.start_kill();
183 let _ = child.wait().await;
184 return Err(Error::Failed(format!(
185 "code search timed out after {} seconds",
186 opts.timeout.as_secs()
187 )));
188 }
189 }
190
191 if truncated {
192 let _ = child.start_kill();
193 }
194 let status = child.wait().await?;
195 let stderr = match stderr_task {
196 Some(task) => task.await.unwrap_or_default(),
197 None => Vec::new(),
198 };
199 if !truncated && !status.success() && status.code() != Some(1) {
200 return Err(Error::Failed(format!(
201 "git grep exited with {status}: {}",
202 String::from_utf8_lossy(&stderr).trim()
203 )));
204 }
205 Ok(GrepResult { hits, truncated })
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use std::process::Command;
212
213 fn env(dir: &Path) -> GitEnv {
214 GitEnv {
215 git_bin: "git".into(),
216 data_dir: dir.to_path_buf(),
217 }
218 }
219
220 fn git_in(dir: &Path, args: &[&str]) {
221 let status = Command::new("git")
222 .current_dir(dir)
223 .env("GIT_CONFIG_NOSYSTEM", "1")
224 .args([
225 "-c",
226 "user.name=Test",
227 "-c",
228 "user.email=test@example.com",
229 "-c",
230 "commit.gpgsign=false",
231 ])
232 .args(args)
233 .status()
234 .expect("git runs");
235 assert!(status.success(), "git {args:?} failed");
236 }
237
238 fn fixture(dir: &Path) -> (std::path::PathBuf, String) {
239 let work = dir.join("work");
240 std::fs::create_dir_all(work.join("src")).unwrap();
241 std::fs::create_dir_all(work.join("docs")).unwrap();
242 std::fs::write(
243 work.join("src/main.rs"),
244 "fn main() {\n println!(\"Hello\");\n}\nlet a.b = 1;\n",
245 )
246 .unwrap();
247 std::fs::write(work.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
248 std::fs::write(work.join("docs/Guide.md"), "say hello there\n").unwrap();
249 git_in(&work, &["init", "-q", "-b", "main"]);
250 git_in(&work, &["add", "-A"]);
251 git_in(&work, &["commit", "-q", "-m", "init"]);
252 let out = Command::new("git")
253 .current_dir(&work)
254 .args(["rev-parse", "HEAD"])
255 .output()
256 .expect("rev-parse");
257 let oid = String::from_utf8(out.stdout).unwrap().trim().to_owned();
258 (work.join(".git"), oid)
259 }
260
261 #[tokio::test]
262 async fn grep_modes_and_limits_on_one_fixture() {
263 let dir = tempfile::tempdir().unwrap();
264 let (repo, oid) = fixture(dir.path());
265 let env = env(dir.path());
266
267 let res = grep(&env, &repo, &oid, "a.b", GrepOptions::default())
268 .await
269 .unwrap();
270 assert_eq!(res.hits.len(), 1, "fixed");
271 assert_eq!(res.hits[0].path, "src/main.rs", "fixed");
272 assert_eq!(res.hits[0].line_no, 4, "fixed");
273 assert_eq!(res.hits[0].line, "let a.b = 1;", "fixed");
274 assert!(!res.truncated, "fixed");
275
276 let sensitive = grep(&env, &repo, &oid, "hello", GrepOptions::default())
277 .await
278 .unwrap();
279 assert_eq!(
280 sensitive.hits.len(),
281 2,
282 "lib.rs and Guide.md, case-sensitive"
283 );
284 let opts = GrepOptions {
285 ignore_case: true,
286 ..GrepOptions::default()
287 };
288 let insensitive = grep(&env, &repo, &oid, "HELLO", opts).await.unwrap();
289 assert_eq!(insensitive.hits.len(), 3, "ignore case");
290
291 let regex = GrepOptions {
292 fixed: false,
293 ..GrepOptions::default()
294 };
295 let res = grep(&env, &repo, &oid, "^pub fn \\w+", regex)
296 .await
297 .unwrap();
298 assert_eq!(res.hits.len(), 1, "regex");
299 assert_eq!(res.hits[0].path, "src/lib.rs", "regex");
300
301 let opts = GrepOptions {
302 path_glob: Some("*.md".into()),
303 ..GrepOptions::default()
304 };
305 let res = grep(&env, &repo, &oid, "hello", opts).await.unwrap();
306 assert_eq!(res.hits.len(), 1, "path glob");
307 assert_eq!(res.hits[0].path, "docs/Guide.md", "path glob");
308
309 let opts = GrepOptions {
310 ignore_case: true,
311 max_matches: 2,
312 ..GrepOptions::default()
313 };
314 let res = grep(&env, &repo, &oid, "hello", opts).await.unwrap();
315 assert_eq!(res.hits.len(), 2, "max matches");
316 assert!(res.truncated, "max matches");
317
318 let res = grep(&env, &repo, &oid, "zzz-not-here", GrepOptions::default())
319 .await
320 .unwrap();
321 assert!(res.hits.is_empty(), "no match");
322 assert!(!res.truncated, "no match");
323 }
324
325 #[tokio::test]
326 async fn query_starting_with_dash_is_a_pattern() {
327 let dir = tempfile::tempdir().unwrap();
328 let (repo, oid) = fixture(dir.path());
329 std::fs::write(dir.path().join("work/flags.txt"), "--verbose\n").unwrap();
330 git_in(&dir.path().join("work"), &["add", "-A"]);
331 git_in(&dir.path().join("work"), &["commit", "-q", "-m", "flags"]);
332 let out = Command::new("git")
333 .current_dir(dir.path().join("work"))
334 .args(["rev-parse", "HEAD"])
335 .output()
336 .unwrap();
337 let oid2 = String::from_utf8(out.stdout).unwrap().trim().to_owned();
338 assert_ne!(oid, oid2);
339 let res = grep(
340 &env(dir.path()),
341 &repo,
342 &oid2,
343 "--verbose",
344 GrepOptions::default(),
345 )
346 .await
347 .unwrap();
348 assert_eq!(res.hits.len(), 1);
349 assert_eq!(res.hits[0].path, "flags.txt");
350 }
351
352 #[tokio::test]
353 async fn bad_inputs_are_rejected() {
354 let dir = tempfile::tempdir().unwrap();
355 let (repo, oid) = fixture(dir.path());
356 let env = env(dir.path());
357 let opts = || GrepOptions::default();
358 let long = "x".repeat(MAX_QUERY_BYTES + 1);
359 for query in ["", long.as_str(), "a\nb", "a\0b", "a\rb"] {
360 assert!(
361 grep(&env, &repo, &oid, query, opts()).await.is_err(),
362 "query {query:?} should be rejected"
363 );
364 }
365 for glob in ["-x", "../etc", "src/../x", ""] {
366 let o = GrepOptions {
367 path_glob: Some(glob.into()),
368 ..GrepOptions::default()
369 };
370 assert!(
371 grep(&env, &repo, &oid, "hello", o).await.is_err(),
372 "glob {glob:?} should be rejected"
373 );
374 }
375 assert!(
376 grep(&env, &repo, "not-an-oid", "hello", opts())
377 .await
378 .is_err()
379 );
380 let bad_regex = GrepOptions {
381 fixed: false,
382 ..GrepOptions::default()
383 };
384 assert!(grep(&env, &repo, &oid, "(", bad_regex).await.is_err());
385 }
386
387 #[test]
388 fn parse_record_truncates_and_strips_cr() {
389 let long = "y".repeat(600);
390 let record = format!("{}:a/b.rs\x007\x00{long}\r", "c".repeat(40));
391 let hit = parse_record(record.as_bytes(), &"c".repeat(40)).unwrap();
392 assert_eq!(hit.path, "a/b.rs");
393 assert_eq!(hit.line_no, 7);
394 assert_eq!(hit.line.chars().count(), MAX_LINE_CHARS);
395 assert!(parse_record(b"other:x\x001\x00t", &"c".repeat(40)).is_none());
396 }
397}