1use 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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
24#[serde(rename_all = "camelCase")]
25pub struct GitHubRepository {
26 pub name_with_owner: String,
28 pub web_url: String,
30}
31
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35pub enum GitHubAvailability {
36 #[default]
38 NoRemote,
39 RemoteUnavailable,
41 GhUnavailable,
43 NotAuthenticated,
45 Authenticated,
47 TimedOut,
49}
50
51#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct GitHubStatus {
55 pub repository: Option<GitHubRepository>,
57 pub availability: GitHubAvailability,
59}
60
61impl GitHubStatus {
62 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 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 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 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 crate::git::git_command(root)
193 .args([
194 "-c",
195 "alias.config=",
196 "config",
197 "--get",
198 "remote.origin.url",
199 ])
200 .stdin(Stdio::null())
201 .stdout(Stdio::piped())
202 .stderr(Stdio::null())
203 .spawn()
204 {
205 Ok(child) => child,
206 Err(_) => return RemoteProbe::Unavailable,
207 };
208 let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
209 let _ = child.kill();
210 let _ = child.wait();
211 return RemoteProbe::Unavailable;
212 };
213 if !status.success() {
214 return RemoteProbe::Missing;
215 }
216 let output = match child.wait_with_output() {
217 Ok(output) if output.stdout.len() <= MAX_REMOTE_BYTES => output.stdout,
218 _ => return RemoteProbe::Unavailable,
219 };
220 let remote = String::from_utf8(output)
221 .ok()
222 .map(|remote| remote.trim().to_string())
223 .filter(|remote| !remote.is_empty());
224 remote.map_or(RemoteProbe::Missing, RemoteProbe::Value)
225}
226
227#[derive(Debug, PartialEq, Eq)]
228enum GhProbe {
229 Missing,
230 Authenticated,
231 NotAuthenticated,
232 TimedOut,
233}
234
235fn run_gh_auth_status(root: &Path) -> GhProbe {
236 let mut child = match Command::new("gh")
237 .args(["auth", "status", "--hostname", "github.com"])
238 .current_dir(root)
239 .stdin(Stdio::null())
240 .stdout(Stdio::null())
241 .stderr(Stdio::null())
242 .spawn()
243 {
244 Ok(child) => child,
245 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return GhProbe::Missing,
246 Err(_) => return GhProbe::NotAuthenticated,
247 };
248 let Some(status) = wait_for_exit(&mut child, PROBE_TIMEOUT) else {
249 let _ = child.kill();
250 let _ = child.wait();
251 return GhProbe::TimedOut;
252 };
253 let _ = child.wait();
254 if status.success() {
255 GhProbe::Authenticated
256 } else {
257 GhProbe::NotAuthenticated
258 }
259}
260
261fn wait_for_exit(child: &mut Child, timeout: Duration) -> Option<ExitStatus> {
262 let deadline = Instant::now() + timeout;
263 loop {
264 match child.try_wait() {
265 Ok(Some(status)) => return Some(status),
266 Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(10)),
267 Ok(None) | Err(_) => return None,
268 }
269 }
270}
271
272pub fn parse_github_remote(remote: &str) -> Option<GitHubRepository> {
274 let remote = remote.trim();
275 let path = if let Some(path) = remote.strip_prefix("git@github.com:") {
276 path
277 } else if let Some((_, authority_and_path)) = remote.split_once("://") {
278 let (authority, path) = authority_and_path.split_once('/')?;
279 let host = authority.rsplit('@').next()?.to_ascii_lowercase();
280 if host != "github.com" {
281 return None;
282 }
283 path
284 } else {
285 return None;
286 };
287
288 let mut segments = path.trim_matches('/').split('/');
289 let owner = segments.next()?.trim();
290 let repository = segments.next()?.trim_end_matches(".git").trim();
291 if segments.next().is_some()
292 || !valid_segment(owner)
293 || !valid_segment(repository)
294 || repository.is_empty()
295 {
296 return None;
297 }
298 let name_with_owner = format!("{owner}/{repository}");
299 Some(GitHubRepository {
300 web_url: format!("https://github.com/{name_with_owner}"),
301 name_with_owner,
302 })
303}
304
305fn valid_segment(segment: &str) -> bool {
306 !segment.is_empty()
307 && segment.len() <= 128
308 && segment
309 .bytes()
310 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
315#[serde(rename_all = "camelCase")]
316pub struct GitHubPullRequest {
317 pub number: u64,
319 pub title: String,
321 pub state: String,
323 pub url: String,
325 pub head_branch: Option<String>,
327 pub base_branch: Option<String>,
329 pub review_decision: Option<String>,
331}
332
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
335#[serde(rename_all = "camelCase")]
336pub struct GitHubCheck {
337 pub name: String,
339 pub status: String,
341 pub conclusion: Option<String>,
343 pub link: Option<String>,
345}
346
347#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
349#[serde(rename_all = "camelCase")]
350pub struct GitHubReview {
351 pub repository: Option<GitHubRepository>,
353 pub branch: Option<String>,
355 pub availability: GitHubAvailability,
357 pub pull_request: Option<GitHubPullRequest>,
359 pub checks: Vec<GitHubCheck>,
361 pub summary: String,
363 pub error: Option<String>,
365}
366
367#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
369#[serde(rename_all = "camelCase")]
370pub struct GitHubShipRequest {
371 pub title: Option<String>,
373 pub body: Option<String>,
375 pub base: Option<String>,
377 pub draft: bool,
379}
380
381#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
383#[serde(rename_all = "camelCase")]
384pub struct GitHubShipResult {
385 pub repository: GitHubRepository,
387 pub branch: String,
389 pub url: Option<String>,
391 pub output: String,
393}
394
395impl GitHubReview {
396 pub fn display(&self) -> String {
398 let checks = self
399 .checks
400 .iter()
401 .take(8)
402 .map(|check| {
403 format!(
404 "{} {}{}",
405 check.name,
406 check.conclusion.as_deref().unwrap_or(check.status.as_str()),
407 check
408 .link
409 .as_deref()
410 .map(|link| format!(" · {link}"))
411 .unwrap_or_default()
412 )
413 })
414 .collect::<Vec<_>>();
415 let mut lines = vec![self.summary.clone()];
416 if let Some(branch) = &self.branch {
417 lines.push(format!("branch {branch}"));
418 }
419 lines.extend(checks);
420 if let Some(error) = &self.error {
421 lines.push(format!("error {error}"));
422 }
423 lines.join("\n")
424 }
425}
426pub fn review(root: &Path) -> DevelopmentResult<GitHubReview> {
430 let status = probe_uncached(root);
431 let branch = current_branch(root);
432 let repository = status.repository.clone();
433 if status.availability != GitHubAvailability::Authenticated {
434 return Ok(GitHubReview {
435 repository,
436 branch,
437 availability: status.availability,
438 pull_request: None,
439 checks: Vec::new(),
440 summary: status.summary(),
441 error: None,
442 });
443 }
444
445 let (exit, stdout, stderr) = run_gh_capture(
446 root,
447 &[
448 "pr",
449 "view",
450 "--json",
451 "number,title,state,url,headRefName,baseRefName,reviewDecision,statusCheckRollup",
452 ],
453 REVIEW_TIMEOUT,
454 MAX_REVIEW_BYTES,
455 )?;
456 if !exit.success() {
457 let detail = compact_process_output(&stderr, &stdout);
458 if detail.to_ascii_lowercase().contains("no pull request") {
459 return Ok(GitHubReview {
460 repository,
461 branch,
462 availability: status.availability,
463 pull_request: None,
464 checks: Vec::new(),
465 summary: "No pull request for the current branch".into(),
466 error: None,
467 });
468 }
469 return Ok(GitHubReview {
470 repository,
471 branch,
472 availability: status.availability,
473 pull_request: None,
474 checks: Vec::new(),
475 summary: "GitHub pull-request review unavailable".into(),
476 error: Some(detail),
477 });
478 }
479 let value: Value = serde_json::from_slice(&stdout)?;
480 let pull_request = parse_pull_request(&value)?;
481 let mut checks = value
482 .get("statusCheckRollup")
483 .map(parse_checks)
484 .unwrap_or_default();
485 if let Some(number) = pull_request
486 .as_ref()
487 .map(|pull_request| pull_request.number)
488 {
489 let (checks_exit, checks_stdout, checks_stderr) = run_gh_capture(
490 root,
491 &[
492 "pr",
493 "checks",
494 &number.to_string(),
495 "--json",
496 "name,state,conclusion,bucket,link",
497 ],
498 REVIEW_TIMEOUT,
499 MAX_REVIEW_BYTES,
500 )?;
501 if checks_exit.success() {
502 if let Ok(value) = serde_json::from_slice::<Value>(&checks_stdout) {
503 checks = parse_checks(&value);
504 }
505 } else if checks.is_empty() {
506 return Ok(GitHubReview {
507 repository,
508 branch,
509 availability: status.availability,
510 pull_request,
511 checks,
512 summary: "Pull request found; checks unavailable".into(),
513 error: Some(compact_process_output(&checks_stderr, &checks_stdout)),
514 });
515 }
516 }
517 let summary = review_summary(pull_request.as_ref(), &checks);
518 Ok(GitHubReview {
519 repository,
520 branch,
521 availability: status.availability,
522 pull_request,
523 checks,
524 summary,
525 error: None,
526 })
527}
528
529pub fn ship(root: &Path, request: &GitHubShipRequest) -> DevelopmentResult<GitHubShipResult> {
532 let status = probe_uncached(root);
533 let repository = status
534 .repository
535 .clone()
536 .ok_or_else(|| DevelopmentError::NotFound("GitHub origin is not configured".into()))?;
537 if status.availability != GitHubAvailability::Authenticated {
538 return Err(DevelopmentError::Conflict(format!(
539 "GitHub ship requires authenticated gh CLI ({})",
540 status.summary()
541 )));
542 }
543 let branch = current_branch(root).ok_or_else(|| {
544 DevelopmentError::Conflict("GitHub ship requires a named current branch".into())
545 })?;
546 if matches!(branch.as_str(), "main" | "master") {
547 return Err(DevelopmentError::Conflict(
548 "GitHub ship requires a feature branch, not the default branch".into(),
549 ));
550 }
551 let title = bounded_optional("title", request.title.as_deref(), 512)?;
552 let body = bounded_optional("body", request.body.as_deref(), 16 * 1024)?;
553 let base = bounded_optional("base", request.base.as_deref(), 256)?;
554 let mut args = vec!["pr", "create"];
555 if let Some(title) = title.as_deref() {
556 args.extend(["--title", title]);
557 args.extend(["--body", body.as_deref().unwrap_or("")]);
558 } else {
559 args.push("--fill");
560 if let Some(body) = body.as_deref() {
561 args.extend(["--body", body]);
562 }
563 }
564 if let Some(base) = base.as_deref() {
565 args.extend(["--base", base]);
566 }
567 if request.draft {
568 args.push("--draft");
569 }
570 let (exit, stdout, stderr) = run_gh_capture(root, &args, SHIP_TIMEOUT, MAX_SHIP_OUTPUT_BYTES)?;
571 let output = compact_process_output(&stdout, &stderr);
572 if !exit.success() {
573 return Err(DevelopmentError::Process(format!(
574 "gh pr create failed: {output}"
575 )));
576 }
577 let url = output
578 .split_whitespace()
579 .find(|part| part.starts_with("https://github.com/"))
580 .map(str::to_string);
581 Ok(GitHubShipResult {
582 repository,
583 branch,
584 url,
585 output,
586 })
587}
588
589fn current_branch(root: &Path) -> Option<String> {
590 let output = crate::git::git_command(root)
591 .args(["-c", "alias.branch=", "branch", "--show-current"])
592 .stdin(Stdio::null())
593 .stderr(Stdio::null())
594 .output()
595 .ok()?;
596 if !output.status.success() || output.stdout.len() > MAX_REMOTE_BYTES {
597 return None;
598 }
599 let branch = String::from_utf8(output.stdout).ok()?.trim().to_string();
600 (!branch.is_empty()
601 && branch.len() <= 256
602 && branch
603 .bytes()
604 .all(|byte| !byte.is_ascii_control() && byte != b' '))
605 .then_some(branch)
606}
607
608fn run_gh_capture(
609 root: &Path,
610 args: &[&str],
611 timeout: Duration,
612 limit: usize,
613) -> DevelopmentResult<(ExitStatus, Vec<u8>, Vec<u8>)> {
614 let mut child = Command::new("gh")
615 .args(args)
616 .env("GH_PROMPT_DISABLED", "1")
617 .current_dir(root)
618 .stdin(Stdio::null())
619 .stdout(Stdio::piped())
620 .stderr(Stdio::piped())
621 .spawn()
622 .map_err(|error| {
623 if error.kind() == std::io::ErrorKind::NotFound {
624 DevelopmentError::NotFound("gh CLI is not installed".into())
625 } else {
626 DevelopmentError::Process(format!("failed to start gh: {error}"))
627 }
628 })?;
629 let stdout = child
630 .stdout
631 .take()
632 .ok_or_else(|| DevelopmentError::Process("gh stdout was unavailable".into()))?;
633 let stderr = child
634 .stderr
635 .take()
636 .ok_or_else(|| DevelopmentError::Process("gh stderr was unavailable".into()))?;
637 let stdout_reader = thread::spawn(move || read_gh_output(stdout, limit));
638 let stderr_reader = thread::spawn(move || read_gh_output(stderr, limit));
639 let Some(status) = wait_for_exit(&mut child, timeout) else {
640 let _ = child.kill();
641 let _ = child.wait();
642 let _ = stdout_reader.join();
643 let _ = stderr_reader.join();
644 return Err(DevelopmentError::Process(format!(
645 "gh command timed out after {} seconds",
646 timeout.as_secs()
647 )));
648 };
649 let stdout = join_gh_output(stdout_reader)?;
650 let stderr = join_gh_output(stderr_reader)?;
651 if stdout.len() > limit || stderr.len() > limit {
652 return Err(DevelopmentError::InvalidInput(
653 "gh output exceeded the bounded GitHub response limit".into(),
654 ));
655 }
656 Ok((status, stdout, stderr))
657}
658
659fn read_gh_output(
660 mut stream: impl std::io::Read + Send + 'static,
661 limit: usize,
662) -> std::io::Result<Vec<u8>> {
663 let mut retained = Vec::new();
664 let mut chunk = [0_u8; 8192];
665 loop {
666 let read = stream.read(&mut chunk)?;
667 if read == 0 {
668 break;
669 }
670 let remaining = limit.saturating_add(1).saturating_sub(retained.len());
671 retained.extend_from_slice(&chunk[..read.min(remaining)]);
672 if retained.len() > limit {
673 let mut discard = [0_u8; 8192];
674 while stream.read(&mut discard)? > 0 {}
675 break;
676 }
677 }
678 Ok(retained)
679}
680
681fn join_gh_output(
682 reader: thread::JoinHandle<std::io::Result<Vec<u8>>>,
683) -> DevelopmentResult<Vec<u8>> {
684 reader
685 .join()
686 .map_err(|_| DevelopmentError::Process("gh output reader panicked".into()))?
687 .map_err(Into::into)
688}
689
690fn compact_process_output(primary: &[u8], secondary: &[u8]) -> String {
691 let bytes = if !primary.is_empty() {
692 primary
693 } else {
694 secondary
695 };
696 String::from_utf8_lossy(bytes)
697 .trim()
698 .chars()
699 .take(2_048)
700 .collect()
701}
702
703fn parse_pull_request(value: &Value) -> DevelopmentResult<Option<GitHubPullRequest>> {
704 if value.is_null() || value.as_object().is_none() {
705 return Ok(None);
706 }
707 let number = value.get("number").and_then(Value::as_u64).ok_or_else(|| {
708 DevelopmentError::Serialization("GitHub PR response has no number".into())
709 })?;
710 let title = bounded_json_text(value, "title", 512)?;
711 let state = bounded_json_text(value, "state", 64)?;
712 let url = bounded_json_text(value, "url", 2_048)?;
713 Ok(Some(GitHubPullRequest {
714 number,
715 title,
716 state,
717 url,
718 head_branch: optional_json_text(value, "headRefName", 256),
719 base_branch: optional_json_text(value, "baseRefName", 256),
720 review_decision: optional_json_text(value, "reviewDecision", 128),
721 }))
722}
723
724fn parse_checks(value: &Value) -> Vec<GitHubCheck> {
725 let values = value
726 .as_array()
727 .cloned()
728 .or_else(|| value.get("contexts").and_then(Value::as_array).cloned())
729 .unwrap_or_default();
730 values
731 .into_iter()
732 .take(256)
733 .filter_map(|value| {
734 let object = value.as_object()?;
735 let name = object
736 .get("name")
737 .or_else(|| object.get("context"))
738 .and_then(Value::as_str)?
739 .chars()
740 .take(256)
741 .collect::<String>();
742 if name.is_empty() {
743 return None;
744 }
745 let status = object
746 .get("status")
747 .or_else(|| object.get("state"))
748 .or_else(|| object.get("bucket"))
749 .and_then(Value::as_str)
750 .unwrap_or("unknown")
751 .chars()
752 .take(64)
753 .collect();
754 let conclusion = object
755 .get("conclusion")
756 .and_then(Value::as_str)
757 .map(|value| value.chars().take(64).collect());
758 let link = object
759 .get("link")
760 .or_else(|| object.get("detailsUrl"))
761 .and_then(Value::as_str)
762 .map(|value| value.split(['?', '#']).next().unwrap_or(value))
763 .map(|value| value.chars().take(2_048).collect());
764 Some(GitHubCheck {
765 name,
766 status,
767 conclusion,
768 link,
769 })
770 })
771 .collect()
772}
773
774fn review_summary(pull_request: Option<&GitHubPullRequest>, checks: &[GitHubCheck]) -> String {
775 let Some(pull_request) = pull_request else {
776 return "No pull request for the current branch".into();
777 };
778 let failing = checks
779 .iter()
780 .filter(|check| {
781 matches!(
782 check.conclusion.as_deref().or(Some(check.status.as_str())),
783 Some("FAILURE" | "failure" | "ERROR" | "error" | "CANCELLED" | "cancelled")
784 )
785 })
786 .count();
787 if failing > 0 {
788 format!(
789 "PR #{} · {} failing check{}",
790 pull_request.number,
791 failing,
792 if failing == 1 { "" } else { "s" }
793 )
794 } else if checks.is_empty() {
795 format!("PR #{} · checks pending", pull_request.number)
796 } else {
797 format!(
798 "PR #{} · {} checks observed",
799 pull_request.number,
800 checks.len()
801 )
802 }
803}
804
805fn bounded_optional(
806 label: &str,
807 value: Option<&str>,
808 limit: usize,
809) -> DevelopmentResult<Option<String>> {
810 value
811 .map(|value| {
812 if value.is_empty() || value.len() > limit || value.contains('\0') {
813 Err(DevelopmentError::InvalidInput(format!(
814 "GitHub {label} must be 1..={limit} bytes without NUL"
815 )))
816 } else {
817 Ok(value.to_string())
818 }
819 })
820 .transpose()
821}
822
823fn bounded_json_text(value: &Value, key: &str, limit: usize) -> DevelopmentResult<String> {
824 value
825 .get(key)
826 .and_then(Value::as_str)
827 .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
828 .map(str::to_string)
829 .ok_or_else(|| {
830 DevelopmentError::Serialization(format!(
831 "GitHub response field {key} is missing or exceeds {limit} bytes"
832 ))
833 })
834}
835
836fn optional_json_text(value: &Value, key: &str, limit: usize) -> Option<String> {
837 value
838 .get(key)
839 .and_then(Value::as_str)
840 .filter(|value| !value.is_empty() && value.len() <= limit && !value.contains('\0'))
841 .map(str::to_string)
842}
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847
848 #[test]
849 fn parses_supported_github_remote_forms() {
850 for remote in [
851 "https://github.com/wanazhar/glass.git",
852 "ssh://git@github.com/wanazhar/glass.git",
853 "git@github.com:wanazhar/glass.git",
854 ] {
855 let repository = parse_github_remote(remote).unwrap();
856 assert_eq!(repository.name_with_owner, "wanazhar/glass");
857 assert_eq!(repository.web_url, "https://github.com/wanazhar/glass");
858 }
859 }
860
861 #[test]
862 fn rejects_non_github_and_unsafe_remote_forms() {
863 for remote in [
864 "https://gitlab.com/owner/repo.git",
865 "git@github.com:owner/repo/extra.git",
866 "git@github.com:owner/../repo.git",
867 "github.com/owner/repo.git",
868 ] {
869 assert!(parse_github_remote(remote).is_none(), "{remote}");
870 }
871 }
872
873 #[test]
874 fn status_summary_never_requires_auth_output() {
875 let status = GitHubStatus {
876 repository: Some(GitHubRepository {
877 name_with_owner: "owner/repo".into(),
878 web_url: "https://github.com/owner/repo".into(),
879 }),
880 availability: GitHubAvailability::NotAuthenticated,
881 };
882 assert_eq!(
883 status.summary(),
884 "owner/repo · gh not authenticated · run `gh auth login`"
885 );
886 }
887}