lziff-github 0.1.3

GitHub backend for lziff. Future plugin candidate; stays compile-time isolated from the lziff body.
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
//! GitHub review backend for lziff.
//!
//! ════════════════════════════════════════════════════════════════════════
//!  FUTURE PLUGIN — DO NOT IMPORT FROM `lziff` INTERNALS
//! ════════════════════════════════════════════════════════════════════════
//!
//! This crate is the GitHub-specific [`ReviewProvider`] implementation.
//! It will eventually be split out into a separate process speaking the
//! `review-protocol` JSON-RPC over stdio. To keep that future viable:
//!
//! - The crate's `Cargo.toml` depends on `review-protocol` and
//!   `serde_json` only. **Adding `lziff = ...` here is a hard policy
//!   violation** — nothing in the GitHub plugin should know what's
//!   inside the host.
//! - All public types and methods are reachable through the
//!   [`ReviewProvider`] trait. The host
//!   (`crates/lziff/src/main.rs` via `crates/lziff/src/review.rs`)
//!   only ever obtains a `Box<dyn ReviewProvider>` from
//!   [`make_provider`] and never names `GithubProvider` directly.
//! - We shell out to the user's `gh` CLI (already authenticated).
//!   Going through HTTP+OAuth is left for the eventual stand-alone
//!   plugin once we hit a perf/feature wall.

use review_protocol::{
    CommentSide, ListQuery, NewComment, PrRef, PrState, PrSummary, ProviderResult, PullRequest,
    ReviewComment, ReviewError, ReviewProvider, ReviewVerdict, WorktreeHandle,
};
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::process::Command;

pub fn make_provider() -> Box<dyn ReviewProvider> {
    Box::new(GithubProvider)
}

struct GithubProvider;

impl ReviewProvider for GithubProvider {
    fn id(&self) -> &'static str {
        "github"
    }

    fn check_ready(&self) -> ProviderResult<()> {
        let out = Command::new("gh")
            .args(["auth", "status"])
            .output()
            .map_err(|e| {
                ReviewError::NotAuthenticated(format!(
                    "could not run `gh` (is the GitHub CLI installed?): {e}"
                ))
            })?;
        if !out.status.success() {
            return Err(ReviewError::NotAuthenticated(
                String::from_utf8_lossy(&out.stderr).trim().to_string(),
            ));
        }
        Ok(())
    }

    fn list_pull_requests(&self, query: ListQuery) -> ProviderResult<Vec<PrSummary>> {
        let fields = "number,title,author,headRefName,baseRefName,state,url";
        let mut args = vec!["pr", "list", "--json", fields];
        if query.assigned_to_me {
            args.extend_from_slice(&["--search", "review-requested:@me state:open"]);
        }
        if let Some(state) = query.state {
            // gh accepts open|closed|merged|all — map our enum.
            let s = match state {
                PrState::Open => "open",
                PrState::Closed => "closed",
                PrState::Merged => "merged",
                PrState::All => "all",
            };
            args.extend_from_slice(&["--state", s]);
        }
        let raw = run_gh(&args)?;
        let parsed: Vec<RawPrSummary> = serde_json::from_slice(&raw)
            .map_err(|e| ReviewError::Backend(format!("parse gh pr list: {e}")))?;
        Ok(parsed.into_iter().map(RawPrSummary::into_protocol).collect())
    }

    fn get_pull_request(&self, r: PrRef) -> ProviderResult<PullRequest> {
        let arg = match &r {
            PrRef::Number(n) => n.to_string(),
            PrRef::Branch(b) => b.clone(),
            PrRef::Url(u) => u.clone(),
        };
        // Note: gh's `pr view --json` does NOT currently expose `baseRefOid`
        // or `baseRepository` (verified against gh 2.x — the field list its
        // error message prints out includes neither). We resolve the base
        // SHA ourselves after fetching the base branch in the host, and we
        // derive owner/name from the URL when needed.
        let fields = "number,title,body,author,headRefName,baseRefName,headRefOid,state,url";
        let raw = run_gh(&["pr", "view", &arg, "--json", fields])?;
        let parsed: RawPrFull = serde_json::from_slice(&raw)
            .map_err(|e| ReviewError::Backend(format!("parse gh pr view: {e}")))?;
        Ok(parsed.into_protocol())
    }

    fn ensure_worktree(
        &self,
        pr: &PullRequest,
        cache_root: &str,
    ) -> ProviderResult<WorktreeHandle> {
        // If the user is already on the PR's branch in the cwd repo, work
        // there. Cheap check: `git rev-parse --abbrev-ref HEAD`.
        if let Ok(cur) = git_current_branch() {
            if cur == pr.branch {
                let cwd = std::env::current_dir()
                    .map(|p| p.display().to_string())
                    .unwrap_or_else(|_| ".".into());
                return Ok(WorktreeHandle {
                    path: cwd,
                    cleanup_on_drop: false,
                });
            }
        }

        // Otherwise: fetch the PR head into a refspec we own and add a
        // worktree at <cache_root>/<owner>-<repo>-<num>. Using the
        // `pull/<n>/head` refspec works on github.com without us needing
        // to know whether the PR comes from a fork.
        let dest_dir =
            format!("{}-{}-{}", pr.repo_owner, pr.repo_name, pr.number);
        let dest = Path::new(cache_root).join(&dest_dir);
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                ReviewError::Backend(format!("create cache dir {}: {}", parent.display(), e))
            })?;
        }

        let pr_ref = format!("pull/{}/head", pr.number);
        let local_ref = format!("refs/lziff/review/{}", pr.number);
        // Inherit stdio for fetch + worktree add so the user sees git's
        // own progress output, and — critically — so SSH/credential
        // prompts (passphrase, host-key confirmation, askpass helpers)
        // are routed to the user's terminal. Capturing them, as
        // `run_git` does, is what made `--review` look hung when origin
        // needed a credential.
        eprintln!(
            "lziff:   git fetch origin +{pr_ref}:{local_ref}"
        );
        run_git_inherit(&[
            "fetch",
            "origin",
            &format!("+{pr_ref}:{local_ref}"),
        ])?;
        // If a stale worktree exists at this path, remove it first.
        let _ = run_git(&["worktree", "remove", "--force", dest.to_str().unwrap_or("")]);
        eprintln!(
            "lziff:   git worktree add {} {}",
            dest.display(),
            short_sha(&pr.head_sha)
        );
        run_git_inherit(&[
            "worktree",
            "add",
            "--detach",
            dest.to_str().unwrap_or_default(),
            &pr.head_sha,
        ])?;
        Ok(WorktreeHandle {
            path: dest.to_string_lossy().into_owned(),
            cleanup_on_drop: true,
        })
    }

    fn list_review_comments(&self, _pr: &PullRequest) -> ProviderResult<Vec<ReviewComment>> {
        // Wire-up plan: combine
        //   `gh api repos/{owner}/{repo}/pulls/{n}/comments` (line-anchored)
        //   `gh api repos/{owner}/{repo}/issues/{n}/comments`  (PR-level)
        // Skipping for the first cut — the diff UX works without comments.
        Ok(Vec::new())
    }

    fn submit_review(
        &self,
        pr: &PullRequest,
        body: &str,
        verdict: ReviewVerdict,
        comments: Vec<NewComment>,
    ) -> ProviderResult<()> {
        if pr.repo_owner.is_empty() || pr.repo_name.is_empty() {
            return Err(ReviewError::Backend(
                "PR is missing repo owner/name (cannot submit)".into(),
            ));
        }
        // Build the JSON body matching GitHub's
        //   POST /repos/{owner}/{repo}/pulls/{n}/reviews
        let payload = ReviewPayload {
            commit_id: pr.head_sha.clone(),
            body: body.to_string(),
            event: match verdict {
                ReviewVerdict::Comment => "COMMENT",
                ReviewVerdict::Approve => "APPROVE",
                ReviewVerdict::RequestChanges => "REQUEST_CHANGES",
            }
            .to_string(),
            comments: comments.into_iter().map(NewCommentJson::from).collect(),
        };
        let body_json = serde_json::to_string(&payload)
            .map_err(|e| ReviewError::Backend(format!("encode review body: {e}")))?;
        let endpoint =
            format!("repos/{}/{}/pulls/{}/reviews", pr.repo_owner, pr.repo_name, pr.number);
        // `gh api -X POST <endpoint> --input -` reads JSON from stdin.
        let mut child = Command::new("gh")
            .args(["api", "-X", "POST", &endpoint, "--input", "-"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| ReviewError::Backend(format!("spawn gh: {e}")))?;
        if let Some(stdin) = child.stdin.as_mut() {
            use std::io::Write;
            stdin
                .write_all(body_json.as_bytes())
                .map_err(|e| ReviewError::Backend(format!("write gh stdin: {e}")))?;
        }
        let out = child
            .wait_with_output()
            .map_err(|e| ReviewError::Backend(format!("wait gh: {e}")))?;
        if !out.status.success() {
            let msg = String::from_utf8_lossy(&out.stderr).trim().to_string();
            return Err(classify_gh_error(&msg));
        }
        Ok(())
    }
}

#[derive(Serialize)]
struct ReviewPayload {
    commit_id: String,
    body: String,
    event: String,
    comments: Vec<NewCommentJson>,
}

#[derive(Serialize)]
struct NewCommentJson {
    path: String,
    line: u32,
    side: &'static str,
    body: String,
}

impl From<NewComment> for NewCommentJson {
    fn from(c: NewComment) -> Self {
        Self {
            path: c.path,
            line: c.line,
            side: match c.side {
                CommentSide::Old => "LEFT",
                CommentSide::New => "RIGHT",
            },
            body: c.body,
        }
    }
}

// ---------------------------------------------------------------------------
// Subprocess helpers

fn run_gh(args: &[&str]) -> ProviderResult<Vec<u8>> {
    let out = Command::new("gh")
        .args(args)
        .output()
        .map_err(|e| ReviewError::Backend(format!("spawn gh: {e}")))?;
    if !out.status.success() {
        let msg = String::from_utf8_lossy(&out.stderr).trim().to_string();
        return Err(classify_gh_error(&msg));
    }
    Ok(out.stdout)
}

fn run_git(args: &[&str]) -> ProviderResult<Vec<u8>> {
    let out = Command::new("git")
        .args(args)
        .output()
        .map_err(|e| ReviewError::Backend(format!("spawn git: {e}")))?;
    if !out.status.success() {
        return Err(ReviewError::Backend(format!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        )));
    }
    Ok(out.stdout)
}

/// Run `git` with stdio inherited from the parent process. Use this for
/// commands that may prompt the user (fetch over SSH/HTTPS, worktree
/// commands that touch the filesystem) so progress and prompts flow to
/// the user's terminal instead of being silently captured.
fn run_git_inherit(args: &[&str]) -> ProviderResult<()> {
    let status = Command::new("git")
        .args(args)
        .status()
        .map_err(|e| ReviewError::Backend(format!("spawn git: {e}")))?;
    if !status.success() {
        return Err(ReviewError::Backend(format!(
            "git {} failed (exit {})",
            args.join(" "),
            status.code().unwrap_or(-1)
        )));
    }
    Ok(())
}

fn short_sha(sha: &str) -> String {
    sha.chars().take(8).collect()
}

fn git_current_branch() -> Result<String, ReviewError> {
    let out = run_git(&["rev-parse", "--abbrev-ref", "HEAD"])?;
    Ok(String::from_utf8_lossy(&out).trim().to_string())
}

fn classify_gh_error(msg: &str) -> ReviewError {
    let lower = msg.to_ascii_lowercase();
    if lower.contains("not authenticated") || lower.contains("authenticate") {
        ReviewError::NotAuthenticated(msg.into())
    } else if lower.contains("no pull requests found")
        || lower.contains("not found")
        || lower.contains("could not find")
    {
        ReviewError::NotFound(msg.into())
    } else if lower.contains("network") || lower.contains("timeout") {
        ReviewError::Network(msg.into())
    } else {
        ReviewError::Backend(msg.into())
    }
}

// ---------------------------------------------------------------------------
// gh JSON shapes

#[derive(Deserialize, Default)]
struct RawAuthor {
    #[serde(default)]
    login: String,
}

#[derive(Deserialize)]
struct RawPrSummary {
    number: u64,
    title: String,
    #[serde(default)]
    author: RawAuthor,
    #[serde(rename = "headRefName", default)]
    head_ref_name: String,
    #[serde(rename = "baseRefName", default)]
    base_ref_name: String,
    #[serde(default)]
    state: String,
    #[serde(default)]
    url: String,
}

impl RawPrSummary {
    fn into_protocol(self) -> PrSummary {
        PrSummary {
            number: self.number,
            title: self.title,
            author: self.author.login,
            branch: self.head_ref_name,
            base: self.base_ref_name,
            state: parse_state(&self.state),
            url: self.url,
        }
    }
}

#[derive(Deserialize)]
struct RawPrFull {
    number: u64,
    title: String,
    #[serde(default)]
    body: String,
    #[serde(default)]
    author: RawAuthor,
    #[serde(rename = "headRefName", default)]
    head_ref_name: String,
    #[serde(rename = "baseRefName", default)]
    base_ref_name: String,
    #[serde(rename = "headRefOid", default)]
    head_ref_oid: String,
    #[serde(default)]
    state: String,
    #[serde(default)]
    url: String,
}

impl RawPrFull {
    fn into_protocol(self) -> PullRequest {
        // owner/name come from the URL — `gh pr view --json` doesn't
        // currently expose `baseRepository`, so we parse them ourselves.
        let (mut owner, mut name) = (String::new(), String::new());
        if let Some((o, n)) = parse_owner_name_from_url(&self.url) {
            owner = o;
            name = n;
        }
        PullRequest {
            number: self.number,
            title: self.title,
            body: self.body,
            author: self.author.login,
            branch: self.head_ref_name,
            base: self.base_ref_name,
            head_sha: self.head_ref_oid,
            // Resolved by the host (lziff::review) after the base branch
            // has been fetched into the worktree.
            base_sha: String::new(),
            state: parse_state(&self.state),
            url: self.url,
            repo_owner: owner,
            repo_name: name,
        }
    }
}


fn parse_state(s: &str) -> PrState {
    match s.to_ascii_uppercase().as_str() {
        "OPEN" => PrState::Open,
        "CLOSED" => PrState::Closed,
        "MERGED" => PrState::Merged,
        _ => PrState::All,
    }
}

/// Parse owner/repo out of a typical PR URL:
///   https://github.com/<owner>/<repo>/pull/<n>
/// Used as a fallback when `gh` doesn't surface the repository fields.
fn parse_owner_name_from_url(url: &str) -> Option<(String, String)> {
    let stripped = url
        .trim_start_matches("https://")
        .trim_start_matches("http://");
    let parts: Vec<&str> = stripped.split('/').collect();
    if parts.len() >= 3 && parts.first().map(|h| h.contains("github")).unwrap_or(false) {
        return Some((parts[1].to_string(), parts[2].to_string()));
    }
    None
}