sqry-cli 10.0.4

CLI for sqry - semantic code search
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Integration tests for P1-11 git-aware index updates
//!
//! These tests verify that `sqry update` correctly leverages git change tracking
//! for incremental builds, with graceful fallback when git is unavailable.
//!
//! # Implementation Notes
//!
//! The git-aware update feature tracks the last indexed commit SHA in the graph
//! manifest (`manifest.json`). This enables:
//! - Git-aware mode: Uses git to detect changed files when a commit is available
//! - Hash-based mode: Falls back to file hash comparison when git is unavailable
//!
//! Environment variables:
//! - `SQRY_GIT_BACKEND=none`: Force hash-based mode even in git repositories
//! - `SQRY_GIT_INCLUDE_UNTRACKED`: Control whether untracked files are indexed

use serial_test::serial;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

mod common;
use common::sqry_bin;

/// Helper to initialize a git repository in a directory
fn init_git_repo(dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
    // Initialize git repo
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["init"])
        .output()?;

    if !output.status.success() {
        return Err(format!(
            "git init failed: {}",
            String::from_utf8_lossy(&output.stderr)
        )
        .into());
    }

    // Configure git user (required for commits)
    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "user.name", "Test User"])
        .output()?;

    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "user.email", "test@example.com"])
        .output()?;

    // Disable commit signing (prevents gitsign OAuth issues in tests)
    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["config", "commit.gpgsign", "false"])
        .output()?;

    Ok(())
}

/// Helper to create and commit a Rust file
fn create_and_commit_file(
    dir: &Path,
    filename: &str,
    content: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let file_path = dir.join(filename);
    fs::write(&file_path, content)?;

    // Add to git
    Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["add", filename])
        .output()?;

    // Commit
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["commit", "-m", &format!("Add {filename}")])
        .output()?;

    if !output.status.success() {
        return Err(format!(
            "git commit failed: {}",
            String::from_utf8_lossy(&output.stderr)
        )
        .into());
    }

    Ok(())
}

/// Helper to run sqry index command
fn run_sqry_index(dir: &Path, force: bool) -> Result<String, Box<dyn std::error::Error>> {
    let mut cmd = Command::new(sqry_bin());
    cmd.arg("index").arg(dir);

    if force {
        cmd.arg("--force");
    }

    let output = cmd.output()?;

    Ok(String::from_utf8_lossy(&output.stdout).to_string()
        + &String::from_utf8_lossy(&output.stderr))
}

/// Helper to run sqry update command
fn run_sqry_update(dir: &Path) -> Result<(String, bool), Box<dyn std::error::Error>> {
    let output = Command::new(sqry_bin()).arg("update").arg(dir).output()?;

    let stdout_stderr = String::from_utf8_lossy(&output.stdout).to_string()
        + &String::from_utf8_lossy(&output.stderr);

    Ok((stdout_stderr, output.status.success()))
}

/// Helper to check if git is available
fn is_git_available() -> bool {
    Command::new("git")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

/// Helper to get current HEAD commit SHA
fn get_head_commit(dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "HEAD"])
        .output()?;

    if !output.status.success() {
        return Err("Failed to get HEAD commit".into());
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Helper to read index metadata and check `last_indexed_commit`
///
/// Reads the graph manifest to get the last indexed commit SHA.
fn get_last_indexed_commit(dir: &Path) -> Result<Option<String>, Box<dyn std::error::Error>> {
    use sqry_core::graph::unified::persistence::GraphStorage;

    let storage = GraphStorage::new(dir);
    if !storage.exists() {
        return Ok(None);
    }

    let manifest = storage.load_manifest()?;
    Ok(manifest.last_indexed_commit)
}

// ============================================================================
// BASIC FUNCTIONALITY TESTS
// ============================================================================

#[test]
#[serial]
fn test_git_aware_update_single_file_change() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    // Initialize git repo
    init_git_repo(repo_path)?;

    // Create initial file and commit
    create_and_commit_file(repo_path, "main.rs", "fn main() { println!(\"v1\"); }")?;

    // Build initial index
    let output = run_sqry_index(repo_path, false)?;
    assert!(output.contains("Index built successfully") || output.contains("indexed"));

    // Verify baseline commit was recorded
    let initial_commit = get_head_commit(repo_path)?;
    let indexed_commit = get_last_indexed_commit(repo_path)?;
    assert_eq!(indexed_commit, Some(initial_commit.clone()));

    // Modify file and commit
    create_and_commit_file(repo_path, "main.rs", "fn main() { println!(\"v2\"); }")?;

    // Update index (should use git-aware mode)
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success, "Update should succeed");

    // Verify it detected the change
    assert!(
        update_output.contains("updated") || update_output.contains("Updated"),
        "Output should indicate files were updated: {update_output}"
    );

    // Verify baseline commit was updated to new HEAD
    let new_commit = get_head_commit(repo_path)?;
    let new_indexed_commit = get_last_indexed_commit(repo_path)?;
    assert_eq!(new_indexed_commit, Some(new_commit));
    assert_ne!(Some(initial_commit), new_indexed_commit);

    Ok(())
}

#[test]
#[serial]
fn test_git_aware_handles_renames() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;

    // Create and commit initial file
    create_and_commit_file(
        repo_path,
        "old_name.rs",
        "fn old_function() { println!(\"hello\"); }",
    )?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Rename file using git mv
    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["mv", "old_name.rs", "new_name.rs"])
        .output()?;

    // Commit rename
    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["commit", "-m", "Rename file"])
        .output()?;

    // Update index
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    // Verify rename was detected and processed
    assert!(
        update_output.contains("updated") || update_output.contains("Updated"),
        "Should detect rename as change: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_full_build_populates_baseline() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "test.rs", "fn test() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Verify baseline commit was recorded
    let head = get_head_commit(repo_path)?;
    let baseline = get_last_indexed_commit(repo_path)?;

    assert_eq!(
        baseline,
        Some(head),
        "Full build should record HEAD as baseline"
    );

    Ok(())
}

#[test]
#[serial]
fn test_uncommitted_changes_detection() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "main.rs", "fn main() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Modify file WITHOUT committing
    fs::write(
        repo_path.join("main.rs"),
        "fn main() { println!(\"modified\"); }",
    )?;

    // Update should detect uncommitted change
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("updated") || update_output.contains("Updated"),
        "Should detect uncommitted changes: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_empty_changeset() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "main.rs", "fn main() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Update without any changes
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    // Should complete quickly with no changes
    assert!(
        update_output.contains("unchanged") || update_output.contains("successfully"),
        "Empty changeset should complete successfully: {update_output}"
    );

    Ok(())
}

// ============================================================================
// FALLBACK TESTS
// ============================================================================

#[test]
#[serial]
fn test_fallback_when_not_git_repo() -> Result<(), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    // Create file WITHOUT initializing git
    fs::write(repo_path.join("main.rs"), "fn main() {}")?;

    // Build index (should work without git)
    let output = run_sqry_index(repo_path, false)?;
    assert!(output.contains("Index built successfully") || output.contains("indexed"));

    // Modify file
    fs::write(repo_path.join("main.rs"), "fn main() { println!(\"v2\"); }")?;

    // Update should fall back to hash-based
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("hash-based") || update_output.contains("updated"),
        "Should fall back to hash-based when not a git repo: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_repo_without_commits() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    // Initialize git repo but DON'T commit anything (HEAD-less)
    init_git_repo(repo_path)?;

    // Create file without committing
    fs::write(repo_path.join("main.rs"), "fn main() {}")?;

    // Build index (should work, baseline will be None)
    let output = run_sqry_index(repo_path, false)?;
    assert!(output.contains("Index built successfully") || output.contains("indexed"));

    // Verify baseline is None (no commits)
    let baseline = get_last_indexed_commit(repo_path)?;
    assert_eq!(baseline, None, "HEAD-less repo should have no baseline");

    // Update should fall back to hash-based
    fs::write(repo_path.join("main.rs"), "fn main() { println!(\"v2\"); }")?;

    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("updated") || update_output.contains("hash-based"),
        "HEAD-less repo should fall back to hash-based: {update_output}"
    );

    Ok(())
}

// ============================================================================
// ENVIRONMENT VARIABLE TESTS
// ============================================================================

#[test]
#[serial]
fn test_untracked_toggle() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "main.rs", "fn main() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Create NEW untracked file (not added to git)
    fs::write(repo_path.join("new.rs"), "fn new() {}")?;

    // Test 1: With SQRY_GIT_INCLUDE_UNTRACKED=1 (default), should include untracked
    let output1 = Command::new(sqry_bin())
        .arg("update")
        .arg(repo_path)
        .env("SQRY_GIT_INCLUDE_UNTRACKED", "1")
        .output()?;

    let output1_str = String::from_utf8_lossy(&output1.stdout).to_string()
        + &String::from_utf8_lossy(&output1.stderr);

    assert!(
        output1_str.contains("updated") || output1_str.contains("Updated"),
        "With SQRY_GIT_INCLUDE_UNTRACKED=1, should index untracked files"
    );

    // Force rebuild for next test
    run_sqry_index(repo_path, true)?;

    // Create another untracked file
    fs::write(repo_path.join("another.rs"), "fn another() {}")?;

    // Test 2: With SQRY_GIT_INCLUDE_UNTRACKED=0, should ignore untracked
    let output2 = Command::new(sqry_bin())
        .arg("update")
        .arg(repo_path)
        .env("SQRY_GIT_INCLUDE_UNTRACKED", "0")
        .output()?;

    assert!(
        output2.status.success(),
        "Update should succeed even with SQRY_GIT_INCLUDE_UNTRACKED=0"
    );

    Ok(())
}

#[test]
#[serial]
fn test_git_backend_none() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "main.rs", "fn main() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Modify and commit
    create_and_commit_file(repo_path, "main.rs", "fn main() { println!(\"v2\"); }")?;

    // Update with SQRY_GIT_BACKEND=none (force hash-based)
    let output = Command::new(sqry_bin())
        .arg("update")
        .arg(repo_path)
        .env("SQRY_GIT_BACKEND", "none")
        .output()?;

    assert!(output.status.success());

    let output_str = String::from_utf8_lossy(&output.stdout).to_string()
        + &String::from_utf8_lossy(&output.stderr);

    // Should not use git-aware mode when explicitly disabled
    assert!(
        output_str.contains("hash-based") || output_str.contains("updated"),
        "SQRY_GIT_BACKEND=none should force hash-based mode"
    );

    Ok(())
}

// ============================================================================
// EDGE CASE TESTS
// ============================================================================

#[test]
#[serial]
fn test_rename_case_change() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "Main.rs", "fn main() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Rename with only case change (Main.rs -> main.rs)
    // Note: This may behave differently on case-insensitive filesystems
    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["mv", "Main.rs", "main.rs"])
        .output()?;

    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["commit", "-m", "Change case"])
        .output()?;

    // Update should handle case change
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success, "Case-change rename should be handled");

    assert!(
        update_output.contains("updated") || update_output.contains("successfully"),
        "Case change should be detected: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_multiple_files_changed() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;

    // Create multiple files
    for i in 1..=10 {
        create_and_commit_file(
            repo_path,
            &format!("file{i}.rs"),
            &format!("fn func{i}() {{}}"),
        )?;
    }

    // Build index
    run_sqry_index(repo_path, false)?;

    // Modify 5 files
    for i in 1..=5 {
        fs::write(
            repo_path.join(format!("file{i}.rs")),
            format!("fn func{i}() {{ println!(\"modified\"); }}"),
        )?;
    }

    // Commit changes
    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["add", "."])
        .output()?;

    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["commit", "-m", "Modify 5 files"])
        .output()?;

    // Update should detect all 5 changes
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("updated") || update_output.contains("Updated"),
        "Should detect multiple file changes: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_deleted_file() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "to_delete.rs", "fn delete_me() {}")?;
    create_and_commit_file(repo_path, "keep.rs", "fn keep() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Delete file
    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["rm", "to_delete.rs"])
        .output()?;

    Command::new("git")
        .arg("-C")
        .arg(repo_path)
        .args(["commit", "-m", "Delete file"])
        .output()?;

    // Update should handle deletion
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("removed")
            || update_output.contains("updated")
            || update_output.contains("successfully"),
        "Should handle file deletion: {update_output}"
    );

    Ok(())
}

#[test]
#[serial]
fn test_added_file() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "existing.rs", "fn existing() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    // Add new file
    create_and_commit_file(repo_path, "new.rs", "fn new() {}")?;

    // Update should detect addition
    let (update_output, success) = run_sqry_update(repo_path)?;
    assert!(success);

    assert!(
        update_output.contains("updated") || update_output.contains("Updated"),
        "Should detect new file: {update_output}"
    );

    Ok(())
}

// ============================================================================
// PERFORMANCE / SMOKE TESTS
// ============================================================================

#[test]
#[serial]
fn test_baseline_commit_updates_after_each_update() -> Result<(), Box<dyn std::error::Error>> {
    if !is_git_available() {
        eprintln!("Skipping test: git not available");
        return Ok(());
    }

    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();

    init_git_repo(repo_path)?;
    create_and_commit_file(repo_path, "v1.rs", "fn v1() {}")?;

    // Build index
    run_sqry_index(repo_path, false)?;

    let baseline1 = get_last_indexed_commit(repo_path)?;
    let head1 = get_head_commit(repo_path)?;
    assert_eq!(baseline1, Some(head1.clone()));

    // Make change 1
    create_and_commit_file(repo_path, "v2.rs", "fn v2() {}")?;
    run_sqry_update(repo_path)?;

    let baseline2 = get_last_indexed_commit(repo_path)?;
    let head2 = get_head_commit(repo_path)?;
    assert_eq!(baseline2, Some(head2.clone()));
    assert_ne!(baseline1, baseline2);

    // Make change 2
    create_and_commit_file(repo_path, "v3.rs", "fn v3() {}")?;
    run_sqry_update(repo_path)?;

    let baseline3 = get_last_indexed_commit(repo_path)?;
    let head3 = get_head_commit(repo_path)?;
    assert_eq!(baseline3, Some(head3));
    assert_ne!(baseline2, baseline3);

    Ok(())
}