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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// GitHub Issues client implementation methods
// This file is include!()'d from github_issues.rs — do NOT add `use` imports or `#!` attributes.
impl GitHubIssuesService {
/// Create a new GitHub Issues service with token authentication
///
/// # Arguments
///
/// * `token` - GitHub personal access token or OAuth token
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::GitHubIssuesService;
///
/// let service = GitHubIssuesService::new("ghp_xxxxxxxxxxxxxxxxxxxx")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn new(token: &str) -> Result<Self, GitHubError> {
let config = GitHubConfig {
token: token.to_string(),
..Default::default()
};
Self::with_config(config)
}
/// Create a new GitHub Issues service with custom configuration
///
/// # Arguments
///
/// * `config` - GitHub service configuration
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::{GitHubIssuesService, GitHubConfig};
/// use std::time::Duration;
///
/// let config = GitHubConfig {
/// token: "ghp_xxxxxxxxxxxxxxxxxxxx".to_string(),
/// timeout: Duration::from_secs(60),
/// max_retries: 5,
/// ..Default::default()
/// };
///
/// let service = GitHubIssuesService::with_config(config)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn with_config(config: GitHubConfig) -> Result<Self, GitHubError> {
if config.token.is_empty() {
return Err(GitHubError::Authentication {
token_type: "empty token".to_string(),
});
}
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
format!("Bearer {}", config.token).parse().expect("valid authorization header"),
);
headers.insert(
reqwest::header::USER_AGENT,
"pmat-github-integration/1.0".parse().expect("valid user-agent header"),
);
headers.insert(
reqwest::header::ACCEPT,
"application/vnd.github.v3+json".parse().expect("valid accept header"),
);
let client = Client::builder()
.timeout(config.timeout)
.default_headers(headers)
.build()
.map_err(GitHubError::Request)?;
Ok(Self { client, config })
}
/// Create a new GitHub issue
///
/// # Arguments
///
/// * `owner` - Repository owner (user or organization)
/// * `repo` - Repository name
/// * `request` - Issue creation request
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::{GitHubIssuesService, IssueRequest};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = GitHubIssuesService::new("token")?;
///
/// let request = IssueRequest {
/// title: "PDMT Feature Implementation".to_string(),
/// body: "Implement using PDMT style with seed 42".to_string(),
/// labels: vec!["enhancement".to_string()],
/// assignees: vec![],
/// };
///
/// let issue = service.create_issue("owner", "repo", request).await?;
/// assert!(!issue.title.is_empty());
/// # Ok(())
/// # }
/// ```
pub async fn create_issue(
&self,
owner: &str,
repo: &str,
request: IssueRequest,
) -> Result<GitHubIssue, GitHubError> {
let url = format!("{}/repos/{}/{}/issues", self.config.base_url, owner, repo);
self.execute_with_retry(|| async {
let response = self
.client
.post(&url)
.json(&request)
.send()
.await?;
self.handle_response(response).await
})
.await
}
/// Read a GitHub issue by number
///
/// # Arguments
///
/// * `owner` - Repository owner (user or organization)
/// * `repo` - Repository name
/// * `issue_number` - Issue number to retrieve
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::GitHubIssuesService;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = GitHubIssuesService::new("token")?;
/// let issue = service.read_issue("owner", "repo", 123).await?;
/// assert_eq!(issue.number, 123);
/// # Ok(())
/// # }
/// ```
pub async fn read_issue(
&self,
owner: &str,
repo: &str,
issue_number: u32,
) -> Result<GitHubIssue, GitHubError> {
let url = format!(
"{}/repos/{}/{}/issues/{}",
self.config.base_url, owner, repo, issue_number
);
self.execute_with_retry(|| async {
let response = self.client.get(&url).send().await?;
self.handle_response(response).await
})
.await
}
/// Update an existing GitHub issue
///
/// # Arguments
///
/// * `owner` - Repository owner (user or organization)
/// * `repo` - Repository name
/// * `issue_number` - Issue number to update
/// * `request` - Issue update request
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::{GitHubIssuesService, IssueUpdateRequest, IssueState};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = GitHubIssuesService::new("token")?;
///
/// let update = IssueUpdateRequest {
/// title: Some("Updated Title".to_string()),
/// state: Some(IssueState::Closed),
/// ..Default::default()
/// };
///
/// let issue = service.update_issue("owner", "repo", 123, update).await?;
/// assert_eq!(issue.state, IssueState::Closed);
/// # Ok(())
/// # }
/// ```
pub async fn update_issue(
&self,
owner: &str,
repo: &str,
issue_number: u32,
request: IssueUpdateRequest,
) -> Result<GitHubIssue, GitHubError> {
let url = format!(
"{}/repos/{}/{}/issues/{}",
self.config.base_url, owner, repo, issue_number
);
self.execute_with_retry(|| async {
let response = self
.client
.patch(&url)
.json(&request)
.send()
.await?;
self.handle_response(response).await
})
.await
}
/// List GitHub issues for a repository
///
/// # Arguments
///
/// * `owner` - Repository owner (user or organization)
/// * `repo` - Repository name
/// * `pagination` - Optional pagination configuration
///
/// # Examples
///
/// ```rust
/// use pmat::services::github_issues::{GitHubIssuesService, Pagination};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let service = GitHubIssuesService::new("token")?;
///
/// let pagination = Pagination {
/// page: 1,
/// per_page: 50,
/// };
///
/// let issues = service.list_issues("owner", "repo", Some(pagination)).await?;
/// assert!(issues.len() <= 50);
/// # Ok(())
/// # }
/// ```
pub async fn list_issues(
&self,
owner: &str,
repo: &str,
pagination: Option<Pagination>,
) -> Result<Vec<GitHubIssue>, GitHubError> {
let pagination = pagination.unwrap_or_default();
let url = format!(
"{}/repos/{}/{}/issues?page={}&per_page={}",
self.config.base_url, owner, repo, pagination.page, pagination.per_page
);
self.execute_with_retry(|| async {
let response = self.client.get(&url).send().await?;
self.handle_response(response).await
})
.await
}
/// Execute HTTP request with retry logic for rate limiting
async fn execute_with_retry<F, Fut, T>(&self, operation: F) -> Result<T, GitHubError>
where
F: Fn() -> Fut,
Fut: std::future::Future<Output = Result<T, GitHubError>>,
{
let mut attempts = 0;
let mut delay = self.config.retry_delay;
loop {
match operation().await {
Ok(result) => return Ok(result),
Err(GitHubError::RateLimit { retry_after }) => {
if attempts >= self.config.max_retries {
return Err(GitHubError::RateLimit { retry_after });
}
attempts += 1;
let sleep_duration = Duration::from_secs(retry_after).max(delay);
sleep(sleep_duration).await;
delay *= 2; // Exponential backoff
}
Err(other) => return Err(other),
}
}
}
/// Handle HTTP response and convert to appropriate types
async fn handle_response<T>(&self, response: reqwest::Response) -> Result<T, GitHubError>
where
T: serde::de::DeserializeOwned,
{
let status = response.status();
if status.is_success() {
let json = response.json::<T>().await?;
return Ok(json);
}
// Handle rate limiting
if status == 403 {
if let Some(retry_after) = response
.headers()
.get("x-ratelimit-reset")
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("system time after UNIX epoch")
.as_secs();
let retry_after = retry_after.saturating_sub(now);
return Err(GitHubError::RateLimit { retry_after });
}
}
// Handle authentication errors
if status == 401 {
return Err(GitHubError::Authentication {
token_type: "invalid or expired token".to_string(),
});
}
// Handle other API errors
let error_body = response.text().await.unwrap_or_default();
Err(GitHubError::Api {
status: status.as_u16(),
message: error_body,
})
}
/// Validate repository format (owner/repo)
#[allow(dead_code)]
fn validate_repo_format(owner: &str, repo: &str) -> Result<(), GitHubError> {
if owner.is_empty() || repo.is_empty() {
return Err(GitHubError::InvalidRepo {
repo: format!("{}/{}", owner, repo),
});
}
// Basic validation for allowed characters
let valid_chars = |s: &str| s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.');
if !valid_chars(owner) || !valid_chars(repo) {
return Err(GitHubError::InvalidRepo {
repo: format!("{}/{}", owner, repo),
});
}
Ok(())
}
}