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 let elsewhere = crate::search::scope_miss_owner(store, query, current, only_repo, &active);
968 let code = no_match_code(out, query, interrupted, incomplete, elsewhere.as_deref());
969 let _span = crate::profile::span("after: record usage");
973 record_usage(
974 store,
975 args,
976 if incomplete { "warming" } else { "miss" },
977 coverage.as_deref(),
978 );
979 return code;
980 }
981
982 let counted_early = show || open || web;
987 if counted_early {
988 let _span = crate::profile::span("record usage");
989 record_usage(store, args, "hit", coverage.as_deref());
990 }
991
992 attach_confidence(&mut hits);
996 hits.truncate(want);
997 let total = total.max(hits.len());
998 for hit in &mut hits {
999 hit.total = total;
1000 if args.explain {
1001 hit.explain = Some(
1002 hit.features
1003 .iter()
1004 .map(|f| (f.name.to_string(), f.value))
1005 .collect(),
1006 );
1007 }
1008 }
1009
1010 let _signatures_span = crate::profile::span("signatures");
1013 for hit in &mut hits {
1014 hit.signature = read_signature(store, &hit.repo_identity, &hit.file, hit.line, here);
1015 }
1016 drop(_signatures_span);
1017
1018 if show && let Some(code) = show_top_definition(store, &mut hits, query, out, here) {
1021 return code;
1022 }
1023
1024 if open || web {
1029 return finish_open(store, &hits, current, root.as_deref(), web);
1030 }
1031
1032 if let Some(code) = render_hits(args, &hits) {
1033 return code;
1034 }
1035
1036 crate::profile::mark("first answer");
1039
1040 if !counted_early {
1043 let _span = crate::profile::span("after: record usage");
1044 record_usage(store, args, "hit", coverage.as_deref());
1045 }
1046
1047 if let Some(refresh) = branch_refresh.take() {
1054 let _span = crate::profile::span("after: branch refresh");
1055 refresh.store(store);
1056 }
1057
1058 if block {
1063 INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1064 }
1065 if let Some(h) = indexer {
1066 let _ = h.join();
1067 }
1068 let _ = settle_warm(
1069 store,
1070 staleness,
1071 true,
1072 was_warming,
1073 warming_ok,
1074 root.as_deref(),
1075 active_paths,
1076 query,
1077 warm_budget,
1078 no_wait,
1079 identity.as_deref(),
1080 );
1081
1082 ExitCode::SUCCESS
1083}
1084
1085fn maybe_detach_warm(
1088 store: &Store,
1089 want_warm: bool,
1090 changed: bool,
1091 root: Option<&std::path::Path>,
1092 identity: Option<&str>,
1093) {
1094 if !warm_detach_enabled() || !want_warm {
1095 return;
1096 }
1097 let (Some(root), Some(id)) = (root, identity) else {
1098 return;
1099 };
1100 if !changed && store.coverage_status(id).ok().flatten().as_deref() == Some("complete") {
1104 return; }
1106 spawn_detached_warm(root);
1107}
1108
1109fn spawn_detached_warm(root: &std::path::Path) {
1113 use std::os::unix::process::CommandExt;
1114 let Ok(exe) = std::env::current_exe() else {
1115 return;
1116 };
1117 let mut cmd = std::process::Command::new(exe);
1118 cmd.arg("--warm")
1119 .arg(root)
1120 .stdin(std::process::Stdio::null())
1121 .stdout(std::process::Stdio::null())
1122 .stderr(std::process::Stdio::null())
1123 .process_group(0);
1124 match cmd.spawn() {
1125 Ok(child) => crate::trace!(
1126 "background warm (detached): pid {} for {}",
1127 child.id(),
1128 crate::trace::abbrev(root)
1129 ),
1130 Err(e) => crate::trace!("detached warm failed to spawn: {e}"),
1131 }
1132}
1133
1134const WARM_LOCK_TTL_SECS: i64 = 600;
1137
1138fn cmd_warm(path: Option<&str>) -> ExitCode {
1143 #[cfg(target_os = "macos")]
1146 unsafe extern "C" {
1147 fn setiopolicy_np(
1150 iotype: libc::c_int,
1151 scope: libc::c_int,
1152 policy: libc::c_int,
1153 ) -> libc::c_int;
1154 }
1155 unsafe {
1156 libc::nice(10);
1157 #[cfg(target_os = "macos")]
1158 setiopolicy_np(0, 0, 3);
1159 }
1160 let mut store = match open_store() {
1161 Ok(s) => s,
1162 Err(_) => return ExitCode::FAILURE,
1163 };
1164 let start = path
1165 .map(PathBuf::from)
1166 .or_else(|| std::env::current_dir().ok())
1167 .unwrap_or_else(|| PathBuf::from("."));
1168 let root = crate::index::repo_root(&start).unwrap_or(start);
1169 let identity = resolve_identity(&store, &root);
1170
1171 if let Ok(Some((pid, ts))) = store.warm_lock(&identity)
1174 && pid != std::process::id()
1175 && unsafe { libc::kill(pid as libc::pid_t, 0) } == 0
1176 && now_unix() - ts < WARM_LOCK_TTL_SECS
1177 {
1178 return ExitCode::SUCCESS;
1179 }
1180 let _ = store.set_warm_lock(&identity, std::process::id());
1181
1182 if store.coverage_status(&identity).ok().flatten().as_deref() == Some("complete") {
1185 let head = store
1186 .repository_id(&identity)
1187 .ok()
1188 .flatten()
1189 .and_then(|id| store.indexed_head(id).ok().flatten());
1190 let edits = worktree_edits(&root, head.as_deref());
1191 if !changed_since_index(&store, Some(&identity), Some(&root), edits) {
1192 crate::trace!("warm: unchanged since indexed, nothing to do");
1193 let _ = store.clear_warm_lock(&identity);
1194 return ExitCode::SUCCESS;
1195 }
1196 }
1197
1198 let deadline = std::time::Instant::now() + warm_bg_budget();
1201 let active = crate::index::branch_changed_files(&root);
1202 loop {
1203 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1204 if remaining.is_zero() {
1205 break;
1206 }
1207 let stats = match crate::index::index_budgeted(&mut store, &root, &active, remaining, None)
1208 {
1209 Ok(s) => s,
1210 Err(_) => break,
1211 };
1212 if store.coverage_status(&identity).ok().flatten().as_deref() == Some("complete")
1213 || stats.files_indexed == 0
1214 {
1215 break;
1216 }
1217 }
1218 let _ = store.clear_warm_lock(&identity);
1219 ExitCode::SUCCESS
1220}
1221
1222fn live_fallback(root: &std::path::Path, query: &str, limit: usize) -> Vec<crate::search::Hit> {
1225 crate::trace!("empty → live (in-memory) scan of an untracked dir");
1226 let deadline = std::time::Instant::now() + live_fallback_budget();
1227 let h = crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), true);
1228 if !h.is_empty() {
1229 return h;
1230 }
1231 crate::search::live_search(root, query, limit, &HashSet::new(), Some(deadline), false)
1232}
1233
1234fn strong(h: &crate::search::Hit) -> bool {
1236 h.features
1237 .iter()
1238 .any(|f| matches!(f.name, "exact" | "prefix"))
1239}
1240
1241fn apply_gates(query: &str, hits: &mut Vec<crate::search::Hit>) {
1250 if hits.iter().any(strong) {
1251 hits.retain(strong);
1252 }
1253 crate::search::apply_scope_gate(query, hits);
1254}
1255
1256fn apply_post_filters(
1259 args: &SearchArgs,
1260 cwd: Option<&std::path::Path>,
1261 root: Option<&std::path::Path>,
1262 hits: &mut Vec<crate::search::Hit>,
1263) {
1264 if !args.paths.is_empty() {
1265 let here = cwd.map_or_else(|| PathBuf::from("."), PathBuf::from);
1269 let base = root.map_or_else(|| here.clone(), PathBuf::from);
1270 let norm: Vec<String> = args
1271 .paths
1272 .iter()
1273 .map(|p| repo_relative(&base, &here, p))
1274 .collect();
1275 hits.retain(|h| under_any(&h.file, &norm));
1276 }
1277 if !args.kinds.is_empty() {
1278 hits.retain(|h| args.kinds.iter().any(|k| k == &h.kind));
1279 }
1280 if !args.langs.is_empty() {
1281 hits.retain(|h| args.langs.iter().any(|l| l == &h.language));
1282 }
1283 if !args.paths.is_empty() || !args.kinds.is_empty() || !args.langs.is_empty() {
1286 hits.truncate(args.want.max(2));
1287 }
1288}
1289
1290fn no_match_code(
1296 out: Output,
1297 query: &str,
1298 interrupted: bool,
1299 incomplete: bool,
1300 elsewhere: Option<&str>,
1304) -> ExitCode {
1305 let status = if interrupted {
1306 "interrupted"
1307 } else if incomplete {
1308 "warming"
1309 } else if elsewhere.is_some() {
1310 "scope_not_found"
1311 } else {
1312 "no_match"
1313 };
1314 match out {
1315 Output::Json | Output::Ndjson => {
1316 let mut obj = serde_json::json!({ "status": status, "query": query });
1317 if let Some(found_in) = elsewhere {
1318 obj["found_in"] = serde_json::json!(found_in);
1319 }
1320 let _ = emit_json(out, &obj); }
1322 Output::Text if interrupted => {
1323 eprintln!("rq: indexing interrupted — run again to finish")
1324 }
1325 Output::Text if incomplete => eprintln!(
1326 "rq: still indexing — no match for {query:?} yet (run again, or `rq --index` to finish)"
1327 ),
1328 Output::Text if elsewhere.is_some() => eprintln!(
1329 "rq: nothing matching {query:?} — that name is defined under {}",
1330 elsewhere.unwrap_or_default()
1331 ),
1332 Output::Text => eprintln!("no matches for {query:?}"),
1333 }
1334 if incomplete {
1335 ExitCode::from(2)
1336 } else {
1337 ExitCode::FAILURE
1338 }
1339}
1340
1341fn attach_confidence(hits: &mut [crate::search::Hit]) {
1345 let (top, second) = hits.iter().fold((None::<f64>, None::<f64>), |(t, s), h| {
1346 if t.is_none_or(|t| h.score > t) {
1347 (Some(h.score), t)
1348 } else if s.is_none_or(|s| h.score > s) {
1349 (t, Some(h.score))
1350 } else {
1351 (t, s)
1352 }
1353 });
1354 for hit in hits.iter_mut() {
1355 let best_other = if Some(hit.score) == top { second } else { top };
1356 hit.confidence = crate::search::confidence(
1357 hit.score,
1358 crate::search::match_quality(&hit.features),
1359 best_other,
1360 );
1361 }
1362}
1363
1364fn render_hits(args: &SearchArgs, hits: &[crate::search::Hit]) -> Option<ExitCode> {
1367 let render_span = crate::profile::span("render");
1371 if args.batch {
1372 #[derive(serde::Serialize)]
1375 struct Tagged<'a> {
1376 query: &'a str,
1377 #[serde(flatten)]
1378 hit: &'a crate::search::Hit,
1379 }
1380 let rows: Vec<Tagged> = hits
1381 .iter()
1382 .map(|hit| Tagged {
1383 query: args.query,
1384 hit,
1385 })
1386 .collect();
1387 if let Some(code) = emit_rows(args.out, &rows) {
1388 return Some(code);
1389 }
1390 } else if let Some(code) = emit_rows(args.out, hits) {
1391 return Some(code);
1392 }
1393 if args.out != Output::Text {
1394 return None;
1395 }
1396 drop(render_span);
1397 let color = match_color();
1398 let c = color.as_deref();
1399 let query = args.query;
1400 if args.show {
1401 let total = hits.first().map_or(hits.len(), |h| h.total);
1403 eprintln!(
1404 "rq: no single confident match for {query:?} — {} of {total} candidates below; narrow the query to --show one",
1405 hits.len()
1406 );
1407 }
1408 for hit in hits {
1409 let name = hl(&hit.name, query, c);
1412 let qualified = match &hit.parent {
1413 Some(p) => format!("{name} · {p}"),
1414 None => name,
1415 };
1416 println!(
1417 "{}:{} {} {}",
1418 hl_path(&hit.file, query, c),
1419 hit.line,
1420 hit.kind,
1421 qualified
1422 );
1423 if let Some(sig) = &hit.signature {
1424 println!(" {}", hl(sig, query, c));
1425 }
1426 if args.explain {
1427 let parts: Vec<String> = hit
1428 .features
1429 .iter()
1430 .map(|f| format!("{} {:.0}", f.name, f.value))
1431 .collect();
1432 println!(
1433 " confidence {:.2} · score {:.0} = {}",
1434 hit.confidence,
1435 hit.score,
1436 parts.join(" + ")
1437 );
1438 }
1439 }
1440 None
1441}
1442
1443fn choose_hit(hits: &[crate::search::Hit]) -> Option<&crate::search::Hit> {
1447 use std::io::{IsTerminal, Write};
1448 if hits.len() == 1 || !std::io::stdin().is_terminal() || !std::io::stderr().is_terminal() {
1449 return hits.first();
1450 }
1451 let mut err = std::io::stderr();
1452 let _ = writeln!(err, "rq: {} matches — pick one (enter = 1):", hits.len());
1453 for (i, h) in hits.iter().enumerate() {
1454 let _ = writeln!(
1455 err,
1456 " {}. {}:{} {} {}",
1457 i + 1,
1458 h.file,
1459 h.line,
1460 h.kind,
1461 h.name
1462 );
1463 }
1464 let _ = write!(err, "rq> ");
1465 let _ = err.flush();
1466 let mut line = String::new();
1467 if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 {
1468 return None; }
1470 parse_choice(&line, hits.len()).and_then(|i| hits.get(i))
1471}
1472
1473fn parse_choice(input: &str, n: usize) -> Option<usize> {
1476 let s = input.trim();
1477 if s.is_empty() {
1478 return Some(0);
1479 }
1480 let i = s.parse::<usize>().ok()?.checked_sub(1)?;
1481 (i < n).then_some(i)
1482}
1483
1484fn finish_open(
1487 store: &Store,
1488 hits: &[crate::search::Hit],
1489 current: Option<i64>,
1490 root: Option<&std::path::Path>,
1491 web: bool,
1492) -> ExitCode {
1493 let Some(hit) = choose_hit(hits) else {
1494 return ExitCode::SUCCESS; };
1496
1497 if web {
1498 return open_web(store, hit, current, root);
1499 }
1500
1501 let target = match root {
1504 Some(r) => r.join(&hit.file),
1505 None => PathBuf::from(&hit.file),
1506 };
1507 launch_editor(&target, hit.line)
1508}
1509
1510fn launch_editor(file: &std::path::Path, line: i64) -> ExitCode {
1514 use std::os::unix::process::CommandExt;
1515 let loc = format!("{}:{}", file.display(), line);
1516 match open_command(file, line, &loc) {
1517 Some((prog, args)) => {
1518 crate::profile::emit(false);
1520 let err = std::process::Command::new(&prog).args(&args).exec();
1522 fail(format_args!("rq --open: cannot run {prog}: {err}"))
1523 }
1524 None => {
1525 println!("{loc}");
1526 ExitCode::SUCCESS
1527 }
1528 }
1529}
1530
1531fn open_command(file: &std::path::Path, line: i64, loc: &str) -> Option<(String, Vec<String>)> {
1535 let fstr = file.to_string_lossy().into_owned();
1536
1537 if let Some(t) = std::env::var_os("RQ_OPEN") {
1538 let t = t.to_string_lossy();
1539 let mut parts = t.split_whitespace().map(|p| {
1540 p.replace("{file}", &fstr)
1541 .replace("{line}", &line.to_string())
1542 .replace("{}", loc)
1543 });
1544 if let Some(prog) = parts.next() {
1545 return Some((prog, parts.collect()));
1546 }
1547 }
1548
1549 if on_path("code") {
1550 return Some(("code".into(), vec!["--goto".into(), loc.into()]));
1551 }
1552
1553 if let Some(ed) = std::env::var_os("VISUAL").or_else(|| std::env::var_os("EDITOR")) {
1554 let ed = ed.to_string_lossy().into_owned();
1555 let l = ed.to_ascii_lowercase();
1556 if ["vim", "nvim", "vi", "nano", "emacs", "kak", "micro"]
1558 .iter()
1559 .any(|e| l.contains(e))
1560 {
1561 return Some((ed, vec![format!("+{line}"), fstr]));
1562 }
1563 return Some((ed, vec![fstr]));
1564 }
1565
1566 None
1567}
1568
1569fn open_web(
1574 store: &Store,
1575 hit: &crate::search::Hit,
1576 current: Option<i64>,
1577 root: Option<&std::path::Path>,
1578) -> ExitCode {
1579 if hit.repo_identity.starts_with("local:") {
1580 return fail(format_args!(
1581 "rq --web: {} has no git remote to link to",
1582 hit.repo_identity
1583 ));
1584 }
1585 let here =
1586 current.is_some() && store.repository_id(&hit.repo_identity).ok().flatten() == current;
1587 let rev = root
1588 .filter(|_| here)
1589 .and_then(crate::index::pushed_head)
1590 .unwrap_or_else(|| "HEAD".into());
1591 let url = web_url(&hit.repo_identity, &rev, &hit.file, hit.line);
1592
1593 use std::os::unix::process::CommandExt;
1594 let browser = std::env::var("BROWSER")
1595 .ok()
1596 .filter(|b| !b.is_empty())
1597 .or_else(|| {
1598 ["open", "xdg-open"]
1599 .into_iter()
1600 .find(|p| on_path(p))
1601 .map(str::to_string)
1602 });
1603 match browser {
1604 Some(prog) => {
1605 crate::profile::emit(false);
1607 let err = std::process::Command::new(&prog).arg(&url).exec();
1609 fail(format_args!("rq --web: cannot run {prog}: {err}"))
1610 }
1611 None => {
1612 println!("{url}");
1613 ExitCode::SUCCESS
1614 }
1615 }
1616}
1617
1618fn web_url(identity: &str, rev: &str, file: &str, line: i64) -> String {
1621 let path: String = file
1622 .bytes()
1623 .map(|b| match b {
1624 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
1625 (b as char).to_string()
1626 }
1627 _ => format!("%{b:02X}"),
1628 })
1629 .collect();
1630 format!("https://{identity}/blob/{rev}/{path}#L{line}")
1631}
1632
1633fn on_path(prog: &str) -> bool {
1635 std::env::var_os("PATH")
1636 .is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(prog).is_file()))
1637}
1638
1639const BRANCH_FILES_TTL_SECS: i64 = 15;
1645
1646const BRANCH_FILES_TTL_MAX_SECS: i64 = 300;
1650
1651const BRANCH_FILES_WINDOW_MULTIPLE: i64 = 100;
1663
1664fn branch_files_ttl(cost_ms: Option<u64>) -> i64 {
1666 let earned = cost_ms.map_or(0, |ms| {
1669 i64::try_from(ms)
1670 .unwrap_or(i64::MAX)
1671 .saturating_mul(BRANCH_FILES_WINDOW_MULTIPLE)
1672 / 1000
1673 });
1674 earned.clamp(BRANCH_FILES_TTL_SECS, BRANCH_FILES_TTL_MAX_SECS)
1675}
1676
1677struct BranchRefresh {
1681 handle: std::thread::JoinHandle<(Vec<String>, u64)>,
1684 identity: String,
1685 stamp: String,
1686}
1687
1688impl BranchRefresh {
1689 fn store(self, store: &Store) {
1691 let Ok((files, cost_ms)) = self.handle.join() else {
1692 return;
1693 };
1694 let _ = store.branch_files_set(&self.identity, &self.stamp, now_unix(), cost_ms, &files);
1695 }
1696}
1697
1698fn cached_branch_files(
1712 store: &Store,
1713 root: &std::path::Path,
1714) -> (Vec<String>, Option<BranchRefresh>, Option<u64>) {
1715 let identity = resolve_identity(store, root);
1716 let stamp = crate::index::branch_files_stamp(root);
1717 let cached = store.branch_files_get(&identity).ok().flatten();
1718 let now = now_unix();
1719
1720 if let (Some(hit), Some(stamp)) = (&cached, &stamp) {
1721 if &hit.stamp == stamp && now.saturating_sub(hit.written_at) < branch_files_ttl(hit.cost_ms)
1722 {
1723 return (hit.files.clone(), None, hit.cost_ms);
1724 }
1725 let owned_root = root.to_path_buf();
1726 let refresh = BranchRefresh {
1727 handle: std::thread::spawn(move || {
1728 let t = std::time::Instant::now();
1729 let files = crate::index::branch_changed_files(&owned_root);
1730 (files, t.elapsed().as_millis() as u64)
1731 }),
1732 identity,
1733 stamp: stamp.clone(),
1734 };
1735 return (hit.files.clone(), Some(refresh), hit.cost_ms);
1736 }
1737
1738 let t = std::time::Instant::now();
1740 let files = crate::index::branch_changed_files(root);
1741 let cost_ms = t.elapsed().as_millis() as u64;
1742 if let Some(stamp) = stamp {
1743 let _ = store.branch_files_set(&identity, &stamp, now, cost_ms, &files);
1744 }
1745 (files, None, Some(cost_ms))
1746}
1747
1748fn worktree_edits(cwd: &std::path::Path, indexed_head: Option<&str>) -> Option<Vec<String>> {
1758 let head = indexed_head?;
1759 let _span = crate::profile::span("git: worktree changed?");
1760 (crate::index::git_head(cwd).as_deref() == Some(head)).then(|| crate::index::dirty_files(cwd))
1761}
1762
1763fn changed_since_index(
1766 store: &Store,
1767 identity: Option<&str>,
1768 root: Option<&std::path::Path>,
1769 edits: Option<Vec<String>>,
1770) -> bool {
1771 let (Some(dirty), Some(root)) = (edits, root) else {
1772 return true;
1773 };
1774 if dirty.is_empty() {
1775 return false;
1776 }
1777 match identity.and_then(|id| store.repository_id(id).ok().flatten()) {
1778 Some(repo_id) => crate::index::has_unindexed_edits(store, repo_id, root, &dirty),
1779 None => true,
1780 }
1781}
1782
1783enum Staleness {
1787 Running(std::thread::JoinHandle<Option<Vec<String>>>),
1790 Deferred(PathBuf, Option<String>),
1794}
1795
1796#[allow(clippy::too_many_arguments)]
1803fn settle_warm(
1804 store: &Store,
1805 staleness: Option<Staleness>,
1806 hit: bool,
1807 was_warming: bool,
1808 warming_ok: bool,
1809 root: Option<&std::path::Path>,
1810 active: &[String],
1811 query: &str,
1812 budget: Duration,
1813 no_wait: bool,
1814 identity: Option<&str>,
1815) -> bool {
1816 let changed = match staleness {
1817 None => false,
1818 Some(Staleness::Deferred(..)) if hit => {
1821 if let Some(r) = root {
1822 spawn_detached_warm(r);
1823 }
1824 return false;
1825 }
1826 Some(Staleness::Deferred(r, head)) => {
1827 let _span = crate::profile::span("after: staleness check");
1828 changed_since_index(store, identity, root, worktree_edits(&r, head.as_deref()))
1829 }
1830 Some(Staleness::Running(h)) => {
1831 let mut span = crate::profile::span("after: staleness wait");
1833 let changed = h.join().map_or(true, |edits| {
1836 changed_since_index(store, identity, root, edits)
1837 });
1838 span.note(|| if changed { "changed" } else { "unchanged" }.to_string());
1839 changed
1840 }
1841 };
1842 if changed
1852 && !no_wait
1853 && !warm_detach_enabled()
1854 && let Some(r) = root
1855 && let Ok(mut idx) = open_store()
1856 {
1857 crate::trace!("background warm (deferred, {budget:?}): worktree changed since index");
1858 let _ = crate::index::index_budgeted(&mut idx, r, active, budget, Some(query));
1859 }
1860 maybe_detach_warm(
1861 store,
1862 warming_ok && (was_warming || changed),
1863 changed,
1864 root,
1865 identity,
1866 );
1867 changed && warm_detach_enabled()
1871}
1872
1873fn answer_warm_budget() -> Duration {
1882 env_budget("RQ_ANSWER_BUDGET_MS", 500)
1883}
1884
1885fn deferred_warm_budget() -> Duration {
1888 env_budget("RQ_DEFERRED_BUDGET_MS", 250)
1889}
1890
1891fn live_fallback_budget() -> Duration {
1894 env_budget("RQ_FALLBACK_BUDGET_MS", 250)
1895}
1896
1897fn warm_bg_budget() -> Duration {
1900 env_budget("RQ_WARM_BUDGET_MS", 20_000)
1901}
1902
1903fn warm_detach_enabled() -> bool {
1907 std::env::var("RQ_WARM_DETACH").map_or(true, |v| v != "0")
1908}
1909
1910fn wait_budget() -> Duration {
1919 env_budget("RQ_WAIT_BUDGET_MS", 60_000)
1920}
1921
1922fn parse_wait(s: &str) -> std::result::Result<Duration, String> {
1927 let s = s.trim();
1928 let bad = || format!("invalid duration {s:?} — use e.g. 50ms, 2s, 1m, or 0");
1929 let (num, unit_ms) = if let Some(n) = s.strip_suffix("ms") {
1931 (n, 1.0)
1932 } else if let Some(n) = s.strip_suffix('s') {
1933 (n, 1_000.0)
1934 } else if let Some(n) = s.strip_suffix('m') {
1935 (n, 60_000.0)
1936 } else {
1937 (s, 1_000.0)
1939 };
1940 let val: f64 = num.trim().parse().map_err(|_| bad())?;
1941 if !val.is_finite() || val < 0.0 {
1942 return Err(bad());
1943 }
1944 Ok(Duration::from_millis((val * unit_ms).round() as u64))
1945}
1946
1947static INTERRUPTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1951
1952extern "C" fn on_sigint(_: libc::c_int) {
1953 INTERRUPTED.store(true, std::sync::atomic::Ordering::Relaxed);
1955}
1956
1957fn install_interrupt_handler() {
1960 static ONCE: std::sync::Once = std::sync::Once::new();
1961 ONCE.call_once(|| unsafe {
1962 let mut action: libc::sigaction = std::mem::zeroed();
1963 action.sa_sigaction = on_sigint as *const () as usize;
1964 libc::sigemptyset(&mut action.sa_mask);
1965 libc::sigaction(libc::SIGINT, &action, std::ptr::null_mut());
1966 });
1967}
1968
1969fn stderr_interactive() -> bool {
1973 std::io::stderr().is_terminal() || std::env::var_os("RQ_ASSUME_INTERACTIVE").is_some()
1974}
1975
1976fn show_progress(out: Output, interactive: bool) -> bool {
1981 interactive && matches!(out, Output::Text)
1982}
1983
1984fn repo_label(root: Option<&std::path::Path>) -> String {
1987 root.and_then(|r| r.file_name())
1988 .map(|n| n.to_string_lossy().into_owned())
1989 .unwrap_or_else(|| "repo".into())
1990}
1991
1992fn draw_progress(store: &Store, identity: Option<&str>, label: &str) {
1996 let files = identity
1997 .and_then(|id| store.repository_id(id).ok().flatten())
1998 .and_then(|rid| store.repo_totals(rid).ok())
1999 .map_or(0, |(f, _)| f);
2000 eprint!("\r\x1b[Krq: indexing {label}… {files} files");
2001 let _ = std::io::stderr().flush();
2002}
2003
2004fn clear_progress() {
2006 eprint!("\r\x1b[K");
2007 let _ = std::io::stderr().flush();
2008}
2009
2010fn env_budget(var: &str, default_ms: u64) -> Duration {
2014 let ms = std::env::var(var)
2015 .ok()
2016 .and_then(|v| v.parse().ok())
2017 .unwrap_or(default_ms);
2018 Duration::from_millis(ms)
2019}
2020
2021#[derive(Clone, Copy)]
2023struct Here<'a> {
2024 identity: &'a str,
2025 root: &'a std::path::Path,
2026}
2027
2028fn hit_file_roots(store: &Store, repo_identity: &str, here: Option<Here>) -> Vec<PathBuf> {
2034 let mut roots: Vec<PathBuf> = here
2035 .filter(|h| h.identity == repo_identity)
2036 .map(|h| h.root.to_path_buf())
2037 .into_iter()
2038 .collect();
2039 let recorded = store
2040 .repository_id(repo_identity)
2041 .ok()
2042 .flatten()
2043 .map(|id| store.checkout_roots(id).unwrap_or_default())
2044 .unwrap_or_default();
2045 for root in recorded.into_iter().map(PathBuf::from) {
2046 if !roots.contains(&root) {
2047 roots.push(root);
2048 }
2049 }
2050 roots
2051}
2052
2053fn read_signature(
2056 store: &Store,
2057 repo_identity: &str,
2058 file: &str,
2059 line: i64,
2060 here: Option<Here>,
2061) -> Option<String> {
2062 hit_file_roots(store, repo_identity, here)
2063 .into_iter()
2064 .find_map(|root| {
2065 let src = std::fs::read_to_string(root.join(file)).ok()?;
2066 signature_in(&src.lines().collect::<Vec<_>>(), line)
2067 })
2068}
2069
2070const SHOW_CONFIDENCE: f64 = 0.85;
2074
2075fn show_top_definition(
2079 store: &Store,
2080 hits: &mut [crate::search::Hit],
2081 query: &str,
2082 out: Output,
2083 here: Option<Here>,
2084) -> Option<ExitCode> {
2085 let top = hits.first()?;
2086 if top.confidence < SHOW_CONFIDENCE {
2087 return None; }
2089 let end = top.end_line.unwrap_or(top.line);
2090 let body = read_span(store, &top.repo_identity, &top.file, top.line, end, here);
2091 hits[0].body = body;
2092 let top = &hits[0];
2093 let code = match out {
2094 Output::Json | Output::Ndjson => {
2095 emit_json(out, top)
2097 }
2098 Output::Text => {
2099 let color = match_color();
2100 let c = color.as_deref();
2101 let name = hl(&top.name, query, c);
2102 let qualified = match &top.parent {
2103 Some(p) => format!("{name} · {p}"),
2104 None => name,
2105 };
2106 println!(
2107 "{}:{} {} {}",
2108 hl_path(&top.file, query, c),
2109 top.line,
2110 top.kind,
2111 qualified
2112 );
2113 match (&top.body, &top.signature) {
2114 (Some(body), _) => println!("{body}"),
2115 (None, Some(sig)) => println!("{sig}"),
2117 (None, None) => {}
2118 }
2119 ExitCode::SUCCESS
2120 }
2121 };
2122
2123 Some(code)
2124}
2125
2126fn read_span(
2129 store: &Store,
2130 repo_identity: &str,
2131 file: &str,
2132 start: i64,
2133 end: i64,
2134 here: Option<Here>,
2135) -> Option<String> {
2136 hit_file_roots(store, repo_identity, here)
2137 .into_iter()
2138 .find_map(|root| span_in(&std::fs::read_to_string(root.join(file)).ok()?, start, end))
2139}
2140
2141fn span_in(content: &str, start: i64, end: i64) -> Option<String> {
2144 let s = usize::try_from(start).ok()?.checked_sub(1)?;
2145 let lines: Vec<&str> = content.lines().collect();
2146 if s >= lines.len() {
2147 return None;
2148 }
2149 let e = usize::try_from(end).ok()?.clamp(s + 1, lines.len());
2150 Some(lines[s..e].join("\n"))
2151}
2152
2153fn signature_in(lines: &[&str], line: i64) -> Option<String> {
2158 let idx = usize::try_from(line).ok()?.checked_sub(1)?;
2159 let l = lines.get(idx)?.trim();
2160 (!l.is_empty()).then(|| l.to_string())
2161}
2162
2163#[derive(serde::Serialize)]
2167struct SymbolOut {
2168 name: String,
2169 kind: String,
2170 language: String,
2171 file: String,
2172 line: i64,
2173 #[serde(skip_serializing_if = "Option::is_none")]
2174 end_line: Option<i64>,
2175 #[serde(skip_serializing_if = "Option::is_none")]
2176 parent: Option<String>,
2177 #[serde(skip_serializing_if = "Option::is_none")]
2178 visibility: Option<String>,
2179 repo: String,
2180 #[serde(skip_serializing_if = "Option::is_none")]
2181 signature: Option<String>,
2182}
2183
2184fn cmd_symbols(file_arg: &str, kinds: &[String], langs: &[String], out: Output) -> ExitCode {
2189 let open_span = crate::profile::span("store open");
2190 let mut store = match open_store() {
2191 Ok(s) => s,
2192 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2193 };
2194 drop(open_span);
2195 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
2196 let root = crate::index::repo_root(&cwd).unwrap_or_else(|| cwd.clone());
2197 let rel = repo_relative(&root, &cwd, file_arg);
2198
2199 let identity = resolve_identity(&store, &root);
2200 let coverage = store.coverage_status(&identity).ok().flatten();
2201 let warming_ok = crate::index::is_git_repo(&root) || coverage.is_some();
2202 let current = store.repository_id(&identity).ok().flatten();
2203 let path = root.join(&rel);
2204 if !path.is_file() {
2206 return emit_symbols(out, &[]);
2207 }
2208 let indexable = path
2209 .extension()
2210 .and_then(|e| e.to_str())
2211 .is_some_and(|e| crate::lang::plugin_for_extension(e).is_some());
2212 match current {
2213 Some(repo_id) if coverage.as_deref() == Some("complete") => {
2217 if indexable {
2218 let _span = crate::profile::span("symbols: refresh");
2219 let _ = crate::index::refresh_file(&mut store, repo_id, &root, &rel);
2220 }
2221 }
2222 _ if warming_ok => {
2226 let budget = answer_warm_budget() + deferred_warm_budget();
2227 let _span = crate::profile::span("symbols: warm");
2228 let active = [rel.clone()];
2229 let _ = crate::index::index_budgeted(&mut store, &root, &active, budget, None);
2230 }
2231 _ => {}
2232 }
2233
2234 let Some(repo_id) = store.repository_id(&identity).ok().flatten() else {
2235 return emit_symbols(out, &[]); };
2237 let mut query_span = crate::profile::span("symbols: query");
2238 let mut rows = match store.symbols_in_file(repo_id, &rel) {
2239 Ok(r) => r,
2240 Err(e) => return fail(format_args!("rq: {e}")),
2241 };
2242 query_span.note(|| format!("{} rows", rows.len()));
2243 drop(query_span);
2244 if !kinds.is_empty() {
2245 rows.retain(|r| kinds.iter().any(|k| k == &r.kind));
2246 }
2247 if !langs.is_empty() {
2248 rows.retain(|r| langs.iter().any(|l| l == &r.language));
2249 }
2250
2251 let signatures_span = crate::profile::span("symbols: signatures");
2254 let content = std::fs::read_to_string(&path).ok();
2255 let lines: Vec<&str> = content
2256 .as_deref()
2257 .map_or_else(Vec::new, |c| c.lines().collect());
2258 let syms: Vec<SymbolOut> = rows
2259 .into_iter()
2260 .map(|r| SymbolOut {
2261 signature: signature_in(&lines, r.line),
2262 name: r.name,
2263 kind: r.kind,
2264 language: r.language,
2265 file: r.file,
2266 line: r.line,
2267 end_line: r.end_line,
2268 parent: r.parent,
2269 visibility: r.visibility,
2270 repo: r.repo_identity,
2271 })
2272 .collect();
2273 drop(signatures_span);
2274 let _span = crate::profile::span("render");
2275 emit_symbols(out, &syms)
2276}
2277
2278fn emit_symbols(out: Output, syms: &[SymbolOut]) -> ExitCode {
2281 if syms.is_empty() {
2282 match out {
2283 Output::Json | Output::Ndjson => {
2284 let obj = serde_json::json!({ "status": "no_match" });
2285 let _ = emit_json(out, &obj); }
2287 Output::Text => eprintln!("no symbols"),
2288 }
2289 return ExitCode::FAILURE;
2290 }
2291 if let Some(code) = emit_rows(out, syms) {
2292 return code;
2293 }
2294 match out {
2295 Output::Json | Output::Ndjson => {}
2296 Output::Text => {
2297 for s in syms {
2298 let qualified = match &s.parent {
2299 Some(p) => format!("{} · {p}", s.name),
2300 None => s.name.clone(),
2301 };
2302 println!("{}:{} {} {}", s.file, s.line, s.kind, qualified);
2303 if let Some(sig) = &s.signature {
2304 println!(" {sig}");
2305 }
2306 }
2307 }
2308 }
2309 ExitCode::SUCCESS
2310}
2311
2312fn keyword_kind(token: &str) -> Option<&'static str> {
2317 match token.to_ascii_lowercase().as_str() {
2318 "class" => Some("class"),
2319 "module" => Some("module"),
2320 "method" => Some("method"),
2321 "function" | "fn" => Some("function"),
2322 "struct" | "type" => Some("struct"),
2323 "enum" => Some("enum"),
2324 "trait" | "interface" => Some("trait"),
2325 "constant" | "const" => Some("constant"),
2326 _ => None,
2327 }
2328}
2329
2330fn split_kind_keyword(
2336 target: String,
2337 dirs: Vec<String>,
2338) -> (Option<&'static str>, String, Vec<String>) {
2339 if let Some((head, rest)) = target.split_once(char::is_whitespace) {
2342 let rest = rest.trim();
2343 if let Some(k) = keyword_kind(head)
2344 && !rest.is_empty()
2345 {
2346 return (Some(k), rest.to_string(), dirs);
2347 }
2348 } else if let Some(k) = keyword_kind(&target)
2349 && let Some((query, extra)) = dirs.split_first()
2350 {
2351 return (Some(k), query.clone(), extra.to_vec());
2353 }
2354 (None, target, dirs)
2355}
2356
2357fn canonical_kind(s: &str) -> Option<&'static str> {
2360 Some(match s.to_ascii_lowercase().as_str() {
2361 "c" | "class" => "class",
2362 "m" | "method" => "method",
2363 "f" | "fn" | "func" | "function" => "function",
2364 "mod" | "module" => "module",
2365 "s" | "struct" | "type" => "struct",
2366 "e" | "enum" => "enum",
2367 "t" | "trait" | "interface" => "trait",
2368 "const" | "constant" => "constant",
2369 _ => return None,
2370 })
2371}
2372
2373fn canonical_langs(s: &str) -> Vec<String> {
2380 let t = s.to_ascii_lowercase();
2381 let alias = match t.as_str() {
2382 "rb" => Some("ruby"),
2383 "rs" => Some("rust"),
2384 "golang" => Some("go"),
2385 "ts" | "tsx" => Some("typescript"),
2386 "js" | "jsx" => Some("javascript"),
2387 _ => None,
2388 };
2389 let matched: Vec<String> = crate::lang::languages()
2390 .into_iter()
2391 .filter(|lang| alias == Some(*lang) || lang.starts_with(&t))
2392 .map(str::to_string)
2393 .collect();
2394 matched
2395}
2396
2397fn match_color() -> Option<String> {
2401 if std::env::var_os("NO_COLOR").is_some() || !std::io::stdout().is_terminal() {
2402 return None;
2403 }
2404 let style = std::env::var("GREP_COLORS").ok().and_then(|gc| {
2405 gc.split(':').find_map(|e| {
2406 e.strip_prefix("mt=")
2407 .or_else(|| e.strip_prefix("ms="))
2408 .filter(|v| !v.is_empty())
2409 .map(str::to_string)
2410 })
2411 });
2412 Some(style.unwrap_or_else(|| "1;31".to_string()))
2413}
2414
2415fn hl(text: &str, query: &str, color: Option<&str>) -> String {
2418 match color {
2419 Some(c) => highlight(text, &crate::search::match_positions(query, text), c),
2420 None => text.to_string(),
2421 }
2422}
2423
2424fn hl_path(path: &str, query: &str, color: Option<&str>) -> String {
2427 let Some(c) = color else {
2428 return path.to_string();
2429 };
2430 let base_byte = path.rfind('/').map(|b| b + 1).unwrap_or(0);
2431 let base_start = path[..base_byte].chars().count();
2432 let stem = crate::search::path_stem(path);
2436 let positions: Vec<usize> = crate::search::match_positions(query, stem)
2437 .into_iter()
2438 .map(|p| p + base_start)
2439 .collect();
2440 highlight(path, &positions, c)
2441}
2442
2443fn highlight(text: &str, positions: &[usize], color: &str) -> String {
2446 if positions.is_empty() {
2447 return text.to_string();
2448 }
2449 let matched: std::collections::HashSet<usize> = positions.iter().copied().collect();
2450 let mut out = String::new();
2451 let mut on = false;
2452 for (i, c) in text.chars().enumerate() {
2453 match (matched.contains(&i), on) {
2454 (true, false) => {
2455 out.push_str("\x1b[");
2456 out.push_str(color);
2457 out.push('m');
2458 on = true;
2459 }
2460 (false, true) => {
2461 out.push_str("\x1b[0m");
2462 on = false;
2463 }
2464 _ => {}
2465 }
2466 out.push(c);
2467 }
2468 if on {
2469 out.push_str("\x1b[0m");
2470 }
2471 out
2472}
2473
2474fn under_any(file: &str, paths: &[String]) -> bool {
2478 paths.iter().any(|p| {
2479 let p = p.trim_start_matches("./").trim_end_matches('/');
2480 p.is_empty() || file == p || file.starts_with(&format!("{p}/"))
2481 })
2482}
2483
2484fn repo_relative(root: &std::path::Path, cwd: &std::path::Path, file: &str) -> String {
2486 let p = std::path::Path::new(file);
2487 let abs = if p.is_absolute() {
2488 p.to_path_buf()
2489 } else {
2490 cwd.join(p)
2491 };
2492 let abs = abs.canonicalize().unwrap_or(abs);
2493 abs.strip_prefix(root)
2494 .map(|r| r.to_string_lossy().into_owned())
2495 .unwrap_or_else(|_| file.to_string())
2496}
2497
2498fn revalidate_top(store: &mut Store, hits: &[crate::search::Hit], here: Option<Here>) -> bool {
2503 use std::collections::HashSet;
2504 let mut seen = HashSet::new();
2505 let mut changed = false;
2506 for hit in hits {
2507 if !seen.insert((hit.repo_identity.as_str(), hit.file.as_str())) {
2508 continue;
2509 }
2510 let Some(repo_id) = store.repository_id(&hit.repo_identity).ok().flatten() else {
2511 continue;
2512 };
2513 let roots = hit_file_roots(store, &hit.repo_identity, here);
2514 let Some(root) = roots.iter().find(|r| r.join(&hit.file).is_file()) else {
2515 continue;
2516 };
2517 if let Ok(crate::index::Refresh::Updated) =
2518 crate::index::refresh_file(store, repo_id, root, &hit.file)
2519 {
2520 changed = true;
2521 }
2522 }
2523 changed
2524}
2525
2526fn resolve_identity(store: &Store, cwd: &std::path::Path) -> String {
2532 if let Ok(canon) = cwd.canonicalize() {
2533 if let Ok(Some(identity)) = store.identity_for_root(&canon.to_string_lossy()) {
2534 return identity;
2535 }
2536 if crate::index::repo_root(cwd).is_none() {
2537 return crate::core::RepoIdentity::local(&canon.to_string_lossy()).to_string();
2538 }
2539 }
2540 crate::index::detect_identity(cwd).to_string()
2541}
2542
2543fn cmd_index(path: Option<PathBuf>, subdirs: &[String], out: Output) -> ExitCode {
2544 let explicit = path.is_some();
2545 let target = path.unwrap_or_else(|| PathBuf::from("."));
2546 let root = crate::index::repo_root(&target).unwrap_or_else(|| target.clone());
2551 let mut subdirs = subdirs.to_vec();
2556 if explicit
2557 && let (Ok(t), Ok(r)) = (target.canonicalize(), root.canonicalize())
2558 && t != r
2559 && let Ok(rel) = t.strip_prefix(&r)
2560 && !rel.as_os_str().is_empty()
2561 {
2562 subdirs.push(rel.to_string_lossy().into_owned());
2563 }
2564 let open_span = crate::profile::span("store open");
2565 let mut store = match open_store() {
2566 Ok(s) => s,
2567 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2568 };
2569 drop(open_span);
2570 let indexed = crate::index::index_under(&mut store, &root, &subdirs);
2571 let identity = resolve_identity(&store, &root);
2574 match indexed {
2575 Ok(stats) => {
2576 let subtree = !subdirs.is_empty();
2577 let totals = store
2579 .repository_id(&identity)
2580 .ok()
2581 .flatten()
2582 .and_then(|id| store.repo_totals(id).ok());
2583 match out {
2584 Output::Json | Output::Ndjson => {
2585 let (files, symbols) = match totals {
2586 Some((f, s)) => (Some(f), Some(s)),
2587 None => (None, None),
2588 };
2589 return emit_json(
2590 out,
2591 &serde_json::json!({
2592 "repo": identity,
2593 "scope": if subtree { "subtree" } else { "full" },
2594 "files_added": stats.files_indexed,
2595 "symbols_added": stats.symbols,
2596 "files": files,
2597 "symbols": symbols,
2598 }),
2599 );
2600 }
2601 Output::Text => {
2602 let scope = if subtree { " (subtree seed)" } else { "" };
2603 match totals {
2604 Some((files, symbols)) => println!(
2605 "{} file(s)/{} symbol(s) added this run; index{scope} now {files} files, {symbols} symbols",
2606 stats.files_indexed, stats.symbols
2607 ),
2608 None => println!(
2609 "{} file(s)/{} symbol(s) added this run{scope}",
2610 stats.files_indexed, stats.symbols
2611 ),
2612 }
2613 }
2614 }
2615 ExitCode::SUCCESS
2616 }
2617 Err(e) => fail(format_args!("rq --index: {e}")),
2618 }
2619}
2620
2621fn cmd_drop(target: Option<String>, out: Output) -> ExitCode {
2622 let mut store = match open_store() {
2623 Ok(s) => s,
2624 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2625 };
2626
2627 let path = PathBuf::from(target.clone().unwrap_or_else(|| ".".to_string()));
2631 let root = crate::index::repo_root(&path).unwrap_or(path);
2632 let from_path = crate::index::detect_identity(&root).to_string();
2633 let resolved = match store.repository_id(&from_path) {
2634 Ok(Some(id)) => Some((from_path.clone(), id)),
2635 Ok(None) => target.as_deref().and_then(|s| {
2636 store
2637 .repository_id(s)
2638 .ok()
2639 .flatten()
2640 .map(|id| (s.to_string(), id))
2641 }),
2642 Err(e) => return fail(format_args!("rq --drop: {e}")),
2643 };
2644
2645 let Some((identity, repo_id)) = resolved else {
2646 return match out {
2648 Output::Text => {
2649 println!("not indexed: {from_path}");
2650 ExitCode::SUCCESS
2651 }
2652 _ => emit_json(
2653 out,
2654 &serde_json::json!({"repo": from_path, "files": 0, "symbols": 0, "dropped": false}),
2655 ),
2656 };
2657 };
2658
2659 let (files, symbols) = store.repo_totals(repo_id).unwrap_or((0, 0));
2660 match store.drop_repository(repo_id) {
2661 Ok(()) => match out {
2662 Output::Text => {
2663 println!("dropped {identity} ({files} file(s), {symbols} symbol(s))");
2664 ExitCode::SUCCESS
2665 }
2666 _ => emit_json(
2667 out,
2668 &serde_json::json!({"repo": identity, "files": files, "symbols": symbols, "dropped": true}),
2669 ),
2670 },
2671 Err(e) => fail(format_args!("rq --drop: {e}")),
2672 }
2673}
2674
2675fn emit_json<T: serde::Serialize>(out: Output, value: &T) -> ExitCode {
2679 let rendered = if out == Output::Json {
2680 serde_json::to_string_pretty(value)
2681 } else {
2682 serde_json::to_string(value)
2683 };
2684 match rendered {
2685 Ok(s) => {
2686 println!("{s}");
2687 ExitCode::SUCCESS
2688 }
2689 Err(e) => fail(format_args!("rq: {e}")),
2690 }
2691}
2692
2693fn emit_rows<T: serde::Serialize>(out: Output, rows: &[T]) -> Option<ExitCode> {
2697 match out {
2698 Output::Json => match serde_json::to_string_pretty(rows) {
2699 Ok(s) => println!("{s}"),
2700 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2701 },
2702 Output::Ndjson => {
2703 for r in rows {
2704 match serde_json::to_string(r) {
2705 Ok(line) => println!("{line}"),
2706 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2707 }
2708 }
2709 }
2710 Output::Text => {}
2711 }
2712 None
2713}
2714
2715fn cmd_status(out: Output) -> ExitCode {
2716 let store = match open_store() {
2717 Ok(s) => s,
2718 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2719 };
2720 let rows = match store.coverage_overview() {
2721 Ok(rows) => rows,
2722 Err(e) => return fail(format_args!("rq --status: {e}")),
2723 };
2724 if let Some(code) = emit_rows(out, &rows) {
2725 return code;
2726 }
2727 match out {
2728 Output::Json | Output::Ndjson => {}
2729 Output::Text if rows.is_empty() => {
2730 println!("no repositories indexed yet (try `rq --index`)");
2731 }
2732 Output::Text => {
2733 for r in &rows {
2734 println!(
2735 "{:<10} {:>6} files {:>7} symbols {}",
2736 r.status, r.files, r.symbols, r.identity
2737 );
2738 }
2739 }
2740 }
2741 ExitCode::SUCCESS
2742}
2743
2744fn cmd_usage(out: Output) -> ExitCode {
2747 let store = match open_store() {
2748 Ok(s) => s,
2749 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2750 };
2751 let rows = match store.usage_overview() {
2752 Ok(rows) => rows,
2753 Err(e) => return fail(format_args!("rq --usage: {e}")),
2754 };
2755 if let Some(code) = emit_rows(out, &rows) {
2756 return code;
2757 }
2758 match out {
2759 Output::Json | Output::Ndjson => {}
2760 Output::Text if rows.is_empty() => {
2761 println!("no usage recorded yet");
2762 }
2763 Output::Text => {
2764 println!(
2767 "{:<10} {:<16} {:>6} {:>7} {:>8} flags",
2768 "day", "caller", "found", "missed", "warming"
2769 );
2770 for r in &rows {
2771 let flags = if r.flags.is_empty() { "-" } else { &r.flags };
2772 println!(
2773 "{:<10} {:<16} {:>6} {:>7} {:>8} {}",
2774 r.day,
2775 r.source,
2776 r.searches - r.misses - r.warming,
2777 r.misses,
2778 r.warming,
2779 flags
2780 );
2781 }
2782 let searches: i64 = rows.iter().map(|r| r.searches).sum();
2783 let misses: i64 = rows.iter().map(|r| r.misses).sum();
2784 let warming: i64 = rows.iter().map(|r| r.warming).sum();
2785 let complete: i64 = rows.iter().map(|r| r.on_complete).sum();
2786 let plural = if searches == 1 { "search" } else { "searches" };
2787 println!(
2790 "{searches} {plural} · {misses} missed · {warming} asked too early · {complete} on a complete index"
2791 );
2792 }
2793 }
2794 if rows.is_empty() {
2796 return ExitCode::from(1);
2797 }
2798 ExitCode::SUCCESS
2799}
2800
2801fn open_store() -> Result<Store, Box<dyn std::error::Error>> {
2803 let path = db_path()?;
2804 if let Some(parent) = path.parent() {
2805 std::fs::create_dir_all(parent)?;
2806 }
2807 Ok(Store::open(&path)?)
2808}
2809
2810fn db_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
2812 if let Ok(p) = std::env::var("RQ_DB") {
2813 return Ok(PathBuf::from(p));
2814 }
2815 let home = std::env::var("HOME")?;
2816 Ok(PathBuf::from(home).join(".local/share/rq/rq.db"))
2817}
2818
2819fn fail(args: std::fmt::Arguments) -> ExitCode {
2820 eprintln!("{args}");
2821 ExitCode::FAILURE
2822}
2823
2824#[cfg(test)]
2825mod tests {
2826 use super::*;
2827
2828 #[test]
2829 fn open_menu_choice_parsing() {
2830 assert_eq!(parse_choice("\n", 5), Some(0));
2832 assert_eq!(parse_choice(" ", 5), Some(0));
2833 assert_eq!(parse_choice("3", 5), Some(2));
2834 assert_eq!(parse_choice("5", 5), Some(4));
2835 assert_eq!(parse_choice("6", 5), None);
2837 assert_eq!(parse_choice("0", 5), None);
2838 assert_eq!(parse_choice("q", 5), None);
2839 }
2840
2841 #[test]
2842 fn web_url_shape() {
2843 assert_eq!(
2844 web_url("github.com/org/repo", "abc123", "src/a b#.rs", 42),
2845 "https://github.com/org/repo/blob/abc123/src/a%20b%23.rs#L42"
2846 );
2847 }
2848
2849 #[test]
2850 fn wait_duration_parsing() {
2851 use std::time::Duration;
2852 assert_eq!(parse_wait("50ms"), Ok(Duration::from_millis(50)));
2854 assert_eq!(parse_wait("2s"), Ok(Duration::from_secs(2)));
2855 assert_eq!(parse_wait("1m"), Ok(Duration::from_secs(60)));
2856 assert_eq!(parse_wait("250"), Ok(Duration::from_secs(250)));
2857 assert_eq!(parse_wait("1.5s"), Ok(Duration::from_millis(1500)));
2859 assert_eq!(parse_wait("0"), Ok(Duration::ZERO));
2860 assert!(parse_wait("0s").unwrap().is_zero());
2861 assert_eq!(parse_wait(" 2s "), Ok(Duration::from_secs(2)));
2863 assert!(parse_wait("2x").is_err());
2865 assert!(parse_wait("").is_err());
2866 assert!(parse_wait("s").is_err());
2867 assert!(parse_wait("-1s").is_err());
2868 }
2869
2870 #[test]
2871 fn leading_kind_keyword_becomes_a_kind_filter() {
2872 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2873 assert_eq!(
2875 split_kind_keyword("class".into(), d(&["Widget"])),
2876 (Some("class"), "Widget".into(), vec![])
2877 );
2878 assert_eq!(
2880 split_kind_keyword("method zoom".into(), vec![]),
2881 (Some("method"), "zoom".into(), vec![])
2882 );
2883 assert_eq!(
2885 split_kind_keyword("fn".into(), d(&["Foo::run"])),
2886 (Some("function"), "Foo::run".into(), vec![])
2887 );
2888 assert_eq!(
2890 split_kind_keyword("struct".into(), d(&["Gadget", "src"])),
2891 (Some("struct"), "Gadget".into(), d(&["src"]))
2892 );
2893 }
2894
2895 #[test]
2896 fn a_bare_or_non_keyword_query_is_left_alone() {
2897 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2898 assert_eq!(
2900 split_kind_keyword("class".into(), vec![]),
2901 (None, "class".into(), vec![])
2902 );
2903 assert_eq!(
2905 split_kind_keyword("Widget".into(), d(&["app"])),
2906 (None, "Widget".into(), d(&["app"]))
2907 );
2908 assert_eq!(
2910 split_kind_keyword("c".into(), d(&["Foo"])),
2911 (None, "c".into(), d(&["Foo"]))
2912 );
2913 }
2914
2915 #[test]
2916 fn the_branch_window_scales_with_what_the_refresh_costs() {
2917 assert_eq!(branch_files_ttl(Some(5)), BRANCH_FILES_TTL_SECS);
2920 assert_eq!(branch_files_ttl(Some(150)), BRANCH_FILES_TTL_SECS);
2921 assert_eq!(branch_files_ttl(Some(700)), 70);
2925 assert_eq!(branch_files_ttl(Some(2_000)), 200);
2926 assert_eq!(branch_files_ttl(Some(60_000)), BRANCH_FILES_TTL_MAX_SECS);
2929 assert_eq!(branch_files_ttl(Some(u64::MAX)), BRANCH_FILES_TTL_MAX_SECS);
2930 assert_eq!(branch_files_ttl(None), BRANCH_FILES_TTL_SECS);
2932 }
2933
2934 #[test]
2935 fn a_language_selects_by_prefix_or_alias() {
2936 assert_eq!(canonical_langs("r"), ["ruby", "rust"]);
2938 assert_eq!(canonical_langs("t"), ["typescript"]);
2939 assert_eq!(canonical_langs("ts"), ["typescript"]);
2941 assert_eq!(canonical_langs("jsx"), ["javascript"]);
2942 assert_eq!(canonical_langs("rb"), ["ruby"]);
2943 assert!(canonical_langs("COBOL").is_empty());
2946 }
2947
2948 #[test]
2949 fn a_kind_normalizes_language_specific_spellings() {
2950 assert_eq!(canonical_kind("f"), Some("function"));
2951 assert_eq!(canonical_kind("interface"), Some("trait"));
2953 assert_eq!(canonical_kind("type"), Some("struct"));
2954 assert_eq!(canonical_kind("const"), Some("constant"));
2955 assert_eq!(canonical_kind("banana"), None);
2956 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2958 assert_eq!(
2959 split_kind_keyword("interface".into(), d(&["Renderer"])),
2960 (Some("trait"), "Renderer".into(), vec![])
2961 );
2962 }
2963
2964 #[test]
2965 fn highlight_wraps_matched_runs() {
2966 assert_eq!(
2967 highlight("FooThing", &[0, 1, 2], "1;31"),
2968 "\u{1b}[1;31mFoo\u{1b}[0mThing"
2969 );
2970 assert_eq!(
2972 highlight("FooThing", &[0, 3], "1"),
2973 "\u{1b}[1mF\u{1b}[0moo\u{1b}[1mT\u{1b}[0mhing"
2974 );
2975 assert_eq!(highlight("FooThing", &[], "1;31"), "FooThing");
2977 }
2978
2979 #[test]
2980 fn progress_ui_only_for_an_interactive_text_terminal() {
2981 assert!(show_progress(Output::Text, true));
2983
2984 assert!(!show_progress(Output::Json, true));
2986 assert!(!show_progress(Output::Ndjson, true));
2987
2988 assert!(!show_progress(Output::Text, false));
2990 }
2991
2992 #[test]
2993 fn signature_in_reads_one_based_trimmed_nonblank_lines() {
2994 let lines = ["class Widget", "", " def go"];
2995 assert_eq!(signature_in(&lines, 1).as_deref(), Some("class Widget"));
2996 assert_eq!(signature_in(&lines, 3).as_deref(), Some("def go"));
2997 assert_eq!(signature_in(&lines, 2), None, "blank line");
2998 assert_eq!(signature_in(&lines, 0), None, "lines are 1-based");
2999 assert_eq!(signature_in(&lines, 4), None, "past the end");
3000 }
3001
3002 #[test]
3003 fn repo_label_uses_the_directory_name() {
3004 assert_eq!(
3005 repo_label(Some(std::path::Path::new("/src/widgets"))),
3006 "widgets"
3007 );
3008 assert_eq!(repo_label(None), "repo");
3009 }
3010
3011 #[test]
3012 fn hl_path_highlights_the_stem_not_the_extension() {
3013 let out = hl_path(
3016 "app/employees_controller.rb",
3017 "employeescontroller",
3018 Some("1;31"),
3019 );
3020 assert!(
3021 out.starts_with("app/\u{1b}[1;31memployees"),
3022 "stem highlighted: {out:?}"
3023 );
3024 assert!(
3025 out.ends_with("controller\u{1b}[0m.rb"),
3026 "`.rb` left un-highlighted: {out:?}"
3027 );
3028 }
3029}