Skip to main content

gitflow_core/
label.rs

1//! Label and Milestone resource types with platform abstraction.
2//!
3//! Defines data types for managing repository labels and milestones,
4//! along with [`LabelProvider`] and [`MilestoneProvider`] traits for
5//! cross-platform implementations (GitHub, GitLab, `GitCode`, etc.).
6
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11use crate::{Result, types::State};
12
13/// A standalone label resource definition.
14///
15/// Unlike [`crate::types::Label`] which represents a label *association*
16/// on an Issue or PR, this type represents the label resource itself —
17/// its name, display color, and description as managed in the repository.
18#[derive(Debug, Clone, Serialize, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct LabelData {
21    /// The label name.
22    pub name: String,
23    /// The label color as a hex string (e.g. `"d73a4a"`).
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub color: Option<String>,
26    /// A human-readable description of the label.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub description: Option<String>,
29}
30
31/// Arguments for creating a new label.
32#[derive(Debug, Clone)]
33pub struct CreateLabelArgs {
34    /// The label name.
35    pub name: String,
36    /// The label color as a hex string (e.g. `"d73a4a"`).
37    pub color: String,
38    /// A human-readable description of the label.
39    pub description: Option<String>,
40}
41
42/// A milestone resource definition.
43///
44/// Milestones group issues and PRs under a shared goal or release
45/// target with optional due dates and progress tracking.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47#[serde(rename_all = "camelCase")]
48pub struct MilestoneData {
49    /// The milestone's numeric identifier.
50    pub number: u64,
51    /// The milestone title.
52    pub title: String,
53    /// The milestone description (Markdown).
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub description: Option<String>,
56    /// The milestone's current state.
57    pub state: State,
58    /// The optional due date (UTC).
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub due_on: Option<DateTime<Utc>>,
61    /// The number of closed issues under this milestone.
62    pub closed_issues: u64,
63    /// The number of open issues under this milestone.
64    pub open_issues: u64,
65}
66
67/// Arguments for creating a new milestone.
68#[derive(Debug, Clone)]
69pub struct CreateMilestoneArgs {
70    /// The milestone title.
71    pub title: String,
72    /// The milestone description (Markdown).
73    pub description: Option<String>,
74    /// The optional due date (UTC).
75    pub due_on: Option<DateTime<Utc>>,
76}
77
78/// Platform abstraction for label management.
79///
80/// All platform implementations (GitHub/GitLab/GitCode) must implement
81/// this trait to provide unified label CRUD operations.
82///
83/// # Errors
84///
85/// All methods return [`CoreError`](crate::CoreError) on platform API
86/// failure, deserialization errors, or authentication failures.
87#[async_trait]
88pub trait LabelProvider: std::fmt::Debug + Send + Sync {
89    /// Create a new label in the repository.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the platform API call fails, the label name
94    /// already exists, or the parameters are invalid.
95    async fn create(&self, args: CreateLabelArgs) -> Result<LabelData>;
96
97    /// List all labels in the repository.
98    ///
99    /// # Errors
100    ///
101    /// Returns an error if the platform API call fails.
102    async fn list(&self) -> Result<Vec<LabelData>>;
103
104    /// Edit an existing label by name.
105    ///
106    /// # Errors
107    ///
108    /// Returns an error if the label does not exist or the platform API call fails.
109    async fn edit(&self, name: &str, args: CreateLabelArgs) -> Result<LabelData>;
110
111    /// Delete a label by name.
112    ///
113    /// # Errors
114    ///
115    /// Returns an error if the label does not exist or the platform API call fails.
116    async fn delete(&self, name: &str) -> Result<()>;
117}
118
119/// Platform abstraction for milestone management.
120///
121/// All platform implementations (GitHub/GitLab/GitCode) must implement
122/// this trait to provide unified milestone lifecycle operations.
123///
124/// # Errors
125///
126/// All methods return [`CoreError`](crate::CoreError) on platform API
127/// failure, deserialization errors, or authentication failures.
128#[async_trait]
129pub trait MilestoneProvider: std::fmt::Debug + Send + Sync {
130    /// Create a new milestone.
131    ///
132    /// # Errors
133    ///
134    /// Returns an error if the platform API call fails or the parameters are invalid.
135    async fn create(&self, args: CreateMilestoneArgs) -> Result<MilestoneData>;
136
137    /// List all milestones in the repository.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error if the platform API call fails.
142    async fn list(&self) -> Result<Vec<MilestoneData>>;
143
144    /// Edit an existing milestone by number.
145    ///
146    /// # Errors
147    ///
148    /// Returns an error if the milestone does not exist or the platform API call fails.
149    async fn edit(&self, number: u64, args: CreateMilestoneArgs) -> Result<MilestoneData>;
150
151    /// Close a milestone by number.
152    ///
153    /// # Errors
154    ///
155    /// Returns an error if the milestone does not exist or the platform API call fails.
156    async fn close(&self, number: u64) -> Result<MilestoneData>;
157
158    /// Reopen a closed milestone by number.
159    ///
160    /// # Errors
161    ///
162    /// Returns an error if the milestone does not exist or the platform API call fails.
163    async fn reopen(&self, number: u64) -> Result<MilestoneData>;
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    // --- LabelData tests ---
171
172    #[test]
173    fn test_should_serialize_label_data_to_camel_case_json() {
174        let label = LabelData {
175            name: "bug".into(),
176            color: Some("d73a4a".into()),
177            description: Some("Something isn't working".into()),
178        };
179        let json = serde_json::to_string(&label).expect("serialize LabelData");
180        assert!(json.contains("\"name\":\"bug\""));
181        assert!(json.contains("\"color\":\"d73a4a\""));
182        assert!(json.contains("\"description\""));
183    }
184
185    #[test]
186    fn test_should_deserialize_label_data_from_camel_case_json() {
187        let json = r#"{"name":"enhancement","color":"a2eeef","description":"New feature"}"#;
188        let label: LabelData = serde_json::from_str(json).expect("valid LabelData");
189        assert_eq!(label.name, "enhancement");
190        assert_eq!(label.color, Some("a2eeef".into()));
191        assert_eq!(label.description, Some("New feature".into()));
192    }
193
194    #[test]
195    fn test_should_deserialize_label_data_with_missing_optional_fields() {
196        let json = r#"{"name":"wip"}"#;
197        let label: LabelData = serde_json::from_str(json).expect("valid LabelData");
198        assert_eq!(label.name, "wip");
199        assert!(label.color.is_none());
200        assert!(label.description.is_none());
201    }
202
203    #[test]
204    fn test_should_serialize_label_data_skips_null_fields() {
205        let label = LabelData {
206            name: "wip".into(),
207            color: None,
208            description: None,
209        };
210        let json = serde_json::to_string(&label).expect("serialize LabelData");
211        assert_eq!(json, r#"{"name":"wip"}"#);
212        assert!(!json.contains("null"));
213    }
214
215    #[test]
216    fn test_should_roundtrip_label_data_via_serde() {
217        let label = LabelData {
218            name: "bug".into(),
219            color: Some("ff0000".into()),
220            description: Some("A defect".into()),
221        };
222        let json = serde_json::to_string(&label).expect("serialize");
223        let round_tripped: LabelData = serde_json::from_str(&json).expect("deserialize");
224        assert_eq!(round_tripped.name, label.name);
225        assert_eq!(round_tripped.color, label.color);
226        assert_eq!(round_tripped.description, label.description);
227    }
228
229    #[test]
230    fn test_should_derive_debug_for_label_data() {
231        let label = LabelData {
232            name: "test".into(),
233            color: None,
234            description: None,
235        };
236        let debug = format!("{label:?}");
237        assert!(debug.contains("LabelData"));
238        assert!(debug.contains("test"));
239    }
240
241    // --- CreateLabelArgs tests ---
242
243    #[test]
244    fn test_should_create_label_args_with_description() {
245        let args = CreateLabelArgs {
246            name: "bug".into(),
247            color: "d73a4a".into(),
248            description: Some("Defect report".into()),
249        };
250        assert_eq!(args.name, "bug");
251        assert_eq!(args.color, "d73a4a");
252        assert_eq!(args.description, Some("Defect report".into()));
253    }
254
255    #[test]
256    fn test_should_create_label_args_without_description() {
257        let args = CreateLabelArgs {
258            name: "wip".into(),
259            color: "ffff00".into(),
260            description: None,
261        };
262        assert_eq!(args.name, "wip");
263        assert!(args.description.is_none());
264    }
265
266    // --- MilestoneData tests ---
267
268    fn sample_milestone_json() -> &'static str {
269        r#"{
270            "number": 1,
271            "title": "v1.0 Release",
272            "description": "First stable release",
273            "state": "open",
274            "dueOn": "2026-06-01T00:00:00Z",
275            "closedIssues": 10,
276            "openIssues": 5
277        }"#
278    }
279
280    #[test]
281    fn test_should_deserialize_milestone_data_from_camel_case_json() {
282        let json = sample_milestone_json();
283        let milestone: MilestoneData = serde_json::from_str(json).expect("valid MilestoneData");
284        assert_eq!(milestone.number, 1);
285        assert_eq!(milestone.title, "v1.0 Release");
286        assert_eq!(milestone.description, Some("First stable release".into()));
287        assert_eq!(milestone.state, State::Open);
288        assert!(milestone.due_on.is_some());
289        assert_eq!(milestone.closed_issues, 10);
290        assert_eq!(milestone.open_issues, 5);
291    }
292
293    #[test]
294    fn test_should_serialize_milestone_data_to_camel_case_json() {
295        let json = sample_milestone_json();
296        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
297        let serialized = serde_json::to_string(&milestone).expect("serialize");
298        assert!(serialized.contains("\"closedIssues\""));
299        assert!(serialized.contains("\"openIssues\""));
300        assert!(serialized.contains("\"dueOn\""));
301        assert!(!serialized.contains("\"closed_issues\""));
302        assert!(!serialized.contains("\"open_issues\""));
303    }
304
305    #[test]
306    fn test_should_roundtrip_milestone_data_via_serde() {
307        let json = sample_milestone_json();
308        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
309        let re_serialized = serde_json::to_string(&milestone).expect("serialize");
310        let round_tripped: MilestoneData =
311            serde_json::from_str(&re_serialized).expect("re-deserialize");
312        assert_eq!(round_tripped.number, milestone.number);
313        assert_eq!(round_tripped.title, milestone.title);
314        assert_eq!(round_tripped.description, milestone.description);
315        assert_eq!(round_tripped.state, milestone.state);
316        assert_eq!(round_tripped.due_on, milestone.due_on);
317        assert_eq!(round_tripped.closed_issues, milestone.closed_issues);
318        assert_eq!(round_tripped.open_issues, milestone.open_issues);
319    }
320
321    #[test]
322    fn test_should_deserialize_milestone_with_null_optional_fields() {
323        let json = r#"{
324            "number": 2,
325            "title": "v1.1",
326            "description": null,
327            "state": "closed",
328            "dueOn": null,
329            "closedIssues": 20,
330            "openIssues": 0
331        }"#;
332        let milestone: MilestoneData = serde_json::from_str(json).expect("deserialize");
333        assert!(milestone.description.is_none());
334        assert!(milestone.due_on.is_none());
335        assert_eq!(milestone.state, State::Closed);
336    }
337
338    #[test]
339    fn test_should_serialize_milestone_skips_null_fields() {
340        let milestone = MilestoneData {
341            number: 3,
342            title: "Future".into(),
343            description: None,
344            state: State::Open,
345            due_on: None,
346            closed_issues: 0,
347            open_issues: 3,
348        };
349        let json = serde_json::to_string(&milestone).expect("serialize");
350        assert!(!json.contains("null"));
351        assert!(!json.contains("\"description\":null"));
352        assert!(!json.contains("\"dueOn\":null"));
353    }
354
355    #[test]
356    fn test_should_derive_debug_for_milestone_data() {
357        let milestone = MilestoneData {
358            number: 1,
359            title: "v1.0".into(),
360            description: None,
361            state: State::Open,
362            due_on: None,
363            closed_issues: 0,
364            open_issues: 1,
365        };
366        let debug = format!("{milestone:?}");
367        assert!(debug.contains("MilestoneData"));
368        assert!(debug.contains("v1.0"));
369    }
370
371    // --- CreateMilestoneArgs tests ---
372
373    #[test]
374    fn test_should_create_milestone_args_with_all_fields() {
375        let args = CreateMilestoneArgs {
376            title: "v2.0".into(),
377            description: Some("Major release".into()),
378            due_on: Some("2026-12-01T00:00:00Z".parse().expect("valid date")),
379        };
380        assert_eq!(args.title, "v2.0");
381        assert_eq!(args.description, Some("Major release".into()));
382        assert!(args.due_on.is_some());
383    }
384
385    #[test]
386    fn test_should_create_milestone_args_minimal() {
387        let args = CreateMilestoneArgs {
388            title: "Backlog".into(),
389            description: None,
390            due_on: None,
391        };
392        assert_eq!(args.title, "Backlog");
393        assert!(args.description.is_none());
394        assert!(args.due_on.is_none());
395    }
396}