pmat 3.19.2

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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

/// Print a single raw search match with surrounding context lines
pub(super) fn print_raw_match_context(
    file_path: &str,
    line_number: usize,
    line_content: &str,
    context_before: &[String],
    context_after: &[String],
) {
    if !context_before.is_empty() {
        let start_line = line_number - context_before.len();
        for (i, line) in context_before.iter().enumerate() {
            println!(
                "{DIM}{}{RESET}:{DIM}{}{RESET}-{}",
                file_path,
                start_line + i,
                line
            );
        }
    }
    println!(
        "{BOLD}{CYAN}{}{RESET}:{YELLOW}{}{RESET}:{}",
        file_path, line_number, line_content
    );
    if !context_after.is_empty() {
        for (i, line) in context_after.iter().enumerate() {
            println!(
                "{DIM}{}{RESET}:{DIM}{}{RESET}-{}",
                file_path,
                line_number + 1 + i,
                line
            );
        }
    }
}

/// Handle `--raw` mode: pure file-level search without the function index
#[allow(clippy::too_many_arguments)]
pub(super) fn handle_raw_search_mode(
    query: &str,
    limit: usize,
    format: &QueryOutputFormat,
    quiet: bool,
    literal: bool,
    ignore_case: bool,
    language: &Option<String>,
    exclude_file: &[String],
    exclude: &[String],
    files_with_matches: bool,
    count: bool,
    context_lines: Option<usize>,
    after_context: Option<usize>,
    before_context: Option<usize>,
    project_path: &std::path::Path,
    exclude_tests: bool,
) -> anyhow::Result<()> {
    let ctx_after = context_lines.or(after_context).unwrap_or(0);
    let ctx_before = context_lines.or(before_context).unwrap_or(0);
    let excl_files: Vec<&str> = exclude_file.iter().map(|s| s.as_str()).collect();
    let raw_opts = RawSearchOptions {
        pattern: query,
        literal,
        case_insensitive: ignore_case,
        before_context: ctx_before,
        after_context: ctx_after,
        limit,
        language_filter: language.as_deref(),
        exclude_file_pattern: excl_files,
        exclude_pattern: exclude.iter().map(|s| s.as_str()).collect(),
        files_with_matches,
        count_mode: count,
    };
    let output = raw_search(project_path, &raw_opts).map_err(|e| anyhow::anyhow!("{}", e))?;
    // --exclude-tests in raw mode: filter results from test files by path
    // heuristic. The glob exclude can't reliably express nested test paths
    // (e.g. src/**/foo_tests_basic.rs), so filter the output directly.
    let output = if exclude_tests {
        drop_test_file_results(output)
    } else {
        output
    };
    print_raw_search_output(&output, format, quiet)
}

/// Drop raw-search results originating from test files (for `--exclude-tests`).
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
fn drop_test_file_results(output: RawSearchOutput) -> RawSearchOutput {
    use super::options::is_test_path;
    match output {
        RawSearchOutput::Files(files) => {
            RawSearchOutput::Files(files.into_iter().filter(|f| !is_test_path(f)).collect())
        }
        RawSearchOutput::Counts(counts) => RawSearchOutput::Counts(
            counts
                .into_iter()
                .filter(|c| !is_test_path(&c.file_path))
                .collect(),
        ),
        RawSearchOutput::Lines(lines) => RawSearchOutput::Lines(
            lines
                .into_iter()
                .filter(|l| !is_test_path(&l.file_path))
                .collect(),
        ),
    }
}

fn print_raw_search_output(
    output: &RawSearchOutput,
    format: &QueryOutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    match output {
        RawSearchOutput::Files(files) => {
            for f in files {
                println!("{CYAN}{f}{RESET}");
            }
        }
        RawSearchOutput::Counts(counts) => {
            for c in counts {
                println!("{CYAN}{}{RESET}:{YELLOW}{}{RESET}", c.file_path, c.count);
            }
        }
        RawSearchOutput::Lines(lines) => {
            print_raw_lines(lines, format, quiet)?;
        }
    }
    Ok(())
}

fn print_raw_lines(
    lines: &[RawSearchResult],
    format: &QueryOutputFormat,
    quiet: bool,
) -> anyhow::Result<()> {
    if matches!(format, QueryOutputFormat::Json) {
        let json = serde_json::to_string_pretty(lines).map_err(|e| anyhow::anyhow!("{}", e))?;
        println!("{}", json);
    } else {
        for r in lines {
            print_raw_match_context(
                &r.file_path,
                r.line_number,
                &r.line_content,
                &r.context_before,
                &r.context_after,
            );
        }
    }
    if !quiet {
        eprintln!("{} matches", lines.len());
    }
    Ok(())
}

/// Run raw search and return non-overlapping results for merge with index results.
/// Used when `--regex` or `--literal` is active (without `--raw`).
#[allow(clippy::too_many_arguments)]
pub(super) fn run_raw_search_for_merge(
    query: &str,
    limit: usize,
    literal: bool,
    ignore_case: bool,
    language: &Option<String>,
    exclude_file: &[String],
    exclude: &[String],
    context_lines: Option<usize>,
    after_context: Option<usize>,
    before_context: Option<usize>,
    project_path: &std::path::Path,
    indexed_results: &[QueryResult],
) -> Vec<RawSearchResult> {
    let remaining = limit.saturating_sub(indexed_results.len());
    if remaining == 0 {
        return Vec::new();
    }

    let ctx_after = context_lines.or(after_context).unwrap_or(0);
    let ctx_before = context_lines.or(before_context).unwrap_or(0);
    let excl_refs: Vec<&str> = exclude_file.iter().map(|s| s.as_str()).collect();
    let raw_opts = RawSearchOptions {
        pattern: query,
        literal,
        case_insensitive: ignore_case,
        before_context: ctx_before,
        after_context: ctx_after,
        limit: remaining + indexed_results.len(), // over-fetch to account for dedup
        language_filter: language.as_deref(),
        exclude_file_pattern: excl_refs,
        exclude_pattern: exclude.iter().map(|s| s.as_str()).collect(),
        files_with_matches: false,
        count_mode: false,
    };

    let output = match raw_search(project_path, &raw_opts) {
        Ok(o) => o,
        Err(_) => return Vec::new(),
    };

    let lines = match output {
        RawSearchOutput::Lines(l) => l,
        _ => return Vec::new(),
    };

    // Filter out matches that overlap with indexed function results
    lines
        .into_iter()
        .filter(|r| !is_within_indexed_function(&r.file_path, r.line_number, indexed_results))
        .take(remaining)
        .collect()
}

/// Run raw search and return file paths for merge with --files-with-matches mode.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_raw_files_for_merge(
    query: &str,
    literal: bool,
    ignore_case: bool,
    language: &Option<String>,
    exclude_file: &[String],
    exclude: &[String],
    project_path: &std::path::Path,
) -> Vec<String> {
    let excl_refs: Vec<&str> = exclude_file.iter().map(|s| s.as_str()).collect();
    let raw_opts = RawSearchOptions {
        pattern: query,
        literal,
        case_insensitive: ignore_case,
        before_context: 0,
        after_context: 0,
        limit: 0,
        language_filter: language.as_deref(),
        exclude_file_pattern: excl_refs,
        exclude_pattern: exclude.iter().map(|s| s.as_str()).collect(),
        files_with_matches: true,
        count_mode: false,
    };
    match raw_search(project_path, &raw_opts) {
        Ok(RawSearchOutput::Files(f)) => f,
        _ => Vec::new(),
    }
}

/// Run raw search and return per-file counts for merge with --count mode.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_raw_counts_for_merge(
    query: &str,
    literal: bool,
    ignore_case: bool,
    language: &Option<String>,
    exclude_file: &[String],
    exclude: &[String],
    project_path: &std::path::Path,
) -> Vec<crate::services::agent_context::FileMatchCount> {
    let excl_refs: Vec<&str> = exclude_file.iter().map(|s| s.as_str()).collect();
    let raw_opts = RawSearchOptions {
        pattern: query,
        literal,
        case_insensitive: ignore_case,
        before_context: 0,
        after_context: 0,
        limit: 0,
        language_filter: language.as_deref(),
        exclude_file_pattern: excl_refs,
        exclude_pattern: exclude.iter().map(|s| s.as_str()).collect(),
        files_with_matches: false,
        count_mode: true,
    };
    match raw_search(project_path, &raw_opts) {
        Ok(RawSearchOutput::Counts(c)) => c,
        _ => Vec::new(),
    }
}

// `items_after_test_module` fires because `modes_raw_search.rs` is
// include!()'d into modes.rs ahead of the other `modes_*.rs` siblings —
// so this test module is *textually* followed by production items from
// other include files. Silence the lint since reordering the includes
// would churn the entire handler module for no gain.
#[allow(clippy::items_after_test_module)]
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod modes_raw_search_tests {
    use super::*;

    /// Drives print_raw_match_context through all four arms:
    /// empty/non-empty context_before × empty/non-empty context_after.
    #[test]
    fn test_print_raw_match_context_all_context_shapes() {
        // No context either side — skips both for/iter blocks.
        print_raw_match_context("a.rs", 10, "let x = 1;", &[], &[]);
        // Before only.
        print_raw_match_context(
            "a.rs",
            10,
            "let x = 1;",
            &["fn foo() {".to_string(), "    // body".to_string()],
            &[],
        );
        // After only.
        print_raw_match_context(
            "a.rs",
            10,
            "let x = 1;",
            &[],
            &["    return x;".to_string(), "}".to_string()],
        );
        // Both.
        print_raw_match_context(
            "a.rs",
            10,
            "let x = 1;",
            &["before".to_string()],
            &["after".to_string()],
        );
    }

    /// print_raw_search_output dispatches on the RawSearchOutput variant.
    /// Each arm only does println!, so just calling it ticks coverage.
    #[test]
    fn test_print_raw_search_output_files_variant() {
        let out = RawSearchOutput::Files(vec!["a.rs".into(), "b.rs".into()]);
        print_raw_search_output(&out, &QueryOutputFormat::Text, true).unwrap();
    }

    #[test]
    fn test_print_raw_search_output_counts_variant() {
        let out = RawSearchOutput::Counts(vec![
            crate::services::agent_context::FileMatchCount {
                file_path: "a.rs".into(),
                count: 3,
            },
            crate::services::agent_context::FileMatchCount {
                file_path: "b.rs".into(),
                count: 1,
            },
        ]);
        print_raw_search_output(&out, &QueryOutputFormat::Text, true).unwrap();
    }

    #[test]
    fn test_print_raw_search_output_lines_variant_text_format() {
        let out = RawSearchOutput::Lines(vec![RawSearchResult {
            file_path: "a.rs".into(),
            line_number: 1,
            line_content: "fn x() {}".into(),
            context_before: vec![],
            context_after: vec![],
        }]);
        // Text format → delegates to print_raw_lines → print_raw_match_context.
        print_raw_search_output(&out, &QueryOutputFormat::Text, true).unwrap();
    }

    #[test]
    fn test_print_raw_search_output_lines_variant_json_format() {
        let out = RawSearchOutput::Lines(vec![RawSearchResult {
            file_path: "a.rs".into(),
            line_number: 1,
            line_content: "fn x() {}".into(),
            context_before: vec!["before".into()],
            context_after: vec!["after".into()],
        }]);
        // JSON format → serializes via serde_json::to_string_pretty.
        print_raw_search_output(&out, &QueryOutputFormat::Json, true).unwrap();
    }

    /// print_raw_lines non-quiet vs quiet: the trailing "N matches" eprintln
    /// only fires when quiet=false.
    #[test]
    fn test_print_raw_lines_quiet_vs_verbose() {
        let lines = vec![RawSearchResult {
            file_path: "a.rs".into(),
            line_number: 1,
            line_content: "x".into(),
            context_before: vec![],
            context_after: vec![],
        }];
        // Verbose: hits the `!quiet` eprintln branch.
        print_raw_lines(&lines, &QueryOutputFormat::Text, false).unwrap();
        // Quiet: skips it.
        print_raw_lines(&lines, &QueryOutputFormat::Text, true).unwrap();
    }

    /// run_raw_search_for_merge should return empty when `remaining = 0`
    /// (the early-exit branch on line 147). limit=0 with empty indexed =>
    /// 0.saturating_sub(0) == 0 => early return.
    #[test]
    fn test_run_raw_search_for_merge_early_exit_on_zero_limit() {
        let tmp = tempfile::tempdir().unwrap();
        let out = run_raw_search_for_merge(
            "fn",
            0, // limit=0 → remaining=0 → early exit
            false,
            false,
            &None,
            &[],
            &[],
            None,
            None,
            None,
            tmp.path(),
            &[],
        );
        assert!(out.is_empty(), "limit=0 → empty merge result");
    }
}