metsuke 0.1.1

metsuke 目付 — the typed review surface of a code forge: read what awaits your judgment (pull requests, diffs, review threads) and record the verdict. Mockable Forge/ForgeReview seams over a `gh` backend; no merge, no close, no push.
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
//! The `gh` backend: argv construction and answer parsing, kept apart from
//! the process that runs them.
//!
//! # Why `gh` and not an HTTP client with a token
//!
//! Not for lack of ambition. `gh` already solves the part of this problem
//! that is nobody's favourite: credential discovery across keyring, config
//! file, `GH_TOKEN`, `GITHUB_TOKEN`, an enterprise host, and a GitHub App
//! installation. An HTTP backend that ignores all that works on the author's
//! machine and fails in CI. The fleet already reached this conclusion once —
//! `izumi`'s GitHub sources all run through `gh` — and reaching it twice by
//! different reasoning is a good sign it is right.
//!
//! It is still a *backend*, behind [`crate::Forge`]. An HTTP one can be added
//! beside it without a consumer noticing, which is the point of the seam.
//!
//! # Why the argv and the parse are separate functions
//!
//! Because then both are testable with no subprocess at all. [`search_argv`]
//! is a pure function from a lane to a command line, and [`parse_search`] is
//! a pure function from bytes to types. The only untestable-without-a-network
//! part left is the four lines that actually spawn — which is exactly how
//! much untested surface this is worth having.

use crate::forge::{Forge, ForgeReview};
use crate::types::{
    FilePatch, ForgeError, Involvement, PrNumber, PrState, PrSummary, RepoId, Result,
    ReviewComment, Verdict,
};

/// The JSON fields a PR search asks for. Named once so the request and the
/// parser cannot drift — the failure mode being a field the parser reads and
/// the request never asked for, which presents as a confusing null.
pub const SEARCH_FIELDS: &str = "number,title,author,state,isDraft,updatedAt,url,repository";

/// The argv for a PR search. Pure — no process, no environment.
#[must_use]
pub fn search_argv(lane: Involvement, limit: usize) -> Vec<String> {
    vec![
        "search".into(),
        "prs".into(),
        lane.qualifier().into(),
        "--state=open".into(),
        "--limit".into(),
        limit.to_string(),
        "--json".into(),
        SEARCH_FIELDS.into(),
    ]
}

/// The argv for one PR's changed files.
#[must_use]
pub fn files_argv(repo: &RepoId, number: PrNumber) -> Vec<String> {
    let mut endpoint = String::from("repos/");
    endpoint.push_str(&repo.owner);
    endpoint.push('/');
    endpoint.push_str(&repo.name);
    endpoint.push_str("/pulls/");
    endpoint.push_str(&number.0.to_string());
    endpoint.push_str("/files");
    vec![
        "api".into(),
        endpoint,
        "--paginate".into(),
        "--slurp".into(),
    ]
}

/// The argv for one PR's review comments.
#[must_use]
pub fn comments_argv(repo: &RepoId, number: PrNumber) -> Vec<String> {
    let mut endpoint = String::from("repos/");
    endpoint.push_str(&repo.owner);
    endpoint.push('/');
    endpoint.push_str(&repo.name);
    endpoint.push_str("/pulls/");
    endpoint.push_str(&number.0.to_string());
    endpoint.push_str("/comments");
    vec![
        "api".into(),
        endpoint,
        "--paginate".into(),
        "--slurp".into(),
    ]
}

/// The argv for submitting a verdict.
///
/// The body goes through `--body`, never interpolated into a shell string:
/// a review body is arbitrary operator prose and will eventually contain a
/// quote, a backtick, or a newline.
#[must_use]
pub fn review_argv(repo: &RepoId, number: PrNumber, verdict: &Verdict) -> Vec<String> {
    let mut slug = String::from(&repo.owner);
    slug.push('/');
    slug.push_str(&repo.name);
    vec![
        "pr".into(),
        "review".into(),
        number.0.to_string(),
        "--repo".into(),
        slug,
        verdict.flag().into(),
        "--body".into(),
        verdict.body().into(),
    ]
}

// ── Parsing ────────────────────────────────────────────────────────────

fn state_from(state: &str, merged_hint: bool) -> PrState {
    match state.to_ascii_uppercase().as_str() {
        "MERGED" => PrState::Merged,
        "CLOSED" if merged_hint => PrState::Merged,
        "CLOSED" => PrState::Closed,
        _ => PrState::Open,
    }
}

fn str_at(v: &serde_json::Value, key: &str) -> String {
    v.get(key).and_then(|x| x.as_str()).unwrap_or("").to_owned()
}

/// Parse `gh search prs --json …` output.
///
/// # Errors
/// [`ForgeError::Unparseable`] when the payload is not a JSON array of
/// objects. A row missing its repository or number is SKIPPED rather than
/// defaulted — a PR whose coordinate we cannot determine is one we must not
/// show, because every action on it would target the wrong place.
pub fn parse_search(raw: &str) -> Result<Vec<PrSummary>> {
    let v: serde_json::Value = serde_json::from_str(raw).map_err(|e| ForgeError::Unparseable {
        operation: "search",
        raw: e.to_string(),
    })?;
    let arr = v.as_array().ok_or_else(|| ForgeError::Unparseable {
        operation: "search",
        raw: raw.chars().take(200).collect(),
    })?;

    let mut out = Vec::with_capacity(arr.len());
    for row in arr {
        let Some(number) = row.get("number").and_then(serde_json::Value::as_u64) else {
            continue;
        };
        let Some(repo) = row
            .get("repository")
            .and_then(|r| r.get("nameWithOwner").or_else(|| r.get("name")))
            .and_then(|x| x.as_str())
            .and_then(|s| RepoId::parse(s).ok())
        else {
            continue;
        };
        out.push(PrSummary {
            repo,
            number: PrNumber(number),
            title: str_at(row, "title"),
            author: row
                .get("author")
                .and_then(|a| a.get("login"))
                .and_then(|x| x.as_str())
                .unwrap_or("")
                .to_owned(),
            state: state_from(&str_at(row, "state"), false),
            draft: row
                .get("isDraft")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false),
            updated_at: str_at(row, "updatedAt"),
            url: str_at(row, "url"),
        });
    }
    Ok(out)
}

/// Parse `GET /pulls/{n}/files`.
///
/// # Errors
/// [`ForgeError::Unparseable`] on a payload that is not an array (or an array
/// of arrays, which is what `--paginate --slurp` produces).
pub fn parse_files(raw: &str) -> Result<Vec<FilePatch>> {
    let rows = flatten_pages(raw, "files")?;
    Ok(rows
        .iter()
        .filter_map(|row| {
            let path = row.get("filename").and_then(|x| x.as_str())?.to_owned();
            Some(FilePatch {
                path,
                previous_path: row
                    .get("previous_filename")
                    .and_then(|x| x.as_str())
                    .map(ToOwned::to_owned),
                additions: row
                    .get("additions")
                    .and_then(serde_json::Value::as_u64)
                    .unwrap_or(0) as u32,
                deletions: row
                    .get("deletions")
                    .and_then(serde_json::Value::as_u64)
                    .unwrap_or(0) as u32,
                // Absent for a binary or oversized file. Kept as `None`
                // rather than `Some("")` — see `FilePatch::patch`.
                patch: row
                    .get("patch")
                    .and_then(|x| x.as_str())
                    .map(ToOwned::to_owned),
            })
        })
        .collect())
}

/// Parse `GET /pulls/{n}/comments`.
///
/// # Errors
/// [`ForgeError::Unparseable`] on a non-array payload.
pub fn parse_comments(raw: &str) -> Result<Vec<ReviewComment>> {
    let rows = flatten_pages(raw, "comments")?;
    Ok(rows
        .iter()
        .map(|row| ReviewComment {
            author: row
                .get("user")
                .and_then(|u| u.get("login"))
                .and_then(|x| x.as_str())
                .unwrap_or("")
                .to_owned(),
            body: str_at(row, "body"),
            path: row
                .get("path")
                .and_then(|x| x.as_str())
                .map(ToOwned::to_owned),
            // GitHub sends `line: null` for an outdated thread. That null is
            // information — it means the anchor is gone — so it is preserved
            // rather than defaulted to line 0, which would point a reader at
            // the top of the file with no hint that it was wrong.
            line: row
                .get("line")
                .and_then(serde_json::Value::as_u64)
                .map(|n| n as u32),
            created_at: str_at(row, "created_at"),
        })
        .collect())
}

/// `gh api --paginate --slurp` yields an array of pages, each an array of
/// rows. A single un-paginated call yields a flat array. Accept both, because
/// which one you get depends on a flag the parser cannot see.
fn flatten_pages(raw: &str, operation: &'static str) -> Result<Vec<serde_json::Value>> {
    let v: serde_json::Value = serde_json::from_str(raw).map_err(|e| ForgeError::Unparseable {
        operation,
        raw: e.to_string(),
    })?;
    let arr = v.as_array().ok_or_else(|| ForgeError::Unparseable {
        operation,
        raw: raw.chars().take(200).collect(),
    })?;
    let mut out = Vec::new();
    for item in arr {
        match item.as_array() {
            Some(page) => out.extend(page.iter().cloned()),
            None => out.push(item.clone()),
        }
    }
    Ok(out)
}

// ── The runner ─────────────────────────────────────────────────────────

/// Runs `gh`. The one part of this module that touches the world.
pub trait GhRunner {
    /// Run `gh` with `args`, returning stdout.
    ///
    /// # Errors
    /// Any [`ForgeError`] — chiefly `NotAuthenticated`, `Unreachable`, or
    /// `Backend` carrying stderr.
    fn run(&self, args: &[String]) -> Result<String>;
}

/// The real runner: spawns `gh`.
#[derive(Debug, Clone, Copy, Default)]
pub struct RealGh;

impl GhRunner for RealGh {
    fn run(&self, args: &[String]) -> Result<String> {
        let out = std::process::Command::new("gh")
            .args(args)
            .output()
            .map_err(|e| ForgeError::Unreachable {
                detail: e.to_string(),
            })?;
        if out.status.success() {
            return String::from_utf8(out.stdout).map_err(|e| ForgeError::Unparseable {
                operation: "gh",
                raw: e.to_string(),
            });
        }
        let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
        // `gh` reports an absent credential on stderr and nowhere else, so
        // this string match is the only signal available. It is a heuristic
        // and is marked as one rather than presented as a typed guarantee.
        if stderr.contains("gh auth login") || stderr.contains("authentication") {
            return Err(ForgeError::NotAuthenticated { detail: stderr });
        }
        Err(ForgeError::Backend {
            operation: "gh",
            detail: stderr,
        })
    }
}

/// The `gh`-backed forge.
#[derive(Debug, Clone, Default)]
pub struct GhForge<R: GhRunner> {
    runner: R,
}

impl<R: GhRunner> GhForge<R> {
    pub const fn new(runner: R) -> Self {
        Self { runner }
    }
}

impl<R: GhRunner> Forge for GhForge<R> {
    fn search(&self, lane: Involvement, limit: usize) -> Result<Vec<PrSummary>> {
        parse_search(&self.runner.run(&search_argv(lane, limit))?)
    }

    fn pull_request(&self, repo: &RepoId, number: PrNumber) -> Result<PrSummary> {
        // Reuses the search parser over a one-element view rather than adding
        // a second PR-shaped parser that would drift from it.
        let mut slug = String::from(&repo.owner);
        slug.push('/');
        slug.push_str(&repo.name);
        let args = vec![
            "pr".into(),
            "view".into(),
            number.0.to_string(),
            "--repo".into(),
            slug,
            "--json".into(),
            SEARCH_FIELDS.into(),
        ];
        let raw = self.runner.run(&args)?;
        // `gh pr view` returns an object; the search parser wants an array.
        let mut wrapped = String::from("[");
        wrapped.push_str(&raw);
        wrapped.push(']');
        parse_search(&wrapped)?
            .into_iter()
            .next()
            .ok_or_else(|| ForgeError::Unparseable {
                operation: "pull_request",
                raw: raw.chars().take(200).collect(),
            })
    }

    fn files(&self, repo: &RepoId, number: PrNumber) -> Result<Vec<FilePatch>> {
        parse_files(&self.runner.run(&files_argv(repo, number))?)
    }

    fn comments(&self, repo: &RepoId, number: PrNumber) -> Result<Vec<ReviewComment>> {
        parse_comments(&self.runner.run(&comments_argv(repo, number))?)
    }
}

impl<R: GhRunner> ForgeReview for GhForge<R> {
    fn submit_review(&self, repo: &RepoId, number: PrNumber, verdict: &Verdict) -> Result<()> {
        self.runner.run(&review_argv(repo, number, verdict))?;
        Ok(())
    }
}

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

    /// Records argv, replays canned stdout. No subprocess.
    #[derive(Default)]
    struct ScriptedGh {
        calls: RefCell<Vec<Vec<String>>>,
        reply: String,
    }

    impl GhRunner for ScriptedGh {
        fn run(&self, args: &[String]) -> Result<String> {
            self.calls.borrow_mut().push(args.to_vec());
            Ok(self.reply.clone())
        }
    }

    #[test]
    fn every_lane_produces_its_own_qualifier_in_argv() {
        for lane in Involvement::all() {
            let argv = search_argv(*lane, 5);
            assert!(
                argv.contains(&lane.qualifier().to_owned()),
                "{lane:?} argv must carry its qualifier: {argv:?}"
            );
            assert!(argv.contains(&"5".to_owned()), "limit must reach argv");
        }
    }

    #[test]
    fn a_review_body_is_a_separate_argv_element_never_interpolated() {
        let repo = RepoId::parse("pleme-io/metsuke").unwrap();
        let nasty = "it's \"wrong\"; `rm -rf /`\nsecond line";
        let argv = review_argv(&repo, PrNumber(7), &Verdict::Comment(nasty.into()));
        assert!(
            argv.iter().any(|a| a == nasty),
            "the body must survive verbatim as ONE argument: {argv:?}"
        );
        assert!(argv.contains(&"--comment".to_owned()));
    }

    #[test]
    fn each_verdict_lowers_to_its_own_flag() {
        let repo = RepoId::parse("pleme-io/metsuke").unwrap();
        let flags: Vec<String> = [
            Verdict::Comment(String::new()),
            Verdict::Approve(String::new()),
            Verdict::RequestChanges(String::new()),
        ]
        .iter()
        .map(|v| review_argv(&repo, PrNumber(1), v)[5].clone())
        .collect();
        assert_eq!(flags, vec!["--comment", "--approve", "--request-changes"]);
    }

    const SEARCH_JSON: &str = r#"[
      {"number":12,"title":"add the thing","author":{"login":"drzzln"},
       "state":"OPEN","isDraft":false,"updatedAt":"2026-08-03T01:00:00Z",
       "url":"https://github.com/pleme-io/metsuke/pull/12",
       "repository":{"nameWithOwner":"pleme-io/metsuke"}},
      {"number":13,"title":"draft work","author":{"login":"other"},
       "state":"OPEN","isDraft":true,"updatedAt":"2026-08-02T01:00:00Z",
       "url":"u","repository":{"nameWithOwner":"pleme-io/banken"}}
    ]"#;

    #[test]
    fn search_parses_into_typed_rows() {
        let got = parse_search(SEARCH_JSON).unwrap();
        assert_eq!(got.len(), 2);
        assert_eq!(got[0].number, PrNumber(12));
        assert_eq!(got[0].repo.to_string(), "pleme-io/metsuke");
        assert_eq!(got[0].author, "drzzln");
        assert!(!got[0].draft);
        assert!(got[1].draft, "isDraft must survive the parse");
    }

    #[test]
    fn a_row_with_no_determinable_repo_is_dropped_not_defaulted() {
        let raw = r#"[{"number":1,"title":"t","repository":{}},
                      {"number":2,"title":"u","repository":{"nameWithOwner":"a/b"}}]"#;
        let got = parse_search(raw).unwrap();
        assert_eq!(
            got.len(),
            1,
            "a PR whose coordinate is unknown must not be shown — every action on it \
             would target the wrong repo"
        );
        assert_eq!(got[0].number, PrNumber(2));
    }

    #[test]
    fn search_rejects_a_non_array_payload_loudly() {
        let e = parse_search("{\"message\":\"Bad credentials\"}").unwrap_err();
        assert!(matches!(e, ForgeError::Unparseable { .. }), "got {e:?}");
    }

    #[test]
    fn files_parse_and_a_binary_file_has_no_patch() {
        let raw = r#"[[
          {"filename":"src/lib.rs","additions":10,"deletions":2,"patch":"@@ -1 +1 @@\n-a\n+b"},
          {"filename":"logo.png","additions":0,"deletions":0},
          {"filename":"new.rs","previous_filename":"old.rs","additions":1,"deletions":1,"patch":"@@"}
        ]]"#;
        let got = parse_files(raw).unwrap();
        assert_eq!(got.len(), 3, "--slurp's page-of-pages must be flattened");
        assert_eq!(got[0].additions, 10);
        assert!(got[0].patch.is_some());
        assert!(
            got[1].patch.is_none(),
            "a binary file has NO patch — not an empty one"
        );
        assert_eq!(got[2].previous_path.as_deref(), Some("old.rs"));
    }

    #[test]
    fn an_unpaginated_flat_array_parses_the_same_as_a_slurped_one() {
        let flat = r#"[{"filename":"a.rs","additions":1,"deletions":0,"patch":"@@"}]"#;
        let slurped = r#"[[{"filename":"a.rs","additions":1,"deletions":0,"patch":"@@"}]]"#;
        assert_eq!(parse_files(flat).unwrap(), parse_files(slurped).unwrap());
    }

    #[test]
    fn an_outdated_comment_keeps_its_null_line() {
        let raw = r#"[{"user":{"login":"a"},"body":"stale note","path":"src/x.rs",
                       "line":null,"created_at":"2026-08-01T00:00:00Z"},
                      {"user":{"login":"b"},"body":"live note","path":"src/x.rs",
                       "line":42,"created_at":"2026-08-02T00:00:00Z"}]"#;
        let got = parse_comments(raw).unwrap();
        assert_eq!(got.len(), 2);
        assert!(
            got[0].line.is_none(),
            "a null line means the anchor is gone; defaulting it to 0 would point \
             the reader at the wrong place with no hint"
        );
        assert_eq!(got[1].line, Some(42));
    }

    #[test]
    fn the_forge_calls_gh_with_the_argv_it_built() {
        let gh = ScriptedGh {
            reply: SEARCH_JSON.to_owned(),
            ..Default::default()
        };
        let forge = GhForge::new(gh);
        let got = forge.search(Involvement::ReviewRequested, 25).unwrap();
        assert_eq!(got.len(), 2);
        let calls = forge.runner.calls.borrow();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0], search_argv(Involvement::ReviewRequested, 25));
    }
}