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
use anyhow::{anyhow, Context, Result};
use crate::auth;
use super::models::{Comment, CreatedIssue, Issue, RepoLabel};
use super::url::IssueRef;
const API_BASE: &str = "https://atomgit.com/api/v5";
/// Thin blocking HTTP client for the AtomGit REST API, authenticated with
/// the OAuth token stored by `crate::auth`. Blocking is fine here — the
/// fixissue flow runs before the agent loop starts.
pub struct Client {
http: reqwest::blocking::Client,
token: String,
}
impl Client {
/// Build a client using the currently-stored OAuth token. Refreshes
/// the token if expired. Errors with a user-friendly message if the
/// user hasn't logged in.
pub fn from_stored_auth() -> Result<Self> {
if !auth::is_logged_in() {
return Err(anyhow!("not logged in — run `atomcode login` first"));
}
let token = auth::get_valid_token()
.context("failed to load OAuth token (try `atomcode login` again)")?;
// Default reqwest UA (`reqwest/<ver>`) is rejected by AtomGit's gate
// — every request here must carry `atomcode/<ver>`. Builder() with
// `.user_agent(...)` is the blocking-client equivalent of what
// `provider/mod.rs::build_http_client` does.
let http = reqwest::blocking::Client::builder()
.user_agent(crate::ATOMCODE_USER_AGENT)
.build()
.unwrap_or_else(|_| reqwest::blocking::Client::new());
Ok(Self { http, token })
}
/// GET /api/v5/repos/{owner}/{repo}/issues/{number}
pub fn get_issue(&self, r: &IssueRef) -> Result<Issue> {
let url = format!(
"{}/repos/{}/{}/issues/{}",
API_BASE, r.owner, r.repo, r.number
);
let resp = self
.http
.get(&url)
.bearer_auth(&self.token)
.header("Accept", "application/json")
.send()
.with_context(|| format!("GET {} failed", url))?;
let status = resp.status();
if status == reqwest::StatusCode::NOT_FOUND {
return Err(anyhow!(
"issue not found: {}/{}/issues/{}",
r.owner,
r.repo,
r.number
));
}
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
return Err(anyhow!(
"authentication failed ({}) — run `atomcode login` again",
status.as_u16()
));
}
if !status.is_success() {
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"AtomGit API returned {} for issue #{}: {}",
status,
r.number,
body
));
}
resp.json::<Issue>().context("failed to parse issue JSON")
}
/// POST /api/v5/repos/{owner}/{repo}/issues — create a new issue in
/// the target repo. Used by the `/issue` wizard in the TUI; returns
/// the server's response so callers can surface the new issue's
/// number + `html_url` to the user.
pub fn create_issue(
&self,
owner: &str,
repo: &str,
title: &str,
body: &str,
) -> Result<CreatedIssue> {
let url = format!("{}/repos/{}/{}/issues", API_BASE, owner, repo);
let payload = serde_json::json!({ "title": title, "body": body });
let resp = self
.http
.post(&url)
.query(&[("access_token", self.token.as_str())])
.header("Accept", "application/json")
.json(&payload)
.send()
.with_context(|| format!("POST {} failed", url))?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"AtomGit returned {} creating issue in {}/{}: {}",
status,
owner,
repo,
body
));
}
resp.json::<CreatedIssue>()
.context("failed to parse created-issue JSON")
}
/// POST /api/v5/repos/{owner}/{repo}/issues/{number}/comments —
/// append a comment to the issue. Used after a successful fixissue
/// run to leave the agent's repair summary on the issue.
pub fn post_issue_comment(&self, r: &IssueRef, body: &str) -> Result<()> {
let url = format!(
"{}/repos/{}/{}/issues/{}/comments",
API_BASE, r.owner, r.repo, r.number
);
let payload = serde_json::json!({ "body": body });
let resp = self
.http
.post(&url)
.bearer_auth(&self.token)
.header("Accept", "application/json")
.json(&payload)
.send()
.with_context(|| format!("POST {} failed", url))?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"AtomGit returned {} posting comment on issue #{}: {}",
status,
r.number,
body
));
}
Ok(())
}
/// GET /api/v5/repos/{owner}/{repo}/labels — list the repo's
/// defined labels. Used by `add_issue_label` to look up the numeric
/// ID that the issue-labels POST endpoint requires (AtomGit rejects
/// label-by-name; names alone return 400 "Request body parsing error").
pub fn list_labels(&self, owner: &str, repo: &str) -> Result<Vec<RepoLabel>> {
let url = format!("{}/repos/{}/{}/labels", API_BASE, owner, repo);
let resp = self
.http
.get(&url)
.bearer_auth(&self.token)
.header("Accept", "application/json")
.send()
.with_context(|| format!("GET {} failed", url))?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"AtomGit returned {} listing labels for {}/{}: {}",
status,
owner,
repo,
body
));
}
resp.json::<Vec<RepoLabel>>()
.context("failed to parse labels list")
}
/// POST /api/v5/repos/{owner}/{repo}/issues/{number}/labels —
/// attach a label to the issue. AtomGit's endpoint expects the
/// label's numeric **ID**, not its name, so this first calls
/// `list_labels` to resolve the name. If the label doesn't exist
/// in the repo we return a clear error instead of auto-creating —
/// label taxonomy is a repo-setting decision.
pub fn add_issue_label(&self, r: &IssueRef, label_name: &str) -> Result<()> {
let labels = self.list_labels(&r.owner, &r.repo)?;
let label = labels
.iter()
.find(|l| l.name.eq_ignore_ascii_case(label_name))
.ok_or_else(|| {
anyhow!(
"label '{}' not found in repo {}/{} — create it first at \
https://atomgit.com/{}/{}/labels (Repo Settings → Labels)",
label_name,
r.owner,
r.repo,
r.owner,
r.repo
)
})?;
let url = format!(
"{}/repos/{}/{}/issues/{}/labels",
API_BASE, r.owner, r.repo, r.number
);
// AtomGit stringifies numeric IDs in JSON (e.g. the `number` field on
// issues comes back as `"140"` not `140`). Mirror that in the request
// body — sending a numeric ID here returns 400 "Request body parsing
// error". Let `.json()` handle the Content-Type; adding it manually
// on top of .json() has caused the server to reject bodies in the past.
let payload = serde_json::json!({ "labels": [label.id.to_string()] });
// This specific endpoint requires the token in a `?access_token=`
// query parameter rather than the `Authorization: Bearer` header.
// Passing it as a Bearer token makes AtomGit respond with
// {"error_code":400,"error_code_name":"BAD_REQUEST",
// "error_message":"Request body parsing error, please check if
// the header content-type:application/json matches"}
// — the message is misleading (the body is fine), but switching
// to the query-parameter form makes the same request succeed.
// The other endpoints on the same API still accept Bearer auth,
// so we keep `bearer_auth` elsewhere and only special-case this
// one route.
let resp = self
.http
.post(&url)
.query(&[("access_token", self.token.as_str())])
.header("Accept", "application/json")
.json(&payload)
.send()
.with_context(|| format!("POST {} failed", url))?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"AtomGit returned {} adding label '{}' (id={}) to issue #{}: {}",
status,
label.name,
label.id,
r.number,
body
));
}
Ok(())
}
/// GET /api/v5/repos/{owner}/{repo}/issues/{number}/comments.
/// Swallowed on error: comments are best-effort context, not required
/// for the fix-issue flow to proceed.
pub fn get_issue_comments(&self, r: &IssueRef) -> Vec<Comment> {
let url = format!(
"{}/repos/{}/{}/issues/{}/comments",
API_BASE, r.owner, r.repo, r.number
);
let Ok(resp) = self
.http
.get(&url)
.bearer_auth(&self.token)
.header("Accept", "application/json")
.send()
else {
return Vec::new();
};
if !resp.status().is_success() {
return Vec::new();
}
resp.json::<Vec<Comment>>().unwrap_or_default()
}
}