Skip to main content

gqls/
cli.rs

1//! clap CLI, dispatch, and output formatting (text / json / ndjson).
2
3use anyhow::Result;
4use clap::{CommandFactory, Parser};
5use clap_complete::{generate, Shell};
6use serde::Serialize;
7
8use crate::load;
9use crate::model::{Kind, SchemaRecord};
10use crate::search;
11
12/// The semantic-only flags (--semantic, --model, --refresh, --clear-cache) are
13/// hidden from --help on builds without the feature, where they'd only error.
14const HIDE_SEMANTIC: bool = !cfg!(feature = "_semantic");
15
16#[cfg(feature = "_semantic")]
17const EXAMPLES: &str = "\
18EXAMPLES:
19  gqls user schema.graphql            fuzzy search an SDL file
20  gqls createUser -k mutation         restrict to a kind (schema auto-discovered)
21  gqls User.email                     qualified Type.field query
22  gqls repo schema.json               search a local introspection dump
23  gqls repo https://api/graphql       introspect a live endpoint
24  gqls 'cancel a subscription'        rank by meaning (fuzzy + semantic, auto)
25  gqls Query.user -R --code ./app     jump to the graphql-ruby resolver
26  gqls user schema.graphql -j         JSON output (-J for ndjson)
27";
28
29#[cfg(not(feature = "_semantic"))]
30const EXAMPLES: &str = "\
31EXAMPLES:
32  gqls user schema.graphql            fuzzy search an SDL file
33  gqls createUser -k mutation         restrict to a kind (schema auto-discovered)
34  gqls User.email                     qualified Type.field query
35  gqls repo schema.json               search a local introspection dump
36  gqls repo https://api/graphql       introspect a live endpoint
37  gqls Query.user -R --code ./app     jump to the graphql-ruby resolver
38  gqls user schema.graphql -j         JSON output (-J for ndjson)
39
40Semantic search (--semantic, rank by meaning) is not compiled into this build. Enable it:
41  cargo install gqls-cli --features semantic
42  brew install dpep/tools/gqls
43";
44
45#[derive(Parser)]
46#[command(
47    name = "gqls",
48    version,
49    about = "Search a GraphQL schema — fuzzy, semantic, or straight to the resolver.",
50    long_about = "Find the types, fields, args, and directives in a GraphQL schema from the \
51                  terminal. The source is an SDL file, a local introspection JSON dump, or a live \
52                  http(s) endpoint; with none given, gqls discovers a schema in the current tree. \
53                  Fuzzy and semantic results are ranked together by default (--semantic or \
54                  --fuzzy forces one); --resolve jumps to the graphql-ruby resolver via rq. All modes \
55                  support -j/--json and -J/--ndjson.",
56    after_help = EXAMPLES
57)]
58struct Cli {
59    /// Search query. Fuzzy by default; abbreviations like `usr` match `User`,
60    /// and `Type.field` queries match against the qualified path.
61    #[arg(required_unless_present_any = ["clear_cache", "completions", "warm"])]
62    query: Option<String>,
63
64    /// Schema source: a `.graphql`/`.graphqls` SDL file, a `.json` introspection
65    /// dump, or an http(s) URL (introspected live). If omitted, gqls searches
66    /// the current directory tree for a schema.
67    source: Option<String>,
68
69    /// Restrict to a kind (object, field, query, mutation, enum, scalar, ...).
70    #[arg(short, long)]
71    kind: Option<String>,
72
73    /// Maximum number of results.
74    #[arg(short, long, default_value_t = 20)]
75    limit: usize,
76
77    /// Pretty JSON array.
78    #[arg(short, long, conflicts_with = "ndjson")]
79    json: bool,
80
81    /// Newline-delimited JSON (one record per line).
82    #[arg(short = 'J', long)]
83    ndjson: bool,
84
85    /// Force semantic-only search. By default fuzzy and semantic results are
86    /// combined once the schema's vectors are cached.
87    #[arg(long, hide = HIDE_SEMANTIC)]
88    semantic: bool,
89
90    /// Force fuzzy-only search — skip the semantic combine.
91    #[arg(long, conflicts_with = "semantic")]
92    fuzzy: bool,
93
94    /// Embedding model for --semantic: a local dir / `.onnx` path, or a
95    /// HuggingFace `org/name` id. Defaults to all-MiniLM-L6-v2.
96    #[arg(long, hide = HIDE_SEMANTIC)]
97    model: Option<String>,
98
99    /// Force a re-embed for --semantic, overwriting the cache. Schema edits
100    /// already re-embed on their own; use this for changes the cache can't see
101    /// (e.g. a new model).
102    #[arg(long, hide = HIDE_SEMANTIC)]
103    refresh: bool,
104
105    /// Delete all cached embedding vector files, then exit.
106    #[arg(long, hide = HIDE_SEMANTIC)]
107    clear_cache: bool,
108
109    /// Pre-embed the schema's vectors (warm the cache), then exit.
110    #[arg(long, hide = HIDE_SEMANTIC)]
111    warm: bool,
112
113    /// Print a shell completion script (bash, zsh, fish, ...) to stdout, then exit.
114    #[arg(long, value_name = "SHELL")]
115    completions: Option<Shell>,
116
117    /// Jump the top match to its graphql-ruby resolver/method in code, via
118    /// `rq` (must be installed).
119    #[arg(short = 'R', long)]
120    resolve: bool,
121
122    /// Directory of the server code for --resolve (defaults to rq's index).
123    #[arg(long)]
124    code: Option<String>,
125
126    /// Header for URL introspection, `Name: Value` (repeatable) — e.g. an
127    /// `Authorization` token for an auth-gated endpoint.
128    #[arg(short = 'H', long = "header", value_name = "NAME: VALUE")]
129    header: Vec<String>,
130
131    /// Verbose stderr diagnostics: cache hits, rq candidates, and why the
132    /// embedding model loaded or fell back.
133    #[arg(short, long, conflicts_with = "quiet")]
134    verbose: bool,
135
136    /// Suppress status chatter on stderr (results and hard errors still print).
137    #[arg(short, long)]
138    quiet: bool,
139}
140
141/// The chosen output format — computed once, honored by every mode.
142#[derive(Clone, Copy)]
143enum Output {
144    Text,
145    Json,
146    Ndjson,
147}
148
149/// A ranked result — from either the fuzzy scorer or the semantic ranker, so
150/// both flow through one output path.
151struct Match<'a> {
152    record: &'a SchemaRecord,
153    score: f64,
154}
155
156fn fuzzy_matches<'a>(
157    query: &str,
158    records: &'a [SchemaRecord],
159    kind: Option<Kind>,
160    limit: usize,
161) -> Vec<Match<'a>> {
162    search::search(query, records, kind, limit)
163        .into_iter()
164        .map(|h| Match {
165            record: h.record,
166            score: h.score as f64,
167        })
168        .collect()
169}
170
171#[cfg(feature = "_semantic")]
172fn semantic_matches<'a>(
173    query: &str,
174    records: &'a [SchemaRecord],
175    kind: Option<Kind>,
176    cli: &Cli,
177) -> Vec<Match<'a>> {
178    crate::semantic::search(
179        query,
180        records,
181        kind,
182        cli.limit,
183        cli.model.as_deref(),
184        cli.refresh,
185    )
186    .into_iter()
187    .map(|(score, record)| Match { record, score })
188    .collect()
189}
190
191/// Merge the fuzzy and semantic rankings via Reciprocal Rank Fusion — precise
192/// name matches and meaning matches both surface, and a record strong in both
193/// rises to the top. Fuzzy is weighted a touch higher so an exact-name hit
194/// keeps the lead; scale-free, so the two score systems needn't be normalized.
195#[cfg(feature = "_semantic")]
196fn combine<'a>(fuzzy: Vec<Match<'a>>, semantic: Vec<Match<'a>>, limit: usize) -> Vec<Match<'a>> {
197    use std::collections::HashMap;
198    const K: f64 = 60.0;
199    // Key on the record's stable qualified path (unique per entity) rather than
200    // pointer identity, so fusion stays correct even if a ranker ever returned
201    // records not borrowed from the same slice.
202    let mut scored: HashMap<&str, (f64, &SchemaRecord)> = HashMap::new();
203    for (rank, m) in fuzzy.iter().enumerate() {
204        scored
205            .entry(m.record.path.as_str())
206            .or_insert((0.0, m.record))
207            .0 += 1.0 / (K + rank as f64 + 1.0);
208    }
209    for (rank, m) in semantic.iter().enumerate() {
210        scored
211            .entry(m.record.path.as_str())
212            .or_insert((0.0, m.record))
213            .0 += 0.7 / (K + rank as f64 + 1.0);
214    }
215    let mut merged: Vec<Match> = scored
216        .into_values()
217        .map(|(score, record)| Match { record, score })
218        .collect();
219    merged.sort_by(|a, b| b.score.total_cmp(&a.score));
220    merged.truncate(limit);
221    merged
222}
223
224/// Spawn a detached `gqls --warm <source>` so the schema's vectors embed in the
225/// background — the next run gets combined fuzzy+semantic results with no wait.
226/// Opt out with `GQLS_NO_AUTOWARM`. Best-effort; failures are ignored.
227#[cfg(feature = "_semantic")]
228fn spawn_background_warm(source: &str, headers: &[String]) {
229    if std::env::var_os("GQLS_NO_AUTOWARM").is_some() {
230        return;
231    }
232    // Single-flight: a detached warm for this source may already be running.
233    // A short-lived lockfile keeps a burst of cold queries from spawning a herd
234    // that all embed the same schema and race the cache.
235    if !claim_warm_lock(source) {
236        return;
237    }
238    if let Ok(exe) = std::env::current_exe() {
239        let mut cmd = std::process::Command::new(exe);
240        cmd.arg("--warm").arg(source);
241        for h in headers {
242            cmd.arg("--header").arg(h);
243        }
244        let _ = cmd
245            .stdin(std::process::Stdio::null())
246            .stdout(std::process::Stdio::null())
247            .stderr(std::process::Stdio::null())
248            .spawn();
249    }
250}
251
252/// Best-effort single-flight guard for background warming: returns true (and
253/// stakes a claim) when no recent warm for `source` is in flight, false when one
254/// likely is. The lockfile self-expires by mtime, so a crashed warm can't wedge
255/// warming forever, and a failed warm won't be retried in a tight loop.
256#[cfg(feature = "_semantic")]
257fn claim_warm_lock(source: &str) -> bool {
258    use std::collections::hash_map::DefaultHasher;
259    use std::hash::{Hash, Hasher};
260    use std::time::Duration;
261
262    const LOCK_TTL: Duration = Duration::from_secs(10 * 60);
263    // Lockfiles live in the system temp dir so the OS auto-reaps them.
264    let dir = crate::paths::temp_dir();
265    let mut h = DefaultHasher::new();
266    source.hash(&mut h);
267    let lock = dir.join(format!("warming-{:016x}.lock", h.finish()));
268    if let Ok(meta) = std::fs::metadata(&lock) {
269        if let Ok(modified) = meta.modified() {
270            if modified.elapsed().is_ok_and(|age| age < LOCK_TTL) {
271                return false; // a recent warm is presumably still running
272            }
273        }
274    }
275    let _ = std::fs::create_dir_all(&dir);
276    std::fs::write(&lock, []).is_ok()
277}
278
279/// Parse `-H "Name: Value"` strings into `(name, value)` pairs.
280fn parse_headers(raw: &[String]) -> Result<Vec<(String, String)>> {
281    raw.iter()
282        .map(|h| {
283            let (name, value) = h
284                .split_once(':')
285                .ok_or_else(|| anyhow::anyhow!("--header {h:?} must be `Name: Value`"))?;
286            Ok((name.trim().to_string(), value.trim().to_string()))
287        })
288        .collect()
289}
290
291pub fn run() -> Result<()> {
292    let cli = Cli::parse();
293    crate::logging::init(cli.verbose, cli.quiet);
294
295    if let Some(shell) = cli.completions {
296        let mut cmd = Cli::command();
297        let name = cmd.get_name().to_string();
298        generate(shell, &mut cmd, name, &mut std::io::stdout());
299        return Ok(());
300    }
301
302    if cli.clear_cache {
303        let introspect = crate::load::introspect::clear_cache();
304        #[cfg(feature = "_semantic")]
305        let vectors = crate::semantic::clear_cache();
306        #[cfg(not(feature = "_semantic"))]
307        let vectors = 0;
308        crate::status!("cleared {} cached file(s)", introspect + vectors);
309        return Ok(());
310    }
311
312    let output = if cli.json {
313        Output::Json
314    } else if cli.ndjson {
315        Output::Ndjson
316    } else {
317        Output::Text
318    };
319
320    let kind: Option<Kind> = match &cli.kind {
321        Some(s) => Some(s.parse()?),
322        None => None,
323    };
324
325    // The schema source. With `--warm` and no explicit source, the sole
326    // positional is the schema (there's no query to warm), so `gqls --warm
327    // schema.graphql` — and the background spawn — target the right file.
328    let source = if let Some(s) = cli.source.clone() {
329        s
330    } else if cli.warm {
331        match cli.query.clone() {
332            Some(s) => s,
333            None => load::discover()?,
334        }
335    } else {
336        load::discover()?
337    };
338    let load_opts = load::LoadOptions {
339        headers: parse_headers(&cli.header)?,
340        refresh: cli.refresh,
341    };
342    let records = load::load(&source, &load_opts)?;
343
344    // --warm: embed + cache the schema's vectors, then exit (no query needed).
345    // Also the primitive the background auto-warm spawns.
346    if cli.warm {
347        #[cfg(feature = "_semantic")]
348        {
349            let n = crate::semantic::warm(&records, cli.model.as_deref(), cli.refresh);
350            crate::status!("warmed {n} record vector(s) into the cache");
351            return Ok(());
352        }
353        #[cfg(not(feature = "_semantic"))]
354        {
355            let _ = (&cli.model, cli.refresh);
356            anyhow::bail!("--warm needs a semantic build");
357        }
358    }
359
360    // clap guarantees a query unless --clear-cache/--completions/--warm.
361    let query = cli
362        .query
363        .as_deref()
364        .ok_or_else(|| anyhow::anyhow!("a QUERY is required (see --help)"))?;
365
366    if cli.resolve {
367        return run_resolve(
368            query,
369            &source,
370            &records,
371            kind,
372            cli.code.as_deref(),
373            cli.limit,
374            output,
375        );
376    }
377
378    let matches: Vec<Match> = if cli.fuzzy {
379        fuzzy_matches(query, &records, kind, cli.limit)
380    } else if cli.semantic {
381        #[cfg(feature = "_semantic")]
382        {
383            semantic_matches(query, &records, kind, &cli)
384        }
385        #[cfg(not(feature = "_semantic"))]
386        {
387            let _ = (&cli.model, cli.refresh);
388            anyhow::bail!(
389                "this build has no semantic search — install it with \
390                 `cargo install gqls-cli --features semantic` or `brew install dpep/tools/gqls`"
391            );
392        }
393    } else {
394        // Default: combine fuzzy + semantic when the cache is warm; when cold,
395        // return fuzzy now and warm the vectors in the background for next time.
396        let fuzzy = fuzzy_matches(query, &records, kind, cli.limit);
397        #[cfg(feature = "_semantic")]
398        {
399            if crate::semantic::is_cached(&records, cli.model.as_deref()) {
400                let semantic = semantic_matches(query, &records, kind, &cli);
401                combine(fuzzy, semantic, cli.limit)
402            } else {
403                spawn_background_warm(&source, &cli.header);
404                crate::status!(
405                    "warming the semantic index in the background — the next run also \
406                     ranks by meaning (--semantic to embed now, --fuzzy to skip)"
407                );
408                fuzzy
409            }
410        }
411        #[cfg(not(feature = "_semantic"))]
412        {
413            let _ = (&cli.model, cli.refresh);
414            fuzzy
415        }
416    };
417
418    if matches.is_empty() {
419        crate::status!("no matches for {query:?}");
420    }
421    output.write_matches(&matches)
422}
423
424impl Output {
425    fn write_matches(self, matches: &[Match]) -> Result<()> {
426        #[derive(Serialize)]
427        struct Row<'a> {
428            #[serde(flatten)]
429            record: &'a SchemaRecord,
430            score: f64,
431        }
432        let rows = || {
433            matches.iter().map(|m| Row {
434                record: m.record,
435                score: m.score,
436            })
437        };
438        match self {
439            Output::Json => println!(
440                "{}",
441                serde_json::to_string_pretty(&rows().collect::<Vec<_>>())?
442            ),
443            Output::Ndjson => {
444                for row in rows() {
445                    println!("{}", serde_json::to_string(&row)?);
446                }
447            }
448            Output::Text => print_text(matches),
449        }
450        Ok(())
451    }
452}
453
454fn print_text(matches: &[Match]) {
455    let width = matches
456        .iter()
457        .map(|m| display_path(m.record).len())
458        .max()
459        .unwrap_or(0)
460        .min(48);
461
462    for m in matches {
463        let r = m.record;
464        let path = display_path(r);
465        let ret = r
466            .type_ref
467            .as_deref()
468            .map(|t| format!(" -> {t}"))
469            .unwrap_or_default();
470        let dep = if r.deprecated.is_some() {
471            " (deprecated)"
472        } else {
473            ""
474        };
475        println!("{path:<width$}{ret}  [{kind}]{dep}", kind = r.kind.as_str());
476    }
477}
478
479/// Fuzzy-find the field, then hand it to rq to locate its resolver in code.
480fn run_resolve(
481    query: &str,
482    source: &str,
483    records: &[SchemaRecord],
484    kind: Option<Kind>,
485    code: Option<&str>,
486    limit: usize,
487    output: Output,
488) -> Result<()> {
489    if code.is_none() {
490        crate::status!("no --code given; resolving against rq's index for the current directory");
491    }
492    let Some(top) = search::search(query, records, kind, 1).into_iter().next() else {
493        anyhow::bail!("no schema entity matches {query:?} to resolve");
494    };
495    crate::status!("resolving {} …", top.record.path);
496    // a local file schema (not a URL) enables package-proximity ranking
497    let schema_path = (!source.starts_with("http://") && !source.starts_with("https://"))
498        .then(|| std::path::Path::new(source))
499        .filter(|p| p.exists());
500    let hits = crate::resolve::resolve(top.record, code, schema_path, limit.min(10))?;
501
502    match output {
503        Output::Json => println!("{}", serde_json::to_string_pretty(&hits)?),
504        Output::Ndjson => {
505            for h in &hits {
506                println!("{}", serde_json::to_string(h)?);
507            }
508        }
509        Output::Text => {
510            if hits.is_empty() {
511                crate::status!(
512                    "no code definition found for {} (tried graphql-ruby rq candidates)",
513                    top.record.path
514                );
515            }
516            for h in &hits {
517                println!("{}:{}  {}  (via {})", h.file, h.line, h.name, h.via);
518            }
519        }
520    }
521    Ok(())
522}
523
524/// `Query.user(id: ID!, first: Int)` — path plus a compact arg signature.
525fn display_path(r: &SchemaRecord) -> String {
526    if r.args.is_empty() {
527        r.path.clone()
528    } else {
529        format!("{}({})", r.path, r.args.join(", "))
530    }
531}