sqry-cli 11.0.1

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
//! Integration tests for pager functionality
//!
//! Tests verify that paging works correctly across different commands,
//! output formats, and environment configurations.

use serial_test::serial;
use std::fs;
use std::process::{Command, Stdio};
use tempfile::{TempDir, tempdir};

mod common;

use common::sqry_bin;

fn create_temp_project() -> TempDir {
    let temp = tempdir().expect("Failed to create temp dir");
    fs::write(
        temp.path().join("main.rs"),
        "fn sample() {}\nfn helper() {}\n",
    )
    .expect("Failed to write sample file");
    temp
}

fn command_with_isolated_env(temp: &TempDir) -> Command {
    let mut cmd = Command::new(sqry_bin());
    cmd.current_dir(temp.path());
    cmd.env("SQRY_CONFIG_DIR", temp.path().join("config"));
    cmd.env("SQRY_CACHE_DIR", temp.path().join("cache"));
    cmd.env("SQRY_DATA_DIR", temp.path().join("data"));
    cmd.env("SQRY_NO_HISTORY", "1");
    cmd
}

fn project_with_index() -> TempDir {
    let temp = create_temp_project();
    let status = command_with_isolated_env(&temp)
        .args(["index", temp.path().to_str().unwrap()])
        .status()
        .expect("Failed to index test project");
    assert!(
        status.success(),
        "Indexing failed for test project with status {:?}",
        status.code()
    );
    temp
}

#[test]
fn test_no_pager_flag_direct_output() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--no-pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    assert!(output.status.success());
    // Output should contain results (not empty)
    assert!(!output.stdout.is_empty() || !output.stderr.is_empty());
}

#[test]
fn test_json_bypasses_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--json", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    assert!(output.status.success());
    // Should be valid JSON
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.starts_with('{') || stdout.starts_with('['));
}

#[test]
fn test_csv_bypasses_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--csv", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    assert!(output.status.success());
    // CSV should be direct output (no pager)
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.is_empty());
}

#[test]
fn test_tsv_bypasses_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--tsv", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    assert!(output.status.success());
    // TSV should be direct output (no pager)
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.is_empty());
}

#[test]
fn test_pipe_bypasses_pager() {
    let temp = project_with_index();
    let sqry = command_with_isolated_env(&temp)
        .args(["query", "kind:function", "."])
        .stdout(Stdio::piped())
        .spawn()
        .expect("Failed to spawn sqry");

    let output = sqry.wait_with_output().expect("Failed to wait");
    assert!(output.status.success());
}

#[test]
fn test_pager_cmd_flag() {
    // Use 'cat' as a simple pager that passes through
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args([
            "--pager-cmd",
            "cat",
            "--pager",
            "query",
            "kind:function",
            ".",
        ])
        .output()
        .expect("Failed to execute");

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

#[test]
#[serial]
fn test_sqry_pager_env_respected() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .env("SQRY_PAGER", "cat")
        .args(["--pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

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

#[test]
#[serial]
fn test_pager_env_fallback() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .env_remove("SQRY_PAGER")
        .env("PAGER", "cat")
        .args(["--pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

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

#[test]
#[serial]
fn test_missing_pager_fallback() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .env("SQRY_PAGER", "nonexistent_pager_command_12345")
        .args(["--pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    // Per CLI spec: pager not found → success (exit 0) + warning
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "Expected success for missing pager (not found fallback), got {:?}. stderr: {}",
        output.status.code(),
        stderr
    );
    // Check for spec-compliant warning message format with actionable guidance
    assert!(
        stderr.contains("Warning: pager") && stderr.contains("not found"),
        "Expected warning about pager not found, got: {stderr}"
    );
    // Verify actionable help text is included
    assert!(
        stderr.contains("SQRY_PAGER"),
        "Expected warning to include actionable guidance about SQRY_PAGER, got: {stderr}"
    );
}

#[test]
#[serial]
fn test_pager_spawn_error_exits_nonzero() {
    // Per CLI spec (§3.3): spawn failures (other than not-found) should exit 1
    // Use a directory as the pager command - will fail with permission/not-executable error
    let temp = project_with_index();

    // Use /tmp (or temp dir) as pager - it exists but is not executable
    let non_executable_path = temp.path().to_str().unwrap();
    let output = command_with_isolated_env(&temp)
        .env("SQRY_PAGER", non_executable_path)
        .args(["--pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // On some systems, trying to execute a directory returns NotFound,
    // on others it returns PermissionDenied or other errors.
    // The key is: if it's NotFound, we get exit 0 + warning;
    // if it's another error, we get exit 1 + error message.
    if stderr.contains("not found") {
        // NotFound case - should succeed (exit 0) per spec
        assert!(
            output.status.success(),
            "Expected success (exit 0) for 'not found' case, got {:?}",
            output.status.code()
        );
        assert!(
            stderr.contains("Warning:"),
            "Expected warning message for not found case, got: {stderr}"
        );
    } else if stderr.contains("Error: Failed to start pager") {
        // Spawn error case - MUST fail with exit code 1 per spec §3.3
        assert!(
            !output.status.success(),
            "Expected non-zero exit for spawn error, got success. stderr: {stderr}"
        );
        // Per Codex review: explicitly assert exit code 1 to prevent regressions
        assert_eq!(
            output.status.code(),
            Some(1),
            "Spec requires exit code 1 for pager spawn failures (non-NotFound). Got {:?}. stderr: {}",
            output.status.code(),
            stderr
        );
    }
    // Either way, output should still be written to stdout (fallback behavior)
    // The deferred error pattern ensures output is produced before exit
}

#[test]
fn test_json_with_explicit_pager() {
    // JSON with explicit --pager should use pager
    // This tests that --pager flag is authoritative
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args([
            "--json",
            "--pager",
            "--pager-cmd",
            "cat",
            "query",
            "kind:function",
            ".",
        ])
        .output()
        .expect("Failed to execute");

    assert!(output.status.success());
    // Should still be valid JSON (cat passes through)
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.starts_with('{') || stdout.starts_with('['));
}

#[test]
fn test_search_command_with_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--pager-cmd", "cat", "--pager", "search", "test", "."])
        .output()
        .expect("Failed to execute");

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

#[test]
fn test_workspace_command_with_pager() {
    let temp = project_with_index();
    let workspace_path = temp.path().join("workspace");
    fs::create_dir_all(&workspace_path).expect("Failed to create workspace dir");

    let init_output = command_with_isolated_env(&temp)
        .args(["workspace", "init", workspace_path.to_str().unwrap()])
        .output()
        .expect("Failed to initialize workspace");

    if init_output.status.success() {
        let output = command_with_isolated_env(&temp)
            .args([
                "--pager-cmd",
                "cat",
                "--pager",
                "workspace",
                "query",
                workspace_path.to_str().unwrap(),
                "kind:function",
            ])
            .output()
            .expect("Failed to execute");

        // Workspace query may return empty results, but should succeed
        assert!(output.status.success() || output.status.code() == Some(1));
    } else {
        panic!(
            "Workspace init failed with status {:?}",
            init_output.status.code()
        );
    }
}

#[test]
fn test_history_command_with_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args([
            "--pager-cmd",
            "cat",
            "--pager",
            "history",
            "list",
            "--limit",
            "10",
        ])
        .output()
        .expect("Failed to execute");

    // History may be empty, but command should succeed
    assert!(output.status.success());
}

#[test]
fn test_alias_command_with_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--pager-cmd", "cat", "--pager", "alias", "list"])
        .output()
        .expect("Failed to execute");

    // Alias list may be empty, but command should succeed
    assert!(output.status.success());
}

#[test]
fn test_index_status_with_pager() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args([
            "--pager-cmd",
            "cat",
            "--pager",
            "index",
            "status",
            temp.path().to_str().unwrap(),
        ])
        .output()
        .expect("Failed to execute");

    // Index may not exist or have validation issues, but command should handle gracefully
    // Exit codes: 0 = success, 1 = no index found, 2 = validation failure (all valid)
    let exit_code = output.status.code().unwrap_or(-1);
    assert!(
        exit_code == 0 || exit_code == 1 || exit_code == 2,
        "Unexpected exit code: {exit_code}"
    );
}

#[test]
#[cfg_attr(
    target_os = "windows",
    ignore = "Windows lacks a portable always-failing pager command"
)]
fn test_pager_exit_code_propagation() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args([
            "--pager",
            "--pager-cmd",
            "false",
            "query",
            "kind:function",
            ".",
        ])
        .output()
        .expect("Failed to execute");

    assert!(
        !output.status.success(),
        "Expected non-zero exit when pager exits with failure"
    );
}

#[test]
fn test_conflicting_pager_and_no_pager_flags() {
    let temp = project_with_index();
    let output = command_with_isolated_env(&temp)
        .args(["--pager", "--no-pager", "query", "kind:function", "."])
        .output()
        .expect("Failed to execute");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "Conflicting pager flags should be rejected cleanly"
    );
    assert!(
        stderr.contains("cannot be used with"),
        "Expected conflict error message about pager flags"
    );
}