1use std::collections::HashSet;
4use std::io::{IsTerminal, Write};
5use std::path::PathBuf;
6use std::process::ExitCode;
7use std::time::Duration;
8
9use clap::{CommandFactory, Parser};
10use clap_complete::Shell;
11
12use crate::core::now_unix;
13use crate::store::Store;
14
15#[derive(Parser)]
19#[command(
20 name = "rq",
21 version,
22 about = "Ranked definition lookup — the one place a symbol is defined, first.",
23 long_about = "rq finds where a symbol is defined and ranks the one you most \
24likely meant to the top — not every match.\n\n\
25Search is the default action; operations are flags, not subcommands, so every \
26word (including \"index\", \"status\", \"record\") stays searchable. Ranking favors \
27your current repo, recently-active files, and the files your branch changes. Run \
28`rq <query> --explain` to see the score behind each result.",
29 after_help = "EXAMPLES:\n \
30rq thing search for a definition named or like \"thing\"\n \
31rq wibble --explain same, plus the score behind each result\n \
32rq thing --json machine-readable results (for editors/agents)\n \
33rq thing --no-wait answer now from the committed index; don't block on a rebuild\n \
34rq thing --wait 2s ...or wait up to a bounded time for the index to warm\n \
35rq thing app/web restrict to a directory (rg-style)\n \
36rq perform -k method restrict to a symbol kind (c/mod/m/f/s/e/t)\n \
37rq class Widget a leading kind keyword is shorthand for -k\n \
38rq --symbols FILE outline a file's definitions, in line order\n \
39rq thing -x rust restrict to a language (ruby/rust/go/python/ts/js)\n \
40rq 'Foo::Bar' qualify by scope — the surest way past an ambiguous name\n \
41rq 'Foo#bar' ...and by owner, for a method\n \
42rq Foo.new the constructor (initialize, __init__, ...)\n \
43rq 'refund*proc' wildcards: * (any run), ? (one char) — quote them\n \
44rq -o thing open the best match in your editor\n \
45rq --index index the current repository\n \
46rq --status show indexing coverage\n \
47rq --usage show how rq has been called (by caller and flags)\n \
48rq --drop remove this repo's index (opposite of --index)\n\n\
49SHORT FLAGS (easy to misread):\n \
50-j = --json (not jobs; --jobs is long-only) -l = --limit (not lang) -x = --lang\n\n\
51The index is a SQLite file at $RQ_DB (default ~/.local/share/rq/rq.db); it warms \
52automatically on the first search in a git repo. On a large, cold repo a search \
53keeps indexing until it can answer rather than reporting a premature \"no \
54matches\" (an interactive run shows progress and stops on Ctrl-C). Exit codes: 0 \
55= matched, 1 = no match, 2 = no match yet (index still warming — try again)."
56)]
57struct Cli {
58 #[arg(value_name = "TARGET", value_hint = clap::ValueHint::Other)]
64 target: Option<String>,
65
66 #[arg(value_name = "PATH")]
68 dirs: Vec<String>,
69
70 #[arg(short = 'e', long)]
72 explain: bool,
73
74 #[arg(long = "no-wait")]
80 no_wait: bool,
81
82 #[arg(long, value_name = "DUR", value_parser = parse_wait, conflicts_with = "no_wait")]
87 wait: Option<Duration>,
88
89 #[arg(short = 'o', long, conflicts_with_all = ["index", "status", "json", "ndjson"])]
94 open: bool,
95
96 #[arg(short = 'w', long, conflicts_with_all = ["open", "index", "status", "json", "ndjson"])]
101 web: bool,
102
103 #[arg(long, conflicts_with_all = ["open", "web", "index", "status", "symbols", "drop"])]
107 show: bool,
108
109 #[arg(short = 'j', long)]
111 json: bool,
112
113 #[arg(short = 'J', long, conflicts_with = "json")]
115 ndjson: bool,
116
117 #[arg(short = 'p', long, value_name = "DIR")]
119 path: Vec<String>,
120
121 #[arg(short = 'l', long, value_name = "N", default_value_t = DEFAULT_LIMIT)]
123 limit: usize,
124
125 #[arg(short = 'k', long, value_name = "KIND", value_delimiter = ',')]
129 kind: Vec<String>,
130
131 #[arg(short = 'x', long = "lang", value_name = "LANG", value_delimiter = ',')]
135 lang: Vec<String>,
136
137 #[arg(short = 'a', long = "all-repos")]
140 all_repos: bool,
141
142 #[arg(long, value_name = "PATH", num_args = 0..=1, value_hint = clap::ValueHint::AnyPath, conflicts_with = "status")]
144 index: Option<Option<String>>,
145
146 #[arg(long, conflicts_with = "index")]
148 status: bool,
149
150 #[arg(long, conflicts_with_all = ["index", "status"])]
152 usage: bool,
153
154 #[arg(long, value_name = "FILE", value_hint = clap::ValueHint::FilePath, conflicts_with_all = ["index", "status", "drop", "open", "web"])]
157 symbols: Option<String>,
158
159 #[arg(long, conflicts_with_all = ["index", "status", "open", "web"])]
163 drop: bool,
164
165 #[arg(long, hide = true, value_name = "PATH", num_args = 0..=1, value_hint = clap::ValueHint::AnyPath, conflicts_with_all = ["index", "status", "drop", "symbols", "open", "web", "show"])]
169 warm: Option<Option<String>>,
170
171 #[arg(long, value_name = "SHELL")]
173 completions: Option<Shell>,
174
175 #[arg(short = 'v', long)]
178 verbose: bool,
179
180 #[arg(long)]
184 profile: bool,
185
186 #[arg(long, value_name = "N", default_value_t = 0)]
189 jobs: usize,
190}
191
192pub fn run() -> ExitCode {
194 let cli = Cli::parse();
195 crate::trace::enable_from(cli.verbose);
196 crate::profile::enable_from(cli.profile);
197 crate::index::set_parse_jobs(cli.jobs);
198 let json_out = output_format(&cli) != Output::Text;
199 let code = dispatch(cli);
200 crate::profile::emit(json_out);
201 code
202}
203
204fn dispatch(cli: Cli) -> ExitCode {
205 if let Some(shell) = cli.completions {
206 clap_complete::generate(shell, &mut Cli::command(), "rq", &mut std::io::stdout());
207 return ExitCode::SUCCESS;
208 }
209 if let Some(path) = &cli.index {
210 let out = output_format(&cli);
212 return cmd_index(path.as_deref().map(PathBuf::from), &cli.path, out);
213 }
214 if let Some(path) = &cli.warm {
215 return cmd_warm(path.as_deref());
216 }
217 if cli.status {
218 return cmd_status(output_format(&cli));
219 }
220 if cli.usage {
221 return cmd_usage(output_format(&cli));
222 }
223 if cli.drop {
224 let out = output_format(&cli);
225 return cmd_drop(cli.target, out);
226 }
227 let out = output_format(&cli);
228 if cli.target.as_deref().is_some_and(|t| t.trim().is_empty()) {
229 return fail(format_args!("rq: empty query"));
230 }
231 let mut kinds: Vec<String> = Vec::new();
235 for k in &cli.kind {
236 match canonical_kind(k) {
237 Some(c) => kinds.push(c.to_string()),
238 None => {
239 return fail(format_args!(
240 "rq: unknown --kind {k:?} (class, module, method, function, struct, enum, trait)"
241 ));
242 }
243 }
244 }
245 let mut langs: Vec<String> = Vec::new();
247 for x in &cli.lang {
248 let matched = canonical_langs(x);
249 if matched.is_empty() {
250 return fail(format_args!(
251 "rq: unknown --lang {x:?} ({})",
252 crate::lang::languages().join(", ")
253 ));
254 }
255 langs.extend(matched);
256 }
257 if let Some(file) = &cli.symbols {
258 return cmd_symbols(file, &kinds, &langs, out);
259 }
260 let mut paths = cli.path.clone();
262 match cli.target {
263 Some(target) => {
264 let query = if cli.kind.is_empty() {
267 let (kw, query, dirs) = split_kind_keyword(target, cli.dirs.clone());
268 if let Some(k) = kw {
269 kinds.push(k.to_string());
270 }
271 paths.extend(dirs);
272 query
273 } else {
274 paths.extend(cli.dirs.clone());
275 target
276 };
277 let mut session = match Session::open() {
278 Ok(s) => s,
279 Err(code) => return code,
280 };
281 cmd_search(
282 &mut session,
283 &SearchArgs {
284 query: &query,
285 explain: cli.explain,
286 out,
287 paths: &paths,
288 kinds: &kinds,
289 langs: &langs,
290 want: requested_limit(cli.limit),
291 no_wait: cli.no_wait,
292 wait: cli.wait,
293 open: cli.open,
294 web: cli.web,
295 all_repos: cli.all_repos,
296 show: cli.show,
297 batch: false,
298 },
299 )
300 }
301 None if !std::io::stdin().is_terminal() => cmd_batch(&cli, out, &paths, &kinds, &langs),
304 None => {
306 let _ = Cli::command().print_long_help();
307 ExitCode::SUCCESS
308 }
309 }
310}
311
312#[derive(Clone, Copy, PartialEq)]
314enum Output {
315 Text,
316 Json,
317 Ndjson,
318}
319
320fn output_format(cli: &Cli) -> Output {
321 if cli.ndjson {
322 Output::Ndjson
323 } else if cli.json {
324 Output::Json
325 } else {
326 Output::Text
327 }
328}
329
330const DEFAULT_LIMIT: usize = 10;
332
333const PATH_HEADROOM: usize = 200;
336
337fn requested_limit(limit: usize) -> usize {
340 if limit == 0 { usize::MAX } else { limit }
341}
342
343fn record_usage(store: &Store, args: &SearchArgs, status: &str, coverage: Option<&str>) {
346 let _ = store.record_search(&crate::store::SearchRecord {
347 source: &crate::origin::detect(),
348 flags: &flag_summary(args),
349 status,
350 coverage: coverage.unwrap_or("none"),
351 });
352}
353
354fn flag_summary(args: &SearchArgs) -> String {
359 let mut on: Vec<&str> = Vec::new();
360 match args.out {
361 Output::Json => on.push("json"),
362 Output::Ndjson => on.push("ndjson"),
363 Output::Text => {}
364 }
365 for (present, name) in [
366 (args.explain, "explain"),
367 (args.show, "show"),
368 (args.open, "open"),
369 (args.web, "web"),
370 (args.all_repos, "all-repos"),
371 (args.no_wait, "no-wait"),
372 (args.batch, "batch"),
373 (!args.paths.is_empty(), "path"),
374 (!args.kinds.is_empty(), "kind"),
375 (!args.langs.is_empty(), "lang"),
376 (args.want != DEFAULT_LIMIT, "limit"),
377 ] {
378 if present {
379 on.push(name);
380 }
381 }
382 on.join(",")
383}
384
385const POLL_INTERVAL: Duration = Duration::from_millis(100);
392
393const HEADS_UP_DELAY: Duration = Duration::from_millis(500);
397
398const PROGRESS_REDRAW: Duration = Duration::from_millis(120);
402
403struct SearchArgs<'a> {
405 query: &'a str,
406 explain: bool,
407 out: Output,
408 paths: &'a [String],
409 kinds: &'a [String],
410 langs: &'a [String],
411 want: usize,
413 no_wait: bool,
415 wait: Option<Duration>,
418 open: bool,
419 web: bool,
420 all_repos: bool,
421 batch: bool,
425 show: bool,
426}
427
428struct Session {
439 store: Store,
440 cwd: Option<PathBuf>,
441 cwd_is_git: bool,
442 root: Option<PathBuf>,
443 active_paths: Vec<String>,
444 branch_refresh: Option<BranchRefresh>,
445 identity: Option<String>,
446 coverage: Option<String>,
447}
448
449impl Session {
450 fn open() -> std::result::Result<Session, ExitCode> {
452 let open_span = crate::profile::span("store open");
453 let store = match open_store() {
454 Ok(s) => s,
455 Err(e) => return Err(fail(format_args!("rq: cannot open database: {e}"))),
456 };
457 drop(open_span);
458 let git_span = crate::profile::span("setup: git root");
459 let cwd = std::env::current_dir().ok();
460 let cwd_is_git = cwd.as_deref().is_some_and(crate::index::is_git_repo);
461
462 let root = cwd
468 .as_deref()
469 .map(|c| crate::index::repo_root(c).unwrap_or_else(|| c.to_path_buf()));
470 drop(git_span);
471
472 let mut branch_span = crate::profile::span("setup: branch files");
475 let (active_paths, branch_refresh, cached_cost) = match &root {
476 Some(c) if cwd_is_git => cached_branch_files(&store, c),
477 _ => (Vec::new(), None, None),
478 };
479 branch_span.note(|| {
480 let how = if branch_refresh.is_some() {
481 "cached, refreshing alongside"
482 } else {
483 "cached"
484 };
485 let ttl = branch_files_ttl(cached_cost);
488 format!("{} changed, {how} ({ttl}s window)", active_paths.len())
489 });
490 drop(branch_span);
491
492 let mut identity_span = crate::profile::span("setup: identity");
497 let identity = root.as_deref().map(|c| resolve_identity(&store, c));
498 let coverage = identity
499 .as_deref()
500 .and_then(|id| store.coverage_status(id).ok())
501 .flatten();
502 identity_span.note(|| coverage.as_deref().unwrap_or("unknown").to_string());
503 drop(identity_span);
504 Ok(Session {
505 store,
506 cwd,
507 cwd_is_git,
508 root,
509 active_paths,
510 branch_refresh,
511 identity,
512 coverage,
513 })
514 }
515}
516
517fn cmd_batch(
532 cli: &Cli,
533 out: Output,
534 paths: &[String],
535 kinds: &[String],
536 langs: &[String],
537) -> ExitCode {
538 if out == Output::Json {
539 return fail(format_args!(
540 "rq: --json can't frame a stream of queries — use --ndjson (-J), \
541 where each line carries the query it answers"
542 ));
543 }
544 if cli.open || cli.web || cli.show {
545 return fail(format_args!(
546 "rq: --open, --web and --show act on a single result, not a stream of queries"
547 ));
548 }
549
550 use std::io::BufRead;
551 let queries: Vec<String> = std::io::stdin()
552 .lock()
553 .lines()
554 .map_while(std::result::Result::ok)
555 .map(|l| l.trim().to_string())
556 .filter(|l| !l.is_empty())
557 .collect();
558 if queries.is_empty() {
562 let _ = Cli::command().print_long_help();
563 return ExitCode::SUCCESS;
564 }
565
566 let mut session = match Session::open() {
567 Ok(s) => s,
568 Err(code) => return code,
569 };
570
571 if !cli.no_wait
574 && session.coverage.as_deref() != Some("complete")
575 && let Some(root) = session.root.clone()
576 {
577 {
578 let budget = cli.wait.unwrap_or_else(wait_budget);
579 crate::trace!(
580 "batch: warming {} queries' worth of index first",
581 queries.len()
582 );
583 let active = session.active_paths.clone();
584 let _ = crate::index::index_budgeted(&mut session.store, &root, &active, budget, None);
585 session.coverage = session
586 .identity
587 .as_deref()
588 .and_then(|id| session.store.coverage_status(id).ok())
589 .flatten();
590 }
591 }
592
593 let mut worst = ExitCode::SUCCESS;
594 let mut any_hit = false;
595 for query in &queries {
596 let code = cmd_search(
597 &mut session,
598 &SearchArgs {
599 query,
600 explain: cli.explain,
601 out,
602 paths,
603 kinds,
604 langs,
605 want: requested_limit(cli.limit),
606 no_wait: true,
610 wait: cli.wait,
611 open: false,
612 web: false,
613 all_repos: cli.all_repos,
614 show: false,
615 batch: true,
616 },
617 );
618 if code == ExitCode::SUCCESS {
619 any_hit = true;
620 } else {
621 worst = code;
622 }
623 }
624 if any_hit { ExitCode::SUCCESS } else { worst }
627}
628
629fn cmd_search(session: &mut Session, args: &SearchArgs) -> ExitCode {
630 let &SearchArgs {
631 query,
632 out,
633 want,
634 no_wait,
635 wait,
636 open,
637 web,
638 all_repos,
639 show,
640 ..
641 } = args;
642 let wait_budget = wait.unwrap_or_else(wait_budget);
645 let no_wait = no_wait || wait_budget.is_zero();
646 let limit = if args.paths.is_empty() && args.kinds.is_empty() && args.langs.is_empty() {
649 want
650 } else {
651 want.saturating_mul(20).max(PATH_HEADROOM)
652 };
653 let _timer = crate::trace::Timer::start("search done");
654 let t_setup = std::time::Instant::now();
655 let setup_span = crate::profile::span("setup");
657 let Session {
660 store,
661 cwd,
662 cwd_is_git,
663 root,
664 active_paths,
665 branch_refresh,
666 identity,
667 coverage,
668 } = session;
669 let cwd_is_git = *cwd_is_git;
670
671 let known = coverage.is_some();
679 let warming_ok = cwd_is_git || known;
680 if crate::trace::enabled() {
681 crate::trace!(
682 "query {query:?}: root={} identity={} coverage={} warming_ok={warming_ok} active={}",
683 root.as_deref().map_or("?".into(), crate::trace::abbrev),
684 identity.as_deref().unwrap_or("none"),
685 coverage.as_deref().unwrap_or("none"),
686 active_paths.len(),
687 );
688 }
689 let repo_span = crate::profile::span("setup: repo state");
690 let current = identity
691 .as_deref()
692 .and_then(|id| store.repository_id(id).ok().flatten());
693 let only_repo = if all_repos { None } else { current };
696 let active = crate::search::ActiveFiles::new(active_paths.clone());
697
698 drop(repo_span);
699 let warm_span = crate::profile::span("setup: warm decision");
700
701 let warm_budget = if warm_detach_enabled() {
708 answer_warm_budget()
709 } else {
710 answer_warm_budget() + deferred_warm_budget()
711 };
712 let was_warming = coverage.as_deref() != Some("complete");
713
714 let indexed_head = (!was_warming)
725 .then(|| current.and_then(|id| store.indexed_head(id).ok().flatten()))
726 .flatten();
727 let staleness = (!was_warming && warming_ok && !args.batch)
730 .then(|| root.clone())
731 .flatten()
732 .map(|c| {
733 if warm_detach_enabled() {
734 Staleness::Deferred(c, indexed_head)
735 } else {
736 Staleness::Running(std::thread::spawn(move || {
737 worktree_edits(&c, indexed_head.as_deref())
738 }))
739 }
740 });
741 let want_warm = warming_ok && was_warming && root.is_some();
744
745 let block = want_warm && was_warming && !no_wait;
759 let progress_ui = block && show_progress(out, stderr_interactive());
764 let indexer_budget = if block { wait_budget } else { warm_budget };
765 if progress_ui {
766 install_interrupt_handler();
767 }
768
769 let warm_done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
772 let indexer = (want_warm && root.is_some() && !no_wait).then(|| {
773 crate::trace!(
774 "background warm ({indexer_budget:?}, block={block}, progress_ui={progress_ui}, {} jobs)",
775 crate::index::parse_jobs()
776 );
777 let root = root.clone().expect("checked");
778 let active = active_paths.clone();
779 let q = query.to_string();
780 let warm_done = std::sync::Arc::clone(&warm_done);
781 std::thread::spawn(move || {
782 if let Ok(mut idx) = open_store() {
783 let _ = if block {
785 crate::index::index_budgeted_cancellable(
788 &mut idx,
789 &root,
790 &active,
791 indexer_budget,
792 Some(&q),
793 &INTERRUPTED,
794 )
795 } else {
796 crate::index::index_budgeted(&mut idx, &root, &active, indexer_budget, Some(&q))
797 };
798 }
799 warm_done.store(true, std::sync::atomic::Ordering::Relaxed);
800 })
801 });
802
803 crate::trace!(
810 "setup (open + repo detect + warm decision): {} ms",
811 t_setup.elapsed().as_millis()
812 );
813 let poll_start = std::time::Instant::now();
814 let deadline = if progress_ui {
818 None
819 } else if block {
820 Some(poll_start + wait_budget)
821 } else {
822 Some(poll_start + answer_warm_budget())
823 };
824 drop(warm_span);
825 let polling = indexer.is_some() && was_warming;
826 drop(setup_span);
830 let mut query_span = crate::profile::span("query");
831 let label = repo_label(root.as_deref());
832 let mut drew_progress = false;
833 let mut last_draw = poll_start;
834 let rank_limit = limit.max(2);
838 let mut total;
839 let mut hits = loop {
840 match crate::search::search(store, query, current, only_repo, &active, rank_limit) {
841 Ok(m) => {
842 total = m.total;
843 let h = m.hits;
844 let confident = h.first().is_some_and(|hit| {
845 hit.features
846 .iter()
847 .any(|f| matches!(f.name, "exact" | "prefix"))
848 });
849 let warm_finished = warm_done.load(std::sync::atomic::Ordering::Relaxed);
850 let stopped = INTERRUPTED.load(std::sync::atomic::Ordering::Relaxed);
851 let timed_out = deadline.is_some_and(|d| std::time::Instant::now() >= d);
852 if !polling || confident || warm_finished || stopped || timed_out {
853 break h;
854 }
855 if progress_ui
856 && poll_start.elapsed() >= HEADS_UP_DELAY
857 && last_draw.elapsed() >= PROGRESS_REDRAW
858 {
859 draw_progress(store, identity.as_deref(), &label);
860 drew_progress = true;
861 last_draw = std::time::Instant::now();
862 }
863 }
864 Err(e) => {
865 if let Some(h) = indexer {
866 let _ = h.join();
867 }
868 return fail(format_args!("rq: {e}"));
869 }
870 }
871 std::thread::sleep(POLL_INTERVAL);
872 };
873 query_span.note(|| {
874 if polling {
875 "polled a warming index".to_string()
876 } else {
877 String::new()
878 }
879 });
880 drop(query_span);
881 if drew_progress {
882 clear_progress();
883 }
884 let interrupted = INTERRUPTED.load(std::sync::atomic::Ordering::Relaxed);
886
887 let here = identity
888 .as_deref()
889 .zip(root.as_deref())
890 .map(|(identity, root)| Here { identity, root });
891 if !hits.is_empty()
893 && revalidate_top(store, &hits, here)
894 && let Ok(m) = crate::search::search(store, query, current, only_repo, &active, rank_limit)
895 {
896 total = m.total;
897 hits = m.hits;
898 }
899
900 if !hits.iter().any(strong)
904 && indexer.is_none()
905 && coverage.is_none()
906 && let Some(root) = &root
907 {
908 let tail = live_fallback(root, query, rank_limit);
909 hits = crate::search::merge(hits, tail, rank_limit);
910 total = total.max(hits.len());
911 }
912
913 apply_gates(query, &mut hits);
914 apply_post_filters(args, cwd.as_deref(), root.as_deref(), &mut hits);
915 if !args.paths.is_empty() || !args.kinds.is_empty() || !args.langs.is_empty() {
918 total = hits.len();
919 }
920
921 if hits.is_empty() {
922 if block {
924 INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
925 }
926 if let Some(h) = indexer {
927 let _ = h.join();
928 }
929 let mut incomplete = (block || no_wait)
936 && identity
937 .as_deref()
938 .and_then(|id| store.coverage_status(id).ok().flatten())
939 .as_deref()
940 != Some("complete");
941 incomplete |= settle_warm(
951 store,
952 staleness,
953 false,
954 was_warming,
955 warming_ok,
956 root.as_deref(),
957 active_paths,
958 query,
959 warm_budget,
960 no_wait,
961 identity.as_deref(),
962 );
963 record_usage(
967 store,
968 args,
969 if incomplete { "warming" } else { "miss" },
970 coverage.as_deref(),
971 );
972 let elsewhere = crate::search::scope_miss_owner(store, query, current, only_repo, &active);
977 return no_match_code(out, query, interrupted, incomplete, elsewhere.as_deref());
978 }
979
980 {
983 let _span = crate::profile::span("record usage");
984 record_usage(store, args, "hit", coverage.as_deref());
985 }
986
987 attach_confidence(&mut hits);
991 hits.truncate(want);
992 let total = total.max(hits.len());
993 for hit in &mut hits {
994 hit.total = total;
995 if args.explain {
996 hit.explain = Some(
997 hit.features
998 .iter()
999 .map(|f| (f.name.to_string(), f.value))
1000 .collect(),
1001 );
1002 }
1003 }
1004
1005 let _signatures_span = crate::profile::span("signatures");
1008 for hit in &mut hits {
1009 hit.signature = read_signature(store, &hit.repo_identity, &hit.file, hit.line, here);
1010 }
1011 drop(_signatures_span);
1012
1013 if show && let Some(code) = show_top_definition(store, &mut hits, query, out, here) {
1016 return code;
1017 }
1018
1019 if open || web {
1024 return finish_open(store, &hits, current, root.as_deref(), web);
1025 }
1026
1027 if let Some(code) = render_hits(args, &hits) {
1028 return code;
1029 }
1030
1031 crate::profile::mark("first answer");
1034
1035 if let Some(refresh) = branch_refresh.take() {
1042 let _span = crate::profile::span("after: branch refresh");
1043 refresh.store(store);
1044 }
1045
1046 if block {
1051 INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1052 }
1053 if let Some(h) = indexer {
1054 let _ = h.join();
1055 }
1056 let _ = settle_warm(
1057 store,
1058 staleness,
1059 true,
1060 was_warming,
1061 warming_ok,
1062 root.as_deref(),
1063 active_paths,
1064 query,
1065 warm_budget,
1066 no_wait,
1067 identity.as_deref(),
1068 );
1069
1070 ExitCode::SUCCESS
1071}
1072
1073fn maybe_detach_warm(
1076 store: &Store,
1077 want_warm: bool,
1078 changed: bool,
1079 root: Option<&std::path::Path>,
1080 identity: Option<&str>,
1081) {
1082 if !warm_detach_enabled() || !want_warm {
1083 return;
1084 }
1085 let (Some(root), Some(id)) = (root, identity) else {
1086 return;
1087 };
1088 if !changed && store.coverage_status(id).ok().flatten().as_deref() == Some("complete") {
1092 return; }
1094 spawn_detached_warm(root);
1095}
1096
1097fn spawn_detached_warm(root: &std::path::Path) {
1101 use std::os::unix::process::CommandExt;
1102 let Ok(exe) = std::env::current_exe() else {
1103 return;
1104 };
1105 let mut cmd = std::process::Command::new(exe);
1106 cmd.arg("--warm")
1107 .arg(root)
1108 .stdin(std::process::Stdio::null())
1109 .stdout(std::process::Stdio::null())
1110 .stderr(std::process::Stdio::null())
1111 .process_group(0);
1112 match cmd.spawn() {
1113 Ok(child) => crate::trace!(
1114 "background warm (detached): pid {} for {}",
1115 child.id(),
1116 crate::trace::abbrev(root)
1117 ),
1118 Err(e) => crate::trace!("detached warm failed to spawn: {e}"),
1119 }
1120}
1121
1122const WARM_LOCK_TTL_SECS: i64 = 600;
1125
1126fn cmd_warm(path: Option<&str>) -> ExitCode {
1131 #[cfg(target_os = "macos")]
1134 unsafe extern "C" {
1135 fn setiopolicy_np(
1138 iotype: libc::c_int,
1139 scope: libc::c_int,
1140 policy: libc::c_int,
1141 ) -> libc::c_int;
1142 }
1143 unsafe {
1144 libc::nice(10);
1145 #[cfg(target_os = "macos")]
1146 setiopolicy_np(0, 0, 3);
1147 }
1148 let mut store = match open_store() {
1149 Ok(s) => s,
1150 Err(_) => return ExitCode::FAILURE,
1151 };
1152 let start = path
1153 .map(PathBuf::from)
1154 .or_else(|| std::env::current_dir().ok())
1155 .unwrap_or_else(|| PathBuf::from("."));
1156 let root = crate::index::repo_root(&start).unwrap_or(start);
1157 let identity = resolve_identity(&store, &root);
1158
1159 if let Ok(Some((pid, ts))) = store.warm_lock(&identity)
1162 && pid != std::process::id()
1163 && unsafe { libc::kill(pid as libc::pid_t, 0) } == 0
1164 && now_unix() - ts < WARM_LOCK_TTL_SECS
1165 {
1166 return ExitCode::SUCCESS;
1167 }
1168 let _ = store.set_warm_lock(&identity, std::process::id());
1169
1170 if store.coverage_status(&identity).ok().flatten().as_deref() == Some("complete") {
1173 let head = store
1174 .repository_id(&identity)
1175 .ok()
1176 .flatten()
1177 .and_then(|id| store.indexed_head(id).ok().flatten());
1178 let edits = worktree_edits(&root, head.as_deref());
1179 if !changed_since_index(&store, Some(&identity), Some(&root), edits) {
1180 crate::trace!("warm: unchanged since indexed, nothing to do");
1181 let _ = store.clear_warm_lock(&identity);
1182 return ExitCode::SUCCESS;
1183 }
1184 }
1185
1186 let deadline = std::time::Instant::now() + warm_bg_budget();
1189 let active = crate::index::branch_changed_files(&root);
1190 loop {
1191 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1192 if remaining.is_zero() {
1193 break;
1194 }
1195 let stats = match crate::index::index_budgeted(&mut store, &root, &active, remaining, None)
1196 {
1197 Ok(s) => s,
1198 Err(_) => break,
1199 };
1200 if store.coverage_status(&identity).ok().flatten().as_deref() == Some("complete")
1201 || stats.files_indexed == 0
1202 {
1203 break;
1204 }
1205 }
1206 let _ = store.clear_warm_lock(&identity);
1207 ExitCode::SUCCESS
1208}
1209
1210fn live_fallback(root: &std::path::Path, query: &str, limit: usize) -> Vec<crate::search::Hit> {
1213 crate::trace!("empty → live (in-memory) scan of an untracked dir");
1214 let deadline = std::time::Instant::now() + live_fallback_budget();
1215 let h = crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), true);
1216 if !h.is_empty() {
1217 return h;
1218 }
1219 crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), false)
1220}
1221
1222fn strong(h: &crate::search::Hit) -> bool {
1224 h.features
1225 .iter()
1226 .any(|f| matches!(f.name, "exact" | "prefix"))
1227}
1228
1229fn apply_gates(query: &str, hits: &mut Vec<crate::search::Hit>) {
1238 if hits.iter().any(strong) {
1239 hits.retain(strong);
1240 }
1241 crate::search::apply_scope_gate(query, hits);
1242}
1243
1244fn apply_post_filters(
1247 args: &SearchArgs,
1248 cwd: Option<&std::path::Path>,
1249 root: Option<&std::path::Path>,
1250 hits: &mut Vec<crate::search::Hit>,
1251) {
1252 if !args.paths.is_empty() {
1253 let here = cwd.map_or_else(|| PathBuf::from("."), PathBuf::from);
1257 let base = root.map_or_else(|| here.clone(), PathBuf::from);
1258 let norm: Vec<String> = args
1259 .paths
1260 .iter()
1261 .map(|p| repo_relative(&base, &here, p))
1262 .collect();
1263 hits.retain(|h| under_any(&h.file, &norm));
1264 }
1265 if !args.kinds.is_empty() {
1266 hits.retain(|h| args.kinds.iter().any(|k| k == &h.kind));
1267 }
1268 if !args.langs.is_empty() {
1269 hits.retain(|h| args.langs.iter().any(|l| l == &h.language));
1270 }
1271 if !args.paths.is_empty() || !args.kinds.is_empty() || !args.langs.is_empty() {
1274 hits.truncate(args.want.max(2));
1275 }
1276}
1277
1278fn no_match_code(
1284 out: Output,
1285 query: &str,
1286 interrupted: bool,
1287 incomplete: bool,
1288 elsewhere: Option<&str>,
1292) -> ExitCode {
1293 let status = if interrupted {
1294 "interrupted"
1295 } else if incomplete {
1296 "warming"
1297 } else if elsewhere.is_some() {
1298 "scope_not_found"
1299 } else {
1300 "no_match"
1301 };
1302 match out {
1303 Output::Json | Output::Ndjson => {
1304 let mut obj = serde_json::json!({ "status": status, "query": query });
1305 if let Some(found_in) = elsewhere {
1306 obj["found_in"] = serde_json::json!(found_in);
1307 }
1308 let _ = emit_json(out, &obj); }
1310 Output::Text if interrupted => {
1311 eprintln!("rq: indexing interrupted — run again to finish")
1312 }
1313 Output::Text if incomplete => eprintln!(
1314 "rq: still indexing — no match for {query:?} yet (run again, or `rq --index` to finish)"
1315 ),
1316 Output::Text if elsewhere.is_some() => eprintln!(
1317 "rq: nothing matching {query:?} — that name is defined under {}",
1318 elsewhere.unwrap_or_default()
1319 ),
1320 Output::Text => eprintln!("no matches for {query:?}"),
1321 }
1322 if incomplete {
1323 ExitCode::from(2)
1324 } else {
1325 ExitCode::FAILURE
1326 }
1327}
1328
1329fn attach_confidence(hits: &mut [crate::search::Hit]) {
1333 let (top, second) = hits.iter().fold((None::<f64>, None::<f64>), |(t, s), h| {
1334 if t.is_none_or(|t| h.score > t) {
1335 (Some(h.score), t)
1336 } else if s.is_none_or(|s| h.score > s) {
1337 (t, Some(h.score))
1338 } else {
1339 (t, s)
1340 }
1341 });
1342 for hit in hits.iter_mut() {
1343 let best_other = if Some(hit.score) == top { second } else { top };
1344 hit.confidence = crate::search::confidence(
1345 hit.score,
1346 crate::search::match_quality(&hit.features),
1347 best_other,
1348 );
1349 }
1350}
1351
1352fn render_hits(args: &SearchArgs, hits: &[crate::search::Hit]) -> Option<ExitCode> {
1355 let render_span = crate::profile::span("render");
1359 if args.batch {
1360 #[derive(serde::Serialize)]
1363 struct Tagged<'a> {
1364 query: &'a str,
1365 #[serde(flatten)]
1366 hit: &'a crate::search::Hit,
1367 }
1368 let rows: Vec<Tagged> = hits
1369 .iter()
1370 .map(|hit| Tagged {
1371 query: args.query,
1372 hit,
1373 })
1374 .collect();
1375 if let Some(code) = emit_rows(args.out, &rows) {
1376 return Some(code);
1377 }
1378 } else if let Some(code) = emit_rows(args.out, hits) {
1379 return Some(code);
1380 }
1381 if args.out != Output::Text {
1382 return None;
1383 }
1384 drop(render_span);
1385 let color = match_color();
1386 let c = color.as_deref();
1387 let query = args.query;
1388 if args.show {
1389 let total = hits.first().map_or(hits.len(), |h| h.total);
1391 eprintln!(
1392 "rq: no single confident match for {query:?} — {} of {total} candidates below; narrow the query to --show one",
1393 hits.len()
1394 );
1395 }
1396 for hit in hits {
1397 let name = hl(&hit.name, query, c);
1400 let qualified = match &hit.parent {
1401 Some(p) => format!("{name} · {p}"),
1402 None => name,
1403 };
1404 println!(
1405 "{}:{} {} {}",
1406 hl_path(&hit.file, query, c),
1407 hit.line,
1408 hit.kind,
1409 qualified
1410 );
1411 if let Some(sig) = &hit.signature {
1412 println!(" {}", hl(sig, query, c));
1413 }
1414 if args.explain {
1415 let parts: Vec<String> = hit
1416 .features
1417 .iter()
1418 .map(|f| format!("{} {:.0}", f.name, f.value))
1419 .collect();
1420 println!(
1421 " confidence {:.2} · score {:.0} = {}",
1422 hit.confidence,
1423 hit.score,
1424 parts.join(" + ")
1425 );
1426 }
1427 }
1428 None
1429}
1430
1431fn choose_hit(hits: &[crate::search::Hit]) -> Option<&crate::search::Hit> {
1435 use std::io::{IsTerminal, Write};
1436 if hits.len() == 1 || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
1437 return hits.first();
1438 }
1439 let mut err = std::io::stderr();
1440 let _ = writeln!(err, "rq: {} matches — pick one (enter = 1):", hits.len());
1441 for (i, h) in hits.iter().enumerate() {
1442 let _ = writeln!(
1443 err,
1444 " {}. {}:{} {} {}",
1445 i + 1,
1446 h.file,
1447 h.line,
1448 h.kind,
1449 h.name
1450 );
1451 }
1452 let _ = write!(err, "rq> ");
1453 let _ = err.flush();
1454 let mut line = String::new();
1455 if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
1456 return None; }
1458 parse_choice(&line, hits.len()).and_then(|i| hits.get(i))
1459}
1460
1461fn parse_choice(input: &str, n: usize) -> Option<usize> {
1464 let s = input.trim();
1465 if s.is_empty() {
1466 return Some(0);
1467 }
1468 let i = s.parse::<usize>().ok()?.checked_sub(1)?;
1469 (i < n).then_some(i)
1470}
1471
1472fn finish_open(
1475 store: &Store,
1476 hits: &[crate::search::Hit],
1477 current: Option<i64>,
1478 root: Option<&std::path::Path>,
1479 web: bool,
1480) -> ExitCode {
1481 let Some(hit) = choose_hit(hits) else {
1482 return ExitCode::SUCCESS; };
1484
1485 if web {
1486 return open_web(store, hit, current, root);
1487 }
1488
1489 let target = match root {
1492 Some(r) => r.join(&hit.file),
1493 None => PathBuf::from(&hit.file),
1494 };
1495 launch_editor(&target, hit.line)
1496}
1497
1498fn launch_editor(file: &std::path::Path, line: i64) -> ExitCode {
1502 use std::os::unix::process::CommandExt;
1503 let loc = format!("{}:{}", file.display(), line);
1504 match open_command(file, line, &loc) {
1505 Some((prog, args)) => {
1506 crate::profile::emit(false);
1508 let err = std::process::Command::new(&prog).args(&args).exec();
1510 fail(format_args!("rq --open: cannot run {prog}: {err}"))
1511 }
1512 None => {
1513 println!("{loc}");
1514 ExitCode::SUCCESS
1515 }
1516 }
1517}
1518
1519fn open_command(file: &std::path::Path, line: i64, loc: &str) -> Option<(String, Vec<String>)> {
1523 let fstr = file.to_string_lossy().into_owned();
1524
1525 if let Some(t) = std::env::var_os("RQ_OPEN") {
1526 let t = t.to_string_lossy();
1527 let mut parts = t.split_whitespace().map(|p| {
1528 p.replace("{file}", &fstr)
1529 .replace("{line}", &line.to_string())
1530 .replace("{}", loc)
1531 });
1532 if let Some(prog) = parts.next() {
1533 return Some((prog, parts.collect()));
1534 }
1535 }
1536
1537 if on_path("code") {
1538 return Some(("code".into(), vec!["--goto".into(), loc.into()]));
1539 }
1540
1541 if let Some(ed) = std::env::var_os("VISUAL").or_else(|| std::env::var_os("EDITOR")) {
1542 let ed = ed.to_string_lossy().into_owned();
1543 let l = ed.to_ascii_lowercase();
1544 if ["vim", "nvim", "vi", "nano", "emacs", "kak", "micro"]
1546 .iter()
1547 .any(|e| l.contains(e))
1548 {
1549 return Some((ed, vec![format!("+{line}"), fstr]));
1550 }
1551 return Some((ed, vec![fstr]));
1552 }
1553
1554 None
1555}
1556
1557fn open_web(
1562 store: &Store,
1563 hit: &crate::search::Hit,
1564 current: Option<i64>,
1565 root: Option<&std::path::Path>,
1566) -> ExitCode {
1567 if hit.repo_identity.starts_with("local:") {
1568 return fail(format_args!(
1569 "rq --web: {} has no git remote to link to",
1570 hit.repo_identity
1571 ));
1572 }
1573 let here =
1574 current.is_some() && store.repository_id(&hit.repo_identity).ok().flatten() == current;
1575 let rev = root
1576 .filter(|_| here)
1577 .and_then(crate::index::pushed_head)
1578 .unwrap_or_else(|| "HEAD".into());
1579 let url = web_url(&hit.repo_identity, &rev, &hit.file, hit.line);
1580
1581 use std::os::unix::process::CommandExt;
1582 let browser = std::env::var("BROWSER")
1583 .ok()
1584 .filter(|b| !b.is_empty())
1585 .or_else(|| {
1586 ["open", "xdg-open"]
1587 .into_iter()
1588 .find(|p| on_path(p))
1589 .map(str::to_string)
1590 });
1591 match browser {
1592 Some(prog) => {
1593 crate::profile::emit(false);
1595 let err = std::process::Command::new(&prog).arg(&url).exec();
1597 fail(format_args!("rq --web: cannot run {prog}: {err}"))
1598 }
1599 None => {
1600 println!("{url}");
1601 ExitCode::SUCCESS
1602 }
1603 }
1604}
1605
1606fn web_url(identity: &str, rev: &str, file: &str, line: i64) -> String {
1609 let path: String = file
1610 .bytes()
1611 .map(|b| match b {
1612 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1613 (b as char).to_string()
1614 }
1615 _ => format!("%{b:02X}"),
1616 })
1617 .collect();
1618 format!("https://{identity}/blob/{rev}/{path}#L{line}")
1619}
1620
1621fn on_path(prog: &str) -> bool {
1623 std::env::var_os("PATH")
1624 .is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(prog).is_file()))
1625}
1626
1627const BRANCH_FILES_TTL_SECS: i64 = 15;
1633
1634const BRANCH_FILES_TTL_MAX_SECS: i64 = 300;
1638
1639const BRANCH_FILES_WINDOW_MULTIPLE: i64 = 100;
1651
1652fn branch_files_ttl(cost_ms: Option<u64>) -> i64 {
1654 let earned = cost_ms.map_or(0, |ms| {
1657 i64::try_from(ms)
1658 .unwrap_or(i64::MAX)
1659 .saturating_mul(BRANCH_FILES_WINDOW_MULTIPLE)
1660 / 1000
1661 });
1662 earned.clamp(BRANCH_FILES_TTL_SECS, BRANCH_FILES_TTL_MAX_SECS)
1663}
1664
1665struct BranchRefresh {
1669 handle: std::thread::JoinHandle<(Vec<String>, u64)>,
1672 identity: String,
1673 stamp: String,
1674}
1675
1676impl BranchRefresh {
1677 fn store(self, store: &Store) {
1679 let Ok((files, cost_ms)) = self.handle.join() else {
1680 return;
1681 };
1682 let _ = store.branch_files_set(&self.identity, &self.stamp, now_unix(), cost_ms, &files);
1683 }
1684}
1685
1686fn cached_branch_files(
1700 store: &Store,
1701 root: &std::path::Path,
1702) -> (Vec<String>, Option<BranchRefresh>, Option<u64>) {
1703 let identity = resolve_identity(store, root);
1704 let stamp = crate::index::branch_files_stamp(root);
1705 let cached = store.branch_files_get(&identity).ok().flatten();
1706 let now = now_unix();
1707
1708 if let (Some(hit), Some(stamp)) = (&cached, &stamp) {
1709 if &hit.stamp == stamp && now.saturating_sub(hit.written_at) < branch_files_ttl(hit.cost_ms)
1710 {
1711 return (hit.files.clone(), None, hit.cost_ms);
1712 }
1713 let owned_root = root.to_path_buf();
1714 let refresh = BranchRefresh {
1715 handle: std::thread::spawn(move || {
1716 let t = std::time::Instant::now();
1717 let files = crate::index::branch_changed_files(&owned_root);
1718 (files, t.elapsed().as_millis() as u64)
1719 }),
1720 identity,
1721 stamp: stamp.clone(),
1722 };
1723 return (hit.files.clone(), Some(refresh), hit.cost_ms);
1724 }
1725
1726 let t = std::time::Instant::now();
1728 let files = crate::index::branch_changed_files(root);
1729 let cost_ms = t.elapsed().as_millis() as u64;
1730 if let Some(stamp) = stamp {
1731 let _ = store.branch_files_set(&identity, &stamp, now, cost_ms, &files);
1732 }
1733 (files, None, Some(cost_ms))
1734}
1735
1736fn worktree_edits(cwd: &std::path::Path, indexed_head: Option<&str>) -> Option<Vec<String>> {
1746 let head = indexed_head?;
1747 let _span = crate::profile::span("git: worktree changed?");
1748 (crate::index::git_head(cwd).as_deref() == Some(head)).then(|| crate::index::dirty_files(cwd))
1749}
1750
1751fn changed_since_index(
1754 store: &Store,
1755 identity: Option<&str>,
1756 root: Option<&std::path::Path>,
1757 edits: Option<Vec<String>>,
1758) -> bool {
1759 let (Some(dirty), Some(root)) = (edits, root) else {
1760 return true;
1761 };
1762 if dirty.is_empty() {
1763 return false;
1764 }
1765 match identity.and_then(|id| store.repository_id(id).ok().flatten()) {
1766 Some(repo_id) => crate::index::has_unindexed_edits(store, repo_id, root, &dirty),
1767 None => true,
1768 }
1769}
1770
1771enum Staleness {
1775 Running(std::thread::JoinHandle<Option<Vec<String>>>),
1778 Deferred(PathBuf, Option<String>),
1782}
1783
1784#[allow(clippy::too_many_arguments)]
1791fn settle_warm(
1792 store: &Store,
1793 staleness: Option<Staleness>,
1794 hit: bool,
1795 was_warming: bool,
1796 warming_ok: bool,
1797 root: Option<&std::path::Path>,
1798 active: &[String],
1799 query: &str,
1800 budget: Duration,
1801 no_wait: bool,
1802 identity: Option<&str>,
1803) -> bool {
1804 let changed = match staleness {
1805 None => false,
1806 Some(Staleness::Deferred(..)) if hit => {
1809 if let Some(r) = root {
1810 spawn_detached_warm(r);
1811 }
1812 return false;
1813 }
1814 Some(Staleness::Deferred(r, head)) => {
1815 let _span = crate::profile::span("after: staleness check");
1816 changed_since_index(store, identity, root, worktree_edits(&r, head.as_deref()))
1817 }
1818 Some(Staleness::Running(h)) => {
1819 let mut span = crate::profile::span("after: staleness wait");
1821 let changed = h.join().map_or(true, |edits| {
1824 changed_since_index(store, identity, root, edits)
1825 });
1826 span.note(|| if changed { "changed" } else { "unchanged" }.to_string());
1827 changed
1828 }
1829 };
1830 if changed
1840 && !no_wait
1841 && !warm_detach_enabled()
1842 && let Some(r) = root
1843 && let Ok(mut idx) = open_store()
1844 {
1845 crate::trace!("background warm (deferred, {budget:?}): worktree changed since index");
1846 let _ = crate::index::index_budgeted(&mut idx, r, active, budget, Some(query));
1847 }
1848 maybe_detach_warm(
1849 store,
1850 warming_ok && (was_warming || changed),
1851 changed,
1852 root,
1853 identity,
1854 );
1855 changed && warm_detach_enabled()
1859}
1860
1861fn answer_warm_budget() -> Duration {
1870 env_budget("RQ_ANSWER_BUDGET_MS", 500)
1871}
1872
1873fn deferred_warm_budget() -> Duration {
1876 env_budget("RQ_DEFERRED_BUDGET_MS", 250)
1877}
1878
1879fn live_fallback_budget() -> Duration {
1882 env_budget("RQ_FALLBACK_BUDGET_MS", 250)
1883}
1884
1885fn warm_bg_budget() -> Duration {
1888 env_budget("RQ_WARM_BUDGET_MS", 20_000)
1889}
1890
1891fn warm_detach_enabled() -> bool {
1895 std::env::var("RQ_WARM_DETACH").map_or(true, |v| v != "0")
1896}
1897
1898fn wait_budget() -> Duration {
1907 env_budget("RQ_WAIT_BUDGET_MS", 60_000)
1908}
1909
1910fn parse_wait(s: &str) -> std::result::Result<Duration, String> {
1915 let s = s.trim();
1916 let bad = || format!("invalid duration {s:?} — use e.g. 50ms, 2s, 1m, or 0");
1917 let (num, unit_ms) = if let Some(n) = s.strip_suffix("ms") {
1919 (n, 1.0)
1920 } else if let Some(n) = s.strip_suffix('s') {
1921 (n, 1_000.0)
1922 } else if let Some(n) = s.strip_suffix('m') {
1923 (n, 60_000.0)
1924 } else {
1925 (s, 1_000.0)
1927 };
1928 let val: f64 = num.trim().parse().map_err(|_| bad())?;
1929 if !val.is_finite() || val < 0.0 {
1930 return Err(bad());
1931 }
1932 Ok(Duration::from_millis((val * unit_ms).round() as u64))
1933}
1934
1935static INTERRUPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1939
1940extern "C" fn on_sigint(_: libc::c_int) {
1941 INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1943}
1944
1945fn install_interrupt_handler() {
1948 static ONCE: std::sync::Once = std::sync::Once::new();
1949 ONCE.call_once(|| unsafe {
1950 let mut action: libc::sigaction = std::mem::zeroed();
1951 action.sa_sigaction = on_sigint as *const () as usize;
1952 libc::sigemptyset(&mut action.sa_mask);
1953 libc::sigaction(libc::SIGINT, &action, std::ptr::null_mut());
1954 });
1955}
1956
1957fn stderr_interactive() -> bool {
1961 std::io::stderr().is_terminal() || std::env::var_os("RQ_ASSUME_INTERACTIVE").is_some()
1962}
1963
1964fn show_progress(out: Output, interactive: bool) -> bool {
1969 interactive && matches!(out, Output::Text)
1970}
1971
1972fn repo_label(root: Option<&std::path::Path>) -> String {
1975 root.and_then(|r| r.file_name())
1976 .map(|n| n.to_string_lossy().into_owned())
1977 .unwrap_or_else(|| "repo".into())
1978}
1979
1980fn draw_progress(store: &Store, identity: Option<&str>, label: &str) {
1984 let files = identity
1985 .and_then(|id| store.repository_id(id).ok().flatten())
1986 .and_then(|rid| store.repo_totals(rid).ok())
1987 .map_or(0, |(f, _)| f);
1988 eprint!("\r\x1b[Krq: indexing {label}… {files} files");
1989 let _ = std::io::stderr().flush();
1990}
1991
1992fn clear_progress() {
1994 eprint!("\r\x1b[K");
1995 let _ = std::io::stderr().flush();
1996}
1997
1998fn env_budget(var: &str, default_ms: u64) -> Duration {
2002 let ms = std::env::var(var)
2003 .ok()
2004 .and_then(|v| v.parse().ok())
2005 .unwrap_or(default_ms);
2006 Duration::from_millis(ms)
2007}
2008
2009#[derive(Clone, Copy)]
2011struct Here<'a> {
2012 identity: &'a str,
2013 root: &'a std::path::Path,
2014}
2015
2016fn hit_file_roots(store: &Store, repo_identity: &str, here: Option<Here>) -> Vec<PathBuf> {
2022 let mut roots: Vec<PathBuf> = here
2023 .filter(|h| h.identity == repo_identity)
2024 .map(|h| h.root.to_path_buf())
2025 .into_iter()
2026 .collect();
2027 let recorded = store
2028 .repository_id(repo_identity)
2029 .ok()
2030 .flatten()
2031 .map(|id| store.checkout_roots(id).unwrap_or_default())
2032 .unwrap_or_default();
2033 for root in recorded.into_iter().map(PathBuf::from) {
2034 if !roots.contains(&root) {
2035 roots.push(root);
2036 }
2037 }
2038 roots
2039}
2040
2041fn read_signature(
2044 store: &Store,
2045 repo_identity: &str,
2046 file: &str,
2047 line: i64,
2048 here: Option<Here>,
2049) -> Option<String> {
2050 hit_file_roots(store, repo_identity, here)
2051 .into_iter()
2052 .find_map(|root| {
2053 let src = std::fs::read_to_string(root.join(file)).ok()?;
2054 signature_in(&src.lines().collect::<Vec<_>>(), line)
2055 })
2056}
2057
2058const SHOW_CONFIDENCE: f64 = 0.85;
2062
2063fn show_top_definition(
2067 store: &Store,
2068 hits: &mut [crate::search::Hit],
2069 query: &str,
2070 out: Output,
2071 here: Option<Here>,
2072) -> Option<ExitCode> {
2073 let top = hits.first()?;
2074 if top.confidence < SHOW_CONFIDENCE {
2075 return None; }
2077 let end = top.end_line.unwrap_or(top.line);
2078 let body = read_span(store, &top.repo_identity, &top.file, top.line, end, here);
2079 hits[0].body = body;
2080 let top = &hits[0];
2081 let code = match out {
2082 Output::Json | Output::Ndjson => {
2083 emit_json(out, top)
2085 }
2086 Output::Text => {
2087 let color = match_color();
2088 let c = color.as_deref();
2089 let name = hl(&top.name, query, c);
2090 let qualified = match &top.parent {
2091 Some(p) => format!("{name} · {p}"),
2092 None => name,
2093 };
2094 println!(
2095 "{}:{} {} {}",
2096 hl_path(&top.file, query, c),
2097 top.line,
2098 top.kind,
2099 qualified
2100 );
2101 match (&top.body, &top.signature) {
2102 (Some(body), _) => println!("{body}"),
2103 (None, Some(sig)) => println!("{sig}"),
2105 (None, None) => {}
2106 }
2107 ExitCode::SUCCESS
2108 }
2109 };
2110
2111 Some(code)
2112}
2113
2114fn read_span(
2117 store: &Store,
2118 repo_identity: &str,
2119 file: &str,
2120 start: i64,
2121 end: i64,
2122 here: Option<Here>,
2123) -> Option<String> {
2124 hit_file_roots(store, repo_identity, here)
2125 .into_iter()
2126 .find_map(|root| span_in(&std::fs::read_to_string(root.join(file)).ok()?, start, end))
2127}
2128
2129fn span_in(content: &str, start: i64, end: i64) -> Option<String> {
2132 let s = usize::try_from(start).ok()?.checked_sub(1)?;
2133 let lines: Vec<&str> = content.lines().collect();
2134 if s >= lines.len() {
2135 return None;
2136 }
2137 let e = usize::try_from(end).ok()?.clamp(s + 1, lines.len());
2138 Some(lines[s..e].join("\n"))
2139}
2140
2141fn signature_in(lines: &[&str], line: i64) -> Option<String> {
2146 let idx = usize::try_from(line).ok()?.checked_sub(1)?;
2147 let l = lines.get(idx)?.trim();
2148 (!l.is_empty()).then(|| l.to_string())
2149}
2150
2151#[derive(serde::Serialize)]
2155struct SymbolOut {
2156 name: String,
2157 kind: String,
2158 language: String,
2159 file: String,
2160 line: i64,
2161 #[serde(skip_serializing_if = "Option::is_none")]
2162 end_line: Option<i64>,
2163 #[serde(skip_serializing_if = "Option::is_none")]
2164 parent: Option<String>,
2165 #[serde(skip_serializing_if = "Option::is_none")]
2166 visibility: Option<String>,
2167 repo: String,
2168 #[serde(skip_serializing_if = "Option::is_none")]
2169 signature: Option<String>,
2170}
2171
2172fn cmd_symbols(file_arg: &str, kinds: &[String], langs: &[String], out: Output) -> ExitCode {
2177 let open_span = crate::profile::span("store open");
2178 let mut store = match open_store() {
2179 Ok(s) => s,
2180 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2181 };
2182 drop(open_span);
2183 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2184 let root = crate::index::repo_root(&cwd).unwrap_or_else(|| cwd.clone());
2185 let rel = repo_relative(&root, &cwd, file_arg);
2186
2187 let identity = resolve_identity(&store, &root);
2188 let coverage = store.coverage_status(&identity).ok().flatten();
2189 let warming_ok = crate::index::is_git_repo(&root) || coverage.is_some();
2190 let current = store.repository_id(&identity).ok().flatten();
2191 let path = root.join(&rel);
2192 if !path.is_file() {
2194 return emit_symbols(out, &[]);
2195 }
2196 let indexable = path
2197 .extension()
2198 .and_then(|e| e.to_str())
2199 .is_some_and(|e| crate::lang::plugin_for_extension(e).is_some());
2200 match current {
2201 Some(repo_id) if coverage.as_deref() == Some("complete") => {
2205 if indexable {
2206 let _span = crate::profile::span("symbols: refresh");
2207 let _ = crate::index::refresh_file(&mut store, repo_id, &root, &rel);
2208 }
2209 }
2210 _ if warming_ok => {
2213 let budget = answer_warm_budget() + deferred_warm_budget();
2214 let _span = crate::profile::span("symbols: warm");
2215 let _ = crate::index::index_budgeted(&mut store, &root, &[], budget, Some(&rel));
2216 }
2217 _ => {}
2218 }
2219
2220 let Some(repo_id) = store.repository_id(&identity).ok().flatten() else {
2221 return emit_symbols(out, &[]); };
2223 let mut query_span = crate::profile::span("symbols: query");
2224 let mut rows = match store.symbols_in_file(repo_id, &rel) {
2225 Ok(r) => r,
2226 Err(e) => return fail(format_args!("rq: {e}")),
2227 };
2228 query_span.note(|| format!("{} rows", rows.len()));
2229 drop(query_span);
2230 if !kinds.is_empty() {
2231 rows.retain(|r| kinds.iter().any(|k| k == &r.kind));
2232 }
2233 if !langs.is_empty() {
2234 rows.retain(|r| langs.iter().any(|l| l == &r.language));
2235 }
2236
2237 let signatures_span = crate::profile::span("symbols: signatures");
2240 let content = std::fs::read_to_string(&path).ok();
2241 let lines: Vec<&str> = content
2242 .as_deref()
2243 .map_or_else(Vec::new, |c| c.lines().collect());
2244 let syms: Vec<SymbolOut> = rows
2245 .into_iter()
2246 .map(|r| SymbolOut {
2247 signature: signature_in(&lines, r.line),
2248 name: r.name,
2249 kind: r.kind,
2250 language: r.language,
2251 file: r.file,
2252 line: r.line,
2253 end_line: r.end_line,
2254 parent: r.parent,
2255 visibility: r.visibility,
2256 repo: r.repo_identity,
2257 })
2258 .collect();
2259 drop(signatures_span);
2260 let _span = crate::profile::span("render");
2261 emit_symbols(out, &syms)
2262}
2263
2264fn emit_symbols(out: Output, syms: &[SymbolOut]) -> ExitCode {
2267 if syms.is_empty() {
2268 match out {
2269 Output::Json | Output::Ndjson => {
2270 let obj = serde_json::json!({ "status": "no_match" });
2271 let _ = emit_json(out, &obj); }
2273 Output::Text => eprintln!("no symbols"),
2274 }
2275 return ExitCode::FAILURE;
2276 }
2277 if let Some(code) = emit_rows(out, syms) {
2278 return code;
2279 }
2280 match out {
2281 Output::Json | Output::Ndjson => {}
2282 Output::Text => {
2283 for s in syms {
2284 let qualified = match &s.parent {
2285 Some(p) => format!("{} · {p}", s.name),
2286 None => s.name.clone(),
2287 };
2288 println!("{}:{} {} {}", s.file, s.line, s.kind, qualified);
2289 if let Some(sig) = &s.signature {
2290 println!(" {sig}");
2291 }
2292 }
2293 }
2294 }
2295 ExitCode::SUCCESS
2296}
2297
2298fn keyword_kind(token: &str) -> Option<&'static str> {
2303 match token.to_ascii_lowercase().as_str() {
2304 "class" => Some("class"),
2305 "module" => Some("module"),
2306 "method" => Some("method"),
2307 "function" | "fn" => Some("function"),
2308 "struct" | "type" => Some("struct"),
2309 "enum" => Some("enum"),
2310 "trait" | "interface" => Some("trait"),
2311 "constant" | "const" => Some("constant"),
2312 _ => None,
2313 }
2314}
2315
2316fn split_kind_keyword(
2322 target: String,
2323 dirs: Vec<String>,
2324) -> (Option<&'static str>, String, Vec<String>) {
2325 if let Some((head, rest)) = target.split_once(char::is_whitespace) {
2328 let rest = rest.trim();
2329 if let Some(k) = keyword_kind(head)
2330 && !rest.is_empty()
2331 {
2332 return (Some(k), rest.to_string(), dirs);
2333 }
2334 } else if let Some(k) = keyword_kind(&target)
2335 && let Some((query, extra)) = dirs.split_first()
2336 {
2337 return (Some(k), query.clone(), extra.to_vec());
2339 }
2340 (None, target, dirs)
2341}
2342
2343fn canonical_kind(s: &str) -> Option<&'static str> {
2346 Some(match s.to_ascii_lowercase().as_str() {
2347 "c" | "class" => "class",
2348 "m" | "method" => "method",
2349 "f" | "fn" | "func" | "function" => "function",
2350 "mod" | "module" => "module",
2351 "s" | "struct" | "type" => "struct",
2352 "e" | "enum" => "enum",
2353 "t" | "trait" | "interface" => "trait",
2354 "const" | "constant" => "constant",
2355 _ => return None,
2356 })
2357}
2358
2359fn canonical_langs(s: &str) -> Vec<String> {
2366 let t = s.to_ascii_lowercase();
2367 let alias = match t.as_str() {
2368 "rb" => Some("ruby"),
2369 "rs" => Some("rust"),
2370 "golang" => Some("go"),
2371 "ts" | "tsx" => Some("typescript"),
2372 "js" | "jsx" => Some("javascript"),
2373 _ => None,
2374 };
2375 let matched: Vec<String> = crate::lang::languages()
2376 .into_iter()
2377 .filter(|lang| alias == Some(*lang) || lang.starts_with(&t))
2378 .map(str::to_string)
2379 .collect();
2380 matched
2381}
2382
2383fn match_color() -> Option<String> {
2387 if std::env::var_os("NO_COLOR").is_some() || !std::io::stdout().is_terminal() {
2388 return None;
2389 }
2390 let style = std::env::var("GREP_COLORS").ok().and_then(|gc| {
2391 gc.split(':').find_map(|e| {
2392 e.strip_prefix("mt=")
2393 .or_else(|| e.strip_prefix("ms="))
2394 .filter(|v| !v.is_empty())
2395 .map(str::to_string)
2396 })
2397 });
2398 Some(style.unwrap_or_else(|| "1;31".to_string()))
2399}
2400
2401fn hl(text: &str, query: &str, color: Option<&str>) -> String {
2404 match color {
2405 Some(c) => highlight(text, &crate::search::match_positions(query, text), c),
2406 None => text.to_string(),
2407 }
2408}
2409
2410fn hl_path(path: &str, query: &str, color: Option<&str>) -> String {
2413 let Some(c) = color else {
2414 return path.to_string();
2415 };
2416 let base_byte = path.rfind('/').map(|b| b + 1).unwrap_or(0);
2417 let base_start = path[..base_byte].chars().count();
2418 let stem = crate::search::path_stem(path);
2422 let positions: Vec<usize> = crate::search::match_positions(query, stem)
2423 .into_iter()
2424 .map(|p| p + base_start)
2425 .collect();
2426 highlight(path, &positions, c)
2427}
2428
2429fn highlight(text: &str, positions: &[usize], color: &str) -> String {
2432 if positions.is_empty() {
2433 return text.to_string();
2434 }
2435 let matched: std::collections::HashSet<usize> = positions.iter().copied().collect();
2436 let mut out = String::new();
2437 let mut on = false;
2438 for (i, c) in text.chars().enumerate() {
2439 match (matched.contains(&i), on) {
2440 (true, false) => {
2441 out.push_str("\x1b[");
2442 out.push_str(color);
2443 out.push('m');
2444 on = true;
2445 }
2446 (false, true) => {
2447 out.push_str("\x1b[0m");
2448 on = false;
2449 }
2450 _ => {}
2451 }
2452 out.push(c);
2453 }
2454 if on {
2455 out.push_str("\x1b[0m");
2456 }
2457 out
2458}
2459
2460fn under_any(file: &str, paths: &[String]) -> bool {
2464 paths.iter().any(|p| {
2465 let p = p.trim_start_matches("./").trim_end_matches('/');
2466 p.is_empty() || file == p || file.starts_with(&format!("{p}/"))
2467 })
2468}
2469
2470fn repo_relative(root: &std::path::Path, cwd: &std::path::Path, file: &str) -> String {
2472 let p = std::path::Path::new(file);
2473 let abs = if p.is_absolute() {
2474 p.to_path_buf()
2475 } else {
2476 cwd.join(p)
2477 };
2478 let abs = abs.canonicalize().unwrap_or(abs);
2479 abs.strip_prefix(root)
2480 .map(|r| r.to_string_lossy().into_owned())
2481 .unwrap_or_else(|_| file.to_string())
2482}
2483
2484fn revalidate_top(store: &mut Store, hits: &[crate::search::Hit], here: Option<Here>) -> bool {
2489 use std::collections::HashSet;
2490 let mut seen = HashSet::new();
2491 let mut changed = false;
2492 for hit in hits {
2493 if !seen.insert((hit.repo_identity.as_str(), hit.file.as_str())) {
2494 continue;
2495 }
2496 let Some(repo_id) = store.repository_id(&hit.repo_identity).ok().flatten() else {
2497 continue;
2498 };
2499 let roots = hit_file_roots(store, &hit.repo_identity, here);
2500 let Some(root) = roots.iter().find(|r| r.join(&hit.file).is_file()) else {
2501 continue;
2502 };
2503 if let Ok(crate::index::Refresh::Updated) =
2504 crate::index::refresh_file(store, repo_id, root, &hit.file)
2505 {
2506 changed = true;
2507 }
2508 }
2509 changed
2510}
2511
2512fn resolve_identity(store: &Store, cwd: &std::path::Path) -> String {
2518 if let Ok(canon) = cwd.canonicalize() {
2519 if let Ok(Some(identity)) = store.identity_for_root(&canon.to_string_lossy()) {
2520 return identity;
2521 }
2522 if crate::index::repo_root(cwd).is_none() {
2523 return crate::core::RepoIdentity::local(&canon.to_string_lossy()).to_string();
2524 }
2525 }
2526 crate::index::detect_identity(cwd).to_string()
2527}
2528
2529fn cmd_index(path: Option<PathBuf>, subdirs: &[String], out: Output) -> ExitCode {
2530 let explicit = path.is_some();
2531 let target = path.unwrap_or_else(|| PathBuf::from("."));
2532 let root = crate::index::repo_root(&target).unwrap_or_else(|| target.clone());
2537 let mut subdirs = subdirs.to_vec();
2542 if explicit
2543 && let (Ok(t), Ok(r)) = (target.canonicalize(), root.canonicalize())
2544 && t != r
2545 && let Ok(rel) = t.strip_prefix(&r)
2546 && !rel.as_os_str().is_empty()
2547 {
2548 subdirs.push(rel.to_string_lossy().into_owned());
2549 }
2550 let open_span = crate::profile::span("store open");
2551 let mut store = match open_store() {
2552 Ok(s) => s,
2553 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2554 };
2555 drop(open_span);
2556 let indexed = crate::index::index_under(&mut store, &root, &subdirs);
2557 let identity = resolve_identity(&store, &root);
2560 match indexed {
2561 Ok(stats) => {
2562 let subtree = !subdirs.is_empty();
2563 let totals = store
2565 .repository_id(&identity)
2566 .ok()
2567 .flatten()
2568 .and_then(|id| store.repo_totals(id).ok());
2569 match out {
2570 Output::Json | Output::Ndjson => {
2571 let (files, symbols) = match totals {
2572 Some((f, s)) => (Some(f), Some(s)),
2573 None => (None, None),
2574 };
2575 return emit_json(
2576 out,
2577 &serde_json::json!({
2578 "repo": identity,
2579 "scope": if subtree { "subtree" } else { "full" },
2580 "files_added": stats.files_indexed,
2581 "symbols_added": stats.symbols,
2582 "files": files,
2583 "symbols": symbols,
2584 }),
2585 );
2586 }
2587 Output::Text => {
2588 let scope = if subtree { " (subtree seed)" } else { "" };
2589 match totals {
2590 Some((files, symbols)) => println!(
2591 "{} file(s)/{} symbol(s) added this run; index{scope} now {files} files, {symbols} symbols",
2592 stats.files_indexed, stats.symbols
2593 ),
2594 None => println!(
2595 "{} file(s)/{} symbol(s) added this run{scope}",
2596 stats.files_indexed, stats.symbols
2597 ),
2598 }
2599 }
2600 }
2601 ExitCode::SUCCESS
2602 }
2603 Err(e) => fail(format_args!("rq --index: {e}")),
2604 }
2605}
2606
2607fn cmd_drop(target: Option<String>, out: Output) -> ExitCode {
2608 let mut store = match open_store() {
2609 Ok(s) => s,
2610 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2611 };
2612
2613 let path = PathBuf::from(target.clone().unwrap_or_else(|| ".".to_string()));
2617 let root = crate::index::repo_root(&path).unwrap_or(path);
2618 let from_path = crate::index::detect_identity(&root).to_string();
2619 let resolved = match store.repository_id(&from_path) {
2620 Ok(Some(id)) => Some((from_path.clone(), id)),
2621 Ok(None) => target.as_deref().and_then(|s| {
2622 store
2623 .repository_id(s)
2624 .ok()
2625 .flatten()
2626 .map(|id| (s.to_string(), id))
2627 }),
2628 Err(e) => return fail(format_args!("rq --drop: {e}")),
2629 };
2630
2631 let Some((identity, repo_id)) = resolved else {
2632 return match out {
2634 Output::Text => {
2635 println!("not indexed: {from_path}");
2636 ExitCode::SUCCESS
2637 }
2638 _ => emit_json(
2639 out,
2640 &serde_json::json!({"repo": from_path, "files": 0, "symbols": 0, "dropped": false}),
2641 ),
2642 };
2643 };
2644
2645 let (files, symbols) = store.repo_totals(repo_id).unwrap_or((0, 0));
2646 match store.drop_repository(repo_id) {
2647 Ok(()) => match out {
2648 Output::Text => {
2649 println!("dropped {identity} ({files} file(s), {symbols} symbol(s))");
2650 ExitCode::SUCCESS
2651 }
2652 _ => emit_json(
2653 out,
2654 &serde_json::json!({"repo": identity, "files": files, "symbols": symbols, "dropped": true}),
2655 ),
2656 },
2657 Err(e) => fail(format_args!("rq --drop: {e}")),
2658 }
2659}
2660
2661fn emit_json<T: serde::Serialize>(out: Output, value: &T) -> ExitCode {
2665 let rendered = if out == Output::Json {
2666 serde_json::to_string_pretty(value)
2667 } else {
2668 serde_json::to_string(value)
2669 };
2670 match rendered {
2671 Ok(s) => {
2672 println!("{s}");
2673 ExitCode::SUCCESS
2674 }
2675 Err(e) => fail(format_args!("rq: {e}")),
2676 }
2677}
2678
2679fn emit_rows<T: serde::Serialize>(out: Output, rows: &[T]) -> Option<ExitCode> {
2683 match out {
2684 Output::Json => match serde_json::to_string_pretty(rows) {
2685 Ok(s) => println!("{s}"),
2686 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2687 },
2688 Output::Ndjson => {
2689 for r in rows {
2690 match serde_json::to_string(r) {
2691 Ok(line) => println!("{line}"),
2692 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2693 }
2694 }
2695 }
2696 Output::Text => {}
2697 }
2698 None
2699}
2700
2701fn cmd_status(out: Output) -> ExitCode {
2702 let store = match open_store() {
2703 Ok(s) => s,
2704 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2705 };
2706 let rows = match store.coverage_overview() {
2707 Ok(rows) => rows,
2708 Err(e) => return fail(format_args!("rq --status: {e}")),
2709 };
2710 if let Some(code) = emit_rows(out, &rows) {
2711 return code;
2712 }
2713 match out {
2714 Output::Json | Output::Ndjson => {}
2715 Output::Text if rows.is_empty() => {
2716 println!("no repositories indexed yet (try `rq --index`)");
2717 }
2718 Output::Text => {
2719 for r in &rows {
2720 println!(
2721 "{:<10} {:>6} files {:>7} symbols {}",
2722 r.status, r.files, r.symbols, r.identity
2723 );
2724 }
2725 }
2726 }
2727 ExitCode::SUCCESS
2728}
2729
2730fn cmd_usage(out: Output) -> ExitCode {
2733 let store = match open_store() {
2734 Ok(s) => s,
2735 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2736 };
2737 let rows = match store.usage_overview() {
2738 Ok(rows) => rows,
2739 Err(e) => return fail(format_args!("rq --usage: {e}")),
2740 };
2741 if let Some(code) = emit_rows(out, &rows) {
2742 return code;
2743 }
2744 match out {
2745 Output::Json | Output::Ndjson => {}
2746 Output::Text if rows.is_empty() => {
2747 println!("no usage recorded yet");
2748 }
2749 Output::Text => {
2750 println!(
2753 "{:<10} {:<16} {:>6} {:>7} {:>8} flags",
2754 "day", "caller", "found", "missed", "warming"
2755 );
2756 for r in &rows {
2757 let flags = if r.flags.is_empty() { "-" } else { &r.flags };
2758 println!(
2759 "{:<10} {:<16} {:>6} {:>7} {:>8} {}",
2760 r.day,
2761 r.source,
2762 r.searches - r.misses - r.warming,
2763 r.misses,
2764 r.warming,
2765 flags
2766 );
2767 }
2768 let searches: i64 = rows.iter().map(|r| r.searches).sum();
2769 let misses: i64 = rows.iter().map(|r| r.misses).sum();
2770 let warming: i64 = rows.iter().map(|r| r.warming).sum();
2771 let complete: i64 = rows.iter().map(|r| r.on_complete).sum();
2772 let plural = if searches == 1 { "search" } else { "searches" };
2773 println!(
2776 "{searches} {plural} · {misses} missed · {warming} asked too early · {complete} on a complete index"
2777 );
2778 }
2779 }
2780 if rows.is_empty() {
2782 return ExitCode::from(1);
2783 }
2784 ExitCode::SUCCESS
2785}
2786
2787fn open_store() -> Result<Store, Box<dyn std::error::Error>> {
2789 let path = db_path()?;
2790 if let Some(parent) = path.parent() {
2791 std::fs::create_dir_all(parent)?;
2792 }
2793 Ok(Store::open(&path)?)
2794}
2795
2796fn db_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
2798 if let Ok(p) = std::env::var("RQ_DB") {
2799 return Ok(PathBuf::from(p));
2800 }
2801 let home = std::env::var("HOME")?;
2802 Ok(PathBuf::from(home).join(".local/share/rq/rq.db"))
2803}
2804
2805fn fail(args: std::fmt::Arguments) -> ExitCode {
2806 eprintln!("{args}");
2807 ExitCode::FAILURE
2808}
2809
2810#[cfg(test)]
2811mod tests {
2812 use super::*;
2813
2814 #[test]
2815 fn open_menu_choice_parsing() {
2816 assert_eq!(parse_choice("\n", 5), Some(0));
2818 assert_eq!(parse_choice(" ", 5), Some(0));
2819 assert_eq!(parse_choice("3", 5), Some(2));
2820 assert_eq!(parse_choice("5", 5), Some(4));
2821 assert_eq!(parse_choice("6", 5), None);
2823 assert_eq!(parse_choice("0", 5), None);
2824 assert_eq!(parse_choice("q", 5), None);
2825 }
2826
2827 #[test]
2828 fn web_url_shape() {
2829 assert_eq!(
2830 web_url("github.com/org/repo", "abc123", "src/a b#.rs", 42),
2831 "https://github.com/org/repo/blob/abc123/src/a%20b%23.rs#L42"
2832 );
2833 }
2834
2835 #[test]
2836 fn wait_duration_parsing() {
2837 use std::time::Duration;
2838 assert_eq!(parse_wait("50ms"), Ok(Duration::from_millis(50)));
2840 assert_eq!(parse_wait("2s"), Ok(Duration::from_secs(2)));
2841 assert_eq!(parse_wait("1m"), Ok(Duration::from_secs(60)));
2842 assert_eq!(parse_wait("250"), Ok(Duration::from_secs(250)));
2843 assert_eq!(parse_wait("1.5s"), Ok(Duration::from_millis(1500)));
2845 assert_eq!(parse_wait("0"), Ok(Duration::ZERO));
2846 assert!(parse_wait("0s").unwrap().is_zero());
2847 assert_eq!(parse_wait(" 2s "), Ok(Duration::from_secs(2)));
2849 assert!(parse_wait("2x").is_err());
2851 assert!(parse_wait("").is_err());
2852 assert!(parse_wait("s").is_err());
2853 assert!(parse_wait("-1s").is_err());
2854 }
2855
2856 #[test]
2857 fn leading_kind_keyword_becomes_a_kind_filter() {
2858 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2859 assert_eq!(
2861 split_kind_keyword("class".into(), d(&["Widget"])),
2862 (Some("class"), "Widget".into(), vec![])
2863 );
2864 assert_eq!(
2866 split_kind_keyword("method zoom".into(), vec![]),
2867 (Some("method"), "zoom".into(), vec![])
2868 );
2869 assert_eq!(
2871 split_kind_keyword("fn".into(), d(&["Foo::run"])),
2872 (Some("function"), "Foo::run".into(), vec![])
2873 );
2874 assert_eq!(
2876 split_kind_keyword("struct".into(), d(&["Gadget", "src"])),
2877 (Some("struct"), "Gadget".into(), d(&["src"]))
2878 );
2879 }
2880
2881 #[test]
2882 fn a_bare_or_non_keyword_query_is_left_alone() {
2883 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2884 assert_eq!(
2886 split_kind_keyword("class".into(), vec![]),
2887 (None, "class".into(), vec![])
2888 );
2889 assert_eq!(
2891 split_kind_keyword("Widget".into(), d(&["app"])),
2892 (None, "Widget".into(), d(&["app"]))
2893 );
2894 assert_eq!(
2896 split_kind_keyword("c".into(), d(&["Foo"])),
2897 (None, "c".into(), d(&["Foo"]))
2898 );
2899 }
2900
2901 #[test]
2902 fn the_branch_window_scales_with_what_the_refresh_costs() {
2903 assert_eq!(branch_files_ttl(Some(5)), BRANCH_FILES_TTL_SECS);
2906 assert_eq!(branch_files_ttl(Some(150)), BRANCH_FILES_TTL_SECS);
2907 assert_eq!(branch_files_ttl(Some(700)), 70);
2911 assert_eq!(branch_files_ttl(Some(2_000)), 200);
2912 assert_eq!(branch_files_ttl(Some(60_000)), BRANCH_FILES_TTL_MAX_SECS);
2915 assert_eq!(branch_files_ttl(Some(u64::MAX)), BRANCH_FILES_TTL_MAX_SECS);
2916 assert_eq!(branch_files_ttl(None), BRANCH_FILES_TTL_SECS);
2918 }
2919
2920 #[test]
2921 fn a_language_selects_by_prefix_or_alias() {
2922 assert_eq!(canonical_langs("r"), ["ruby", "rust"]);
2924 assert_eq!(canonical_langs("t"), ["typescript"]);
2925 assert_eq!(canonical_langs("ts"), ["typescript"]);
2927 assert_eq!(canonical_langs("jsx"), ["javascript"]);
2928 assert_eq!(canonical_langs("rb"), ["ruby"]);
2929 assert!(canonical_langs("COBOL").is_empty());
2932 }
2933
2934 #[test]
2935 fn a_kind_normalizes_language_specific_spellings() {
2936 assert_eq!(canonical_kind("f"), Some("function"));
2937 assert_eq!(canonical_kind("interface"), Some("trait"));
2939 assert_eq!(canonical_kind("type"), Some("struct"));
2940 assert_eq!(canonical_kind("const"), Some("constant"));
2941 assert_eq!(canonical_kind("banana"), None);
2942 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2944 assert_eq!(
2945 split_kind_keyword("interface".into(), d(&["Renderer"])),
2946 (Some("trait"), "Renderer".into(), vec![])
2947 );
2948 }
2949
2950 #[test]
2951 fn highlight_wraps_matched_runs() {
2952 assert_eq!(
2953 highlight("FooThing", &[0, 1, 2], "1;31"),
2954 "\u{1b}[1;31mFoo\u{1b}[0mThing"
2955 );
2956 assert_eq!(
2958 highlight("FooThing", &[0, 3], "1"),
2959 "\u{1b}[1mF\u{1b}[0moo\u{1b}[1mT\u{1b}[0mhing"
2960 );
2961 assert_eq!(highlight("FooThing", &[], "1;31"), "FooThing");
2963 }
2964
2965 #[test]
2966 fn progress_ui_only_for_an_interactive_text_terminal() {
2967 assert!(show_progress(Output::Text, true));
2969
2970 assert!(!show_progress(Output::Json, true));
2972 assert!(!show_progress(Output::Ndjson, true));
2973
2974 assert!(!show_progress(Output::Text, false));
2976 }
2977
2978 #[test]
2979 fn signature_in_reads_one_based_trimmed_nonblank_lines() {
2980 let lines = ["class Widget", "", " def go"];
2981 assert_eq!(signature_in(&lines, 1).as_deref(), Some("class Widget"));
2982 assert_eq!(signature_in(&lines, 3).as_deref(), Some("def go"));
2983 assert_eq!(signature_in(&lines, 2), None, "blank line");
2984 assert_eq!(signature_in(&lines, 0), None, "lines are 1-based");
2985 assert_eq!(signature_in(&lines, 4), None, "past the end");
2986 }
2987
2988 #[test]
2989 fn repo_label_uses_the_directory_name() {
2990 assert_eq!(
2991 repo_label(Some(std::path::Path::new("/src/widgets"))),
2992 "widgets"
2993 );
2994 assert_eq!(repo_label(None), "repo");
2995 }
2996
2997 #[test]
2998 fn hl_path_highlights_the_stem_not_the_extension() {
2999 let out = hl_path(
3002 "app/employees_controller.rb",
3003 "employeescontroller",
3004 Some("1;31"),
3005 );
3006 assert!(
3007 out.starts_with("app/\u{1b}[1;31memployees"),
3008 "stem highlighted: {out:?}"
3009 );
3010 assert!(
3011 out.ends_with("controller\u{1b}[0m.rb"),
3012 "`.rb` left un-highlighted: {out:?}"
3013 );
3014 }
3015}