1use std::collections::HashSet;
3use std::path::Path;
4use std::path::PathBuf;
5use std::time::{Duration, Instant};
6
7use glob::Pattern;
8use ignore::WalkBuilder;
9use regex::RegexBuilder;
10
11use crate::tools::CrpMode;
12use lean_ctx::core::protocol;
13use lean_ctx::core::tokens::count_tokens;
14use lean_ctx_ext::core::symbol_map::{self, SymbolMap};
15
16pub(crate) use lean_ctx::core::search_walk::{
17 MAX_FILE_SIZE, MAX_WALK_DEPTH, is_binary_ext, is_generated_file,
18};
19const MAX_EXPLICIT_FILE_SIZE: u64 = 64 * 1024 * 1024;
24const MAX_NAMED_SKIPS: usize = 3;
26const MAX_MATCH_LINE_WIDTH: usize = 150;
27
28pub const NATIVE_GREP_BASELINE_FACTOR: f64 = 2.5;
35
36pub struct SearchOutcome {
38 pub text: String,
40 pub modeled_baseline: usize,
43 pub observed_tokens: usize,
46 pub failed: bool,
51 pub secret_paths_withheld: usize,
54}
55
56impl SearchOutcome {
57 fn error(text: String) -> Self {
59 Self {
60 text,
61 modeled_baseline: 0,
62 observed_tokens: 0,
63 failed: true,
64 secret_paths_withheld: 0,
65 }
66 }
67
68 fn without_matches(text: String) -> Self {
70 Self {
71 text,
72 modeled_baseline: 0,
73 observed_tokens: 0,
74 failed: false,
75 secret_paths_withheld: 0,
76 }
77 }
78
79 fn from_observed(text: String, observed_tokens: usize) -> Self {
80 let modeled = (observed_tokens as f64 * NATIVE_GREP_BASELINE_FACTOR).ceil() as usize;
81 Self {
82 text,
83 modeled_baseline: modeled.max(observed_tokens),
84 observed_tokens,
85 failed: false,
86 secret_paths_withheld: 0,
87 }
88 }
89
90 fn withholding(mut self, secret_paths: usize) -> Self {
91 self.secret_paths_withheld = secret_paths;
92 self
93 }
94}
95
96fn search_deadline() -> Option<Duration> {
103 const DEFAULT_MS: u64 = 10_000;
104 let ms = std::env::var("LEAN_CTX_SEARCH_DEADLINE_MS")
105 .ok()
106 .and_then(|v| v.trim().parse::<u64>().ok())
107 .unwrap_or(DEFAULT_MS);
108 (ms > 0).then(|| Duration::from_millis(ms))
109}
110
111#[allow(clippy::too_many_arguments)]
115pub fn handle(
116 pattern: &str,
117 dir: &str,
118 include: Option<&str>,
119 max_results: usize,
120 crp_mode: CrpMode,
121 respect_gitignore: bool,
122 allow_secret_paths: bool,
123 anchored: bool,
124) -> SearchOutcome {
125 handle_filtered(
126 pattern,
127 dir,
128 include,
129 max_results,
130 crp_mode,
131 respect_gitignore,
132 allow_secret_paths,
133 anchored,
134 None,
135 None,
136 )
137}
138
139#[allow(clippy::too_many_arguments)]
154pub fn handle_filtered(
155 pattern: &str,
156 dir: &str,
157 include: Option<&str>,
158 max_results: usize,
159 crp_mode: CrpMode,
160 respect_gitignore: bool,
161 allow_secret_paths: bool,
162 anchored: bool,
163 exclude: Option<&str>,
164 exclude_pattern: Option<&str>,
165) -> SearchOutcome {
166 let literal = matches!(regex::Regex::new(pattern), Err(regex::Error::Syntax(_)))
167 .then(|| regex::escape(pattern));
168 let mut outcome = search_compiled_pattern(
169 literal.as_deref().unwrap_or(pattern),
170 dir,
171 include,
172 max_results,
173 crp_mode,
174 respect_gitignore,
175 allow_secret_paths,
176 anchored,
177 exclude,
178 exclude_pattern,
179 );
180 if literal.is_some() && !outcome.text.starts_with("ERROR:") {
181 outcome.text = format!(
182 "note: '{pattern}' is not valid regex — searched for it literally.\n{}",
183 outcome.text
184 );
185 }
186 outcome
187}
188
189#[allow(clippy::too_many_arguments)]
190fn search_compiled_pattern(
191 pattern: &str,
192 dir: &str,
193 include: Option<&str>,
194 max_results: usize,
195 _crp_mode: CrpMode,
196 respect_gitignore: bool,
197 allow_secret_paths: bool,
198 anchored: bool,
199 exclude: Option<&str>,
200 exclude_pattern: Option<&str>,
201) -> SearchOutcome {
202 let include_patterns = compile_include(include);
209 let exclude_patterns = compile_include(exclude);
212 const MAX_PATTERN_LEN: usize = 1024;
213 const MAX_REGEX_SIZE: usize = 1 << 20; let redact = lean_ctx::core::redaction::redaction_enabled_for_active_role();
216 let protected = lean_ctx::core::policy::runtime::active().is_some();
217 let protected_root = lean_ctx::core::policy::diagnostics::project();
218 let admission = lean_ctx::core::context_admission::stores::StoreAdmission::current();
221 let mut protected_budget = lean_ctx::core::limits::max_read_bytes()
222 .min(lean_ctx::core::policy::content::MAX_PROTECTED_CONTENT_BYTES);
223 let mut matched_sources: Vec<std::path::PathBuf> = Vec::new();
225 if pattern.len() > MAX_PATTERN_LEN {
226 return SearchOutcome::error(format!(
227 "ERROR: pattern too long ({} > {MAX_PATTERN_LEN} chars)",
228 pattern.len()
229 ));
230 }
231 let re = match RegexBuilder::new(pattern)
232 .size_limit(MAX_REGEX_SIZE)
233 .dfa_size_limit(MAX_REGEX_SIZE)
234 .build()
235 {
236 Ok(r) => r,
237 Err(e) => return SearchOutcome::error(format!("ERROR: invalid regex: {e}")),
238 };
239 let exclude_re = exclude_pattern.and_then(|p| {
243 RegexBuilder::new(p)
244 .size_limit(MAX_REGEX_SIZE)
245 .dfa_size_limit(MAX_REGEX_SIZE)
246 .build()
247 .ok()
248 });
249
250 let root = Path::new(dir);
251 if !root.exists() {
252 let hint = lean_ctx::core::path_suggest::hint(root);
253 return SearchOutcome::error(format!("ERROR: {dir} does not exist{hint}"));
254 }
255 if let Some(err) = crate::tools::walk_guard::deny_unsafe_walk_root(dir) {
258 return SearchOutcome::error(err);
259 }
260 let size_limit = if std::fs::metadata(root).is_ok_and(|m| m.is_file()) {
261 MAX_EXPLICIT_FILE_SIZE
262 } else {
263 MAX_FILE_SIZE
264 };
265
266 let mut files: Vec<PathBuf> = Vec::new();
267 let mut matches = Vec::new();
268 let mut raw_tokens_accum: usize = 0;
269 let mut files_searched = 0u32;
270 let mut files_skipped_size = 0u32;
271 let mut skipped_size_files: Vec<String> = Vec::new();
274 let mut files_skipped_encoding = 0u32;
275 let mut files_withheld = 0u32;
276 let mut skipped_boundary_files: Vec<(String, &'static str)> = Vec::new();
277 let mut files_skipped_special = 0u32;
278 let mut deadline_hit = false;
279 let mut cap_hit = false;
283 let mut budget_hit = false;
287
288 let mut narrowed_scope: Option<usize> = None;
298 let used_index = if !protected
299 && let Some(idx) =
300 lean_ctx::core::search_index::get_fresh(dir, respect_gitignore, allow_secret_paths)
301 {
302 let candidates = idx.candidate_paths(pattern, &include_patterns, root);
303 if matches!(
304 candidates,
305 lean_ctx::core::search_index::CandidateSet::Narrowed(_)
306 ) {
307 narrowed_scope = Some(idx.scope_count(&include_patterns, &exclude_patterns, root));
308 }
309 files = candidates.into_paths();
310 if !allow_secret_paths {
311 skipped_boundary_files = lean_ctx::core::search_index::boundary_skipped_files(
312 dir,
313 respect_gitignore,
314 &include_patterns,
315 );
316 }
317 true
318 } else {
319 false
320 };
321
322 if !used_index {
323 let walker = WalkBuilder::new(root)
328 .hidden(false)
329 .max_depth(Some(MAX_WALK_DEPTH))
330 .git_ignore(respect_gitignore)
331 .git_global(respect_gitignore)
332 .git_exclude(respect_gitignore)
333 .require_git(false)
334 .filter_entry(move |e| {
335 if respect_gitignore {
336 lean_ctx::core::walk_filter::keep_entry(e)
337 } else {
338 lean_ctx::core::cloud_files::keep_entry(e)
339 }
340 })
341 .build();
342
343 for entry in walker.filter_map(std::result::Result::ok) {
344 if entry.file_type().is_none_or(|ft| ft.is_dir()) {
345 continue;
346 }
347
348 if entry.file_type().is_some_and(|ft| ft.is_symlink()) {
349 continue;
350 }
351
352 let path = entry.path();
353
354 if is_binary_ext(path) || is_generated_file(path) {
355 continue;
356 }
357
358 if !include_patterns.is_empty() {
359 let rel_str = filter_rel(path, root);
360 if !include_patterns.iter().any(|p| p.matches(&rel_str)) {
361 continue;
362 }
363 }
364
365 if let Some(reason) =
366 lean_ctx::core::io_boundary::withheld_secret(path, allow_secret_paths)
367 {
368 skipped_boundary_files.push((filter_rel(path, root).into_owned(), reason));
369 continue;
370 }
371
372 files.push(path.to_path_buf());
376 }
377 skipped_boundary_files.sort_unstable();
378 }
379
380 if !exclude_patterns.is_empty() {
383 files.retain(|path| {
384 let rel_str = filter_rel(path, root);
385 !exclude_patterns.iter().any(|p| p.matches(&rel_str))
386 });
387 }
388
389 match lean_ctx::core::io_boundary::cloud_io_rules(None) {
393 Ok(None) => {}
394 Ok(Some(rules)) => {
395 files.retain(|path| match rules.refusal(path) {
396 None => true,
397 Some(refusal) => {
398 let reason = match refusal {
399 lean_ctx::core::policy::cloud_io::Refusal::OutsideRoots => {
400 "outside the Cloud readable roots"
401 }
402 lean_ctx::core::policy::cloud_io::Refusal::NeverSend(_) => {
403 "Cloud never_send"
404 }
405 };
406 skipped_boundary_files.push((filter_rel(path, root).into_owned(), reason));
407 false
408 }
409 });
410 skipped_boundary_files.sort_unstable();
411 }
412 Err(e) => {
413 return SearchOutcome::error(format!(
414 "ERROR: [I/O BOUNDARY] search refused: {e}; reads stay refused until a valid \
415 Cloud policy is installed."
416 ));
417 }
418 }
419
420 files.sort_unstable_by(|a, b| a.as_os_str().cmp(b.as_os_str()));
422
423 let files_in_scope = narrowed_scope.unwrap_or(files.len());
428 let index_pruned =
429 u32::try_from(files_in_scope.saturating_sub(files.len())).unwrap_or(u32::MAX);
430
431 let root_str = root.to_string_lossy();
432 let deadline = search_deadline().map(|budget| Instant::now() + budget);
433 for path in &files {
434 if matches.len() >= max_results {
435 cap_hit = true;
436 break;
437 }
438
439 if deadline.is_some_and(|dl| Instant::now() >= dl) {
443 deadline_hit = true;
444 break;
445 }
446
447 let file_len: u64;
452 let state = match std::fs::metadata(path) {
453 Ok(meta) if !meta.file_type().is_file() => {
454 files_skipped_special += 1;
455 continue;
456 }
457 Ok(meta) if meta.len() > size_limit => {
458 files_skipped_size += 1;
459 if skipped_size_files.len() < MAX_NAMED_SKIPS {
460 skipped_size_files.push(protocol::shorten_path_relative(
461 &path.to_string_lossy(),
462 &root_str,
463 ));
464 }
465 continue;
466 }
467 Ok(meta) => {
468 file_len = meta.len();
469 lean_ctx::core::content_cache::FileState::from_metadata(&meta)
470 }
471 Err(_) => {
472 files_skipped_encoding += 1;
473 continue;
474 }
475 };
476
477 let content: std::sync::Arc<str> = if protected {
483 if (protected_budget as u64) < file_len {
486 budget_hit = true;
487 break;
488 }
489 let admitted = protected_root.as_ref().and_then(|root| {
494 lean_ctx::core::archive::authority::without_capture(|| {
495 crate::tools::ctx_read::read_file_for_tool_rooted_budgeted(
496 path.to_str()?,
497 root.to_str()?,
498 "ctx_search",
499 &mut protected_budget,
500 )
501 .ok()
502 })
503 });
504 if let Some(text) = admitted {
505 std::sync::Arc::from(text)
506 } else {
507 files_withheld += 1;
510 continue;
511 }
512 } else if let Some(cached) = state.and_then(|s| lean_ctx::core::content_cache::get(path, s))
513 {
514 lean_ctx::core::cache::record_search_content_read(true);
515 cached
516 } else {
517 if state.is_some() {
518 lean_ctx::core::cache::record_search_content_read(false);
519 }
520 let Ok(decoded) = lean_ctx::core::text_decode::read_text_checked(path) else {
521 files_skipped_encoding += 1;
522 continue;
523 };
524 let complete = decoded.complete();
529 if !complete
530 && admission.admission_policy().gateway.mode
531 != lean_ctx_protocol::context_gateway::GatewayModeV1::Developer
532 {
533 files_withheld += 1;
534 continue;
535 }
536 let text = decoded.text;
537 let Some(text) = admission.admit(&text, path, None) else {
541 files_withheld += 1;
542 continue;
543 };
544 let arc: std::sync::Arc<str> = std::sync::Arc::from(text);
545 if complete
548 && let Some(s) = state
549 && arc.len() as u64 <= MAX_FILE_SIZE
550 {
551 lean_ctx::core::content_cache::insert(
552 path,
553 s,
554 std::sync::Arc::clone(&arc),
555 &admission,
556 );
557 }
558 arc
559 };
560
561 files_searched += 1;
562 let mut file_enclosing: Option<EnclosingIndex> = None;
565
566 for (i, line) in content.lines().enumerate() {
567 if re.is_match(line) && !exclude_re.as_ref().is_some_and(|ex| ex.is_match(line)) {
569 let short_path =
570 protocol::shorten_path_relative(&path.to_string_lossy(), &root_str);
571 let source: &Path = path.as_ref();
572 if matched_sources
573 .last()
574 .is_none_or(|last| last.as_path() != source)
575 {
576 matched_sources.push(source.to_path_buf());
577 }
578 raw_tokens_accum += count_tokens(line.trim()) + 2;
580 let mut shown = if redact {
581 lean_ctx::core::redaction::redact_text(line.trim())
582 } else {
583 line.trim().to_string()
584 };
585 if shown.len() > MAX_MATCH_LINE_WIDTH {
586 shown.truncate(shown.floor_char_boundary(MAX_MATCH_LINE_WIDTH));
587 shown.push_str("...");
588 }
589 let tag = file_enclosing
594 .get_or_insert_with(|| EnclosingIndex::for_file(path, content.as_ref()))
595 .tag_for(i + 1)
596 .unwrap_or_default();
597 if anchored {
601 matches.push(format!(
602 "{short_path}:{}:{} {}{}",
603 i + 1,
604 lean_ctx_ext::core::anchor::line_hash(line),
605 shown,
606 tag
607 ));
608 } else {
609 matches.push(format!("{short_path}:{} {}{}", i + 1, shown, tag));
610 }
611 if matches.len() >= max_results {
612 cap_hit = true;
613 break;
614 }
615 }
616 }
617 }
618
619 let lineage_root = lean_ctx::core::policy::diagnostics::project().map_or_else(
626 || dir.to_owned(),
627 |root| root.to_string_lossy().into_owned(),
628 );
629 for source in &matched_sources {
630 crate::tools::ctx_read::publish_requested_source(
631 &source.to_string_lossy(),
632 &lineage_root,
633 "ctx_search",
634 );
635 }
636
637 if matches.len() > 1 {
640 use std::collections::HashMap;
641 let mut file_counts: HashMap<String, usize> = HashMap::new();
642 for m in &matches {
643 let file = extract_file_from_match(m).to_string();
644 *file_counts.entry(file).or_default() += 1;
645 }
646 matches.sort_by(|a, b| {
647 let fa = extract_file_from_match(a);
648 let fb = extract_file_from_match(b);
649 let ca = file_counts.get(fa).copied().unwrap_or(0);
650 let cb = file_counts.get(fb).copied().unwrap_or(0);
651 cb.cmp(&ca).then_with(|| fa.cmp(fb))
652 });
653 }
654
655 let files_covered = files_searched.saturating_add(index_pruned);
656
657 if matches.is_empty() {
658 let mut msg = format!("0 matches for '{pattern}' (scanned {files_covered} files)");
661 if files_withheld > 0 {
662 msg.push_str(&format!(
663 " ({files_withheld} sources withheld under policy)"
664 ));
665 }
666 if files_in_scope == 0 {
667 msg.push_str(&empty_scope_note(dir, include, exclude));
668 }
669 if files_skipped_size > 0 {
670 msg.push_str(&format!(
671 " ({files_skipped_size} large files skipped: {})",
672 name_skipped(&skipped_size_files, files_skipped_size)
673 ));
674 }
675 if files_skipped_encoding > 0 {
676 msg.push_str(&format!(
677 " ({files_skipped_encoding} files skipped: binary/encoding)"
678 ));
679 }
680 if let Some(note) = format_boundary_skips(&skipped_boundary_files, false) {
681 msg.push_str(¬e);
682 }
683 if files_skipped_special > 0 {
684 msg.push_str(&format!(
685 " ({files_skipped_special} special files skipped: not regular files)"
686 ));
687 }
688 if deadline_hit {
689 msg.push_str(
690 " (search stopped at the time budget — refine the pattern or scope with path=)",
691 );
692 }
693 if budget_hit {
694 msg.push_str(&budget_note(files_covered));
695 }
696 return SearchOutcome::without_matches(msg).withholding(skipped_boundary_files.len());
697 }
698
699 let matched_files: Vec<&str> = {
701 let mut seen = HashSet::new();
702 matches
703 .iter()
704 .filter_map(|m| {
705 let file = extract_file_from_match(m);
706 if seen.insert(file) { Some(file) } else { None }
707 })
708 .collect()
709 };
710
711 let mut result = format!(
715 "{} matches in {} files (scanned {files_covered})",
716 matches.len(),
717 matched_files.len()
718 );
719 if matched_files.len() > 1 {
720 if matched_files.len() <= 10 {
721 result.push_str(" [");
722 result.push_str(&matched_files.join(", "));
723 result.push(']');
724 } else {
725 let shown: Vec<&str> = matched_files.iter().take(8).copied().collect();
726 result.push_str(&format!(
727 " [{}, +{} more]",
728 shown.join(", "),
729 matched_files.len() - 8
730 ));
731 }
732 }
733 result.push_str(":\n");
734 if anchored {
736 result.push_str("[anchored: path:line:hh → edit via ctx_patch]\n");
737 }
738 result.push_str(&matches.join("\n"));
743 if files_withheld > 0 {
744 result.push_str(&format!(
745 "\n({files_withheld} sources withheld under policy)"
746 ));
747 }
748
749 if files_skipped_size > 0 {
750 result.push_str(&format!(
751 "\n({files_skipped_size} files >512KB skipped: {})",
752 name_skipped(&skipped_size_files, files_skipped_size)
753 ));
754 }
755 if files_skipped_encoding > 0 {
756 result.push_str(&format!(
757 "\n({files_skipped_encoding} files skipped: binary/encoding)"
758 ));
759 }
760 if let Some(note) = format_boundary_skips(&skipped_boundary_files, true) {
761 result.push_str(¬e);
762 }
763 if files_skipped_special > 0 {
764 result.push_str(&format!(
765 "\n({files_skipped_special} special files skipped: not regular files)"
766 ));
767 }
768 if deadline_hit {
769 result.push_str(&format!(
770 "\n(search stopped after the {}s budget — {files_covered} files scanned; \
771 refine the pattern or scope with path= for full coverage)",
772 search_deadline().map_or(0, |d| d.as_secs())
773 ));
774 }
775 if budget_hit {
776 result.push('\n');
777 result.push_str(budget_note(files_covered).trim_start());
778 }
779 if cap_hit {
784 result.push_str(&format!(
785 "\n(stopped at max_results={max_results}: {files_covered} of {files_in_scope} \
786 files scanned; counts are a floor, not a total)"
787 ));
788 }
789
790 if let Some(delta) = lean_ctx::core::search_delta::compute_delta(pattern, &matches) {
791 return SearchOutcome::from_observed(delta, raw_tokens_accum)
792 .withholding(skipped_boundary_files.len());
793 }
794
795 if symbol_map::substitution_enabled() {
796 let exts = extract_extensions(include);
797 let ext_refs: Vec<&str> = exts.iter().map(String::as_str).collect();
798 let mut sym = SymbolMap::new();
799 let idents = symbol_map::extract_identifiers(&result, &ext_refs);
800 for ident in &idents {
801 sym.register(ident);
802 }
803 if sym.len() >= 3 {
804 let sym_table = sym.format_table();
805 let compressed = sym.apply(&result);
806 let original_tok = count_tokens(&result);
807 let compressed_tok = count_tokens(&compressed) + count_tokens(&sym_table);
808 let net_saving = original_tok.saturating_sub(compressed_tok);
809 if original_tok > 0 && net_saving * 100 / original_tok >= 5 {
810 result = format!("{compressed}{sym_table}");
811 }
812 }
813 }
814
815 SearchOutcome::from_observed(result, raw_tokens_accum).withholding(skipped_boundary_files.len())
816}
817
818fn name_skipped(named: &[String], total: u32) -> String {
821 let mut out = named.join(", ");
822 let rest = (total as usize).saturating_sub(named.len());
823 if rest > 0 {
824 out.push_str(&format!(", +{rest} more"));
825 }
826 out
827}
828
829fn format_boundary_skips(skipped: &[(String, &'static str)], newline: bool) -> Option<String> {
831 if skipped.is_empty() {
832 return None;
833 }
834 const MAX_SHOW: usize = 10;
835 let n = skipped.len();
836 let details: Vec<String> = skipped
837 .iter()
838 .take(MAX_SHOW)
839 .map(|(p, r)| format!("{p} [{r}]"))
840 .collect();
841 let prefix = if newline { "\n(" } else { " (" };
842 let mut msg = format!(
843 "{prefix}{n} secret-like files skipped by boundary policy: {}",
844 details.join(", ")
845 );
846 if n > MAX_SHOW {
847 msg.push_str(&format!(", and {} more...", n - MAX_SHOW));
848 }
849 msg.push(')');
850 Some(msg)
851}
852
853struct EnclosingIndex {
861 spans: Vec<(usize, usize, String)>,
863}
864
865impl EnclosingIndex {
866 fn for_file(path: &Path, content: &str) -> Self {
867 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
868 let mut spans: Vec<(usize, usize, String)> =
869 lean_ctx::core::signatures::extract_signatures(content, ext)
870 .into_iter()
871 .filter_map(|s| match (s.start_line, s.end_line) {
872 (Some(a), Some(b)) if b > a => Some((a, b, s.name)),
873 _ => None,
874 })
875 .collect();
876 spans.sort_by(|x, y| x.0.cmp(&y.0).then(x.1.cmp(&y.1)));
877 Self { spans }
878 }
879
880 fn tag_for(&self, line: usize) -> Option<String> {
883 let mut best: Option<&(usize, usize, String)> = None;
884 for sp in &self.spans {
885 if line >= sp.0 && line <= sp.1 {
886 match best {
887 None => best = Some(sp),
888 Some(b) if (sp.1 - sp.0) < (b.1 - b.0) => best = Some(sp),
889 _ => {}
890 }
891 }
892 }
893 best.map(|(start, _, name)| format!(" ∈{name}@L{start}"))
894 }
895}
896
897const MAX_INCLUDE_GLOBS: usize = 64;
900
901fn compile_include(include: Option<&str>) -> Vec<Pattern> {
917 let Some(raw) = include else {
918 return Vec::new();
919 };
920 split_top_level_commas(raw)
921 .into_iter()
922 .flat_map(expand_braces)
923 .take(MAX_INCLUDE_GLOBS)
924 .filter(|g| !g.is_empty())
925 .map(|g| {
926 if g.contains('/') {
927 g
928 } else {
929 format!("**/{g}")
930 }
931 })
932 .filter_map(|g| Pattern::new(&g).ok())
933 .collect()
934}
935
936fn split_top_level_commas(raw: &str) -> Vec<&str> {
938 let mut pieces = Vec::new();
939 let mut depth = 0usize;
940 let mut start = 0;
941 for (i, c) in raw.char_indices() {
942 match c {
943 '{' => depth += 1,
944 '}' => depth = depth.saturating_sub(1),
945 ',' if depth == 0 => {
946 pieces.push(raw[start..i].trim());
947 start = i + 1;
948 }
949 _ => {}
950 }
951 }
952 pieces.push(raw[start..].trim());
953 pieces
954}
955
956fn budget_note(files_covered: u32) -> String {
960 format!(
961 " (search stopped after {files_covered} files: the protected-content read budget of this \
962 search is spent; the remaining files were not scanned, not withheld — narrow with \
963 path= or include= for full coverage)"
964 )
965}
966
967fn filter_rel<'a>(path: &'a Path, root: &Path) -> std::borrow::Cow<'a, str> {
971 match path.strip_prefix(root) {
972 Ok(rel) if !rel.as_os_str().is_empty() => rel.to_string_lossy(),
973 _ => path
974 .file_name()
975 .map_or_else(|| path.to_string_lossy(), |name| name.to_string_lossy()),
976 }
977}
978
979fn empty_scope_note(dir: &str, include: Option<&str>, exclude: Option<&str>) -> String {
982 match (include, exclude) {
983 (Some(include), _) => format!(
984 " — include=`{include}` admits no file under {dir}, so nothing was searched. \
985 Check the glob; a list is `*.{{go,yaml}}` or `*.go,*.yaml`."
986 ),
987 (None, Some(exclude)) => format!(
988 " — exclude=`{exclude}` removes every file under {dir}, so nothing was searched."
989 ),
990 (None, None) => format!(" — {dir} holds no searchable text file."),
991 }
992}
993
994fn expand_braces(pattern: &str) -> Vec<String> {
998 let Some(open) = pattern.find('{') else {
999 return vec![pattern.to_string()];
1000 };
1001 let Some(close_rel) = pattern[open..].find('}') else {
1002 return vec![pattern.to_string()];
1003 };
1004 let close = open + close_rel;
1005 let prefix = &pattern[..open];
1006 let inner = &pattern[open + 1..close];
1007 let suffix = &pattern[close + 1..];
1008
1009 let mut out = Vec::new();
1010 for alt in inner.split(',') {
1011 let alt = alt.trim();
1012 for expanded_suffix in expand_braces(suffix) {
1013 out.push(format!("{prefix}{alt}{expanded_suffix}"));
1014 if out.len() >= MAX_INCLUDE_GLOBS {
1015 return out;
1016 }
1017 }
1018 }
1019 out
1020}
1021
1022fn extract_extensions(include: Option<&str>) -> Vec<String> {
1032 let Some(list) = include else {
1033 return Vec::new();
1034 };
1035 split_top_level_commas(list)
1036 .into_iter()
1037 .flat_map(extensions_of_glob)
1038 .collect()
1039}
1040
1041fn extensions_of_glob(pattern: &str) -> Vec<String> {
1042 let filename = pattern.rsplit('/').next().unwrap_or(pattern);
1043 let Some(dot) = filename.rfind('.') else {
1044 return Vec::new();
1045 };
1046 let ext_part = &filename[dot + 1..];
1047
1048 if let Some(inner) = ext_part.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
1049 return inner
1050 .split(',')
1051 .map(|e| e.trim().to_string())
1052 .filter(|e| !e.is_empty())
1053 .collect();
1054 }
1055
1056 if ext_part.is_empty() {
1057 return Vec::new();
1058 }
1059 vec![ext_part.to_string()]
1060}
1061
1062fn extract_file_from_match(line: &str) -> &str {
1064 let start = if line.len() >= 2
1065 && line.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
1066 && line.as_bytes().get(1) == Some(&b':')
1067 {
1068 2
1069 } else {
1070 0
1071 };
1072 match line[start..].find(':') {
1073 Some(pos) => &line[..start + pos],
1074 None => line,
1075 }
1076}
1077
1078#[cfg(test)]
1079#[path = "tests.rs"]
1080mod tests;