gitflow-core 2.0.0

gf 核心库:细粒度 provider trait 集合、URL 平台探测、跨平台适配器契约与 toon 输出。Core library: provider traits, URL-based platform detection, cross-platform adapter contracts & toon output.
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
//! Label and Milestone resource types with platform abstraction.
//!
//! Defines data types for managing repository labels and milestones,
//! along with [`LabelProvider`] and [`MilestoneProvider`] traits for
//! cross-platform implementations (GitHub, GitLab, `GitCode`, etc.).

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::{Result, paging::Paged, types::State};

/// A standalone label resource definition.
///
/// Unlike [`crate::types::Label`] which represents a label *association*
/// on an Issue or PR, this type represents the label resource itself —
/// its name, display color, and description as managed in the repository.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LabelData {
    /// The label name.
    pub name: String,
    /// The label color as a hex string (e.g. `"d73a4a"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub color: Option<String>,
    /// A human-readable description of the label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Arguments for creating a new label.
#[derive(Debug, Clone)]
pub struct CreateLabelArgs {
    /// The label name.
    pub name: String,
    /// The label color as a hex string (e.g. `"d73a4a"`).
    pub color: String,
    /// A human-readable description of the label.
    pub description: Option<String>,
}

/// A milestone resource definition.
///
/// Milestones group issues and PRs under a shared goal or release
/// target with optional due dates and progress tracking.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MilestoneData {
    /// The milestone's numeric identifier.
    pub number: u64,
    /// The milestone title.
    pub title: String,
    /// The milestone description (Markdown).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The milestone's current state.
    pub state: State,
    /// The optional due date (UTC).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub due_on: Option<DateTime<Utc>>,
    /// The number of closed issues under this milestone.
    pub closed_issues: u64,
    /// The number of open issues under this milestone.
    pub open_issues: u64,
}

/// Arguments for creating a new milestone.
#[derive(Debug, Clone)]
pub struct CreateMilestoneArgs {
    /// The milestone title.
    pub title: String,
    /// The milestone description (Markdown).
    pub description: Option<String>,
    /// The optional due date (UTC).
    pub due_on: Option<DateTime<Utc>>,
}

/// Platform abstraction for label management.
///
/// All platform implementations (GitHub/GitLab/GitCode) must implement
/// this trait to provide unified label CRUD operations.
///
/// # Errors
///
/// All methods return [`CoreError`](crate::CoreError) on platform API
/// failure, deserialization errors, or authentication failures.
#[async_trait]
pub trait LabelProvider: std::fmt::Debug + Send + Sync {
    /// Create a new label in the repository.
    ///
    /// # Errors
    ///
    /// Returns an error if the platform API call fails, the label name
    /// already exists, or the parameters are invalid.
    async fn create(&self, args: CreateLabelArgs) -> Result<LabelData>;

    /// List all labels in the repository.
    ///
    /// `limit` 为 `None` 时取至 [`crate::paging::DEFAULT_LIST_LIMIT`]。
    ///
    /// # Errors
    ///
    /// Returns an error if the platform API call fails.
    async fn list(&self, limit: Option<u32>) -> Result<Paged<LabelData>>;

    /// Edit an existing label by name.
    ///
    /// # Errors
    ///
    /// Returns an error if the label does not exist or the platform API call fails.
    async fn edit(&self, name: &str, args: CreateLabelArgs) -> Result<LabelData>;

    /// Delete a label by name.
    ///
    /// # Errors
    ///
    /// Returns an error if the label does not exist or the platform API call fails.
    async fn delete(&self, name: &str) -> Result<()>;
}

/// Platform abstraction for milestone management.
///
/// All platform implementations (GitHub/GitLab/GitCode) must implement
/// this trait to provide unified milestone lifecycle operations.
///
/// # Errors
///
/// All methods return [`CoreError`](crate::CoreError) on platform API
/// failure, deserialization errors, or authentication failures.
#[async_trait]
pub trait MilestoneProvider: std::fmt::Debug + Send + Sync {
    /// Create a new milestone.
    ///
    /// # Errors
    ///
    /// Returns an error if the platform API call fails or the parameters are invalid.
    async fn create(&self, args: CreateMilestoneArgs) -> Result<MilestoneData>;

    /// List all milestones in the repository.
    ///
    /// `limit` 为 `None` 时取至 [`crate::paging::DEFAULT_LIST_LIMIT`]。
    ///
    /// # Errors
    ///
    /// Returns an error if the platform API call fails.
    async fn list(&self, limit: Option<u32>) -> Result<Paged<MilestoneData>>;

    /// Edit an existing milestone by number.
    ///
    /// # Errors
    ///
    /// Returns an error if the milestone does not exist or the platform API call fails.
    async fn edit(&self, number: u64, args: CreateMilestoneArgs) -> Result<MilestoneData>;

    /// Close a milestone by number.
    ///
    /// # Errors
    ///
    /// Returns an error if the milestone does not exist or the platform API call fails.
    async fn close(&self, number: u64) -> Result<MilestoneData>;

    /// Reopen a closed milestone by number.
    ///
    /// # Errors
    ///
    /// Returns an error if the milestone does not exist or the platform API call fails.
    async fn reopen(&self, number: u64) -> Result<MilestoneData>;
}

/// Resolves a user-supplied milestone identifier (`--milestone <NUMBER|TITLE>`)
/// against the repository's milestone list, matching by number first (if the
/// identifier parses as `u64`) then by exact title.
///
/// # Errors
///
/// Returns an error if no milestone matches by either number or exact title.
pub async fn resolve_milestone_identifier(
    provider: &dyn MilestoneProvider,
    identifier: &str,
) -> Result<crate::types::MilestoneRef> {
    let milestones = provider.list(None).await?;
    if let Ok(number) = identifier.parse::<u64>()
        && let Some(m) = milestones.items.iter().find(|m| m.number == number)
    {
        return Ok(crate::types::MilestoneRef {
            number: m.number,
            title: m.title.clone(),
        });
    }
    milestones
        .items
        .iter()
        .find(|m| m.title == identifier)
        .map(|m| crate::types::MilestoneRef {
            number: m.number,
            title: m.title.clone(),
        })
        .ok_or_else(|| {
            crate::CoreError::Platform(format!(
                "milestone '{identifier}' not found (matched by neither number nor exact title)"
            ))
        })
}

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

    // --- LabelData tests ---

    #[test]
    fn test_should_serialize_label_data_to_camel_case_json() {
        let label = LabelData {
            name: "bug".into(),
            color: Some("d73a4a".into()),
            description: Some("Something isn't working".into()),
        };
        let json = serde_json::to_string(&label).expect("serialize LabelData");
        assert!(json.contains("\"name\":\"bug\""));
        assert!(json.contains("\"color\":\"d73a4a\""));
        assert!(json.contains("\"description\""));
    }

    #[test]
    fn test_should_deserialize_label_data_from_camel_case_json() {
        let json = r#"{"name":"enhancement","color":"a2eeef","description":"New feature"}"#;
        let label: LabelData = serde_json::from_str(json).expect("valid LabelData");
        assert_eq!(label.name, "enhancement");
        assert_eq!(label.color, Some("a2eeef".into()));
        assert_eq!(label.description, Some("New feature".into()));
    }

    #[test]
    fn test_should_deserialize_label_data_with_missing_optional_fields() {
        let json = r#"{"name":"wip"}"#;
        let label: LabelData = serde_json::from_str(json).expect("valid LabelData");
        assert_eq!(label.name, "wip");
        assert!(label.color.is_none());
        assert!(label.description.is_none());
    }

    #[test]
    fn test_should_serialize_label_data_skips_null_fields() {
        let label = LabelData {
            name: "wip".into(),
            color: None,
            description: None,
        };
        let json = serde_json::to_string(&label).expect("serialize LabelData");
        assert_eq!(json, r#"{"name":"wip"}"#);
        assert!(!json.contains("null"));
    }

    #[test]
    fn test_should_roundtrip_label_data_via_serde() {
        let label = LabelData {
            name: "bug".into(),
            color: Some("ff0000".into()),
            description: Some("A defect".into()),
        };
        let json = serde_json::to_string(&label).expect("serialize");
        let round_tripped: LabelData = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(round_tripped.name, label.name);
        assert_eq!(round_tripped.color, label.color);
        assert_eq!(round_tripped.description, label.description);
    }

    #[test]
    fn test_should_derive_debug_for_label_data() {
        let label = LabelData {
            name: "test".into(),
            color: None,
            description: None,
        };
        let debug = format!("{label:?}");
        assert!(debug.contains("LabelData"));
        assert!(debug.contains("test"));
    }

    // --- CreateLabelArgs tests ---

    #[test]
    fn test_should_create_label_args_with_description() {
        let args = CreateLabelArgs {
            name: "bug".into(),
            color: "d73a4a".into(),
            description: Some("Defect report".into()),
        };
        assert_eq!(args.name, "bug");
        assert_eq!(args.color, "d73a4a");
        assert_eq!(args.description, Some("Defect report".into()));
    }

    #[test]
    fn test_should_create_label_args_without_description() {
        let args = CreateLabelArgs {
            name: "wip".into(),
            color: "ffff00".into(),
            description: None,
        };
        assert_eq!(args.name, "wip");
        assert!(args.description.is_none());
    }

    // --- MilestoneData tests ---

    fn sample_milestone_json() -> &'static str {
        r#"{
            "number": 1,
            "title": "v1.0 Release",
            "description": "First stable release",
            "state": "open",
            "dueOn": "2026-06-01T00:00:00Z",
            "closedIssues": 10,
            "openIssues": 5
        }"#
    }

    #[test]
    fn test_should_deserialize_milestone_data_from_camel_case_json() {
        let json = sample_milestone_json();
        let milestone: MilestoneData = serde_json::from_str(json).expect("valid MilestoneData");
        assert_eq!(milestone.number, 1);
        assert_eq!(milestone.title, "v1.0 Release");
        assert_eq!(milestone.description, Some("First stable release".into()));
        assert_eq!(milestone.state, State::Open);
        assert!(milestone.due_on.is_some());
        assert_eq!(milestone.closed_issues, 10);
        assert_eq!(milestone.open_issues, 5);
    }

    #[test]
    fn test_should_serialize_milestone_data_to_camel_case_json() {
        let json = sample_milestone_json();
        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
        let serialized = serde_json::to_string(&milestone).expect("serialize");
        assert!(serialized.contains("\"closedIssues\""));
        assert!(serialized.contains("\"openIssues\""));
        assert!(serialized.contains("\"dueOn\""));
        assert!(!serialized.contains("\"closed_issues\""));
        assert!(!serialized.contains("\"open_issues\""));
    }

    #[test]
    fn test_should_roundtrip_milestone_data_via_serde() {
        let json = sample_milestone_json();
        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
        let re_serialized = serde_json::to_string(&milestone).expect("serialize");
        let round_tripped: MilestoneData =
            serde_json::from_str(&re_serialized).expect("re-deserialize");
        assert_eq!(round_tripped.number, milestone.number);
        assert_eq!(round_tripped.title, milestone.title);
        assert_eq!(round_tripped.description, milestone.description);
        assert_eq!(round_tripped.state, milestone.state);
        assert_eq!(round_tripped.due_on, milestone.due_on);
        assert_eq!(round_tripped.closed_issues, milestone.closed_issues);
        assert_eq!(round_tripped.open_issues, milestone.open_issues);
    }

    #[test]
    fn test_should_deserialize_milestone_with_null_optional_fields() {
        let json = r#"{
            "number": 2,
            "title": "v1.1",
            "description": null,
            "state": "closed",
            "dueOn": null,
            "closedIssues": 20,
            "openIssues": 0
        }"#;
        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
        assert!(milestone.description.is_none());
        assert!(milestone.due_on.is_none());
        assert_eq!(milestone.state, State::Closed);
    }

    #[test]
    fn test_should_serialize_milestone_skips_null_fields() {
        let milestone = MilestoneData {
            number: 3,
            title: "Future".into(),
            description: None,
            state: State::Open,
            due_on: None,
            closed_issues: 0,
            open_issues: 3,
        };
        let json = serde_json::to_string(&milestone).expect("serialize");
        assert!(!json.contains("null"));
        assert!(!json.contains("\"description\":null"));
        assert!(!json.contains("\"dueOn\":null"));
    }

    #[test]
    fn test_should_derive_debug_for_milestone_data() {
        let milestone = MilestoneData {
            number: 1,
            title: "v1.0".into(),
            description: None,
            state: State::Open,
            due_on: None,
            closed_issues: 0,
            open_issues: 1,
        };
        let debug = format!("{milestone:?}");
        assert!(debug.contains("MilestoneData"));
        assert!(debug.contains("v1.0"));
    }

    // --- CreateMilestoneArgs tests ---

    #[test]
    fn test_should_create_milestone_args_with_all_fields() {
        let args = CreateMilestoneArgs {
            title: "v2.0".into(),
            description: Some("Major release".into()),
            due_on: Some("2026-12-01T00:00:00Z".parse().expect("valid date")),
        };
        assert_eq!(args.title, "v2.0");
        assert_eq!(args.description, Some("Major release".into()));
        assert!(args.due_on.is_some());
    }

    #[test]
    fn test_should_create_milestone_args_minimal() {
        let args = CreateMilestoneArgs {
            title: "Backlog".into(),
            description: None,
            due_on: None,
        };
        assert_eq!(args.title, "Backlog");
        assert!(args.description.is_none());
        assert!(args.due_on.is_none());
    }

    // --- resolve_milestone_identifier tests ---

    #[derive(Debug)]
    struct MockMilestoneProvider {
        milestones: Vec<MilestoneData>,
    }

    #[async_trait::async_trait]
    impl MilestoneProvider for MockMilestoneProvider {
        async fn create(&self, _args: CreateMilestoneArgs) -> Result<MilestoneData> {
            unimplemented!("not used by resolver tests")
        }
        async fn list(&self, _limit: Option<u32>) -> Result<Paged<MilestoneData>> {
            Ok(Paged {
                items: self.milestones.clone(),
                truncated: false,
                limit: 100,
            })
        }
        async fn edit(&self, _number: u64, _args: CreateMilestoneArgs) -> Result<MilestoneData> {
            unimplemented!("not used by resolver tests")
        }
        async fn close(&self, _number: u64) -> Result<MilestoneData> {
            unimplemented!("not used by resolver tests")
        }
        async fn reopen(&self, _number: u64) -> Result<MilestoneData> {
            unimplemented!("not used by resolver tests")
        }
    }

    fn sample_milestone(number: u64, title: &str) -> MilestoneData {
        MilestoneData {
            number,
            title: title.to_string(),
            description: None,
            state: State::Open,
            due_on: None,
            closed_issues: 0,
            open_issues: 0,
        }
    }

    #[tokio::test]
    async fn test_should_resolve_milestone_by_number() {
        let provider = MockMilestoneProvider {
            milestones: vec![sample_milestone(1, "v1.0"), sample_milestone(2, "v2.0")],
        };
        let resolved = resolve_milestone_identifier(&provider, "2")
            .await
            .expect("resolve");
        assert_eq!(
            resolved,
            crate::types::MilestoneRef {
                number: 2,
                title: "v2.0".into()
            }
        );
    }

    #[tokio::test]
    async fn test_should_resolve_milestone_by_title() {
        let provider = MockMilestoneProvider {
            milestones: vec![sample_milestone(1, "v1.0"), sample_milestone(2, "v2.0")],
        };
        let resolved = resolve_milestone_identifier(&provider, "v1.0")
            .await
            .expect("resolve");
        assert_eq!(
            resolved,
            crate::types::MilestoneRef {
                number: 1,
                title: "v1.0".into()
            }
        );
    }

    #[tokio::test]
    async fn test_should_prefer_number_match_over_title_match() {
        // Identifier "2" happens to also be a different milestone's title.
        let provider = MockMilestoneProvider {
            milestones: vec![sample_milestone(1, "2"), sample_milestone(2, "v2.0")],
        };
        let resolved = resolve_milestone_identifier(&provider, "2")
            .await
            .expect("resolve");
        assert_eq!(
            resolved.number, 2,
            "numeric identifier must match by number first, not by a milestone whose title \
             happens to equal the same string"
        );
    }

    #[tokio::test]
    async fn test_should_error_when_milestone_identifier_not_found() {
        let provider = MockMilestoneProvider {
            milestones: vec![sample_milestone(1, "v1.0")],
        };
        let result = resolve_milestone_identifier(&provider, "does-not-exist").await;
        assert!(result.is_err());
    }
}