loctree 0.13.1

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
//! Parsers for scan-related commands: auto, scan, tree.
//!
//! These commands handle the initial codebase scanning and visualization.

use std::path::PathBuf;

use super::super::command::{
    AutoOptions, Command, ScanOptions, TreeOptions, WatchMode, WatchOptions,
};

/// Parse `loct auto [options]` command - the default full analysis command.
pub(super) fn parse_auto_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err(
            "loct auto - Full auto-scan with stack detection (default command)

USAGE:
    loct auto [OPTIONS] [PATHS...]
    loct [OPTIONS] [PATHS...]    # 'auto' is the default command

DESCRIPTION:
    Performs a comprehensive analysis of your codebase:
    - Detects project type and language stack automatically
    - Builds dependency graph and import relationships
    - Analyzes code structure and exports
    - Identifies potential issues (dead code, cycles, etc.)

    This is the default command when no subcommand is specified.

OPTIONS:
    --full-scan          Force full rescan (ignore cache)
    --scan-all           Scan all files including hidden/ignored
    --no-duplicates      Hide duplicate export sections in CLI output
    --no-dynamic-imports Hide dynamic import sections in CLI output
    --help, -h           Show this help message

ARGUMENTS:
    [PATHS...]           Root directories to scan (default: current directory)

EXAMPLES:
    loct                         # Auto-scan current directory
    loct auto                    # Explicit auto command
    loct auto --full-scan        # Force full rescan
    loct auto src/ lib/          # Scan specific directories
    loct context                 # Agent-ready Markdown ContextPack (preferred)
    loct context --json          # Full ContextPack JSON for tooling

See `loct --help-legacy` for deprecated flag migration."
                .to_string(),
        );
    }

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

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--full-scan" => {
                opts.full_scan = true;
                i += 1;
            }
            "--scan-all" => {
                opts.scan_all = true;
                i += 1;
            }
            "--for-agent-feed" => {
                eprintln!(
                    "warning: --for-agent-feed is deprecated; use `loct context --json` for an agent-ready ContextPack."
                );
                opts.for_agent_feed = true;
                i += 1;
            }
            "--agent-json" => {
                eprintln!(
                    "warning: --agent-json is deprecated; use `loct context --json` for a raw ContextPack."
                );
                opts.for_agent_feed = true;
                opts.agent_json = true;
                i += 1;
            }
            "--no-duplicates" => {
                opts.suppress_duplicates = true;
                i += 1;
            }
            "--no-dynamic-imports" => {
                opts.suppress_dynamic = true;
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'auto' command.", arg));
            }
        }
    }

    // Default to current directory if no roots specified
    if opts.roots.is_empty() {
        opts.roots.push(PathBuf::from("."));
    }

    Ok(Command::Auto(opts))
}

/// Parse `loct scan [options]` command - build/update snapshot.
pub(super) fn parse_scan_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct scan - Build/update snapshot for current HEAD

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

DESCRIPTION:
    Scans the codebase and updates the internal snapshot database.
    This command builds the dependency graph, analyzes imports/exports,
    and prepares data for other commands like 'dead', 'cycles', 'tree'.

    Unlike 'auto', this command only builds the snapshot without
    running additional analysis passes.

OPTIONS:
    --full-scan       Force full rescan, ignore cached data
    --scan-all        Include hidden and ignored files
    --watch           Watch for changes and re-scan automatically
    --help, -h        Show this help message

ARGUMENTS:
    [PATHS...]        Root directories to scan (default: current directory)

EXAMPLES:
    loct scan                    # Scan current directory
    loct scan --full-scan        # Force complete rescan
    loct scan src/ lib/          # Scan specific directories
    loct scan --scan-all         # Include all files (even hidden)
    loct scan --watch            # Watch mode with live refresh"
            .to_string());
    }

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

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--full-scan" => {
                opts.full_scan = true;
                i += 1;
            }
            "--scan-all" => {
                opts.scan_all = true;
                i += 1;
            }
            "--watch" => {
                opts.watch = true;
                i += 1;
            }
            "--replace" => {
                opts.replace = true;
                i += 1;
            }
            "--wait" => {
                opts.wait_indefinite = true;
                i += 1;
            }
            s if s.starts_with("--wait=") => {
                let raw = s.trim_start_matches("--wait=");
                let secs: u64 = raw
                    .parse()
                    .map_err(|_| format!("--wait={} must be a non-negative integer", raw))?;
                opts.wait_seconds = Some(secs);
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'scan' command.", arg));
            }
        }
    }

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

    if (opts.replace || opts.wait_seconds.is_some() || opts.wait_indefinite) && !opts.watch {
        return Err("--replace and --wait only make sense together with --watch.".to_string());
    }

    Ok(Command::Scan(opts))
}

/// Parse `loct watch [MODE] [OPTIONS] [PATHS...]` — the new shape of `loct scan --watch`.
pub(super) fn parse_watch_command(args: &[String]) -> Result<Command, String> {
    if args.iter().any(|a| a == "--help" || a == "-h") {
        // Help text is rendered via `Command::format_command_help("watch")`
        // so the parser only has to refuse to keep going.
        return Err(super::super::command::Command::format_command_help("watch")
            .unwrap_or("loct watch — see --help")
            .to_string());
    }

    let mut opts = WatchOptions::default();
    let mut explicit_mode = false;
    let mut i = 0;

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--dev" => {
                if explicit_mode {
                    return Err("`loct watch`: only one mode flag may be passed".to_string());
                }
                opts.mode = WatchMode::Dev;
                explicit_mode = true;
                i += 1;
            }
            "--bg" => {
                if explicit_mode {
                    return Err("`loct watch`: only one mode flag may be passed".to_string());
                }
                opts.mode = WatchMode::Bg;
                explicit_mode = true;
                i += 1;
            }
            "--lsp" => {
                if explicit_mode {
                    return Err("`loct watch`: only one mode flag may be passed".to_string());
                }
                opts.mode = WatchMode::Lsp;
                explicit_mode = true;
                i += 1;
            }
            "--http" => {
                if explicit_mode {
                    return Err("`loct watch`: only one mode flag may be passed".to_string());
                }
                opts.mode = WatchMode::Http;
                explicit_mode = true;
                i += 1;
            }
            "--report" => {
                if explicit_mode {
                    return Err("`loct watch`: only one mode flag may be passed".to_string());
                }
                opts.mode = WatchMode::Report;
                explicit_mode = true;
                i += 1;
            }
            "--full-scan" => {
                opts.full_scan = true;
                i += 1;
            }
            "--scan-all" => {
                opts.scan_all = true;
                i += 1;
            }
            "--replace" => {
                opts.replace = true;
                i += 1;
            }
            "--wait" => {
                opts.wait_indefinite = true;
                i += 1;
            }
            s if s.starts_with("--wait=") => {
                let raw = s.trim_start_matches("--wait=");
                let secs: u64 = raw
                    .parse()
                    .map_err(|_| format!("--wait={} must be a non-negative integer", raw))?;
                opts.wait_seconds = Some(secs);
                i += 1;
            }
            "--port" => {
                if i + 1 >= args.len() {
                    return Err("--port requires a value (e.g. --port 5174)".to_string());
                }
                let raw = &args[i + 1];
                let port: u16 = raw
                    .parse()
                    .map_err(|_| format!("--port {} must be a u16 (1..65535)", raw))?;
                opts.port = Some(port);
                i += 2;
            }
            s if s.starts_with("--port=") => {
                let raw = s.trim_start_matches("--port=");
                let port: u16 = raw
                    .parse()
                    .map_err(|_| format!("--port={} must be a u16 (1..65535)", raw))?;
                opts.port = Some(port);
                i += 1;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'watch' command.", arg));
            }
        }
    }

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

    Ok(Command::Watch(opts))
}

/// Parse `loct tree [options]` command - display LOC tree.
pub(super) fn parse_tree_command(args: &[String]) -> Result<Command, String> {
    // Check for help flag first
    if args.iter().any(|a| a == "--help" || a == "-h") {
        return Err("loct tree - Display LOC tree / structural overview

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

DESCRIPTION:
    Displays a hierarchical tree view of your codebase structure,
    annotated with lines of code (LOC) metrics for each directory
    and file. Helps understand code distribution and organization.

    Similar to 'tree' command but with LOC counting and better
    handling of gitignored files.

OPTIONS:
    --depth <N>, -L <N>    Maximum depth to display (default: unlimited)
    --summary [N]          Show summary of top N largest items (default: 5)
    --top [N]              Show only top N largest items (default: 50)
    --loc <N>              Only show items with LOC >= N
    --min-loc <N>          Alias for --loc
    --show-hidden, -H      Include hidden files/directories
    --find-artifacts       Highlight build artifacts and generated files
    --show-ignored         Show gitignored files (normally hidden)
    --files                Print matching file paths only, one per line
    --match <REGEX>        Filter output paths by regex
    --help, -h             Show this help message

ARGUMENTS:
    [PATHS...]             Root directories to analyze (default: current directory)

EXAMPLES:
    loct tree                       # Full tree of current directory
    loct tree --depth 3             # Limit to 3 levels deep
    loct tree --summary             # Show top 5 largest items
    loct tree --summary 10          # Show top 10 largest items
    loct tree --loc 100             # Only show files/dirs with 100+ LOC
    loct tree src/ --show-hidden    # Include hidden files in src
    loct tree server --files --match 'test|route' # Exact file list for report/gate work"
            .to_string());
    }

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

    while i < args.len() {
        let arg = &args[i];
        match arg.as_str() {
            "--depth" | "-L" => {
                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;
            }
            "--summary" => {
                if let Some(next) = args.get(i + 1)
                    && !next.starts_with('-')
                {
                    opts.summary = Some(
                        next.parse()
                            .map_err(|_| "--summary value must be a number")?,
                    );
                    i += 2;
                    continue;
                }
                opts.summary = Some(5); // Default summary limit
                i += 1;
            }
            "--top" => {
                if let Some(next) = args.get(i + 1)
                    && !next.starts_with('-')
                {
                    opts.summary = Some(next.parse().map_err(|_| "--top value must be a number")?);
                    i += 2;
                } else {
                    opts.summary = Some(50);
                    i += 1;
                }
                opts.summary_only = true;
            }
            "--loc" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--loc requires a value".to_string())?;
                opts.loc_threshold = Some(value.parse().map_err(|_| "--loc requires a number")?);
                i += 2;
            }
            "--min-loc" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--min-loc requires a value".to_string())?;
                opts.loc_threshold =
                    Some(value.parse().map_err(|_| "--min-loc requires a number")?);
                i += 2;
            }
            "--show-hidden" | "-H" => {
                opts.show_hidden = true;
                i += 1;
            }
            "--find-artifacts" => {
                opts.find_artifacts = true;
                i += 1;
            }
            "--show-ignored" => {
                opts.show_ignored = true;
                i += 1;
            }
            "--files" => {
                opts.files_only = true;
                i += 1;
            }
            "--match" | "--path" => {
                let value = args
                    .get(i + 1)
                    .ok_or_else(|| "--match requires a regex".to_string())?;
                opts.path_filter = Some(value.clone());
                i += 2;
            }
            _ if !arg.starts_with('-') => {
                opts.roots.push(PathBuf::from(arg));
                i += 1;
            }
            _ => {
                return Err(format!("Unknown option '{}' for 'tree' command.", arg));
            }
        }
    }

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

    Ok(Command::Tree(opts))
}

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

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

    #[test]
    fn test_parse_auto_default() {
        let result = parse_auto_command(&[]).unwrap();
        if let Command::Auto(opts) = result {
            assert!(opts.roots.contains(&PathBuf::from(".")));
            assert!(!opts.full_scan);
        } else {
            panic!("Expected Auto command");
        }
    }

    #[test]
    fn test_parse_auto_with_flags() {
        let args = vec!["--full-scan".into(), "--scan-all".into()];
        let result = parse_auto_command(&args).unwrap();
        if let Command::Auto(opts) = result {
            assert!(opts.full_scan);
            assert!(opts.scan_all);
        } else {
            panic!("Expected Auto command");
        }
    }

    #[test]
    fn test_parse_scan_command() {
        let args = vec!["--full-scan".into()];
        let result = parse_scan_command(&args).unwrap();
        if let Command::Scan(opts) = result {
            assert!(opts.full_scan);
        } else {
            panic!("Expected Scan command");
        }
    }

    #[test]
    fn test_parse_tree_command_with_depth() {
        let args = vec!["--depth".into(), "3".into()];
        let result = parse_tree_command(&args).unwrap();
        if let Command::Tree(opts) = result {
            assert_eq!(opts.depth, Some(3));
        } else {
            panic!("Expected Tree command");
        }
    }

    #[test]
    fn test_parse_tree_command_with_files_and_match() {
        let args = vec![
            "--files".into(),
            "--match".into(),
            "test|route".into(),
            "server".into(),
        ];
        let result = parse_tree_command(&args).unwrap();
        if let Command::Tree(opts) = result {
            assert!(opts.files_only);
            assert_eq!(opts.path_filter, Some("test|route".to_string()));
            assert_eq!(opts.roots, vec![PathBuf::from("server")]);
        } else {
            panic!("Expected Tree command");
        }
    }

    #[test]
    fn test_parse_scan_watch_with_replace() {
        let args = vec!["--watch".into(), "--replace".into()];
        let result = parse_scan_command(&args).unwrap();
        if let Command::Scan(opts) = result {
            assert!(opts.watch);
            assert!(opts.replace);
        } else {
            panic!("Expected Scan command");
        }
    }

    #[test]
    fn test_parse_scan_watch_with_wait_seconds() {
        let args = vec!["--watch".into(), "--wait=30".into()];
        let result = parse_scan_command(&args).unwrap();
        if let Command::Scan(opts) = result {
            assert!(opts.watch);
            assert_eq!(opts.wait_seconds, Some(30));
            assert!(!opts.wait_indefinite);
        } else {
            panic!("Expected Scan command");
        }
    }

    #[test]
    fn test_parse_scan_watch_with_wait_indefinite() {
        let args = vec!["--watch".into(), "--wait".into()];
        let result = parse_scan_command(&args).unwrap();
        if let Command::Scan(opts) = result {
            assert!(opts.wait_indefinite);
            assert_eq!(opts.wait_seconds, None);
        } else {
            panic!("Expected Scan command");
        }
    }

    #[test]
    fn test_parse_scan_rejects_replace_without_watch() {
        let args = vec!["--replace".into()];
        let err = parse_scan_command(&args).unwrap_err();
        assert!(
            err.contains("--watch"),
            "error should explain the constraint, got: {err}"
        );
    }

    #[test]
    fn test_parse_watch_default_is_dev_foreground() {
        let result = parse_watch_command(&[]).unwrap();
        if let Command::Watch(opts) = result {
            assert_eq!(opts.mode, WatchMode::Dev);
            assert!(opts.roots.contains(&PathBuf::from(".")));
            assert!(!opts.replace);
            assert!(!opts.wait_indefinite);
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_watch_modes() {
        for (flag, expected) in [
            ("--dev", WatchMode::Dev),
            ("--bg", WatchMode::Bg),
            ("--lsp", WatchMode::Lsp),
            ("--http", WatchMode::Http),
            ("--report", WatchMode::Report),
        ] {
            let result = parse_watch_command(&[flag.into()]).unwrap();
            if let Command::Watch(opts) = result {
                assert_eq!(opts.mode, expected, "for flag {flag}");
            } else {
                panic!("Expected Watch command for {flag}");
            }
        }
    }

    #[test]
    fn test_parse_watch_rejects_two_mode_flags() {
        let args = vec!["--bg".into(), "--lsp".into()];
        let err = parse_watch_command(&args).unwrap_err();
        assert!(
            err.contains("only one mode"),
            "expected mode-conflict error, got: {err}"
        );
    }

    #[test]
    fn test_parse_watch_with_replace_and_wait() {
        let args = vec!["--bg".into(), "--replace".into(), "--wait=15".into()];
        let result = parse_watch_command(&args).unwrap();
        if let Command::Watch(opts) = result {
            assert_eq!(opts.mode, WatchMode::Bg);
            assert!(opts.replace);
            assert_eq!(opts.wait_seconds, Some(15));
        } else {
            panic!("Expected Watch command");
        }
    }

    #[test]
    fn test_parse_watch_with_positional_path() {
        let args = vec!["--dev".into(), "src/".into()];
        let result = parse_watch_command(&args).unwrap();
        if let Command::Watch(opts) = result {
            assert_eq!(opts.roots, vec![PathBuf::from("src/")]);
        } else {
            panic!("Expected Watch command");
        }
    }
}