1use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use gitflow_core::{
11 CoreError, Result,
12 issue::{CreateIssueArgs, IssueData, IssueProvider, ListIssueArgs},
13 types::{CommentData, Label, State, UserSummary},
14};
15use serde::Deserialize;
16use tracing::debug;
17
18use crate::{
19 error::parse_gitcode_error,
20 runner::{CommandRunner, RealCommandRunner},
21};
22
23#[derive(Debug, Clone, Deserialize)]
25#[serde(rename_all = "lowercase")]
26struct IssueApiResponse {
27 number: String,
28 title: String,
29 body: Option<String>,
30 state: String,
31 #[serde(default)]
32 labels: Option<Vec<LabelApi>>,
33 user: Option<UserApi>,
34 #[serde(default)]
35 assignees: Option<Vec<UserApi>>,
36 created_at: Option<String>,
37 updated_at: Option<String>,
38 html_url: String,
39}
40
41#[derive(Debug, Clone, Deserialize)]
42#[serde(rename_all = "lowercase")]
43struct LabelApi {
44 name: String,
45 #[serde(default)]
46 color: Option<String>,
47 #[serde(default)]
48 description: Option<String>,
49}
50
51#[derive(Debug, Clone, Deserialize)]
52struct UserApi {
53 login: String,
54 #[serde(default)]
55 id: Option<String>,
56}
57
58impl From<IssueApiResponse> for IssueData {
59 fn from(api: IssueApiResponse) -> Self {
60 Self {
61 number: api.number.parse().unwrap_or(0),
62 title: api.title,
63 body: api.body,
64 state: match api.state.as_str() {
65 "closed" => State::Closed,
66 _ => State::Open,
67 },
68 labels: api
69 .labels
70 .unwrap_or_default()
71 .into_iter()
72 .map(Label::from)
73 .collect(),
74 author: api.user.map_or(
75 UserSummary {
76 login: "unknown".into(),
77 id: String::new(),
78 },
79 UserSummary::from,
80 ),
81 assignees: api
82 .assignees
83 .unwrap_or_default()
84 .into_iter()
85 .map(UserSummary::from)
86 .collect(),
87 created_at: api
88 .created_at
89 .and_then(|s| {
90 DateTime::parse_from_rfc3339(&s)
91 .ok()
92 .map(|d| d.with_timezone(&Utc))
93 })
94 .unwrap_or_else(Utc::now),
95 updated_at: api
96 .updated_at
97 .and_then(|s| {
98 DateTime::parse_from_rfc3339(&s)
99 .ok()
100 .map(|d| d.with_timezone(&Utc))
101 })
102 .unwrap_or_else(Utc::now),
103 url: api.html_url,
104 }
105 }
106}
107
108impl From<LabelApi> for Label {
109 fn from(api: LabelApi) -> Self {
110 Self {
111 name: api.name,
112 color: api.color,
113 description: api.description,
114 }
115 }
116}
117
118impl From<UserApi> for UserSummary {
119 fn from(api: UserApi) -> Self {
120 Self {
121 login: api.login,
122 id: api.id.unwrap_or_default(),
123 }
124 }
125}
126
127#[derive(Debug, Clone, Deserialize)]
131struct CommentApiResponse {
132 #[serde(deserialize_with = "gitflow_core::types::deserialize_u64_or_string")]
133 id: u64,
134 #[serde(default)]
135 body: String,
136 #[serde(default)]
137 author: Option<String>,
138 #[serde(default)]
139 user: Option<UserApi>,
140 #[serde(default)]
141 created_at: Option<String>,
142}
143
144impl From<CommentApiResponse> for CommentData {
145 fn from(api: CommentApiResponse) -> Self {
146 let author = api.user.map_or_else(
147 || UserSummary {
148 login: api.author.unwrap_or_else(|| "unknown".into()),
149 id: String::new(),
150 },
151 UserSummary::from,
152 );
153 let created_at = api.created_at.as_deref().map_or_else(Utc::now, |s| {
154 DateTime::parse_from_rfc3339(s)
155 .map(|dt| dt.with_timezone(&Utc))
156 .or_else(|_| {
157 chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
158 .map(|ndt| ndt.and_utc())
159 })
160 .unwrap_or_else(|_| Utc::now())
161 });
162 Self {
163 id: api.id,
164 body: api.body,
165 author,
166 created_at,
167 }
168 }
169}
170
171#[derive(Debug, Clone, Deserialize)]
176struct CloseApiResponse {
177 number: u64,
178 state: String,
179 url: String,
180}
181
182impl From<CloseApiResponse> for IssueData {
183 fn from(api: CloseApiResponse) -> Self {
184 Self {
185 number: api.number,
186 title: String::new(),
187 body: None,
188 state: match api.state.as_str() {
189 "closed" => State::Closed,
190 _ => State::Open,
191 },
192 labels: Vec::new(),
193 author: UserSummary {
194 login: "unknown".into(),
195 id: String::new(),
196 },
197 assignees: Vec::new(),
198 created_at: Utc::now(),
199 updated_at: Utc::now(),
200 url: api.url,
201 }
202 }
203}
204
205#[derive(Debug, Clone)]
210pub struct GitCodeIssueProvider<R: CommandRunner = RealCommandRunner> {
211 repo: String,
213 runner: R,
215}
216
217impl GitCodeIssueProvider<RealCommandRunner> {
218 #[must_use]
220 pub fn new(repo: impl Into<String>) -> Self {
221 Self {
222 repo: repo.into(),
223 runner: RealCommandRunner,
224 }
225 }
226}
227
228impl<R: CommandRunner> GitCodeIssueProvider<R> {
229 #[must_use]
233 pub fn with_runner(repo: impl Into<String>, runner: R) -> Self {
234 Self {
235 repo: repo.into(),
236 runner,
237 }
238 }
239
240 async fn ensure_label_exists(&self, name: &str) -> Result<()> {
246 let binary = crate::gitcode_binary();
247 debug!(repo = %self.repo, name, "auto-creating missing label via `gc label create`");
248
249 let output = self
250 .runner
251 .run(
252 &binary,
253 &[
254 "label", "create", name, "--color", "ededed", "-R", &self.repo,
255 ],
256 )
257 .await
258 .map_err(|e| {
259 CoreError::Platform(format!("Failed to spawn gitcode label create: {e}"))
260 })?;
261
262 if !output.status.success() {
263 let gitcode_err = parse_gitcode_error(&output.stderr);
264 tracing::debug!(error = %gitcode_err, "Failed to auto-create label");
265 return Err(CoreError::Platform(format!(
266 "Failed to auto-create label '{name}': {}",
267 gitcode_err.user_message
268 )));
269 }
270
271 Ok(())
272 }
273}
274
275#[async_trait]
276impl<R: CommandRunner + 'static> IssueProvider for GitCodeIssueProvider<R> {
277 async fn create(&self, args: CreateIssueArgs) -> Result<IssueData> {
278 let binary = crate::gitcode_binary();
279 let mut cmd_args: Vec<&str> = vec![
280 "issue",
281 "create",
282 "-R",
283 &self.repo,
284 "--title",
285 &args.title,
286 "--json",
287 ];
288
289 if let Some(body) = &args.body {
290 cmd_args.push("--body");
291 cmd_args.push(body);
292 }
293 for label in &args.labels {
294 cmd_args.push("--label");
295 cmd_args.push(label);
296 }
297 for assignee in &args.assignees {
298 cmd_args.push("--assignee");
299 cmd_args.push(assignee);
300 }
301
302 debug!(repo = %self.repo, title = %args.title, "spawning gitcode issue create");
303 let output = self
304 .runner
305 .run(&binary, &cmd_args)
306 .await
307 .map_err(|e| CoreError::Platform(format!("{e}")))?;
308 if !output.status.success() {
309 let missing = extract_missing_labels_from_error(&output.stderr);
312 if !missing.is_empty() {
313 debug!(
314 repo = %self.repo,
315 missing_count = missing.len(),
316 "auto-creating missing label(s) before retrying issue create"
317 );
318 for label in &missing {
319 self.ensure_label_exists(label).await?;
320 }
321
322 let retry_output = self.runner.run(&binary, &cmd_args).await.map_err(|e| {
323 CoreError::Platform(format!("Failed to spawn gitcode on retry: {e}"))
324 })?;
325 if !retry_output.status.success() {
326 return Err(parse_gitcode_error(&retry_output.stderr).into());
327 }
328 return serde_json::from_slice::<IssueApiResponse>(&retry_output.stdout)
329 .map(IssueData::from)
330 .map_err(CoreError::Serialization);
331 }
332
333 return Err(parse_gitcode_error(&output.stderr).into());
334 }
335 serde_json::from_slice::<IssueApiResponse>(&output.stdout)
336 .map(IssueData::from)
337 .map_err(CoreError::Serialization)
338 }
339
340 async fn list(&self, args: ListIssueArgs) -> Result<Vec<IssueData>> {
341 let binary = crate::gitcode_binary();
342 let mut cmd_args: Vec<&str> = vec!["issue", "list", "-R", &self.repo, "--json"];
343
344 if let Some(ref state) = args.state {
345 cmd_args.push("--state");
346 cmd_args.push(match state {
347 State::Open => "open",
348 State::Closed => "closed",
349 });
350 }
351 if let Some(ref search) = args.search {
352 cmd_args.push("--search");
353 cmd_args.push(search);
354 }
355 let limit_str = args.limit.map(|limit| limit.to_string());
356 if let Some(ref limit) = limit_str {
357 cmd_args.push("--limit");
358 cmd_args.push(limit);
359 }
360 for label in &args.labels {
361 cmd_args.push("--label");
362 cmd_args.push(label);
363 }
364
365 debug!(repo = %self.repo, "spawning gitcode issue list");
366 let output = self
367 .runner
368 .run(&binary, &cmd_args)
369 .await
370 .map_err(|e| CoreError::Platform(format!("{e}")))?;
371 if !output.status.success() {
372 return Err(parse_gitcode_error(&output.stderr).into());
373 }
374 let issues: Vec<IssueApiResponse> =
375 serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
376 Ok(issues.into_iter().map(IssueData::from).collect())
377 }
378
379 async fn view(&self, number: u64) -> Result<IssueData> {
380 let binary = crate::gitcode_binary();
381 let number_str = number.to_string();
382 debug!(repo = %self.repo, number, "spawning gitcode issue view");
383 let output = self
384 .runner
385 .run(
386 &binary,
387 &["issue", "view", &number_str, "-R", &self.repo, "--json"],
388 )
389 .await
390 .map_err(|e| CoreError::Platform(format!("{e}")))?;
391
392 if !output.status.success() {
393 return Err(parse_gitcode_error(&output.stderr).into());
394 }
395 serde_json::from_slice::<IssueApiResponse>(&output.stdout)
396 .map(IssueData::from)
397 .map_err(CoreError::Serialization)
398 }
399
400 async fn close(&self, number: u64) -> Result<IssueData> {
401 let binary = crate::gitcode_binary();
402 let number_str = number.to_string();
403 debug!(repo = %self.repo, number, "spawning gitcode issue close");
404 let output = self
405 .runner
406 .run(
407 &binary,
408 &[
409 "issue",
410 "close",
411 &number_str,
412 "-R",
413 &self.repo,
414 "--yes",
415 "--json",
416 ],
417 )
418 .await
419 .map_err(|e| CoreError::Platform(format!("{e}")))?;
420
421 if !output.status.success() {
422 return Err(parse_gitcode_error(&output.stderr).into());
423 }
424 serde_json::from_slice::<CloseApiResponse>(&output.stdout)
425 .map(IssueData::from)
426 .map_err(CoreError::Serialization)
427 }
428
429 async fn reopen(&self, number: u64) -> Result<IssueData> {
430 let binary = crate::gitcode_binary();
431 let number_str = number.to_string();
432 debug!(repo = %self.repo, number, "spawning gitcode issue reopen");
433 let output = self
434 .runner
435 .run(
436 &binary,
437 &[
438 "issue",
439 "reopen",
440 &number_str,
441 "-R",
442 &self.repo,
443 "--yes",
444 "--json",
445 ],
446 )
447 .await
448 .map_err(|e| CoreError::Platform(format!("{e}")))?;
449
450 if !output.status.success() {
451 return Err(parse_gitcode_error(&output.stderr).into());
452 }
453 serde_json::from_slice::<CloseApiResponse>(&output.stdout)
454 .map(IssueData::from)
455 .map_err(CoreError::Serialization)
456 }
457
458 async fn comment(&self, number: u64, body: &str) -> Result<CommentData> {
467 let binary = crate::gitcode_binary();
468 let number_str = number.to_string();
469 debug!(repo = %self.repo, number, "spawning `gc issue comment`");
470
471 let output = self
472 .runner
473 .run(
474 &binary,
475 &[
476 "issue",
477 "comment",
478 &number_str,
479 "-R",
480 &self.repo,
481 "--body",
482 body,
483 "--json",
484 ],
485 )
486 .await
487 .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
488
489 if !output.status.success() {
490 return Err(parse_gitcode_error(&output.stderr).into());
491 }
492
493 let api: CommentApiResponse =
494 serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
495
496 Ok(CommentData::from(api))
497 }
498
499 async fn list_comments(&self, number: u64) -> Result<Vec<CommentData>> {
508 let binary = crate::gitcode_binary();
509 debug!(repo = %self.repo, number, "spawning `gitcode api` GET issue comments");
510
511 let api_path = format!("/repos/{}/issues/{}/comments", self.repo, number);
512
513 let output = self
514 .runner
515 .run(&binary, &["api", &api_path])
516 .await
517 .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode api: {e}")))?;
518
519 if !output.status.success() {
520 return Err(parse_gitcode_error(&output.stderr).into());
521 }
522
523 let comments: Vec<CommentApiResponse> =
524 serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;
525
526 Ok(comments.into_iter().map(CommentData::from).collect())
527 }
528
529 async fn add_labels(&self, number: u64, labels: &[String]) -> Result<()> {
544 if labels.is_empty() {
545 return Ok(());
546 }
547
548 let binary = crate::gitcode_binary();
549 let number_str = number.to_string();
550 let joined = labels.join(",");
551 debug!(
552 repo = %self.repo,
553 number,
554 label_count = labels.len(),
555 "spawning `gitcode issue label --add`"
556 );
557
558 let cmd_args: Vec<&str> = vec![
559 "issue",
560 "label",
561 &number_str,
562 "--add",
563 &joined,
564 "-R",
565 &self.repo,
566 ];
567
568 let output = self
569 .runner
570 .run(&binary, &cmd_args)
571 .await
572 .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
573
574 if output.status.success() {
575 return Ok(());
576 }
577
578 let missing = extract_missing_labels_from_error(&output.stderr);
580 if missing.is_empty() {
581 return Err(parse_gitcode_error(&output.stderr).into());
582 }
583
584 debug!(
585 repo = %self.repo,
586 missing_count = missing.len(),
587 "auto-creating missing label(s) before retry"
588 );
589
590 for label in &missing {
591 self.ensure_label_exists(label).await?;
592 }
593
594 let retry_output =
595 self.runner.run(&binary, &cmd_args).await.map_err(|e| {
596 CoreError::Platform(format!("Failed to spawn gitcode on retry: {e}"))
597 })?;
598
599 if !retry_output.status.success() {
600 return Err(parse_gitcode_error(&retry_output.stderr).into());
601 }
602
603 Ok(())
604 }
605
606 async fn remove_label(&self, number: u64, label: &str) -> Result<()> {
614 let binary = crate::gitcode_binary();
615 let number_str = number.to_string();
616 debug!(repo = %self.repo, number, label, "spawning `gitcode issue label --remove`");
617
618 let output = self
619 .runner
620 .run(
621 &binary,
622 &[
623 "issue",
624 "label",
625 &number_str,
626 "--remove",
627 label,
628 "-R",
629 &self.repo,
630 ],
631 )
632 .await
633 .map_err(|e| CoreError::Platform(format!("Failed to spawn gitcode: {e}")))?;
634
635 if !output.status.success() {
636 return Err(parse_gitcode_error(&output.stderr).into());
637 }
638
639 Ok(())
640 }
641}
642
643fn extract_missing_labels_from_error(stderr: &[u8]) -> Vec<String> {
648 let text = String::from_utf8_lossy(stderr);
649 let mut labels = Vec::new();
650 let mut search_from: usize = 0;
651
652 while let Some(rel_open) = text[search_from..].find('\'') {
653 let open_pos = search_from + rel_open + 1;
654 let Some(rel_close) = text[open_pos..].find('\'') else {
655 break;
656 };
657 let close_pos = open_pos + rel_close;
658 let after_close = &text[close_pos + 1..];
659
660 if after_close.starts_with(" not found") {
661 let label = text[open_pos..close_pos].to_string();
662 if !label.is_empty() {
663 labels.push(label);
664 }
665 }
666 search_from = close_pos + 1;
667 }
668
669 labels
670}
671
672#[cfg(test)]
673mod tests {
674 use gitflow_core::types::UserSummary;
675
676 use super::*;
677 use crate::runner::{MockCommandRunner, RecordingMockRunner, SequencedMockCommandRunner};
678
679 #[test]
680 fn test_should_construct_gitcode_issue_provider() {
681 let provider = GitCodeIssueProvider::new("octocat/hello-world");
682 assert_eq!(provider.repo, "octocat/hello-world");
683 }
684
685 #[test]
686 fn test_should_construct_gitcode_issue_provider_from_string() {
687 let repo = String::from("octocat/hello-world");
688 let provider = GitCodeIssueProvider::new(repo);
689 assert_eq!(provider.repo, "octocat/hello-world");
690 }
691
692 #[test]
693 fn test_should_deserialize_issue_data_from_gc_output() {
694 let gc_json = br#"{
695 "number": 42,
696 "title": "Fix login bug",
697 "body": "Reproduced on v1.2.3",
698 "state": "open",
699 "labels": [
700 {"name": "bug", "color": "d73a4a", "description": "Something isn't working"}
701 ],
702 "author": {"login": "octocat", "id": "1"},
703 "assignees": [{"login": "alice", "id": "7"}],
704 "createdAt": "2026-01-15T09:30:00Z",
705 "updatedAt": "2026-01-16T11:00:00Z",
706 "url": "https://gitcode.com/octocat/hello-world/issues/42"
707 }"#;
708
709 let issue: IssueData = serde_json::from_slice(gc_json).expect("valid IssueData JSON");
710 assert_eq!(issue.number, 42);
711 assert_eq!(issue.title, "Fix login bug");
712 assert_eq!(issue.state, State::Open);
713 assert_eq!(issue.labels.len(), 1);
714 assert_eq!(issue.author.login, "octocat");
715 assert_eq!(issue.assignees.len(), 1);
716 assert_eq!(
717 issue.url,
718 "https://gitcode.com/octocat/hello-world/issues/42"
719 );
720 }
721
722 #[test]
723 fn test_should_deserialize_empty_issue_list_from_gc_output() {
724 let gc_json = b"[]";
725 let issues: Vec<IssueData> = serde_json::from_slice(gc_json).expect("valid IssueData list");
726 assert!(issues.is_empty());
727 }
728
729 #[test]
730 fn test_should_debug_format_provider() {
731 let provider = GitCodeIssueProvider::new("octocat/hello-world");
732 let debug = format!("{provider:?}");
733 assert!(debug.contains("GitCodeIssueProvider"));
734 assert!(debug.contains("octocat/hello-world"));
735 }
736
737 #[test]
738 fn test_should_deserialize_closed_issue_from_gc_close_output() {
739 let gc_json = br#"{
740 "number": 10,
741 "title": "Fixed typo",
742 "body": null,
743 "state": "closed",
744 "labels": [],
745 "author": {"login": "dev", "id": "5"},
746 "assignees": [],
747 "createdAt": "2026-06-01T08:00:00Z",
748 "updatedAt": "2026-06-02T12:00:00Z",
749 "url": "https://gitcode.com/octocat/hello-world/issues/10"
750 }"#;
751
752 let issue: IssueData = serde_json::from_slice(gc_json).expect("valid closed IssueData");
753 assert_eq!(issue.number, 10);
754 assert_eq!(issue.state, State::Closed);
755 }
756
757 #[test]
758 fn test_should_deserialize_reopened_issue_from_gc_reopen_output() {
759 let gc_json = br#"{
760 "number": 10,
761 "title": "Fixed typo",
762 "body": null,
763 "state": "open",
764 "labels": [],
765 "author": {"login": "dev", "id": "5"},
766 "assignees": [],
767 "createdAt": "2026-06-01T08:00:00Z",
768 "updatedAt": "2026-06-03T09:00:00Z",
769 "url": "https://gitcode.com/octocat/hello-world/issues/10"
770 }"#;
771
772 let issue: IssueData = serde_json::from_slice(gc_json).expect("valid reopened IssueData");
773 assert_eq!(issue.number, 10);
774 assert_eq!(issue.state, State::Open);
775 }
776
777 #[test]
778 fn test_should_deserialize_comment_data_from_gc_comment_output() {
779 let gc_json = br#"{
780 "id": "1001",
781 "body": "Thanks for reporting, looking into it.",
782 "author": "maintainer",
783 "created_at": "2026-06-15 14:00:00"
784 }"#;
785
786 let api: CommentApiResponse =
787 serde_json::from_slice(gc_json).expect("valid CommentApiResponse");
788 let comment = CommentData::from(api);
789 assert_eq!(comment.id, 1001);
790 assert_eq!(comment.body, "Thanks for reporting, looking into it.");
791 assert_eq!(comment.author.login, "maintainer");
792 }
793
794 #[test]
795 fn test_should_roundtrip_comment_data_via_serde() {
796 let comment = CommentData {
797 id: 77,
798 body: "reviewed".into(),
799 author: UserSummary {
800 login: "alice".into(),
801 id: "3".to_string(),
802 },
803 created_at: "2026-05-01T00:00:00Z".parse().expect("valid date"),
804 };
805 let json = serde_json::to_string(&comment).expect("serialize");
806 let round_tripped: CommentData = serde_json::from_str(&json).expect("deserialize");
807 assert_eq!(round_tripped.id, comment.id);
808 assert_eq!(round_tripped.body, comment.body);
809 assert_eq!(round_tripped.author.login, comment.author.login);
810 }
811
812 #[test]
813 fn test_should_create_provider_with_different_repos() {
814 let r1 = GitCodeIssueProvider::new("org/repo-a");
815 let r2 = GitCodeIssueProvider::new("org/repo-b");
816 assert_eq!(r1.repo, "org/repo-a");
817 assert_eq!(r2.repo, "org/repo-b");
818 }
819
820 #[test]
821 fn test_should_clone_gitcode_issue_provider() {
822 let original = GitCodeIssueProvider::new("owner/repo");
823 let cloned = original.clone();
824 assert_eq!(original.repo, cloned.repo);
825 }
826
827 fn sample_create_args() -> CreateIssueArgs {
830 CreateIssueArgs {
831 title: "Bug report".to_string(),
832 body: Some("Steps to reproduce".to_string()),
833 labels: vec!["bug".to_string()],
834 assignees: vec!["alice".to_string()],
835 }
836 }
837
838 #[tokio::test]
839 async fn test_should_return_platform_error_when_gc_fails_for_view() {
840 let runner = MockCommandRunner::failure("issue not found", 256);
841 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
842
843 let result = provider.view(999).await;
844
845 assert!(matches!(
846 result.unwrap_err(),
847 gitflow_core::CoreError::Cli(_)
848 ));
849 }
850
851 #[tokio::test]
852 async fn test_should_return_serialization_error_on_invalid_json_for_view() {
853 let runner = MockCommandRunner::success("not valid json");
854 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
855
856 let result = provider.view(1).await;
857
858 assert!(matches!(
859 result.unwrap_err(),
860 gitflow_core::CoreError::Serialization(_)
861 ));
862 }
863
864 #[tokio::test]
865 async fn test_should_return_platform_error_when_gc_fails_for_list() {
866 let runner = MockCommandRunner::failure("forbidden", 256);
867 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
868
869 let result = provider.list(ListIssueArgs::default()).await;
870
871 assert!(matches!(
872 result.unwrap_err(),
873 gitflow_core::CoreError::Cli(_)
874 ));
875 }
876
877 #[tokio::test]
878 async fn test_should_return_serialization_error_on_invalid_json_for_list() {
879 let runner = MockCommandRunner::success("invalid");
880 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
881
882 let result = provider.list(ListIssueArgs::default()).await;
883
884 assert!(matches!(
885 result.unwrap_err(),
886 gitflow_core::CoreError::Serialization(_)
887 ));
888 }
889
890 #[tokio::test]
891 async fn test_should_return_platform_error_when_gc_fails_for_create() {
892 let runner = MockCommandRunner::failure("validation failed", 256);
893 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
894
895 let result = provider.create(sample_create_args()).await;
896
897 assert!(matches!(
898 result.unwrap_err(),
899 gitflow_core::CoreError::Cli(_)
900 ));
901 }
902
903 #[tokio::test]
904 async fn test_should_return_serialization_error_on_invalid_json_for_create() {
905 let runner = MockCommandRunner::success("not valid json");
906 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
907
908 let result = provider.create(sample_create_args()).await;
909
910 assert!(matches!(
911 result.unwrap_err(),
912 gitflow_core::CoreError::Serialization(_)
913 ));
914 }
915
916 #[tokio::test]
917 async fn test_should_return_platform_error_when_gc_fails_for_close() {
918 let runner = MockCommandRunner::failure("not found", 256);
919 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
920
921 let result = provider.close(42).await;
922
923 assert!(matches!(
924 result.unwrap_err(),
925 gitflow_core::CoreError::Cli(_)
926 ));
927 }
928
929 #[tokio::test]
930 async fn test_should_return_platform_error_when_gc_fails_for_reopen() {
931 let runner = MockCommandRunner::failure("not found", 256);
932 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
933
934 let result = provider.reopen(42).await;
935
936 assert!(matches!(
937 result.unwrap_err(),
938 gitflow_core::CoreError::Cli(_)
939 ));
940 }
941
942 #[tokio::test]
943 async fn test_should_return_platform_error_when_gc_fails_for_comment() {
944 let runner = MockCommandRunner::failure("not found", 256);
945 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
946
947 let result = provider.comment(42, "a comment").await;
948
949 assert!(matches!(
950 result.unwrap_err(),
951 gitflow_core::CoreError::Cli(_)
952 ));
953 }
954
955 #[tokio::test]
956 async fn test_should_return_platform_error_when_gc_fails_for_add_labels() {
957 let runner = MockCommandRunner::failure("not found", 256);
958 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
959
960 let result = provider.add_labels(42, &["bug".to_string()]).await;
961
962 assert!(matches!(
963 result.unwrap_err(),
964 gitflow_core::CoreError::Cli(_)
965 ));
966 }
967
968 #[tokio::test]
969 async fn test_should_return_platform_error_when_gc_fails_for_remove_label() {
970 let runner = MockCommandRunner::failure("not found", 256);
971 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
972
973 let result = provider.remove_label(42, "bug").await;
974
975 assert!(matches!(
976 result.unwrap_err(),
977 gitflow_core::CoreError::Cli(_)
978 ));
979 }
980
981 #[test]
984 fn test_should_extract_single_missing_label_from_gc_stderr() {
985 let stderr =
986 b"failed to update https://gitcode.com/owner/repo/issues/18: 'type:enhancement' not found";
987 let missing = extract_missing_labels_from_error(stderr);
988 assert_eq!(missing, vec!["type:enhancement".to_string()]);
989 }
990
991 #[test]
992 fn test_should_return_empty_when_no_label_not_found_in_gc_stderr() {
993 let stderr = b"gitcode: Not logged in";
994 let missing = extract_missing_labels_from_error(stderr);
995 assert!(missing.is_empty());
996 }
997
998 #[tokio::test]
1001 async fn test_should_auto_create_label_and_retry_on_add_labels() {
1002 let runner = SequencedMockCommandRunner::from_results(&[
1007 (
1008 false,
1009 "failed to update https://gitcode.com/owner/repo/issues/18: 'type:enhancement' \
1010 not found",
1011 ),
1012 (true, ""),
1013 (true, ""),
1014 ]);
1015 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
1016
1017 let result = provider
1018 .add_labels(18, &["type:enhancement".to_string()])
1019 .await;
1020
1021 assert!(result.is_ok(), "expected Ok, got {result:?}");
1022 }
1023
1024 #[tokio::test]
1025 async fn test_should_propagate_error_when_gc_label_create_fails() {
1026 let runner = SequencedMockCommandRunner::from_results(&[
1027 (false, "failed to update ...: 'ghost' not found"),
1028 (false, "gitcode: 403 Forbidden"),
1029 ]);
1030 let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1031
1032 let result = provider.add_labels(1, &["ghost".to_string()]).await;
1033
1034 assert!(result.is_err());
1035 }
1036
1037 #[tokio::test]
1038 async fn test_should_not_retry_on_non_label_error_gc() {
1039 let runner = SequencedMockCommandRunner::from_results(&[(false, "gitcode: Not logged in")]);
1040 let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1041
1042 let result = provider.add_labels(1, &["bug".to_string()]).await;
1043
1044 assert!(result.is_err());
1045 }
1046
1047 #[tokio::test]
1048 async fn test_should_invoke_issue_label_subcommand_for_add_labels() {
1049 let runner = RecordingMockRunner::success("");
1050 let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1051
1052 provider
1053 .add_labels(54, &["type:bug".to_string(), "priority:high".to_string()])
1054 .await
1055 .expect("add_labels should succeed");
1056
1057 let calls = runner.calls();
1058 assert_eq!(calls.len(), 1);
1059 assert_eq!(
1060 calls[0],
1061 vec![
1062 "issue",
1063 "label",
1064 "54",
1065 "--add",
1066 "type:bug,priority:high",
1067 "-R",
1068 "o/r"
1069 ],
1070 r"gitcode v0.6.1 的 issue edit 没有 --add-label flag(Issue #90)"
1071 );
1072 }
1073
1074 #[tokio::test]
1075 async fn test_should_return_ok_without_any_call_for_empty_labels() {
1076 let runner = RecordingMockRunner::success("");
1077 let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1078
1079 provider
1080 .add_labels(1, &[])
1081 .await
1082 .expect("empty labels is a no-op");
1083
1084 assert!(runner.calls().is_empty());
1085 }
1086
1087 #[tokio::test]
1088 async fn test_should_invoke_issue_label_subcommand_for_remove_label() {
1089 let runner = RecordingMockRunner::success("");
1090 let provider = GitCodeIssueProvider::with_runner("o/r", runner.clone());
1091
1092 provider
1093 .remove_label(54, "triage:done")
1094 .await
1095 .expect("remove should succeed");
1096
1097 assert_eq!(
1098 runner.calls()[0],
1099 vec![
1100 "issue",
1101 "label",
1102 "54",
1103 "--remove",
1104 "triage:done",
1105 "-R",
1106 "o/r"
1107 ]
1108 );
1109 }
1110
1111 #[tokio::test]
1112 async fn test_should_auto_create_missing_label_and_retry_via_issue_label() {
1113 let runner = SequencedMockCommandRunner::from_results(&[
1117 (false, "HTTP 404: 'type:new' not found"),
1118 (true, r#"{"name": "type:new", "color": "ededed"}"#),
1119 (true, ""),
1120 ]);
1121 let provider = GitCodeIssueProvider::with_runner("o/r", runner);
1122
1123 provider
1124 .add_labels(18, &["type:new".to_string()])
1125 .await
1126 .expect("should recover by auto-creating the label");
1127 }
1128
1129 #[test]
1130 fn test_should_parse_issue_comment_with_user_object() {
1131 let json = r#"{"id": 12, "body": "hi", "user": {"login": "bob", "id": "u2"}, "created_at": "2026-07-30T12:00:00+08:00"}"#;
1132 let api: CommentApiResponse = serde_json::from_str(json).expect("user-object shape");
1133 let comment: CommentData = api.into();
1134 assert_eq!(comment.id, 12);
1135 assert_eq!(comment.author.login, "bob");
1136 assert_eq!(comment.author.id, "u2");
1137 }
1138}
1139
1140#[cfg(test)]
1141mod contract_tests {
1142 use super::*;
1143 use crate::runner::MockCommandRunner;
1144
1145 #[tokio::test]
1149 async fn test_contract_issue_list_gitcode_v0_6() {
1150 let fixture = include_str!("../tests/fixtures/issue_list_gitcode_v0.6.json");
1151 let runner = MockCommandRunner::success(fixture);
1152 let provider = GitCodeIssueProvider::with_runner("owner/repo", runner);
1153
1154 let issues = provider
1155 .list(ListIssueArgs::default())
1156 .await
1157 .expect("contract fixture must parse");
1158
1159 assert_eq!(issues.len(), 1);
1160 let issue = &issues[0];
1161 assert_eq!(issue.number, 15);
1162 assert!(!issue.title.is_empty());
1163 assert_eq!(issue.state, gitflow_core::types::State::Open);
1164 }
1165}