croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! GitHub code scanning (#577): the analyses a repository has, one
//! analysis as a SARIF log, and dismissing an alert — as `gh` arguments and
//! parsers, so the calls themselves stay with the caller.
//!
//! Every endpoint uses `gh`'s `{owner}/{repo}` placeholders, which `gh`
//! fills from the repository it runs in.

use super::model::SarifResult;

/// One code scanning analysis, as the analyses list reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Analysis {
    pub id: u64,
    pub git_ref: String,
    pub commit_sha: String,
    pub tool: String,
    pub category: String,
    pub created_at: String,
    pub results_count: u64,
    /// Non-empty when the upload failed processing.
    pub error: String,
}

/// One open or dismissed alert, enough to find it from a result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alert {
    pub number: u64,
    pub rule_id: String,
    pub path: String,
    pub start_line: i64,
    pub state: String,
}

/// Why an alert is dismissed: the three reasons the API accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DismissReason {
    FalsePositive,
    WontFix,
    UsedInTests,
}

impl DismissReason {
    pub const ALL: [DismissReason; 3] = [
        DismissReason::FalsePositive,
        DismissReason::WontFix,
        DismissReason::UsedInTests,
    ];

    /// The API's spelling.
    pub fn api(self) -> &'static str {
        match self {
            DismissReason::FalsePositive => "false positive",
            DismissReason::WontFix => "won't fix",
            DismissReason::UsedInTests => "used in tests",
        }
    }
}

/// Percent-encode a query value: everything but RFC 3986 unreserved bytes.
fn encode(v: &str) -> String {
    let mut out = String::new();
    for b in v.bytes() {
        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

fn with_ref(mut url: String, git_ref: Option<&str>) -> String {
    if let Some(r) = git_ref {
        url.push_str("&ref=");
        url.push_str(&encode(r));
    }
    url
}

/// Whether croft loads GitHub code scanning results by itself (#577): the
/// `code_scanning` setting. `On` loads the current branch's analyses, and
/// again whenever the branch changes; `Prompt` says they are there and
/// waits for "SARIF: Load Code Scanning Results"; `Off` (the default) never
/// calls GitHub unasked.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CodeScanningMode {
    #[default]
    Off,
    On,
    Prompt,
}

/// The analyses to load for a checkout (#577): those at the nearest
/// scanned commit, walking `history` (the local first-parent history, HEAD
/// first), newest per tool and category. When none of the history was
/// scanned, the newest analysis per tool and category instead.
pub fn nearest_per_tool(analyses: &[Analysis], history: &[String]) -> Vec<Analysis> {
    let usable: Vec<&Analysis> = analyses.iter().filter(|a| a.error.is_empty()).collect();
    let at_nearest: Vec<&Analysis> = history
        .iter()
        .map(|sha| {
            usable
                .iter()
                .copied()
                .filter(|a| &a.commit_sha == sha)
                .collect::<Vec<_>>()
        })
        .find(|found| !found.is_empty())
        .unwrap_or(usable);
    let mut newest: std::collections::BTreeMap<(String, String), &Analysis> =
        std::collections::BTreeMap::new();
    for a in at_nearest {
        let key = (a.tool.clone(), a.category.clone());
        match newest.get(&key) {
            Some(b) if b.created_at >= a.created_at => {}
            _ => {
                newest.insert(key, a);
            }
        }
    }
    newest.into_values().cloned().collect()
}

/// `gh` arguments listing the most recent analyses, optionally for one ref.
/// One page only: the newest analyses are the ones worth opening.
pub fn analyses_args(git_ref: Option<&str>) -> Vec<String> {
    vec![
        String::from("api"),
        with_ref(
            String::from("repos/{owner}/{repo}/code-scanning/analyses?per_page=30"),
            git_ref,
        ),
    ]
}

/// A JSON array from the API, or the message of the error object it sent.
/// Several arrays one after another (`gh api --paginate`'s pages) are one
/// list; an error object anywhere is the error.
fn api_array(json: &str) -> Result<Vec<serde_json::Value>, String> {
    let mut out = Vec::new();
    for v in serde_json::Deserializer::from_str(json).into_iter::<serde_json::Value>() {
        match v.map_err(|e| format!("unreadable reply: {e}"))? {
            serde_json::Value::Array(a) => out.extend(a),
            other => {
                return Err(other
                    .get("message")
                    .and_then(|m| m.as_str())
                    .unwrap_or("unexpected reply")
                    .to_string());
            }
        }
    }
    Ok(out)
}

fn text(v: &serde_json::Value, key: &str) -> String {
    v.get(key)
        .and_then(|x| x.as_str())
        .unwrap_or_default()
        .to_string()
}

/// The analyses list, or the API's own message when it answered an error
/// object (no code scanning, a missing scope).
pub fn parse_analyses(json: &str) -> Result<Vec<Analysis>, String> {
    Ok(api_array(json)?
        .iter()
        .map(|a| {
            let tool = a.get("tool").cloned().unwrap_or_default();
            let name = text(&tool, "name");
            let version = text(&tool, "version");
            Analysis {
                id: a.get("id").and_then(|x| x.as_u64()).unwrap_or(0),
                git_ref: text(a, "ref"),
                commit_sha: text(a, "commit_sha"),
                tool: if version.is_empty() {
                    name
                } else {
                    format!("{name} {version}")
                },
                category: text(a, "category"),
                created_at: text(a, "created_at"),
                results_count: a.get("results_count").and_then(|x| x.as_u64()).unwrap_or(0),
                error: text(a, "error"),
            }
        })
        .collect())
}

/// A picker line: "#id ref · tool category · N results · created".
pub fn label(a: &Analysis) -> String {
    let git_ref = a
        .git_ref
        .strip_prefix("refs/heads/")
        .or_else(|| a.git_ref.strip_prefix("refs/"))
        .unwrap_or(&a.git_ref);
    let tool = if a.category.is_empty() {
        a.tool.clone()
    } else {
        format!("{} {}", a.tool, a.category)
    };
    let when: String = a
        .created_at
        .chars()
        .take(16)
        .collect::<String>()
        .replace('T', " ");
    let mut out = format!(
        "#{} {git_ref} \u{b7} {tool} \u{b7} {} result{} \u{b7} {when}",
        a.id,
        a.results_count,
        if a.results_count == 1 { "" } else { "s" }
    );
    if !a.error.is_empty() {
        out.push_str(&format!(" \u{b7} failed: {}", a.error));
    }
    out
}

/// `gh` arguments fetching one analysis as SARIF.
pub fn sarif_args(id: u64) -> Vec<String> {
    vec![
        String::from("api"),
        String::from("-H"),
        String::from("Accept: application/sarif+json"),
        format!("repos/{{owner}}/{{repo}}/code-scanning/analyses/{id}"),
    ]
}

/// `gh` arguments listing every alert, for matching results. All pages:
/// the alert a result is dismissed through can be anywhere in the list, and
/// one page of 100 left a repository's older alerts unmatchable (#577).
/// `gh --paginate` prints the pages as JSON arrays one after another, which
/// [`parse_alerts`] reads as one list.
pub fn alerts_args(git_ref: Option<&str>) -> Vec<String> {
    vec![
        String::from("api"),
        String::from("--paginate"),
        with_ref(
            String::from("repos/{owner}/{repo}/code-scanning/alerts?per_page=100"),
            git_ref,
        ),
    ]
}

/// The alerts list, or the API's message.
pub fn parse_alerts(json: &str) -> Result<Vec<Alert>, String> {
    Ok(api_array(json)?
        .iter()
        .map(|a| {
            let loc = a
                .get("most_recent_instance")
                .and_then(|i| i.get("location"))
                .cloned()
                .unwrap_or_default();
            Alert {
                number: a.get("number").and_then(|x| x.as_u64()).unwrap_or(0),
                rule_id: a.get("rule").map(|r| text(r, "id")).unwrap_or_default(),
                path: text(&loc, "path"),
                start_line: loc.get("start_line").and_then(|x| x.as_i64()).unwrap_or(0),
                state: text(a, "state"),
            }
        })
        .collect())
}

/// The alert number GitHub stamped on a result (`github/alertNumber`).
pub fn alert_number(result: &SarifResult) -> Option<u64> {
    result.properties.get("github/alertNumber")?.as_u64()
}

/// The alert a result stands for: same rule, same repository path, same
/// start line.
pub fn match_alert(alerts: &[Alert], rule_id: &str, path: &str, line: i64) -> Option<u64> {
    alerts
        .iter()
        .find(|a| a.rule_id == rule_id && a.path == path && a.start_line == line)
        .map(|a| a.number)
}

/// `gh` arguments dismissing alert `number`; a blank comment is left out.
pub fn dismiss_args(number: u64, reason: DismissReason, comment: &str) -> Vec<String> {
    let mut args: Vec<String> = [
        "api",
        "-X",
        "PATCH",
        &format!("repos/{{owner}}/{{repo}}/code-scanning/alerts/{number}"),
        "-f",
        "state=dismissed",
        "-f",
        &format!("dismissed_reason={}", reason.api()),
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    if !comment.trim().is_empty() {
        args.push(String::from("-f"));
        args.push(format!("dismissed_comment={}", comment.trim()));
    }
    args
}

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

    fn analysis(id: u64, sha: &str, tool: &str, created: &str) -> Analysis {
        Analysis {
            id,
            git_ref: String::from("refs/heads/main"),
            commit_sha: sha.into(),
            tool: tool.into(),
            category: String::new(),
            created_at: created.into(),
            results_count: 0,
            error: String::new(),
        }
    }

    #[test]
    fn the_nearest_scanned_commit_gives_one_analysis_per_tool() {
        let list = vec![
            analysis(1, "c3", "CodeQL", "2026-09-03"),
            analysis(2, "c2", "CodeQL", "2026-09-02"),
            analysis(3, "c2", "Semgrep", "2026-09-02"),
            analysis(4, "c2", "CodeQL", "2026-09-02T10"),
        ];
        // HEAD (c9) was never scanned; its parent c2 was, twice by CodeQL.
        let history: Vec<String> = ["c9", "c2", "c3"].map(String::from).to_vec();
        let ids: Vec<u64> = nearest_per_tool(&list, &history)
            .iter()
            .map(|a| a.id)
            .collect();
        assert_eq!(ids, [4, 3], "newest CodeQL at c2, and Semgrep");
        // Nothing in the history scanned: the newest per tool anywhere.
        let ids: Vec<u64> = nearest_per_tool(&list, &[String::from("zz")])
            .iter()
            .map(|a| a.id)
            .collect();
        assert_eq!(ids, [1, 3]);
        // A failed analysis is never chosen.
        let mut failed = analysis(5, "c9", "CodeQL", "2026-09-09");
        failed.error = String::from("boom");
        let mut with_failed = list.clone();
        with_failed.push(failed);
        assert!(
            nearest_per_tool(&with_failed, &history)
                .iter()
                .all(|a| a.id != 5)
        );
        assert_eq!(
            serde_json::from_str::<CodeScanningMode>("\"prompt\"").unwrap(),
            CodeScanningMode::Prompt
        );
        assert_eq!(CodeScanningMode::default(), CodeScanningMode::Off);
    }

    const ANALYSES: &str = r#"[
      {"id":201,"ref":"refs/heads/main","commit_sha":"abc123","analysis_key":".github/workflows/codeql.yml:analyze",
       "environment":"{}","error":"","category":"/language:rust","created_at":"2026-09-20T10:00:00Z",
       "results_count":7,"rules_count":40,"tool":{"name":"CodeQL","version":"2.19.3"},"deletable":true},
      {"id":200,"ref":"refs/pull/12/merge","commit_sha":"def456","error":"upload failed",
       "category":"","created_at":"2026-09-19T09:00:00Z","results_count":0,"tool":{"name":"Semgrep","version":null}}
    ]"#;

    #[test]
    fn analyses_are_listed_one_page_newest_first_optionally_for_a_ref() {
        assert_eq!(
            analyses_args(None),
            vec![
                "api",
                "repos/{owner}/{repo}/code-scanning/analyses?per_page=30"
            ]
        );
        assert_eq!(
            analyses_args(Some("refs/heads/feat/x y")),
            vec![
                "api",
                "repos/{owner}/{repo}/code-scanning/analyses?per_page=30&ref=refs%2Fheads%2Ffeat%2Fx%20y"
            ]
        );
    }

    #[test]
    fn analyses_parse_with_their_tool_and_error() {
        let list = parse_analyses(ANALYSES).unwrap();
        assert_eq!(list.len(), 2);
        assert_eq!(
            list[0],
            Analysis {
                id: 201,
                git_ref: "refs/heads/main".into(),
                commit_sha: "abc123".into(),
                tool: "CodeQL 2.19.3".into(),
                category: "/language:rust".into(),
                created_at: "2026-09-20T10:00:00Z".into(),
                results_count: 7,
                error: String::new(),
            }
        );
        assert_eq!(list[1].tool, "Semgrep");
        assert_eq!(list[1].error, "upload failed");
    }

    #[test]
    fn an_api_error_object_is_reported_in_its_own_words() {
        let err = parse_analyses(
            r#"{"message":"no analysis found","documentation_url":"https://docs.github.com"}"#,
        )
        .unwrap_err();
        assert_eq!(err, "no analysis found");
        assert!(parse_analyses("not json").is_err());
    }

    #[test]
    fn a_label_names_the_ref_tool_count_and_date() {
        let list = parse_analyses(ANALYSES).unwrap();
        assert_eq!(
            label(&list[0]),
            "#201 main \u{b7} CodeQL 2.19.3 /language:rust \u{b7} 7 results \u{b7} 2026-09-20 10:00"
        );
        assert_eq!(
            label(&list[1]),
            "#200 pull/12/merge \u{b7} Semgrep \u{b7} 0 results \u{b7} 2026-09-19 09:00 \u{b7} failed: upload failed"
        );
    }

    #[test]
    fn an_analysis_is_fetched_as_sarif() {
        assert_eq!(
            sarif_args(201),
            vec![
                "api",
                "-H",
                "Accept: application/sarif+json",
                "repos/{owner}/{repo}/code-scanning/analyses/201"
            ]
        );
    }

    const ALERTS: &str = r#"[
      {"number":7,"state":"open","rule":{"id":"rust/sql-injection"},
       "most_recent_instance":{"location":{"path":"src/db.rs","start_line":42}}},
      {"number":8,"state":"dismissed","rule":{"id":"rust/sql-injection"},
       "most_recent_instance":{"location":{"path":"src/db.rs","start_line":90}}}
    ]"#;

    #[test]
    fn alerts_parse_and_a_result_finds_its_alert_by_rule_path_and_line() {
        assert_eq!(
            alerts_args(Some("refs/heads/main")),
            vec![
                "api",
                "--paginate",
                "repos/{owner}/{repo}/code-scanning/alerts?per_page=100&ref=refs%2Fheads%2Fmain"
            ]
        );
        // `--paginate` prints each page as its own array; they are one list.
        let paged = format!("{ALERTS}\n{ALERTS}");
        assert_eq!(parse_alerts(&paged).unwrap().len(), 4);
        assert_eq!(parse_alerts("[]\n[]").unwrap().len(), 0);
        assert_eq!(parse_alerts("").unwrap().len(), 0);
        assert_eq!(
            parse_alerts(r#"[] {"message": "Resource not accessible"}"#).unwrap_err(),
            "Resource not accessible"
        );
        let alerts = parse_alerts(ALERTS).unwrap();
        assert_eq!(alerts.len(), 2);
        assert_eq!(alerts[1].state, "dismissed");
        assert_eq!(
            match_alert(&alerts, "rust/sql-injection", "src/db.rs", 90),
            Some(8)
        );
        assert_eq!(
            match_alert(&alerts, "rust/sql-injection", "src/db.rs", 41),
            None
        );
        assert_eq!(match_alert(&alerts, "other", "src/db.rs", 42), None);
    }

    #[test]
    fn a_stamped_alert_number_is_read_from_the_result() {
        let r: SarifResult =
            serde_json::from_str(r#"{"properties":{"github/alertNumber":7}}"#).unwrap();
        assert_eq!(alert_number(&r), Some(7));
        let none: SarifResult = serde_json::from_str("{}").unwrap();
        assert_eq!(alert_number(&none), None);
    }

    #[test]
    fn dismissing_sends_the_reason_in_the_apis_spelling_and_the_comment() {
        assert_eq!(
            dismiss_args(7, DismissReason::WontFix, "tracked in #12"),
            vec![
                "api",
                "-X",
                "PATCH",
                "repos/{owner}/{repo}/code-scanning/alerts/7",
                "-f",
                "state=dismissed",
                "-f",
                "dismissed_reason=won't fix",
                "-f",
                "dismissed_comment=tracked in #12"
            ]
        );
        // No comment, no empty field.
        assert_eq!(dismiss_args(7, DismissReason::FalsePositive, " ").len(), 8);
    }
}