loctree 0.8.16

Structural code intelligence for AI agents. Scan once, query everything.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Parsers for code analysis commands: dead, cycles, find, query, impact, twins, sniff.
//!
//! These commands analyze the codebase for issues, patterns, and relationships.

use std::path::PathBuf;

use super::super::command::{
    Command, CyclesOptions, DeadOptions, FindOptions, ImpactCommandOptions, QueryKind,
    QueryOptions, SniffOptions, TwinsOptions,
};

/// Parse `loct dead [options]` command - detect unused exports.
pub(super) fn parse_dead_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct dead - Detect unused exports / dead code

USAGE:
    loct dead [OPTIONS] [PATHS...]

DESCRIPTION:
    Finds exported symbols that are never imported anywhere in the codebase.
    Uses import graph analysis with alias-awareness to minimize false positives.

OPTIONS:
    --confidence <LEVEL>   Filter by confidence: high, medium, low (default: all)
    --top <N>              Limit to top N results (default: 20)
    --full, --all          Show all results (ignore top limit)
    --path <PATTERN>       Filter to files matching pattern
    --with-tests           Include test files in analysis
    --exclude-tests        Exclude test files (default)
    --with-helpers         Include helper/utility files
    --help, -h             Show this help message

EXAMPLES:
    loct dead                          # All dead exports
    loct dead --confidence high        # Only high-confidence
    loct dead --path src/components/   # Dead exports in components
    loct dead --top 50                 # Top 50 dead exports"
            .to_string());
    }

    let mut opts = DeadOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--confidence" => {
                let value = args.get(i + 1).ok_or_else(|| {
                    "--confidence requires a value (high, medium, low)".to_string()
                })?;
                opts.confidence = Some(value.clone());
                i += 2;
            }
            "--top" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--top requires a number".to_string())?;
                opts.top = Some(value.parse().map_err(|_| "--top requires a number")?);
                i += 2;
            }
            "--full" | "--all" => {
                opts.full = true;
                i += 1;
            }
            "--path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--path requires a pattern".to_string())?;
                opts.path_filter = Some(value.clone());
                i += 2;
            }
            "--with-tests" => {
                opts.with_tests = true;
                i += 1;
            }
            "--exclude-tests" => {
                opts.with_tests = false;
                i += 1;
            }
            "--with-helpers" => {
                opts.with_helpers = true;
                i += 1;
            }
            "--with-shadows" => {
                opts.with_shadows = true;
                i += 1;
            }
            "--with-ambient" | "--include-ambient" => {
                opts.with_ambient = true;
                i += 1;
            }
            "--with-dynamic" | "--include-dynamic" => {
                opts.with_dynamic = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'dead' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Dead(opts))
}

/// Parse `loct cycles [options]` command - detect circular imports.
pub(super) fn parse_cycles_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct cycles - Detect circular import chains

USAGE:
    loct cycles [OPTIONS] [PATHS...]

DESCRIPTION:
    Detects circular dependencies in your import graph and classifies them
    by compilability impact.

OPTIONS:
    --path <PATTERN>     Filter to files matching path pattern
    --breaking-only      Only show cycles that would break compilation
    --explain            Show detailed explanation for each cycle
    --legacy             Use legacy output format (old grouping by pattern)
    --help, -h           Show this help message

EXAMPLES:
    loct cycles                       # Show all cycles with new format
    loct cycles --breaking-only       # Only show compilation-breaking cycles
    loct cycles --explain             # Detailed pattern explanations"
            .to_string());
    }

    let mut opts = CyclesOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--path requires a pattern".to_string())?;
                opts.path_filter = Some(value.clone());
                i += 2;
            }
            "--breaking-only" => {
                opts.breaking_only = true;
                i += 1;
            }
            "--explain" => {
                opts.explain = true;
                i += 1;
            }
            "--legacy" => {
                opts.legacy_format = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'cycles' command.", arg));
            }
        }
    }

    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Cycles(opts))
}

/// Parse `loct find [options]` command - semantic search for symbols.
pub(super) fn parse_find_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct find - Semantic search for symbols by name pattern

USAGE:
    loct find [QUERY...] [OPTIONS]

DESCRIPTION:
    Semantic search for symbols (functions, classes, types) matching name patterns.
    Uses regex patterns. Multi-arg QUERY defaults to split-mode (subqueries + cross-match).
    Use --or to combine multiple QUERY args into a single OR regex.
    Uses snapshot for instant results (15x faster than re-scanning).

OPTIONS:
    --or                                Combine multiple QUERY args with OR (legacy behavior)
    --symbol <PATTERN>, -s <PATTERN>    Search for symbols matching regex
    --pattern <PATTERN>                 Alias for --symbol (regex)
    --file <PATTERN>, -f <PATTERN>      Search for files matching regex
    --similar <SYMBOL>                  Find symbols with similar names (fuzzy)
    --dead                              Only show dead/unused symbols
    --exported                          Only show exported symbols
    --lang <LANG>                       Filter by language (ts, rs, js, py, etc.)
    --limit <N>                         Maximum results to show (default: unlimited)
    --help, -h                          Show this help message

EXAMPLES:
    loct find Patient                   # Find symbols containing \"Patient\"
    loct find Props Options ViewModel   # Split-mode: run subqueries + cross-match
    loct find \"Props Options\"          # AND-mode: require ALL terms (quoted)
    loct find --or foo bar baz          # Legacy: combine with OR
    loct find --symbol \".*Config$\"      # Regex: symbols ending with Config"
            .to_string());
    }

    let mut opts = FindOptions::default();
    let mut queries: Vec<String> = Vec::new();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--or" => {
                opts.or_mode = true;
                i += 1;
            }
            "--symbol" | "-s" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--symbol requires a pattern".to_string())?;
                opts.symbol = Some(value.clone());
                i += 2;
            }
            "--pattern" => {
                let value = args.get(i + 1).ok_or_else(|| {
                    "--pattern requires a pattern (alias for --symbol)".to_string()
                })?;
                opts.symbol = Some(value.clone());
                i += 2;
            }
            "--file" | "-f" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--file requires a pattern".to_string())?;
                opts.file = Some(value.clone());
                i += 2;
            }
            "--impact" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--impact requires a file path".to_string())?;
                opts.impact = Some(value.clone());
                i += 2;
            }
            "--similar" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--similar requires a symbol name".to_string())?;
                opts.similar = Some(value.clone());
                i += 2;
            }
            "--dead" => {
                opts.dead_only = true;
                i += 1;
            }
            "--exported" => {
                opts.exported_only = true;
                i += 1;
            }
            "--lang" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--lang requires a language".to_string())?;
                opts.lang = Some(value.clone());
                i += 2;
            }
            "--limit" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--limit requires a number".to_string())?;
                opts.limit = Some(value.parse().map_err(|_| "--limit requires a number")?);
                i += 2;
            }
            _ if !arg.starts_with('-') => {
                // Collect all positional args as queries (multi-query support!)
                queries.push(arg.clone());
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'find' command.", arg));
            }
        }
    }

    // Preserve positional queries as provided; dispatch decides split/AND/OR behavior.
    if !queries.is_empty() {
        opts.queries = queries.clone();
    }

    // Validate that at least one search criterion is specified and not empty
    let effective_query = opts
        .query
        .as_ref()
        .or_else(|| opts.queries.first())
        .or(opts.symbol.as_ref())
        .or(opts.file.as_ref())
        .or(opts.similar.as_ref())
        .or(opts.impact.as_ref());

    if effective_query.is_some_and(|q| q.trim().is_empty()) {
        return Err("Error: Query cannot be empty".to_string());
    }

    Ok(Command::Find(opts))
}

/// Parse `loct query <kind> <target>` command - graph queries.
pub(super) fn parse_query_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct query - Graph queries (who-imports, who-exports, etc.)

USAGE:
    loct query <KIND> <TARGET>

QUERY KINDS:
    who-imports <FILE>        Find all files that import the specified file
    where-symbol <SYMBOL>     Find where a symbol is defined/exported
    component-of <FILE>       Show which components/modules contain this file

EXAMPLES:
    loct query who-imports src/utils.ts
    loct query where-symbol PatientRecord"
            .to_string());
    }

    if args.len() < 2 {
        return Err(
            "query command requires a kind and target.\nUsage: loct query <kind> <target>\nKinds: who-imports, where-symbol, component-of"
                .to_string(),
        );
    }

    let kind_str = &args[0];
    let target = args[1].clone();

    let kind = match kind_str.as_str() {
        "who-imports" => QueryKind::WhoImports,
        "where-symbol" => QueryKind::WhereSymbol,
        "component-of" => QueryKind::ComponentOf,
        _ => {
            return Err(format!(
                "Unknown query kind '{}'. Valid kinds: who-imports, where-symbol, component-of",
                kind_str
            ));
        }
    };

    Ok(Command::Query(QueryOptions { kind, target }))
}

/// Parse `loct impact <file> [options]` command - analyze impact of file changes.
pub(super) fn parse_impact_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct impact - Analyze impact of modifying/removing a file

USAGE:
    loct impact <FILE> [OPTIONS]

OPTIONS:
    --depth <N>          Limit traversal depth (default: unlimited)
    --root <PATH>        Project root (default: current directory)
    --help, -h           Show this help message

EXAMPLES:
    loct impact src/utils.ts
    loct impact src/api.ts --depth 2"
            .to_string());
    }

    let mut opts = ImpactCommandOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--depth" | "--max-depth" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--depth requires a value".to_string())?;
                opts.depth = Some(value.parse().map_err(|_| "--depth requires a number")?);
                i += 2;
            }
            "--root" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--root requires a path".to_string())?;
                opts.root = Some(PathBuf::from(value));
                i += 2;
            }
            _ if !arg.starts_with('-') => {
                if opts.target.is_empty() {
                    opts.target = arg.clone();
                } else {
                    return Err(format!(
                        "Unexpected argument '{}'. impact takes one target path.",
                        arg
                    ));
                }
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'impact' command.", arg));
            }
        }
    }

    if opts.target.is_empty() {
        return Err(
            "'impact' command requires a target file path. Usage: loct impact <path>".to_string(),
        );
    }

    Ok(Command::Impact(opts))
}

/// Parse `loct twins [options]` command - find dead parrots and duplicate exports.
pub(super) fn parse_twins_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err(
            "loct twins - Find dead parrots (0 imports) and duplicate exports

USAGE:
    loct twins [OPTIONS] [PATH]

OPTIONS:
    --path <DIR>       Root directory to analyze (default: current directory)
    --dead-only        Show only dead parrots (exports with 0 imports)
    --include-tests    Include test files in analysis (excluded by default)
    --help, -h         Show this help message

EXAMPLES:
    loct twins
    loct twins --dead-only"
                .to_string(),
        );
    }

    let mut opts = TwinsOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--path requires a directory".to_string())?;
                opts.path = Some(PathBuf::from(value));
                i += 2;
            }
            "--dead-only" => {
                opts.dead_only = true;
                i += 1;
            }
            "--include-suppressed" => {
                opts.include_suppressed = true;
                i += 1;
            }
            "--include-tests" => {
                opts.include_tests = true;
                i += 1;
            }
            "--ignore-conventions" => {
                opts.ignore_conventions = true;
                i += 1;
            }
            _ => {
                // Treat as path if no flag prefix
                if !arg.starts_with('-') {
                    opts.path = Some(PathBuf::from(arg));
                    i += 1;
                } else {
                    return Err(format!("Unknown option '{}' for 'twins' command.", arg));
                }
            }
        }
    }

    Ok(Command::Twins(opts))
}

/// Parse `loct sniff [options]` command - aggregate code smell analysis.
pub(super) fn parse_sniff_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct sniff - Sniff for code smells (aggregate analysis)

USAGE:
    loct sniff [OPTIONS]

OPTIONS:
    --path <DIR>           Root directory to analyze (default: current directory)
    --dead-only            Show only dead parrots (skip twins and crowds)
    --twins-only           Show only twins (skip dead parrots and crowds)
    --crowds-only          Show only crowds (skip twins and dead parrots)
    --include-tests        Include test files in analysis (default: false)
    --min-crowd-size <N>   Minimum crowd size to report (default: 2)
    --help, -h             Show this help message

EXAMPLES:
    loct sniff
    loct sniff --dead-only"
            .to_string());
    }

    let mut opts = SniffOptions::default();
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--path requires a directory".to_string())?;
                opts.path = Some(PathBuf::from(value));
                i += 2;
            }
            "--dead-only" => {
                opts.dead_only = true;
                i += 1;
            }
            "--twins-only" => {
                opts.twins_only = true;
                i += 1;
            }
            "--crowds-only" => {
                opts.crowds_only = true;
                i += 1;
            }
            "--include-tests" => {
                opts.include_tests = true;
                i += 1;
            }
            "--min-crowd-size" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--min-crowd-size requires a number".to_string())?;
                opts.min_crowd_size = Some(
                    value
                        .parse::<usize>()
                        .map_err(|_| format!("Invalid number for --min-crowd-size: {}", value))?,
                );
                i += 2;
            }
            _ => {
                // Treat as path if no flag prefix
                if !arg.starts_with('-') {
                    opts.path = Some(PathBuf::from(arg));
                    i += 1;
                } else {
                    return Err(format!("Unknown option '{}' for 'sniff' command.", arg));
                }
            }
        }
    }

    Ok(Command::Sniff(opts))
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_parse_dead_command() {
        let args = vec!["--confidence".into(), "high".into()];
        let result = parse_dead_command(&args).unwrap();
        if let Command::Dead(opts) = result {
            assert_eq!(opts.confidence, Some("high".into()));
        } else {
            panic!("Expected Dead command");
        }
    }

    #[test]
    fn test_parse_cycles_command() {
        let args = vec!["--breaking-only".into()];
        let result = parse_cycles_command(&args).unwrap();
        if let Command::Cycles(opts) = result {
            assert!(opts.breaking_only);
        } else {
            panic!("Expected Cycles command");
        }
    }

    #[test]
    fn test_parse_find_with_regex() {
        let args = vec![
            "--symbol".into(),
            ".*patient.*".into(),
            "--lang".into(),
            "ts".into(),
        ];
        let result = parse_find_command(&args).unwrap();
        if let Command::Find(opts) = result {
            assert_eq!(opts.symbol, Some(".*patient.*".into()));
            assert_eq!(opts.lang, Some("ts".into()));
        } else {
            panic!("Expected Find command");
        }
    }

    #[test]
    fn test_parse_query_who_imports() {
        let args = vec!["who-imports".into(), "src/utils.ts".into()];
        let result = parse_query_command(&args).unwrap();
        if let Command::Query(opts) = result {
            assert!(matches!(opts.kind, QueryKind::WhoImports));
            assert_eq!(opts.target, "src/utils.ts");
        } else {
            panic!("Expected Query command");
        }
    }

    #[test]
    fn test_parse_twins_command() {
        let args = vec!["--dead-only".into()];
        let result = parse_twins_command(&args).unwrap();
        if let Command::Twins(opts) = result {
            assert!(opts.dead_only);
        } else {
            panic!("Expected Twins command");
        }
    }
}