gitflow-github 1.1.0

gf 的 GitHub 适配器,基于 gh CLI 提供 Issue/PR/Release/Review 等能力。GitHub adapter for gf via gh CLI.
Documentation
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! GitHub Label 和 Milestone 提供者实现。
//!
//! 通过 `gh label` 和 `gh api` CLI 命令实现 [`LabelProvider`] 和
//! [`MilestoneProvider`] trait,支持标签和里程碑的完整生命周期管理。

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use gitflow_core::{
    CoreError, Result,
    label::{
        CreateLabelArgs, CreateMilestoneArgs, LabelData, LabelProvider, MilestoneData,
        MilestoneProvider,
    },
    types::State,
};
use serde::Deserialize;
use tracing::debug;

use crate::error::parse_gh_error;

/// GitHub Label 提供者,通过 `gh` CLI 管理仓库标签。
///
/// # Examples
///
/// ```no_run
/// use gitflow_github::GitHubLabelProvider;
///
/// let provider = GitHubLabelProvider::new("octocat/hello-world");
/// ```
#[derive(Debug, Clone)]
pub struct GitHubLabelProvider {
    /// GitHub `owner/repo`。
    repo: String,
}

impl GitHubLabelProvider {
    /// 创建新的 GitHub Label 提供者。
    ///
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self { repo: repo.into() }
    }
}

/// `gh label list/create` 请求的 JSON 字段列表。
const LABEL_FIELDS: &str = "name,color,description";

#[async_trait]
impl LabelProvider for GitHubLabelProvider {
    async fn create(&self, args: CreateLabelArgs) -> Result<LabelData> {
        debug!(
            repo = %self.repo,
            name = %args.name,
            color = %args.color,
            "spawning `gh label create`"
        );

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["label", "create"])
            .arg(&args.name)
            .arg("--color")
            .arg(&args.color)
            .arg("--repo")
            .arg(&self.repo);

        if let Some(ref desc) = args.description {
            cmd.arg("--description").arg(desc);
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label create: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        // gh label create doesn't return JSON, construct the response manually
        Ok(LabelData {
            name: args.name,
            color: Some(args.color),
            description: args.description,
        })
    }

    async fn list(&self) -> Result<Vec<LabelData>> {
        debug!(repo = %self.repo, "spawning `gh label list`");

        let output = tokio::process::Command::new("gh")
            .args(["label", "list"])
            .arg("--repo")
            .arg(&self.repo)
            .arg("--json")
            .arg(LABEL_FIELDS)
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label list: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let labels: Vec<LabelData> =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(labels)
    }

    async fn edit(&self, name: &str, args: CreateLabelArgs) -> Result<LabelData> {
        debug!(repo = %self.repo, name, "spawning `gh label edit`");

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["label", "edit"])
            .arg(name)
            .arg("--repo")
            .arg(&self.repo)
            .arg("--color")
            .arg(&args.color);

        if let Some(ref desc) = args.description {
            cmd.arg("--description").arg(desc);
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label edit: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        // gh label edit 不返回 JSON,重新 fetch 获取最新数据
        self.fetch_label(name).await
    }

    async fn delete(&self, name: &str) -> Result<()> {
        debug!(repo = %self.repo, name, "spawning `gh label delete`");

        let output = tokio::process::Command::new("gh")
            .args(["label", "delete"])
            .arg(name)
            .arg("--yes")
            .arg("--repo")
            .arg(&self.repo)
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label delete: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        Ok(())
    }
}

impl GitHubLabelProvider {
    /// 获取指定名称的标签数据(内部辅助方法)。
    async fn fetch_label(&self, name: &str) -> Result<LabelData> {
        let output = tokio::process::Command::new("gh")
            .args(["label", "view"])
            .arg(name)
            .arg("--repo")
            .arg(&self.repo)
            .arg("--json")
            .arg(LABEL_FIELDS)
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh label view: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let label: LabelData =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(label)
    }
}

/// GitHub 里程碑提供者,通过 `gh api` 管理仓库里程碑。
///
/// # Examples
///
/// ```no_run
/// use gitflow_github::GitHubMilestoneProvider;
///
/// let provider = GitHubMilestoneProvider::new("octocat/hello-world");
/// ```
#[derive(Debug, Clone)]
pub struct GitHubMilestoneProvider {
    /// GitHub `owner/repo`。
    repo: String,
}

impl GitHubMilestoneProvider {
    /// 创建新的 GitHub Milestone 提供者。
    ///
    /// `repo` 格式为 `owner/repo`。
    #[must_use]
    pub fn new(repo: impl Into<String>) -> Self {
        Self { repo: repo.into() }
    }
}

/// `gh api milestones` 返回的 JSON 结构。
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct MilestoneApiResponse {
    number: u64,
    title: String,
    #[serde(default)]
    description: Option<String>,
    state: String,
    #[serde(default)]
    due_on: Option<String>,
    #[serde(default)]
    closed_issues: u64,
    #[serde(default)]
    open_issues: u64,
}

impl From<MilestoneApiResponse> for MilestoneData {
    fn from(api: MilestoneApiResponse) -> Self {
        Self {
            number: api.number,
            title: api.title,
            description: api.description,
            state: if api.state == "closed" {
                State::Closed
            } else {
                State::Open
            },
            due_on: api.due_on.and_then(|s| {
                DateTime::parse_from_rfc3339(&s).map_or(None, |dt| Some(dt.with_timezone(&Utc)))
            }),
            closed_issues: api.closed_issues,
            open_issues: api.open_issues,
        }
    }
}

#[async_trait]
impl MilestoneProvider for GitHubMilestoneProvider {
    async fn create(&self, args: CreateMilestoneArgs) -> Result<MilestoneData> {
        debug!(repo = %self.repo, title = %args.title, "spawning `gh api milestones POST`");

        let api_path = format!("repos/{repo}/milestones", repo = self.repo);

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["api", &api_path, "-X", "POST"])
            .arg("-f")
            .arg(format!("title={}", args.title));

        if let Some(ref desc) = args.description {
            cmd.arg("-f").arg(format!("description={desc}"));
        }

        if let Some(ref due) = args.due_on {
            cmd.arg("-f").arg(format!("due_on={}", due.to_rfc3339()));
        }

        let output = cmd
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api milestones: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn list(&self) -> Result<Vec<MilestoneData>> {
        debug!(repo = %self.repo, "spawning `gh api milestones list`");

        let api_path = format!("repos/{repo}/milestones", repo = self.repo);

        let output = tokio::process::Command::new("gh")
            .args(["api", &api_path])
            .output()
            .await
            .map_err(|e| CoreError::Platform(format!("Failed to spawn gh api milestones: {e}")))?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let milestones: Vec<MilestoneApiResponse> =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(milestones.into_iter().map(MilestoneData::from).collect())
    }

    async fn edit(&self, number: u64, args: CreateMilestoneArgs) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones PATCH`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let mut cmd = tokio::process::Command::new("gh");
        cmd.args(["api", &api_path, "-X", "PATCH"]);

        cmd.arg("-f").arg(format!("title={}", args.title));

        if let Some(ref desc) = args.description {
            cmd.arg("-f").arg(format!("description={desc}"));
        }

        if let Some(ref due) = args.due_on {
            cmd.arg("-f").arg(format!("due_on={}", due.to_rfc3339()));
        }

        let output = cmd.output().await.map_err(|e| {
            CoreError::Platform(format!("Failed to spawn gh api milestone edit: {e}"))
        })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn close(&self, number: u64) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones close`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let output = tokio::process::Command::new("gh")
            .args(["api", &api_path, "-X", "PATCH", "-f", "state=closed"])
            .output()
            .await
            .map_err(|e| {
                CoreError::Platform(format!("Failed to spawn gh api milestone close: {e}"))
            })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }

    async fn reopen(&self, number: u64) -> Result<MilestoneData> {
        debug!(repo = %self.repo, number, "spawning `gh api milestones reopen`");

        let api_path = format!("repos/{repo}/milestones/{number}", repo = self.repo);

        let output = tokio::process::Command::new("gh")
            .args(["api", &api_path, "-X", "PATCH", "-f", "state=open"])
            .output()
            .await
            .map_err(|e| {
                CoreError::Platform(format!("Failed to spawn gh api milestone reopen: {e}"))
            })?;

        if !output.status.success() {
            return Err(parse_gh_error(&output.stderr).into());
        }

        let api_response: MilestoneApiResponse =
            serde_json::from_slice(&output.stdout).map_err(CoreError::Serialization)?;

        Ok(api_response.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- GitHubLabelProvider tests ---

    #[test]
    fn test_should_construct_github_label_provider() {
        let provider = GitHubLabelProvider::new("octocat/hello-world");
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_construct_github_label_provider_from_string() {
        let repo = String::from("octocat/hello-world");
        let provider = GitHubLabelProvider::new(repo);
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_debug_format_label_provider() {
        let provider = GitHubLabelProvider::new("owner/repo");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitHubLabelProvider"));
        assert!(debug.contains("owner/repo"));
    }

    #[test]
    fn test_should_clone_github_label_provider() {
        let original = GitHubLabelProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    // --- GitHubMilestoneProvider tests ---

    #[test]
    fn test_should_construct_github_milestone_provider() {
        let provider = GitHubMilestoneProvider::new("octocat/hello-world");
        assert_eq!(provider.repo, "octocat/hello-world");
    }

    #[test]
    fn test_should_debug_format_milestone_provider() {
        let provider = GitHubMilestoneProvider::new("owner/repo");
        let debug = format!("{provider:?}");
        assert!(debug.contains("GitHubMilestoneProvider"));
        assert!(debug.contains("owner/repo"));
    }

    #[test]
    fn test_should_clone_github_milestone_provider() {
        let original = GitHubMilestoneProvider::new("owner/repo");
        let cloned = original.clone();
        assert_eq!(original.repo, cloned.repo);
    }

    // --- LabelData deserialization tests ---

    #[test]
    fn test_should_deserialize_label_data_from_gh_output() {
        let json = br#"[
            {"name": "bug", "color": "d73a4a", "description": "Something isn't working"},
            {"name": "enhancement", "color": "a2eeef", "description": null}
        ]"#;

        let labels: Vec<LabelData> = serde_json::from_slice(json).expect("valid LabelData list");
        assert_eq!(labels.len(), 2);
        assert_eq!(labels[0].name, "bug");
        assert_eq!(labels[0].color.as_deref(), Some("d73a4a"));
        assert_eq!(labels[1].description, None);
    }

    #[test]
    fn test_should_deserialize_single_label_from_gh_output() {
        let json = br#"{"name": "wip", "color": "ffff00", "description": "Work in progress"}"#;

        let label: LabelData = serde_json::from_slice(json).expect("valid LabelData");
        assert_eq!(label.name, "wip");
        assert_eq!(label.color.as_deref(), Some("ffff00"));
        assert_eq!(label.description.as_deref(), Some("Work in progress"));
    }

    #[test]
    fn test_should_deserialize_empty_label_list() {
        let json = b"[]";
        let labels: Vec<LabelData> =
            serde_json::from_slice(json).expect("valid empty LabelData list");
        assert!(labels.is_empty());
    }

    // --- MilestoneData deserialization tests ---

    #[test]
    fn test_should_deserialize_milestone_api_response() {
        let json = br#"{
            "number": 1,
            "title": "v1.0 Release",
            "description": "First stable release",
            "state": "open",
            "dueOn": "2026-06-01T00:00:00Z",
            "closedIssues": 10,
            "openIssues": 5
        }"#;

        let api: MilestoneApiResponse =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse");
        let data: MilestoneData = api.into();

        assert_eq!(data.number, 1);
        assert_eq!(data.title, "v1.0 Release");
        assert_eq!(data.description, Some("First stable release".into()));
        assert_eq!(data.state, State::Open);
        assert!(data.due_on.is_some());
        assert_eq!(data.closed_issues, 10);
        assert_eq!(data.open_issues, 5);
    }

    #[test]
    fn test_should_deserialize_closed_milestone() {
        let json = br#"{
            "number": 2,
            "title": "v0.9 Beta",
            "description": null,
            "state": "closed",
            "dueOn": null,
            "closedIssues": 20,
            "openIssues": 0
        }"#;

        let api: MilestoneApiResponse =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse");
        let data: MilestoneData = api.into();

        assert_eq!(data.state, State::Closed);
        assert!(data.description.is_none());
        assert!(data.due_on.is_none());
    }

    #[test]
    fn test_should_deserialize_milestone_list() {
        let json = br#"[
            {"number": 1, "title": "v1.0", "description": null, "state": "open", "dueOn": null, "closedIssues": 0, "openIssues": 3},
            {"number": 2, "title": "v0.9", "description": "Beta", "state": "closed", "dueOn": "2026-01-01T00:00:00Z", "closedIssues": 15, "openIssues": 0}
        ]"#;

        let milestones: Vec<MilestoneApiResponse> =
            serde_json::from_slice(json).expect("valid MilestoneApiResponse list");
        assert_eq!(milestones.len(), 2);
        assert_eq!(milestones[0].title, "v1.0");
        assert_eq!(milestones[1].title, "v0.9");
    }

    #[test]
    fn test_should_convert_milestone_api_to_data() {
        let api = MilestoneApiResponse {
            number: 42,
            title: "Test Milestone".into(),
            description: Some("A test".into()),
            state: "open".into(),
            due_on: Some("2026-12-01T00:00:00Z".into()),
            closed_issues: 5,
            open_issues: 10,
        };

        let data: MilestoneData = api.clone().into();
        assert_eq!(data.number, api.number);
        assert_eq!(data.title, api.title);
    }
}