rust-analyzer-cli 0.5.0

A library and CLI tool built on top of rust-analyzer for codebase navigation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[command(
    name = "rust-analyzer-cli",
    author,
    version,
    about = "Compiler-accurate Rust codebase navigation powered by rust-analyzer LSP",
    after_help = "Workflow:\n  1. Start the daemon: rust-analyzer-cli daemon --workspace .\n  2. Wait for indexing: rust-analyzer-cli status\n  3. Run a query, such as: rust-analyzer-cli hover --file src/main.rs --line 15 --col 10\n\nCoordinates use 1-based line and column numbers. Use --json for machine-readable stdout.\nMost query commands require the daemon to be running first."
)]
pub struct Cli {
    /// Port for the background daemon HTTP server (default: 60094; env: RUST_ANALYZER_CLI_PORT)
    #[arg(short, long, env = "RUST_ANALYZER_CLI_PORT", default_value_t = 60094)]
    pub port: u16,

    /// Print only machine-readable JSON to stdout; errors are reported on stderr
    #[arg(short, long, global = true)]
    pub json: bool,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Start the background LSP daemon and HTTP server
    #[command(
        after_help = "Example:\n  rust-analyzer-cli daemon --workspace .\n\nThe daemon must stay running while query commands are used. Use --port to choose a different local port."
    )]
    Daemon {
        /// Workspace root directory (default: current directory)
        #[arg(short, long, default_value = ".")]
        workspace: PathBuf,
    },
    /// Query daemon and rust-analyzer status
    #[command(
        after_help = "Example:\n  rust-analyzer-cli status\n  rust-analyzer-cli --json status\n\nA status of INITIALIZING means rust-analyzer is still indexing the workspace."
    )]
    Status,
    /// Refresh / restart the rust-analyzer session
    #[command(
        after_help = "Example:\n  rust-analyzer-cli refresh\n\nThe daemon must be running. Query status again after refreshing to confirm indexing state."
    )]
    Refresh,
    /// Search workspace symbols
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli symbol LspClient struct --exact\n  rust-analyzer-cli symbol LspClient --body --max-lines 50\n\nThe optional kind must be one of: any, struct, enum, fn, trait, type, const, var."
    )]
    Symbol {
        /// Symbol name to search for
        name: String,
        /// Optional symbol filter: any, struct, enum, fn, trait, type, const, var
        #[arg(value_parser = ["any", "struct", "enum", "fn", "trait", "type", "const", "var"], default_value = "any")]
        kind: String,
        /// Match exact symbol name
        #[arg(long)]
        exact: bool,
        /// Include source code body/snippet; output is limited by --max-lines
        #[arg(short, long)]
        body: bool,
        /// Maximum body lines (default: 100; 0 means unlimited)
        #[arg(long, default_value_t = 100)]
        max_lines: usize,
    },
    /// Extract file document symbols outline
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli outline --file src/main.rs\n  rust-analyzer-cli outline --file-list src/main.rs,src/lib.rs --body --max-lines 50\n\nProvide exactly one of --file or --file-list. Paths are interpreted from the current workspace."
    )]
    Outline {
        /// Target file path; mutually exclusive with --file-list
        #[arg(
            short,
            long,
            required_unless_present = "file_list",
            conflicts_with = "file_list"
        )]
        file: Option<PathBuf>,
        /// Comma-separated target file paths; mutually exclusive with --file
        #[arg(long, conflicts_with = "file")]
        file_list: Option<String>,
        /// Write outline output to a file instead of stdout
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Include source code body/snippet for symbols; output is limited by --max-lines
        #[arg(short, long)]
        body: bool,
        /// Maximum body lines (default: 100; 0 means unlimited)
        #[arg(long, default_value_t = 100)]
        max_lines: usize,
    },
    /// Go to definition at file line and column
    #[command(
        after_help = "Example:\n  rust-analyzer-cli definition --file src/main.rs --line 13 --col 10 --body\n\nLine and column numbers are 1-based. Start the daemon before querying."
    )]
    Definition {
        /// File path
        #[arg(short, long)]
        file: PathBuf,
        /// Line number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        line: u32,
        /// Column number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        col: u32,
        /// Include source code body/snippet of the definition target
        #[arg(short, long)]
        body: bool,
        /// Maximum body lines (default: 100; 0 means unlimited)
        #[arg(long, default_value_t = 100)]
        max_lines: usize,
        /// Omit line numbers in terminal output
        #[arg(long)]
        no_line_numbers: bool,
    },
    /// Inspect source code body of struct, function, enum, impl, trait, or module
    #[command(
        after_help = "Example:\n  rust-analyzer-cli body --file src/main.rs --line 15 --col 10 --max-lines 100\n\nLine and column numbers are 1-based. If the body exceeds --max-lines, the human-readable output includes a truncation warning. Use --max-lines 0 for unlimited output."
    )]
    Body {
        /// File path
        #[arg(short, long)]
        file: PathBuf,
        /// Line number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        line: u32,
        /// Column number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        col: u32,
        /// Maximum body lines (default: 100; 0 means unlimited)
        #[arg(long, default_value_t = 100)]
        max_lines: usize,
        /// Omit line numbers in terminal output
        #[arg(long)]
        no_line_numbers: bool,
    },
    /// Show documentation and type information at a file position
    #[command(
        after_help = "Example:\n  rust-analyzer-cli hover --file src/main.rs --line 15 --col 10\n\nThe output preserves Markdown documentation and Rust code blocks. A valid query with no hover information returns null in JSON mode or an explicit message in human-readable mode."
    )]
    Hover {
        /// File path
        #[arg(short, long)]
        file: PathBuf,
        /// Line number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        line: u32,
        /// Column number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        col: u32,
    },
    /// Find references or call hierarchy at file line and column
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli cursor --file src/main.rs --line 25 --col 8 --mode incoming\n  rust-analyzer-cli cursor --file src/main.rs --line 25 --col 8 --mode outgoing --depth 2\n\nModes: incoming, outgoing, references. Depth applies to call hierarchy modes; references always returns the direct reference query."
    )]
    Cursor {
        /// File path
        #[arg(short, long)]
        file: PathBuf,
        /// Line number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        line: u32,
        /// Column number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        col: u32,
        /// Mode: incoming, outgoing, or references (default: incoming)
        #[arg(short, long, value_parser = ["incoming", "outgoing", "references"], default_value = "incoming")]
        mode: String,
        /// Call hierarchy traversal depth (default: 1; must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_depth, default_value_t = 1)]
        depth: u32,
    },
    /// Query type hierarchy (supertypes / subtypes)
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli type-hierarchy --file src/main.rs --line 25 --col 8\n  rust-analyzer-cli type-hierarchy --file src/main.rs --line 25 --col 8 --mode subtypes --depth 2\n\nModes: supertypes and subtypes. Depth controls how many hierarchy levels are traversed."
    )]
    TypeHierarchy {
        /// File path
        #[arg(short, long)]
        file: PathBuf,
        /// Line number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        line: u32,
        /// Column number (1-based and must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_u32)]
        col: u32,
        /// Mode: supertypes or subtypes (default: supertypes)
        #[arg(short, long, value_parser = ["supertypes", "subtypes"], default_value = "supertypes")]
        mode: String,
        /// Hierarchy traversal depth (default: 1; must be greater than zero)
        #[arg(short, long, value_parser = parse_positive_depth, default_value_t = 1)]
        depth: u32,
    },
    /// Run cargo check compilation verification
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli check\n  rust-analyzer-cli check --target x86_64-pc-windows-msvc\n\nCompilation failures are returned with Cargo's diagnostic text and source locations when available."
    )]
    Check {
        /// Optional cargo build target
        #[arg(short, long)]
        target: Option<String>,
    },
    /// Initialize/install the rust-codebase-navigation SKILL.md in a workspace
    #[command(
        after_help = "Examples:\n  rust-analyzer-cli init-skill --workspace .\n  rust-analyzer-cli init-skill --workspace . --dir .agents/skills/rust-codebase-navigation/SKILL.md\n\nThe default destination is .agents/skills/rust-codebase-navigation/SKILL.md. The custom path is relative to --workspace."
    )]
    InitSkill {
        /// Target workspace directory (default: current directory)
        #[arg(short, long, default_value = ".")]
        workspace: PathBuf,
        /// Custom project-relative skill path (default: .agents/skills/rust-codebase-navigation/SKILL.md)
        #[arg(short, long)]
        dir: Option<PathBuf>,
    },
}

fn parse_positive_u32(value: &str) -> Result<u32, String> {
    let parsed = value
        .parse::<u32>()
        .map_err(|_| format!("{value} must be a positive integer"))?;
    if parsed == 0 {
        return Err("value must be at least 1; line and column numbers are 1-based".to_string());
    }
    Ok(parsed)
}

fn parse_positive_depth(value: &str) -> Result<u32, String> {
    let parsed = value
        .parse::<u32>()
        .map_err(|_| format!("{value} must be a positive integer depth"))?;
    if parsed == 0 {
        return Err("depth must be at least 1".to_string());
    }
    Ok(parsed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn test_cli_symbol_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "symbol",
            "ExampleStruct",
            "struct",
            "--exact",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        assert_eq!(cli.port, 60094);
        assert!(!cli.json);
        match cli.command {
            Commands::Symbol {
                name,
                kind,
                exact,
                body,
                max_lines,
            } => {
                assert_eq!(name, "ExampleStruct");
                assert_eq!(kind, "struct");
                assert!(exact);
                assert!(!body);
                assert_eq!(max_lines, 100);
            }
            _ => panic!("Expected Symbol command"),
        }
    }

    #[test]
    fn test_cli_outline_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "--json",
            "outline",
            "-f",
            "tests/code_example.rs",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        assert!(cli.json);
        match cli.command {
            Commands::Outline {
                file,
                file_list,
                output,
                body,
                max_lines,
            } => {
                assert_eq!(file, Some(PathBuf::from("tests/code_example.rs")));
                assert!(file_list.is_none());
                assert!(output.is_none());
                assert!(!body);
                assert_eq!(max_lines, 100);
            }
            _ => panic!("Expected Outline command"),
        }
    }

    #[test]
    fn test_cli_definition_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "definition",
            "-f",
            "tests/code_example.rs",
            "-l",
            "10",
            "-c",
            "5",
            "--body",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        match cli.command {
            Commands::Definition {
                file,
                line,
                col,
                body,
                max_lines,
                no_line_numbers,
            } => {
                assert_eq!(file, PathBuf::from("tests/code_example.rs"));
                assert_eq!(line, 10);
                assert_eq!(col, 5);
                assert!(body);
                assert_eq!(max_lines, 100);
                assert!(!no_line_numbers);
            }
            _ => panic!("Expected Definition command"),
        }
    }

    #[test]
    fn test_cli_body_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "body",
            "-f",
            "tests/code_example.rs",
            "-l",
            "10",
            "-c",
            "5",
            "--max-lines",
            "50",
            "--no-line-numbers",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        match cli.command {
            Commands::Body {
                file,
                line,
                col,
                max_lines,
                no_line_numbers,
            } => {
                assert_eq!(file, PathBuf::from("tests/code_example.rs"));
                assert_eq!(line, 10);
                assert_eq!(col, 5);
                assert_eq!(max_lines, 50);
                assert!(no_line_numbers);
            }
            _ => panic!("Expected Body command"),
        }
    }

    #[test]
    fn test_cli_hover_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "hover",
            "-f",
            "tests/code_example.rs",
            "-l",
            "155",
            "-c",
            "5",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        match cli.command {
            Commands::Hover { file, line, col } => {
                assert_eq!(file, PathBuf::from("tests/code_example.rs"));
                assert_eq!(line, 155);
                assert_eq!(col, 5);
            }
            _ => panic!("Expected Hover command"),
        }
    }

    #[test]
    fn test_cli_init_skill_parsing() {
        let args = vec![
            "rust-analyzer-cli",
            "init-skill",
            "-w",
            "/my/proj",
            "-d",
            "custom/SKILL.md",
        ];
        let cli = Cli::try_parse_from(args).unwrap();
        match cli.command {
            Commands::InitSkill { workspace, dir } => {
                assert_eq!(workspace, PathBuf::from("/my/proj"));
                assert_eq!(dir, Some(PathBuf::from("custom/SKILL.md")));
            }
            _ => panic!("Expected InitSkill command"),
        }
    }

    #[test]
    fn test_cli_help_explains_workflow_and_coordinates() {
        let mut command = Cli::command();
        let top_help = command.render_help().to_string();
        assert!(top_help.contains("Start the daemon"));
        assert!(top_help.contains("1-based line and column numbers"));
        assert!(top_help.contains("--json"));

        let body_help = command
            .find_subcommand_mut("body")
            .expect("body subcommand should be present")
            .render_help()
            .to_string();
        assert!(body_help.contains("must be greater than zero"));
        assert!(body_help.contains("--max-lines 0"));
    }

    #[test]
    fn test_cli_rejects_invalid_positions_and_modes() {
        let position_error = Cli::try_parse_from([
            "rust-analyzer-cli",
            "hover",
            "--file",
            "tests/code_example.rs",
            "--line",
            "0",
            "--col",
            "1",
        ])
        .expect_err("zero-based line should be rejected");
        assert!(position_error.to_string().contains("at least 1"));

        let mode_error = Cli::try_parse_from([
            "rust-analyzer-cli",
            "cursor",
            "--file",
            "tests/code_example.rs",
            "--line",
            "1",
            "--col",
            "1",
            "--mode",
            "invalid",
        ])
        .expect_err("unsupported cursor mode should be rejected");
        assert!(mode_error.to_string().contains("incoming"));
        assert!(mode_error.to_string().contains("references"));

        let kind_error =
            Cli::try_parse_from(["rust-analyzer-cli", "symbol", "ExampleStruct", "invalid"])
                .expect_err("unsupported symbol kind should be rejected");
        assert!(kind_error.to_string().contains("struct"));

        let depth_error = Cli::try_parse_from([
            "rust-analyzer-cli",
            "cursor",
            "--file",
            "tests/code_example.rs",
            "--line",
            "1",
            "--col",
            "1",
            "--depth",
            "0",
        ])
        .expect_err("zero depth should be rejected");
        assert!(depth_error.to_string().contains("depth must be at least 1"));
    }

    #[test]
    fn test_cli_outline_requires_exactly_one_input() {
        let missing_error = Cli::try_parse_from(["rust-analyzer-cli", "outline"])
            .expect_err("outline should require a file input");
        assert!(missing_error.to_string().contains("--file"));

        let conflict_error = Cli::try_parse_from([
            "rust-analyzer-cli",
            "outline",
            "--file",
            "src/main.rs",
            "--file-list",
            "src/lib.rs",
        ])
        .expect_err("outline file inputs should be mutually exclusive");
        assert!(conflict_error.to_string().contains("cannot be used"));
    }
}