Skip to main content

glass_dev/
github.rs

1//! GitHub integration through the user's authenticated `gh` CLI.
2//!
3//! Read-only status remains cheap and cached for the TUI. Review and ship
4//! operations are explicit, bounded subprocess calls used by the command
5//! palette, task loop, and private cockpit; no shell is involved.
6
7use crate::development::{DevelopmentError, DevelopmentResult};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::path::{Path, PathBuf};
11use std::process::{Child, Command, ExitStatus, Stdio};
12use std::thread;
13use std::time::{Duration, Instant};
14const PROBE_INTERVAL: Duration = Duration::from_secs(15);
15const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
16const REVIEW_TIMEOUT: Duration = Duration::from_secs(8);
17const SHIP_TIMEOUT: Duration = Duration::from_secs(20);
18const MAX_REMOTE_BYTES: usize = 4 * 1024;
19const MAX_REVIEW_BYTES: usize = 64 * 1024;
20const MAX_SHIP_OUTPUT_BYTES: usize = 16 * 1024;
21
22/// Parsed GitHub repository owner/name and canonical web URL.
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(rename_all = "camelCase")]
25pub struct GitHubRepository {
26    /// Repository in `owner/name` form.
27    pub name_with_owner: String,
28    /// HTTPS repository URL.
29    pub web_url: String,
30}
31
32/// Availability of the repository remote and authenticated `gh` CLI.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub enum GitHubAvailability {
36    /// No GitHub origin is configured.
37    #[default]
38    NoRemote,
39    /// The configured origin could not be read.
40    RemoteUnavailable,
41    /// The `gh` executable is unavailable.
42    GhUnavailable,
43    /// `gh` is installed but not authenticated.
44    NotAuthenticated,
45    /// Authenticated `gh` status.
46    Authenticated,
47    /// The bounded authentication probe timed out.
48    TimedOut,
49}
50
51/// Cached repository and `gh` availability status.
52#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct GitHubStatus {
55    /// Parsed GitHub origin, if present.
56    pub repository: Option<GitHubRepository>,
57    /// Current availability classification.
58    pub availability: GitHubAvailability,
59}
60
61impl GitHubStatus {
62    /// Format a compact status string for the TUI and command palette.
63    pub fn summary(&self) -> String {
64        match (&self.repository, self.availability) {
65            (None, GitHubAvailability::NoRemote) => "no GitHub origin".into(),
66            (None, GitHubAvailability::RemoteUnavailable) => "origin unavailable".into(),
67            (Some(repository), GitHubAvailability::GhUnavailable) => format!(
68                "{} · gh unavailable · install github.com/cli/cli",
69                repository.name_with_owner
70            ),
71            (Some(repository), GitHubAvailability::NotAuthenticated) => format!(
72                "{} · gh not authenticated · run `gh auth login`",
73                repository.name_with_owner
74            ),
75            (Some(repository), GitHubAvailability::Authenticated) => {
76                format!("{} · gh authenticated", repository.name_with_owner)
77            }
78            (Some(repository), GitHubAvailability::TimedOut) => format!(
79                "{} · gh auth check timed out · retrying automatically",
80                repository.name_with_owner
81            ),
82            (Some(repository), _) => {
83                format!("{} · GitHub status unavailable", repository.name_with_owner)
84            }
85            (None, _) => "GitHub status unavailable".into(),
86        }
87    }
88
89    /// Whether `gh auth status` succeeded for this repository.
90    pub fn is_authenticated(&self) -> bool {
91        self.availability == GitHubAvailability::Authenticated
92    }
93}
94
95#[derive(Debug, Default)]
96pub struct GitHubProbeCache {
97    root: Option<PathBuf>,
98    checked_at: Option<Instant>,
99    status: GitHubStatus,
100}
101
102impl GitHubProbeCache {
103    /// Probe GitHub status, reusing a result for 15 seconds per root.
104    pub fn probe(&mut self, root: &Path) -> GitHubStatus {
105        if self.root.as_deref() == Some(root)
106            && self
107                .checked_at
108                .is_some_and(|checked_at| checked_at.elapsed() < PROBE_INTERVAL)
109        {
110            return self.status.clone();
111        }
112
113        let status = probe_uncached(root);
114        self.root = Some(root.to_path_buf());
115        self.checked_at = Some(Instant::now());
116        self.status = status.clone();
117        status
118    }
119}
120
121#[derive(Debug, Default)]
122pub struct GitHubReviewCache {
123    root: Option<PathBuf>,
124    checked_at: Option<Instant>,
125    review: Option<GitHubReview>,
126}
127
128impl GitHubReviewCache {
129    /// Fetch review data, reusing a result for 15 seconds per root.
130    pub fn review(&mut self, root: &Path) -> GitHubReview {
131        if self.root.as_deref() == Some(root)
132            && self
133                .checked_at
134                .is_some_and(|checked_at| checked_at.elapsed() < PROBE_INTERVAL)
135            && let Some(review) = &self.review
136        {
137            return review.clone();
138        }
139        let review = review(root).unwrap_or_else(|error| GitHubReview {
140            repository: None,
141            branch: current_branch(root),
142            availability: GitHubAvailability::RemoteUnavailable,
143            pull_request: None,
144            checks: Vec::new(),
145            summary: "GitHub review unavailable".into(),
146            error: Some(error.to_string()),
147        });
148        self.root = Some(root.to_path_buf());
149        self.checked_at = Some(Instant::now());
150        self.review = Some(review.clone());
151        review
152    }
153}
154
155fn probe_uncached(root: &Path) -> GitHubStatus {
156    let remote = match read_origin(root) {
157        RemoteProbe::Missing => {
158            return GitHubStatus::default();
159        }
160        RemoteProbe::Unavailable => {
161            return GitHubStatus {
162                repository: None,
163                availability: GitHubAvailability::RemoteUnavailable,
164            };
165        }
166        RemoteProbe::Value(remote) => remote,
167    };
168    let Some(repository) = parse_github_remote(&remote) else {
169        return GitHubStatus::default();
170    };
171
172    let availability = match run_gh_auth_status(root) {
173        GhProbe::Missing => GitHubAvailability::GhUnavailable,
174        GhProbe::Authenticated => GitHubAvailability::Authenticated,
175        GhProbe::NotAuthenticated => GitHubAvailability::NotAuthenticated,
176        GhProbe::TimedOut => GitHubAvailability::TimedOut,
177    };
178    GitHubStatus {
179        repository: Some(repository),
180        availability,
181    }
182}
183
184#[derive(Debug, PartialEq, Eq)]
185enum RemoteProbe {
186    Missing,
187    Unavailable,
188    Value(String),
189}
190
191fn read_origin(root: &Path) -> RemoteProbe {
192    let mut child = match Command::new("git")
193        .args(["config", "--get", "remote.origin.url"])
194        .current_dir(root)
195        .stdin(Stdio::null())
196        .stdout(Stdio::piped())
197        .stderr(Stdio::null())
198        .spawn()
199    {
200        Ok(child) => child,
201        Err(_) => return RemoteProbe::Unavailable,
202    };
203    let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
204        let _ = child.kill();
205        let _ = child.wait();
206        return RemoteProbe::Unavailable;
207    };
208    if !status.success() {
209        return RemoteProbe::Missing;
210    }
211    let output = match child.wait_with_output() {
212        Ok(output) if output.stdout.len() <= MAX_REMOTE_BYTES => output.stdout,
213        _ => return RemoteProbe::Unavailable,
214    };
215    let remote = String::from_utf8(output)
216        .ok()
217        .map(|remote| remote.trim().to_string())
218        .filter(|remote| !remote.is_empty());
219    remote.map_or(RemoteProbe::Missing, RemoteProbe::Value)
220}
221
222#[derive(Debug, PartialEq, Eq)]
223enum GhProbe {
224    Missing,
225    Authenticated,
226    NotAuthenticated,
227    TimedOut,
228}
229
230fn run_gh_auth_status(root: &Path) -> GhProbe {
231    let mut child = match Command::new("gh")
232        .args(["auth", "status", "--hostname", "github.com"])
233        .current_dir(root)
234        .stdin(Stdio::null())
235        .stdout(Stdio::null())
236        .stderr(Stdio::null())
237        .spawn()
238    {
239        Ok(child) => child,
240        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return GhProbe::Missing,
241        Err(_) => return GhProbe::NotAuthenticated,
242    };
243    let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
244        let _ = child.kill();
245        let _ = child.wait();
246        return GhProbe::TimedOut;
247    };
248    let _ = child.wait();
249    if status.success() {
250        GhProbe::Authenticated
251    } else {
252        GhProbe::NotAuthenticated
253    }
254}
255
256fn wait_for_exit(child: &mut Child, timeout: Duration) -> Option<ExitStatus> {
257    let deadline = Instant::now() + timeout;
258    loop {
259        match child.try_wait() {
260            Ok(Some(status)) => return Some(status),
261            Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
262            Ok(None) | Err(_) => return None,
263        }
264    }
265}
266
267/// Parse a GitHub HTTPS or SCP-style remote into repository metadata.
268pub fn parse_github_remote(remote: &str) -> Option<GitHubRepository> {
269    let remote = remote.trim();
270    let path = if let Some(path) = remote.strip_prefix("git@github.com:") {
271        path
272    } else if let Some((_, authority_and_path)) = remote.split_once("://") {
273        let (authority, path) = authority_and_path.split_once('/')?;
274        let host = authority.rsplit('@').next()?.to_ascii_lowercase();
275        if host != "github.com" {
276            return None;
277        }
278        path
279    } else {
280        return None;
281    };
282
283    let mut segments = path.trim_matches('/').split('/');
284    let owner = segments.next()?.trim();
285    let repository = segments.next()?.trim_end_matches(".git").trim();
286    if segments.next().is_some()
287        || !valid_segment(owner)
288        || !valid_segment(repository)
289        || repository.is_empty()
290    {
291        return None;
292    }
293    let name_with_owner = format!("{owner}/{repository}");
294    Some(GitHubRepository {
295        web_url: format!("https://github.com/{name_with_owner}"),
296        name_with_owner,
297    })
298}
299
300fn valid_segment(segment: &str) -> bool {
301    !segment.is_empty()
302        && segment.len() <= 128
303        && segment
304            .bytes()
305            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
306}
307
308/// Pull request summary returned by `gh pr view`.
309#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
310#[serde(rename_all = "camelCase")]
311pub struct GitHubPullRequest {
312    /// Pull request number.
313    pub number: u64,
314    /// Pull request title.
315    pub title: String,
316    /// GitHub pull request state.
317    pub state: String,
318    /// Pull request web URL.
319    pub url: String,
320    /// Source branch, when available.
321    pub head_branch: Option<String>,
322    /// Target branch, when available.
323    pub base_branch: Option<String>,
324    /// GitHub's review decision, when available.
325    pub review_decision: Option<String>,
326}
327
328/// One status-check entry associated with a pull request.
329#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
330#[serde(rename_all = "camelCase")]
331pub struct GitHubCheck {
332    /// Check or workflow name.
333    pub name: String,
334    /// Provider-reported status.
335    pub status: String,
336    /// Provider conclusion, when complete.
337    pub conclusion: Option<String>,
338    /// Details URL, when supplied.
339    pub link: Option<String>,
340}
341
342/// Bounded GitHub review projection for a repository branch.
343#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
344#[serde(rename_all = "camelCase")]
345pub struct GitHubReview {
346    /// Parsed repository metadata.
347    pub repository: Option<GitHubRepository>,
348    /// Current branch, when available.
349    pub branch: Option<String>,
350    /// Remote/authentication availability.
351    pub availability: GitHubAvailability,
352    /// Pull request for the current branch, when found.
353    pub pull_request: Option<GitHubPullRequest>,
354    /// Associated status checks.
355    pub checks: Vec<GitHubCheck>,
356    /// Human-readable summary.
357    pub summary: String,
358    /// Non-fatal review error, when status was still returned.
359    pub error: Option<String>,
360}
361
362/// Explicit caller inputs for creating a pull request.
363#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
364#[serde(rename_all = "camelCase")]
365pub struct GitHubShipRequest {
366    /// Optional pull request title.
367    pub title: Option<String>,
368    /// Optional pull request body.
369    pub body: Option<String>,
370    /// Optional base branch.
371    pub base: Option<String>,
372    /// Whether to create the pull request as a draft.
373    pub draft: bool,
374}
375
376/// Result of a successful pull-request creation.
377#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
378#[serde(rename_all = "camelCase")]
379pub struct GitHubShipResult {
380    /// Repository receiving the pull request.
381    pub repository: GitHubRepository,
382    /// Current source branch.
383    pub branch: String,
384    /// Created pull request URL, when returned by `gh`.
385    pub url: Option<String>,
386    /// Bounded command output.
387    pub output: String,
388}
389
390impl GitHubReview {
391    /// Render the summary, branch, first eight checks, and any error.
392    pub fn display(&self) -> String {
393        let checks = self
394            .checks
395            .iter()
396            .take(8)
397            .map(|check| {
398                format!(
399                    "{} {}{}",
400                    check.name,
401                    check.conclusion.as_deref().unwrap_or(check.status.as_str()),
402                    check
403                        .link
404                        .as_deref()
405                        .map(|link| format!(" · {link}"))
406                        .unwrap_or_default()
407                )
408            })
409            .collect::<Vec<_>>();
410        let mut lines = vec![self.summary.clone()];
411        if let Some(branch) = &self.branch {
412            lines.push(format!("branch {branch}"));
413        }
414        lines.extend(checks);
415        if let Some(error) = &self.error {
416            lines.push(format!("error {error}"));
417        }
418        lines.join("\n")
419    }
420}
421/// Fetch authenticated pull-request and check status through bounded `gh`
422/// subprocess calls. Normal workflow states are returned as data rather than
423/// transport errors.
424pub fn review(root: &Path) -> DevelopmentResult<GitHubReview> {
425    let status = probe_uncached(root);
426    let branch = current_branch(root);
427    let repository = status.repository.clone();
428    if status.availability != GitHubAvailability::Authenticated {
429        return Ok(GitHubReview {
430            repository,
431            branch,
432            availability: status.availability,
433            pull_request: None,
434            checks: Vec::new(),
435            summary: status.summary(),
436            error: None,
437        });
438    }
439
440    let (exit, stdout, stderr) = run_gh_capture(
441        root,
442        &[
443            "pr",
444            "view",
445            "--json",
446            "number,title,state,url,headRefName,baseRefName,reviewDecision,statusCheckRollup",
447        ],
448        REVIEW_TIMEOUT,
449        MAX_REVIEW_BYTES,
450    )?;
451    if !exit.success() {
452        let detail = compact_process_output(&stderr, &stdout);
453        if detail.to_ascii_lowercase().contains("no pull request") {
454            return Ok(GitHubReview {
455                repository,
456                branch,
457                availability: status.availability,
458                pull_request: None,
459                checks: Vec::new(),
460                summary: "No pull request for the current branch".into(),
461                error: None,
462            });
463        }
464        return Ok(GitHubReview {
465            repository,
466            branch,
467            availability: status.availability,
468            pull_request: None,
469            checks: Vec::new(),
470            summary: "GitHub pull-request review unavailable".into(),
471            error: Some(detail),
472        });
473    }
474    let value: Value = serde_json::from_slice(&stdout)?;
475    let pull_request = parse_pull_request(&value)?;
476    let mut checks = value
477        .get("statusCheckRollup")
478        .map(parse_checks)
479        .unwrap_or_default();
480    if let Some(number) = pull_request
481        .as_ref()
482        .map(|pull_request| pull_request.number)
483    {
484        let (checks_exit, checks_stdout, checks_stderr) = run_gh_capture(
485            root,
486            &[
487                "pr",
488                "checks",
489                &number.to_string(),
490                "--json",
491                "name,state,conclusion,bucket,link",
492            ],
493            REVIEW_TIMEOUT,
494            MAX_REVIEW_BYTES,
495        )?;
496        if checks_exit.success() {
497            if let Ok(value) = serde_json::from_slice::<Value>(&checks_stdout) {
498                checks = parse_checks(&value);
499            }
500        } else if checks.is_empty() {
501            return Ok(GitHubReview {
502                repository,
503                branch,
504                availability: status.availability,
505                pull_request,
506                checks,
507                summary: "Pull request found; checks unavailable".into(),
508                error: Some(compact_process_output(&checks_stderr, &checks_stdout)),
509            });
510        }
511    }
512    let summary = review_summary(pull_request.as_ref(), &checks);
513    Ok(GitHubReview {
514        repository,
515        branch,
516        availability: status.availability,
517        pull_request,
518        checks,
519        summary,
520        error: None,
521    })
522}
523
524/// Create a pull request from the current branch after explicit caller
525/// confirmation. Arguments are passed directly to `gh`; no shell is used.
526pub fn ship(root: &Path, request: &GitHubShipRequest) -> DevelopmentResult<GitHubShipResult> {
527    let status = probe_uncached(root);
528    let repository = status
529        .repository
530        .clone()
531        .ok_or_else(|| DevelopmentError::NotFound("GitHub origin is not configured".into()))?;
532    if status.availability != GitHubAvailability::Authenticated {
533        return Err(DevelopmentError::Conflict(format!(
534            "GitHub ship requires authenticated gh CLI ({})",
535            status.summary()
536        )));
537    }
538    let branch = current_branch(root).ok_or_else(|| {
539        DevelopmentError::Conflict("GitHub ship requires a named current branch".into())
540    })?;
541    if matches!(branch.as_str(), "main" | "master") {
542        return Err(DevelopmentError::Conflict(
543            "GitHub ship requires a feature branch, not the default branch".into(),
544        ));
545    }
546    let title = bounded_optional("title", request.title.as_deref(), 512)?;
547    let body = bounded_optional("body", request.body.as_deref(), 16 * 1024)?;
548    let base = bounded_optional("base", request.base.as_deref(), 256)?;
549    let mut args = vec!["pr", "create"];
550    if let Some(title) = title.as_deref() {
551        args.extend(["--title", title]);
552        args.extend(["--body", body.as_deref().unwrap_or("")]);
553    } else {
554        args.push("--fill");
555        if let Some(body) = body.as_deref() {
556            args.extend(["--body", body]);
557        }
558    }
559    if let Some(base) = base.as_deref() {
560        args.extend(["--base", base]);
561    }
562    if request.draft {
563        args.push("--draft");
564    }
565    let (exit, stdout, stderr) = run_gh_capture(root, &args, SHIP_TIMEOUT, MAX_SHIP_OUTPUT_BYTES)?;
566    let output = compact_process_output(&stdout, &stderr);
567    if !exit.success() {
568        return Err(DevelopmentError::Process(format!(
569            "gh pr create failed: {output}"
570        )));
571    }
572    let url = output
573        .split_whitespace()
574        .find(|part| part.starts_with("https://github.com/"))
575        .map(str::to_string);
576    Ok(GitHubShipResult {
577        repository,
578        branch,
579        url,
580        output,
581    })
582}
583
584fn current_branch(root: &Path) -> Option<String> {
585    let output = Command::new("git")
586        .args(["branch", "--show-current"])
587        .current_dir(root)
588        .stdin(Stdio::null())
589        .stderr(Stdio::null())
590        .output()
591        .ok()?;
592    if !output.status.success() || output.stdout.len() > MAX_REMOTE_BYTES {
593        return None;
594    }
595    let branch = String::from_utf8(output.stdout).ok()?.trim().to_string();
596    (!branch.is_empty()
597        && branch.len() <= 256
598        && branch
599            .bytes()
600            .all(|byte| !byte.is_ascii_control() && byte != b' '))
601    .then_some(branch)
602}
603
604fn run_gh_capture(
605    root: &Path,
606    args: &[&str],
607    timeout: Duration,
608    limit: usize,
609) -> DevelopmentResult<(ExitStatus, Vec<u8>, Vec<u8>)> {
610    let mut child = Command::new("gh")
611        .args(args)
612        .env("GH_PROMPT_DISABLED", "1")
613        .current_dir(root)
614        .stdin(Stdio::null())
615        .stdout(Stdio::piped())
616        .stderr(Stdio::piped())
617        .spawn()
618        .map_err(|error| {
619            if error.kind() == std::io::ErrorKind::NotFound {
620                DevelopmentError::NotFound("gh CLI is not installed".into())
621            } else {
622                DevelopmentError::Process(format!("failed to start gh: {error}"))
623            }
624        })?;
625    let Some(status) = wait_for_exit(&mut child, timeout) else {
626        let _ = child.kill();
627        let _ = child.wait();
628        return Err(DevelopmentError::Process(format!(
629            "gh command timed out after {} seconds",
630            timeout.as_secs()
631        )));
632    };
633    let output = child.wait_with_output()?;
634    if output.stdout.len() > limit || output.stderr.len() > limit {
635        return Err(DevelopmentError::InvalidInput(
636            "gh output exceeded the bounded GitHub response limit".into(),
637        ));
638    }
639    Ok((status, output.stdout, output.stderr))
640}
641
642fn compact_process_output(primary: &[u8], secondary: &[u8]) -> String {
643    let bytes = if !primary.is_empty() {
644        primary
645    } else {
646        secondary
647    };
648    String::from_utf8_lossy(bytes)
649        .trim()
650        .chars()
651        .take(2_048)
652        .collect()
653}
654
655fn parse_pull_request(value: &Value) -> DevelopmentResult<Option<GitHubPullRequest>> {
656    if value.is_null() || value.as_object().is_none() {
657        return Ok(None);
658    }
659    let number = value.get("number").and_then(Value::as_u64).ok_or_else(|| {
660        DevelopmentError::Serialization("GitHub PR response has no number".into())
661    })?;
662    let title = bounded_json_text(value, "title", 512)?;
663    let state = bounded_json_text(value, "state", 64)?;
664    let url = bounded_json_text(value, "url", 2_048)?;
665    Ok(Some(GitHubPullRequest {
666        number,
667        title,
668        state,
669        url,
670        head_branch: optional_json_text(value, "headRefName", 256),
671        base_branch: optional_json_text(value, "baseRefName", 256),
672        review_decision: optional_json_text(value, "reviewDecision", 128),
673    }))
674}
675
676fn parse_checks(value: &Value) -> Vec<GitHubCheck> {
677    let values = value
678        .as_array()
679        .cloned()
680        .or_else(|| value.get("contexts").and_then(Value::as_array).cloned())
681        .unwrap_or_default();
682    values
683        .into_iter()
684        .take(256)
685        .filter_map(|value| {
686            let object = value.as_object()?;
687            let name = object
688                .get("name")
689                .or_else(|| object.get("context"))
690                .and_then(Value::as_str)?
691                .chars()
692                .take(256)
693                .collect::<String>();
694            if name.is_empty() {
695                return None;
696            }
697            let status = object
698                .get("status")
699                .or_else(|| object.get("state"))
700                .or_else(|| object.get("bucket"))
701                .and_then(Value::as_str)
702                .unwrap_or("unknown")
703                .chars()
704                .take(64)
705                .collect();
706            let conclusion = object
707                .get("conclusion")
708                .and_then(Value::as_str)
709                .map(|value| value.chars().take(64).collect());
710            let link = object
711                .get("link")
712                .or_else(|| object.get("detailsUrl"))
713                .and_then(Value::as_str)
714                .map(|value| value.split(['?', '#']).next().unwrap_or(value))
715                .map(|value| value.chars().take(2_048).collect());
716            Some(GitHubCheck {
717                name,
718                status,
719                conclusion,
720                link,
721            })
722        })
723        .collect()
724}
725
726fn review_summary(pull_request: Option<&GitHubPullRequest>, checks: &[GitHubCheck]) -> String {
727    let Some(pull_request) = pull_request else {
728        return "No pull request for the current branch".into();
729    };
730    let failing = checks
731        .iter()
732        .filter(|check| {
733            matches!(
734                check.conclusion.as_deref().or(Some(check.status.as_str())),
735                Some("FAILURE" | "failure" | "ERROR" | "error" | "CANCELLED" | "cancelled")
736            )
737        })
738        .count();
739    if failing > 0 {
740        format!(
741            "PR #{} · {} failing check{}",
742            pull_request.number,
743            failing,
744            if failing == 1 { "" } else { "s" }
745        )
746    } else if checks.is_empty() {
747        format!("PR #{} · checks pending", pull_request.number)
748    } else {
749        format!(
750            "PR #{} · {} checks observed",
751            pull_request.number,
752            checks.len()
753        )
754    }
755}
756
757fn bounded_optional(
758    label: &str,
759    value: Option<&str>,
760    limit: usize,
761) -> DevelopmentResult<Option<String>> {
762    value
763        .map(|value| {
764            if value.is_empty() || value.len() > limit || value.contains('\0') {
765                Err(DevelopmentError::InvalidInput(format!(
766                    "GitHub {label} must be 1..={limit} bytes without NUL"
767                )))
768            } else {
769                Ok(value.to_string())
770            }
771        })
772        .transpose()
773}
774
775fn bounded_json_text(value: &Value, key: &str, limit: usize) -> DevelopmentResult<String> {
776    value
777        .get(key)
778        .and_then(Value::as_str)
779        .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
780        .map(str::to_string)
781        .ok_or_else(|| {
782            DevelopmentError::Serialization(format!(
783                "GitHub response field {key} is missing or exceeds {limit} bytes"
784            ))
785        })
786}
787
788fn optional_json_text(value: &Value, key: &str, limit: usize) -> Option<String> {
789    value
790        .get(key)
791        .and_then(Value::as_str)
792        .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
793        .map(str::to_string)
794}
795
796#[cfg(test)]
797mod tests {
798    use super::*;
799
800    #[test]
801    fn parses_supported_github_remote_forms() {
802        for remote in [
803            "https://github.com/wanazhar/glass.git",
804            "ssh://git@github.com/wanazhar/glass.git",
805            "git@github.com:wanazhar/glass.git",
806        ] {
807            let repository = parse_github_remote(remote).unwrap();
808            assert_eq!(repository.name_with_owner, "wanazhar/glass");
809            assert_eq!(repository.web_url, "https://github.com/wanazhar/glass");
810        }
811    }
812
813    #[test]
814    fn rejects_non_github_and_unsafe_remote_forms() {
815        for remote in [
816            "https://gitlab.com/owner/repo.git",
817            "git@github.com:owner/repo/extra.git",
818            "git@github.com:owner/../repo.git",
819            "github.com/owner/repo.git",
820        ] {
821            assert!(parse_github_remote(remote).is_none(), "{remote}");
822        }
823    }
824
825    #[test]
826    fn status_summary_never_requires_auth_output() {
827        let status = GitHubStatus {
828            repository: Some(GitHubRepository {
829                name_with_owner: "owner/repo".into(),
830                web_url: "https://github.com/owner/repo".into(),
831            }),
832            availability: GitHubAvailability::NotAuthenticated,
833        };
834        assert_eq!(
835            status.summary(),
836            "owner/repo · gh not authenticated · run `gh auth login`"
837        );
838    }
839}