use anyhow::{Context, Result, bail};
use crate::integrations::subprocess;
use crate::model::Task;
pub fn parse_issue_list(raw: &[u8]) -> Result<serde_json::Value> {
serde_json::from_slice(raw).context("gh issue list: invalid JSON")
}
pub fn issues_to_tasks(value: &serde_json::Value, label: Option<&str>) -> Vec<Task> {
let issues = match value.as_array() {
Some(arr) => arr,
None => return vec![],
};
issues
.iter()
.filter(|issue| {
if let Some(filter) = label {
issue
.get("labels")
.and_then(|ls| ls.as_array())
.map(|ls| {
ls.iter()
.any(|l| l.get("name").and_then(|n| n.as_str()) == Some(filter))
})
.unwrap_or(false)
} else {
true
}
})
.filter_map(|issue| {
let number = issue.get("number")?.as_u64()?;
let title = issue.get("title")?.as_str()?;
let id = format!("gh-{}", number);
let mut task = Task::new(id, title);
if let Some(body) = issue.get("body").and_then(|b| b.as_str())
&& !body.is_empty()
{
task.notes = body.to_string();
}
Some(task)
})
.collect()
}
pub fn pull_issues(repo: Option<&str>, label: Option<&str>) -> Result<Vec<Task>> {
let mut args = vec![
"issue",
"list",
"--state",
"open",
"--json",
"number,title,body,labels",
];
let repo_flag;
if let Some(r) = repo {
repo_flag = r.to_string();
args.push("--repo");
args.push(&repo_flag);
}
let label_flag;
if let Some(l) = label {
label_flag = l.to_string();
args.push("--label");
args.push(&label_flag);
}
let raw = subprocess::run("gh", &args, "install the GitHub CLI to use --github")?;
let value = parse_issue_list(raw.as_bytes())?;
Ok(issues_to_tasks(&value, label))
}
pub fn issue_close(number: u64, repo: Option<&str>, commit_sha: &str) -> Result<()> {
let number_str = number.to_string();
let comment = format!("Implemented in {}.", commit_sha);
let mut args = vec!["issue", "close", &number_str];
let repo_flag;
if let Some(r) = repo {
repo_flag = r.to_string();
args.push("--repo");
args.push(&repo_flag);
}
args.push("--comment");
args.push(&comment);
let out = std::process::Command::new("gh")
.args(&args)
.output()
.context("gh issue close failed")?;
if !out.status.success() {
bail!("gh issue close exited with {}", out.status);
}
Ok(())
}
pub struct GhIssueClient {
repo: String,
}
impl GhIssueClient {
pub fn new(repo: Option<&str>) -> Result<Self> {
let repo = match repo {
Some(value) => value.to_string(),
None => subprocess::run(
"gh",
&[
"repo",
"view",
"--json",
"nameWithOwner",
"--jq",
".nameWithOwner",
],
"authenticate the GitHub CLI to synchronize TODOs",
)?
.trim()
.to_string(),
};
Ok(Self { repo })
}
}
impl crate::todo_issue_sync::GitHubIssuePort for GhIssueClient {
fn list_open_issues_page(
&self,
page: usize,
per_page: usize,
) -> Result<Vec<crate::todo_issue_sync::GitHubIssue>> {
let endpoint = format!(
"search/issues?q=repo:{}+is:issue+is:open&per_page={per_page}&page={page}",
self.repo
);
let raw = subprocess::run(
"gh",
&["api", "--method", "GET", &endpoint],
"authenticate the GitHub CLI to synchronize TODOs",
)?;
let value: serde_json::Value =
serde_json::from_str(&raw).context("gh api issues: invalid JSON")?;
let values = value
.get("items")
.and_then(|items| items.as_array())
.context("gh api issues: missing items")?;
values
.iter()
.map(|value| {
Ok(crate::todo_issue_sync::GitHubIssue {
number: value
.get("number")
.and_then(|item| item.as_u64())
.context("issue missing number")?,
title: value
.get("title")
.and_then(|item| item.as_str())
.unwrap_or_default()
.to_string(),
body: value
.get("body")
.and_then(|item| item.as_str())
.unwrap_or_default()
.to_string(),
url: value
.get("html_url")
.and_then(|item| item.as_str())
.unwrap_or_default()
.to_string(),
})
})
.collect()
}
fn create_issue(
&self,
issue: &crate::todo_issue_sync::NewIssue,
) -> Result<crate::todo_issue_sync::CreatedIssue> {
let endpoint = format!("repos/{}/issues", self.repo);
let title = format!("title={}", issue.title);
let body = format!("body={}", issue.body);
let raw = subprocess::run(
"gh",
&[
"api", "--method", "POST", &endpoint, "-f", &title, "-f", &body,
],
"authenticate the GitHub CLI to synchronize TODOs",
)?;
let value: serde_json::Value =
serde_json::from_str(&raw).context("gh api create issue: invalid JSON")?;
Ok(crate::todo_issue_sync::CreatedIssue {
number: value
.get("number")
.and_then(|item| item.as_u64())
.context("created issue missing number")?,
url: value
.get("html_url")
.and_then(|item| item.as_str())
.context("created issue missing html_url")?
.to_string(),
})
}
}