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 => {
2214 let budget = answer_warm_budget() + deferred_warm_budget();
2215 let _span = crate::profile::span("symbols: warm");
2216 let active = [rel.clone()];
2217 let _ = crate::index::index_budgeted(&mut store, &root, &active, budget, None);
2218 }
2219 _ => {}
2220 }
2221
2222 let Some(repo_id) = store.repository_id(&identity).ok().flatten() else {
2223 return emit_symbols(out, &[]); };
2225 let mut query_span = crate::profile::span("symbols: query");
2226 let mut rows = match store.symbols_in_file(repo_id, &rel) {
2227 Ok(r) => r,
2228 Err(e) => return fail(format_args!("rq: {e}")),
2229 };
2230 query_span.note(|| format!("{} rows", rows.len()));
2231 drop(query_span);
2232 if !kinds.is_empty() {
2233 rows.retain(|r| kinds.iter().any(|k| k == &r.kind));
2234 }
2235 if !langs.is_empty() {
2236 rows.retain(|r| langs.iter().any(|l| l == &r.language));
2237 }
2238
2239 let signatures_span = crate::profile::span("symbols: signatures");
2242 let content = std::fs::read_to_string(&path).ok();
2243 let lines: Vec<&str> = content
2244 .as_deref()
2245 .map_or_else(Vec::new, |c| c.lines().collect());
2246 let syms: Vec<SymbolOut> = rows
2247 .into_iter()
2248 .map(|r| SymbolOut {
2249 signature: signature_in(&lines, r.line),
2250 name: r.name,
2251 kind: r.kind,
2252 language: r.language,
2253 file: r.file,
2254 line: r.line,
2255 end_line: r.end_line,
2256 parent: r.parent,
2257 visibility: r.visibility,
2258 repo: r.repo_identity,
2259 })
2260 .collect();
2261 drop(signatures_span);
2262 let _span = crate::profile::span("render");
2263 emit_symbols(out, &syms)
2264}
2265
2266fn emit_symbols(out: Output, syms: &[SymbolOut]) -> ExitCode {
2269 if syms.is_empty() {
2270 match out {
2271 Output::Json | Output::Ndjson => {
2272 let obj = serde_json::json!({ "status": "no_match" });
2273 let _ = emit_json(out, &obj); }
2275 Output::Text => eprintln!("no symbols"),
2276 }
2277 return ExitCode::FAILURE;
2278 }
2279 if let Some(code) = emit_rows(out, syms) {
2280 return code;
2281 }
2282 match out {
2283 Output::Json | Output::Ndjson => {}
2284 Output::Text => {
2285 for s in syms {
2286 let qualified = match &s.parent {
2287 Some(p) => format!("{} · {p}", s.name),
2288 None => s.name.clone(),
2289 };
2290 println!("{}:{} {} {}", s.file, s.line, s.kind, qualified);
2291 if let Some(sig) = &s.signature {
2292 println!(" {sig}");
2293 }
2294 }
2295 }
2296 }
2297 ExitCode::SUCCESS
2298}
2299
2300fn keyword_kind(token: &str) -> Option<&'static str> {
2305 match token.to_ascii_lowercase().as_str() {
2306 "class" => Some("class"),
2307 "module" => Some("module"),
2308 "method" => Some("method"),
2309 "function" | "fn" => Some("function"),
2310 "struct" | "type" => Some("struct"),
2311 "enum" => Some("enum"),
2312 "trait" | "interface" => Some("trait"),
2313 "constant" | "const" => Some("constant"),
2314 _ => None,
2315 }
2316}
2317
2318fn split_kind_keyword(
2324 target: String,
2325 dirs: Vec<String>,
2326) -> (Option<&'static str>, String, Vec<String>) {
2327 if let Some((head, rest)) = target.split_once(char::is_whitespace) {
2330 let rest = rest.trim();
2331 if let Some(k) = keyword_kind(head)
2332 && !rest.is_empty()
2333 {
2334 return (Some(k), rest.to_string(), dirs);
2335 }
2336 } else if let Some(k) = keyword_kind(&target)
2337 && let Some((query, extra)) = dirs.split_first()
2338 {
2339 return (Some(k), query.clone(), extra.to_vec());
2341 }
2342 (None, target, dirs)
2343}
2344
2345fn canonical_kind(s: &str) -> Option<&'static str> {
2348 Some(match s.to_ascii_lowercase().as_str() {
2349 "c" | "class" => "class",
2350 "m" | "method" => "method",
2351 "f" | "fn" | "func" | "function" => "function",
2352 "mod" | "module" => "module",
2353 "s" | "struct" | "type" => "struct",
2354 "e" | "enum" => "enum",
2355 "t" | "trait" | "interface" => "trait",
2356 "const" | "constant" => "constant",
2357 _ => return None,
2358 })
2359}
2360
2361fn canonical_langs(s: &str) -> Vec<String> {
2368 let t = s.to_ascii_lowercase();
2369 let alias = match t.as_str() {
2370 "rb" => Some("ruby"),
2371 "rs" => Some("rust"),
2372 "golang" => Some("go"),
2373 "ts" | "tsx" => Some("typescript"),
2374 "js" | "jsx" => Some("javascript"),
2375 _ => None,
2376 };
2377 let matched: Vec<String> = crate::lang::languages()
2378 .into_iter()
2379 .filter(|lang| alias == Some(*lang) || lang.starts_with(&t))
2380 .map(str::to_string)
2381 .collect();
2382 matched
2383}
2384
2385fn match_color() -> Option<String> {
2389 if std::env::var_os("NO_COLOR").is_some() || !std::io::stdout().is_terminal() {
2390 return None;
2391 }
2392 let style = std::env::var("GREP_COLORS").ok().and_then(|gc| {
2393 gc.split(':').find_map(|e| {
2394 e.strip_prefix("mt=")
2395 .or_else(|| e.strip_prefix("ms="))
2396 .filter(|v| !v.is_empty())
2397 .map(str::to_string)
2398 })
2399 });
2400 Some(style.unwrap_or_else(|| "1;31".to_string()))
2401}
2402
2403fn hl(text: &str, query: &str, color: Option<&str>) -> String {
2406 match color {
2407 Some(c) => highlight(text, &crate::search::match_positions(query, text), c),
2408 None => text.to_string(),
2409 }
2410}
2411
2412fn hl_path(path: &str, query: &str, color: Option<&str>) -> String {
2415 let Some(c) = color else {
2416 return path.to_string();
2417 };
2418 let base_byte = path.rfind('/').map(|b| b + 1).unwrap_or(0);
2419 let base_start = path[..base_byte].chars().count();
2420 let stem = crate::search::path_stem(path);
2424 let positions: Vec<usize> = crate::search::match_positions(query, stem)
2425 .into_iter()
2426 .map(|p| p + base_start)
2427 .collect();
2428 highlight(path, &positions, c)
2429}
2430
2431fn highlight(text: &str, positions: &[usize], color: &str) -> String {
2434 if positions.is_empty() {
2435 return text.to_string();
2436 }
2437 let matched: std::collections::HashSet<usize> = positions.iter().copied().collect();
2438 let mut out = String::new();
2439 let mut on = false;
2440 for (i, c) in text.chars().enumerate() {
2441 match (matched.contains(&i), on) {
2442 (true, false) => {
2443 out.push_str("\x1b[");
2444 out.push_str(color);
2445 out.push('m');
2446 on = true;
2447 }
2448 (false, true) => {
2449 out.push_str("\x1b[0m");
2450 on = false;
2451 }
2452 _ => {}
2453 }
2454 out.push(c);
2455 }
2456 if on {
2457 out.push_str("\x1b[0m");
2458 }
2459 out
2460}
2461
2462fn under_any(file: &str, paths: &[String]) -> bool {
2466 paths.iter().any(|p| {
2467 let p = p.trim_start_matches("./").trim_end_matches('/');
2468 p.is_empty() || file == p || file.starts_with(&format!("{p}/"))
2469 })
2470}
2471
2472fn repo_relative(root: &std::path::Path, cwd: &std::path::Path, file: &str) -> String {
2474 let p = std::path::Path::new(file);
2475 let abs = if p.is_absolute() {
2476 p.to_path_buf()
2477 } else {
2478 cwd.join(p)
2479 };
2480 let abs = abs.canonicalize().unwrap_or(abs);
2481 abs.strip_prefix(root)
2482 .map(|r| r.to_string_lossy().into_owned())
2483 .unwrap_or_else(|_| file.to_string())
2484}
2485
2486fn revalidate_top(store: &mut Store, hits: &[crate::search::Hit], here: Option<Here>) -> bool {
2491 use std::collections::HashSet;
2492 let mut seen = HashSet::new();
2493 let mut changed = false;
2494 for hit in hits {
2495 if !seen.insert((hit.repo_identity.as_str(), hit.file.as_str())) {
2496 continue;
2497 }
2498 let Some(repo_id) = store.repository_id(&hit.repo_identity).ok().flatten() else {
2499 continue;
2500 };
2501 let roots = hit_file_roots(store, &hit.repo_identity, here);
2502 let Some(root) = roots.iter().find(|r| r.join(&hit.file).is_file()) else {
2503 continue;
2504 };
2505 if let Ok(crate::index::Refresh::Updated) =
2506 crate::index::refresh_file(store, repo_id, root, &hit.file)
2507 {
2508 changed = true;
2509 }
2510 }
2511 changed
2512}
2513
2514fn resolve_identity(store: &Store, cwd: &std::path::Path) -> String {
2520 if let Ok(canon) = cwd.canonicalize() {
2521 if let Ok(Some(identity)) = store.identity_for_root(&canon.to_string_lossy()) {
2522 return identity;
2523 }
2524 if crate::index::repo_root(cwd).is_none() {
2525 return crate::core::RepoIdentity::local(&canon.to_string_lossy()).to_string();
2526 }
2527 }
2528 crate::index::detect_identity(cwd).to_string()
2529}
2530
2531fn cmd_index(path: Option<PathBuf>, subdirs: &[String], out: Output) -> ExitCode {
2532 let explicit = path.is_some();
2533 let target = path.unwrap_or_else(|| PathBuf::from("."));
2534 let root = crate::index::repo_root(&target).unwrap_or_else(|| target.clone());
2539 let mut subdirs = subdirs.to_vec();
2544 if explicit
2545 && let (Ok(t), Ok(r)) = (target.canonicalize(), root.canonicalize())
2546 && t != r
2547 && let Ok(rel) = t.strip_prefix(&r)
2548 && !rel.as_os_str().is_empty()
2549 {
2550 subdirs.push(rel.to_string_lossy().into_owned());
2551 }
2552 let open_span = crate::profile::span("store open");
2553 let mut store = match open_store() {
2554 Ok(s) => s,
2555 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2556 };
2557 drop(open_span);
2558 let indexed = crate::index::index_under(&mut store, &root, &subdirs);
2559 let identity = resolve_identity(&store, &root);
2562 match indexed {
2563 Ok(stats) => {
2564 let subtree = !subdirs.is_empty();
2565 let totals = store
2567 .repository_id(&identity)
2568 .ok()
2569 .flatten()
2570 .and_then(|id| store.repo_totals(id).ok());
2571 match out {
2572 Output::Json | Output::Ndjson => {
2573 let (files, symbols) = match totals {
2574 Some((f, s)) => (Some(f), Some(s)),
2575 None => (None, None),
2576 };
2577 return emit_json(
2578 out,
2579 &serde_json::json!({
2580 "repo": identity,
2581 "scope": if subtree { "subtree" } else { "full" },
2582 "files_added": stats.files_indexed,
2583 "symbols_added": stats.symbols,
2584 "files": files,
2585 "symbols": symbols,
2586 }),
2587 );
2588 }
2589 Output::Text => {
2590 let scope = if subtree { " (subtree seed)" } else { "" };
2591 match totals {
2592 Some((files, symbols)) => println!(
2593 "{} file(s)/{} symbol(s) added this run; index{scope} now {files} files, {symbols} symbols",
2594 stats.files_indexed, stats.symbols
2595 ),
2596 None => println!(
2597 "{} file(s)/{} symbol(s) added this run{scope}",
2598 stats.files_indexed, stats.symbols
2599 ),
2600 }
2601 }
2602 }
2603 ExitCode::SUCCESS
2604 }
2605 Err(e) => fail(format_args!("rq --index: {e}")),
2606 }
2607}
2608
2609fn cmd_drop(target: Option<String>, out: Output) -> ExitCode {
2610 let mut store = match open_store() {
2611 Ok(s) => s,
2612 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2613 };
2614
2615 let path = PathBuf::from(target.clone().unwrap_or_else(|| ".".to_string()));
2619 let root = crate::index::repo_root(&path).unwrap_or(path);
2620 let from_path = crate::index::detect_identity(&root).to_string();
2621 let resolved = match store.repository_id(&from_path) {
2622 Ok(Some(id)) => Some((from_path.clone(), id)),
2623 Ok(None) => target.as_deref().and_then(|s| {
2624 store
2625 .repository_id(s)
2626 .ok()
2627 .flatten()
2628 .map(|id| (s.to_string(), id))
2629 }),
2630 Err(e) => return fail(format_args!("rq --drop: {e}")),
2631 };
2632
2633 let Some((identity, repo_id)) = resolved else {
2634 return match out {
2636 Output::Text => {
2637 println!("not indexed: {from_path}");
2638 ExitCode::SUCCESS
2639 }
2640 _ => emit_json(
2641 out,
2642 &serde_json::json!({"repo": from_path, "files": 0, "symbols": 0, "dropped": false}),
2643 ),
2644 };
2645 };
2646
2647 let (files, symbols) = store.repo_totals(repo_id).unwrap_or((0, 0));
2648 match store.drop_repository(repo_id) {
2649 Ok(()) => match out {
2650 Output::Text => {
2651 println!("dropped {identity} ({files} file(s), {symbols} symbol(s))");
2652 ExitCode::SUCCESS
2653 }
2654 _ => emit_json(
2655 out,
2656 &serde_json::json!({"repo": identity, "files": files, "symbols": symbols, "dropped": true}),
2657 ),
2658 },
2659 Err(e) => fail(format_args!("rq --drop: {e}")),
2660 }
2661}
2662
2663fn emit_json<T: serde::Serialize>(out: Output, value: &T) -> ExitCode {
2667 let rendered = if out == Output::Json {
2668 serde_json::to_string_pretty(value)
2669 } else {
2670 serde_json::to_string(value)
2671 };
2672 match rendered {
2673 Ok(s) => {
2674 println!("{s}");
2675 ExitCode::SUCCESS
2676 }
2677 Err(e) => fail(format_args!("rq: {e}")),
2678 }
2679}
2680
2681fn emit_rows<T: serde::Serialize>(out: Output, rows: &[T]) -> Option<ExitCode> {
2685 match out {
2686 Output::Json => match serde_json::to_string_pretty(rows) {
2687 Ok(s) => println!("{s}"),
2688 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2689 },
2690 Output::Ndjson => {
2691 for r in rows {
2692 match serde_json::to_string(r) {
2693 Ok(line) => println!("{line}"),
2694 Err(e) => return Some(fail(format_args!("rq: {e}"))),
2695 }
2696 }
2697 }
2698 Output::Text => {}
2699 }
2700 None
2701}
2702
2703fn cmd_status(out: Output) -> ExitCode {
2704 let store = match open_store() {
2705 Ok(s) => s,
2706 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2707 };
2708 let rows = match store.coverage_overview() {
2709 Ok(rows) => rows,
2710 Err(e) => return fail(format_args!("rq --status: {e}")),
2711 };
2712 if let Some(code) = emit_rows(out, &rows) {
2713 return code;
2714 }
2715 match out {
2716 Output::Json | Output::Ndjson => {}
2717 Output::Text if rows.is_empty() => {
2718 println!("no repositories indexed yet (try `rq --index`)");
2719 }
2720 Output::Text => {
2721 for r in &rows {
2722 println!(
2723 "{:<10} {:>6} files {:>7} symbols {}",
2724 r.status, r.files, r.symbols, r.identity
2725 );
2726 }
2727 }
2728 }
2729 ExitCode::SUCCESS
2730}
2731
2732fn cmd_usage(out: Output) -> ExitCode {
2735 let store = match open_store() {
2736 Ok(s) => s,
2737 Err(e) => return fail(format_args!("rq: cannot open database: {e}")),
2738 };
2739 let rows = match store.usage_overview() {
2740 Ok(rows) => rows,
2741 Err(e) => return fail(format_args!("rq --usage: {e}")),
2742 };
2743 if let Some(code) = emit_rows(out, &rows) {
2744 return code;
2745 }
2746 match out {
2747 Output::Json | Output::Ndjson => {}
2748 Output::Text if rows.is_empty() => {
2749 println!("no usage recorded yet");
2750 }
2751 Output::Text => {
2752 println!(
2755 "{:<10} {:<16} {:>6} {:>7} {:>8} flags",
2756 "day", "caller", "found", "missed", "warming"
2757 );
2758 for r in &rows {
2759 let flags = if r.flags.is_empty() { "-" } else { &r.flags };
2760 println!(
2761 "{:<10} {:<16} {:>6} {:>7} {:>8} {}",
2762 r.day,
2763 r.source,
2764 r.searches - r.misses - r.warming,
2765 r.misses,
2766 r.warming,
2767 flags
2768 );
2769 }
2770 let searches: i64 = rows.iter().map(|r| r.searches).sum();
2771 let misses: i64 = rows.iter().map(|r| r.misses).sum();
2772 let warming: i64 = rows.iter().map(|r| r.warming).sum();
2773 let complete: i64 = rows.iter().map(|r| r.on_complete).sum();
2774 let plural = if searches == 1 { "search" } else { "searches" };
2775 println!(
2778 "{searches} {plural} · {misses} missed · {warming} asked too early · {complete} on a complete index"
2779 );
2780 }
2781 }
2782 if rows.is_empty() {
2784 return ExitCode::from(1);
2785 }
2786 ExitCode::SUCCESS
2787}
2788
2789fn open_store() -> Result<Store, Box<dyn std::error::Error>> {
2791 let path = db_path()?;
2792 if let Some(parent) = path.parent() {
2793 std::fs::create_dir_all(parent)?;
2794 }
2795 Ok(Store::open(&path)?)
2796}
2797
2798fn db_path() -> Result<PathBuf, Box<dyn std::error::Error>> {
2800 if let Ok(p) = std::env::var("RQ_DB") {
2801 return Ok(PathBuf::from(p));
2802 }
2803 let home = std::env::var("HOME")?;
2804 Ok(PathBuf::from(home).join(".local/share/rq/rq.db"))
2805}
2806
2807fn fail(args: std::fmt::Arguments) -> ExitCode {
2808 eprintln!("{args}");
2809 ExitCode::FAILURE
2810}
2811
2812#[cfg(test)]
2813mod tests {
2814 use super::*;
2815
2816 #[test]
2817 fn open_menu_choice_parsing() {
2818 assert_eq!(parse_choice("\n", 5), Some(0));
2820 assert_eq!(parse_choice(" ", 5), Some(0));
2821 assert_eq!(parse_choice("3", 5), Some(2));
2822 assert_eq!(parse_choice("5", 5), Some(4));
2823 assert_eq!(parse_choice("6", 5), None);
2825 assert_eq!(parse_choice("0", 5), None);
2826 assert_eq!(parse_choice("q", 5), None);
2827 }
2828
2829 #[test]
2830 fn web_url_shape() {
2831 assert_eq!(
2832 web_url("github.com/org/repo", "abc123", "src/a b#.rs", 42),
2833 "https://github.com/org/repo/blob/abc123/src/a%20b%23.rs#L42"
2834 );
2835 }
2836
2837 #[test]
2838 fn wait_duration_parsing() {
2839 use std::time::Duration;
2840 assert_eq!(parse_wait("50ms"), Ok(Duration::from_millis(50)));
2842 assert_eq!(parse_wait("2s"), Ok(Duration::from_secs(2)));
2843 assert_eq!(parse_wait("1m"), Ok(Duration::from_secs(60)));
2844 assert_eq!(parse_wait("250"), Ok(Duration::from_secs(250)));
2845 assert_eq!(parse_wait("1.5s"), Ok(Duration::from_millis(1500)));
2847 assert_eq!(parse_wait("0"), Ok(Duration::ZERO));
2848 assert!(parse_wait("0s").unwrap().is_zero());
2849 assert_eq!(parse_wait(" 2s "), Ok(Duration::from_secs(2)));
2851 assert!(parse_wait("2x").is_err());
2853 assert!(parse_wait("").is_err());
2854 assert!(parse_wait("s").is_err());
2855 assert!(parse_wait("-1s").is_err());
2856 }
2857
2858 #[test]
2859 fn leading_kind_keyword_becomes_a_kind_filter() {
2860 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2861 assert_eq!(
2863 split_kind_keyword("class".into(), d(&["Widget"])),
2864 (Some("class"), "Widget".into(), vec![])
2865 );
2866 assert_eq!(
2868 split_kind_keyword("method zoom".into(), vec![]),
2869 (Some("method"), "zoom".into(), vec![])
2870 );
2871 assert_eq!(
2873 split_kind_keyword("fn".into(), d(&["Foo::run"])),
2874 (Some("function"), "Foo::run".into(), vec![])
2875 );
2876 assert_eq!(
2878 split_kind_keyword("struct".into(), d(&["Gadget", "src"])),
2879 (Some("struct"), "Gadget".into(), d(&["src"]))
2880 );
2881 }
2882
2883 #[test]
2884 fn a_bare_or_non_keyword_query_is_left_alone() {
2885 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2886 assert_eq!(
2888 split_kind_keyword("class".into(), vec![]),
2889 (None, "class".into(), vec![])
2890 );
2891 assert_eq!(
2893 split_kind_keyword("Widget".into(), d(&["app"])),
2894 (None, "Widget".into(), d(&["app"]))
2895 );
2896 assert_eq!(
2898 split_kind_keyword("c".into(), d(&["Foo"])),
2899 (None, "c".into(), d(&["Foo"]))
2900 );
2901 }
2902
2903 #[test]
2904 fn the_branch_window_scales_with_what_the_refresh_costs() {
2905 assert_eq!(branch_files_ttl(Some(5)), BRANCH_FILES_TTL_SECS);
2908 assert_eq!(branch_files_ttl(Some(150)), BRANCH_FILES_TTL_SECS);
2909 assert_eq!(branch_files_ttl(Some(700)), 70);
2913 assert_eq!(branch_files_ttl(Some(2_000)), 200);
2914 assert_eq!(branch_files_ttl(Some(60_000)), BRANCH_FILES_TTL_MAX_SECS);
2917 assert_eq!(branch_files_ttl(Some(u64::MAX)), BRANCH_FILES_TTL_MAX_SECS);
2918 assert_eq!(branch_files_ttl(None), BRANCH_FILES_TTL_SECS);
2920 }
2921
2922 #[test]
2923 fn a_language_selects_by_prefix_or_alias() {
2924 assert_eq!(canonical_langs("r"), ["ruby", "rust"]);
2926 assert_eq!(canonical_langs("t"), ["typescript"]);
2927 assert_eq!(canonical_langs("ts"), ["typescript"]);
2929 assert_eq!(canonical_langs("jsx"), ["javascript"]);
2930 assert_eq!(canonical_langs("rb"), ["ruby"]);
2931 assert!(canonical_langs("COBOL").is_empty());
2934 }
2935
2936 #[test]
2937 fn a_kind_normalizes_language_specific_spellings() {
2938 assert_eq!(canonical_kind("f"), Some("function"));
2939 assert_eq!(canonical_kind("interface"), Some("trait"));
2941 assert_eq!(canonical_kind("type"), Some("struct"));
2942 assert_eq!(canonical_kind("const"), Some("constant"));
2943 assert_eq!(canonical_kind("banana"), None);
2944 let d = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2946 assert_eq!(
2947 split_kind_keyword("interface".into(), d(&["Renderer"])),
2948 (Some("trait"), "Renderer".into(), vec![])
2949 );
2950 }
2951
2952 #[test]
2953 fn highlight_wraps_matched_runs() {
2954 assert_eq!(
2955 highlight("FooThing", &[0, 1, 2], "1;31"),
2956 "\u{1b}[1;31mFoo\u{1b}[0mThing"
2957 );
2958 assert_eq!(
2960 highlight("FooThing", &[0, 3], "1"),
2961 "\u{1b}[1mF\u{1b}[0moo\u{1b}[1mT\u{1b}[0mhing"
2962 );
2963 assert_eq!(highlight("FooThing", &[], "1;31"), "FooThing");
2965 }
2966
2967 #[test]
2968 fn progress_ui_only_for_an_interactive_text_terminal() {
2969 assert!(show_progress(Output::Text, true));
2971
2972 assert!(!show_progress(Output::Json, true));
2974 assert!(!show_progress(Output::Ndjson, true));
2975
2976 assert!(!show_progress(Output::Text, false));
2978 }
2979
2980 #[test]
2981 fn signature_in_reads_one_based_trimmed_nonblank_lines() {
2982 let lines = ["class Widget", "", " def go"];
2983 assert_eq!(signature_in(&lines, 1).as_deref(), Some("class Widget"));
2984 assert_eq!(signature_in(&lines, 3).as_deref(), Some("def go"));
2985 assert_eq!(signature_in(&lines, 2), None, "blank line");
2986 assert_eq!(signature_in(&lines, 0), None, "lines are 1-based");
2987 assert_eq!(signature_in(&lines, 4), None, "past the end");
2988 }
2989
2990 #[test]
2991 fn repo_label_uses_the_directory_name() {
2992 assert_eq!(
2993 repo_label(Some(std::path::Path::new("/src/widgets"))),
2994 "widgets"
2995 );
2996 assert_eq!(repo_label(None), "repo");
2997 }
2998
2999 #[test]
3000 fn hl_path_highlights_the_stem_not_the_extension() {
3001 let out = hl_path(
3004 "app/employees_controller.rb",
3005 "employeescontroller",
3006 Some("1;31"),
3007 );
3008 assert!(
3009 out.starts_with("app/\u{1b}[1;31memployees"),
3010 "stem highlighted: {out:?}"
3011 );
3012 assert!(
3013 out.ends_with("controller\u{1b}[0m.rb"),
3014 "`.rb` left un-highlighted: {out:?}"
3015 );
3016 }
3017}