Skip to main content

ralph/git/
issue.rs

1//! GitHub Issue helpers using the `gh` CLI.
2//!
3//! Responsibilities:
4//! - Create and edit GitHub issues for Ralph tasks via `gh issue`.
5//! - Parse issue URLs/numbers from `gh` output for persistence.
6//!
7//! Not handled here:
8//! - Queue mutation or task persistence.
9//! - Rendering issue bodies from tasks (see `cli::queue::export`).
10//!
11//! Invariants/assumptions:
12//! - `gh` is installed and authenticated.
13//! - Commands run with `GH_NO_UPDATE_NOTIFIER=1` to avoid noisy prompts.
14
15use anyhow::{Context, Result, bail};
16use serde::Serialize;
17use sha2::{Digest, Sha256};
18use std::path::Path;
19
20use crate::git::github_cli::{extract_first_url, gh_command, run_gh_command};
21use crate::runutil::TimeoutClass;
22
23pub(crate) const GITHUB_ISSUE_SYNC_HASH_KEY: &str = "github_issue_sync_hash";
24
25pub(crate) struct IssueInfo {
26    pub url: String,
27    pub number: Option<u32>,
28}
29
30#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
31struct IssueSyncPayload<'a> {
32    title: &'a str,
33    body: &'a str,
34    labels: Vec<String>,
35    assignees: Vec<String>,
36    repo: Option<&'a str>,
37}
38
39pub(crate) fn normalize_issue_metadata_list(values: &[String]) -> Vec<String> {
40    let mut values = values
41        .iter()
42        .map(|value| value.trim())
43        .filter(|value| !value.is_empty())
44        .map(ToString::to_string)
45        .collect::<Vec<_>>();
46    values.sort_unstable();
47    values.dedup();
48    values
49}
50
51pub(crate) fn compute_issue_sync_hash(
52    title: &str,
53    body: &str,
54    labels: &[String],
55    assignees: &[String],
56    repo: Option<&str>,
57) -> Result<String> {
58    let payload = IssueSyncPayload {
59        title: title.trim(),
60        body: body.trim(),
61        labels: normalize_issue_metadata_list(labels),
62        assignees: normalize_issue_metadata_list(assignees),
63        repo: repo.map(str::trim).filter(|r| !r.is_empty()),
64    };
65
66    let encoded = serde_json::to_string(&payload)
67        .context("failed to serialize issue sync fingerprint payload")?;
68    let mut hasher = Sha256::new();
69    hasher.update(encoded.as_bytes());
70    Ok(hex::encode(hasher.finalize()))
71}
72
73pub(crate) fn parse_issue_number(url: &str) -> Option<u32> {
74    let marker = "/issues/";
75    let idx = url.find(marker)?;
76    let rest = &url[idx + marker.len()..];
77    let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
78    digits.parse().ok()
79}
80
81pub(crate) fn create_issue(
82    repo_root: &Path,
83    selector_repo: Option<&str>,
84    title: &str,
85    body_file: &Path,
86    labels: &[String],
87    assignees: &[String],
88) -> Result<IssueInfo> {
89    let safe_title = title.trim();
90    if safe_title.is_empty() {
91        bail!("Issue title must be non-empty");
92    }
93
94    let mut cmd = gh_command(repo_root);
95    cmd.arg("issue")
96        .arg("create")
97        .arg("--title")
98        .arg(safe_title)
99        .arg("--body-file")
100        .arg(body_file);
101
102    if let Some(repo) = selector_repo {
103        cmd.arg("-R").arg(repo);
104    }
105
106    for label in labels {
107        cmd.arg("--label").arg(label);
108    }
109    for assignee in assignees {
110        cmd.arg("--assignee").arg(assignee);
111    }
112
113    let output = run_gh_issue_command(cmd, "gh issue create")
114        .with_context(|| format!("run gh issue create in {}", repo_root.display()))?;
115
116    if !output.status.success() {
117        let stderr = String::from_utf8_lossy(&output.stderr);
118        bail!("gh issue create failed: {}", stderr.trim());
119    }
120
121    let stdout = String::from_utf8_lossy(&output.stdout);
122    let url = extract_first_url(&stdout).ok_or_else(|| {
123        anyhow::anyhow!(
124            "Unable to parse issue URL from gh output. Output: {}",
125            stdout.trim()
126        )
127    })?;
128
129    Ok(IssueInfo {
130        number: parse_issue_number(&url),
131        url,
132    })
133}
134
135pub(crate) fn edit_issue(
136    repo_root: &Path,
137    selector_repo: Option<&str>,
138    issue_selector: &str, // number or URL
139    title: &str,
140    body_file: &Path,
141    add_labels: &[String],
142    add_assignees: &[String],
143) -> Result<()> {
144    let safe_title = title.trim();
145    if safe_title.is_empty() {
146        bail!("Issue title must be non-empty");
147    }
148
149    let mut cmd = gh_command(repo_root);
150    cmd.arg("issue")
151        .arg("edit")
152        .arg(issue_selector)
153        .arg("--title")
154        .arg(safe_title)
155        .arg("--body-file")
156        .arg(body_file);
157
158    if let Some(repo) = selector_repo {
159        cmd.arg("-R").arg(repo);
160    }
161
162    for label in add_labels {
163        cmd.arg("--add-label").arg(label);
164    }
165    for assignee in add_assignees {
166        cmd.arg("--add-assignee").arg(assignee);
167    }
168
169    let output = run_gh_issue_command(cmd, "gh issue edit")
170        .with_context(|| format!("run gh issue edit in {}", repo_root.display()))?;
171
172    if !output.status.success() {
173        let stderr = String::from_utf8_lossy(&output.stderr);
174        bail!("gh issue edit failed: {}", stderr.trim());
175    }
176
177    Ok(())
178}
179
180fn run_gh_issue_command(
181    command: std::process::Command,
182    description: impl Into<String>,
183) -> Result<std::process::Output> {
184    run_gh_command(command, description, TimeoutClass::GitHubCli, "gh issue")
185}
186
187#[cfg(test)]
188mod tests {
189    use super::parse_issue_number;
190    use crate::git::github_cli::extract_first_url;
191
192    #[test]
193    fn extract_first_url_picks_first_url_line() {
194        let output = "Creating issue for task...\nhttps://github.com/org/repo/issues/5\n";
195        let url = extract_first_url(output).expect("url");
196        assert_eq!(url, "https://github.com/org/repo/issues/5");
197    }
198
199    #[test]
200    fn extract_first_url_returns_none_when_no_url() {
201        let output = "Some output without a URL\n";
202        assert!(extract_first_url(output).is_none());
203    }
204
205    #[test]
206    fn parse_issue_number_extracts_number() {
207        assert_eq!(
208            parse_issue_number("https://github.com/org/repo/issues/123"),
209            Some(123)
210        );
211        assert_eq!(
212            parse_issue_number("https://github.com/org/repo/issues/42?foo=bar"),
213            Some(42)
214        );
215    }
216
217    #[test]
218    fn parse_issue_number_returns_none_for_invalid() {
219        assert!(parse_issue_number("https://github.com/org/repo/pull/123").is_none());
220        assert!(parse_issue_number("not a url").is_none());
221        assert!(parse_issue_number("").is_none());
222    }
223}