Skip to main content

gitfox_client/models/
label.rs

1use serde::{Deserialize, Serialize};
2
3/// A label defined on a repository or a space.
4///
5/// GitFox labels are keyed rather than named, and a label may carry a set of
6/// values (`priority:high`). Colours come from a fixed palette of names.
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8pub struct Label {
9    #[serde(default)]
10    pub id: i64,
11    #[serde(default)]
12    pub key: String,
13    #[serde(default)]
14    pub description: Option<String>,
15    #[serde(default)]
16    pub color: Option<String>,
17    /// `static` or `dynamic`.
18    #[serde(default, rename = "type")]
19    pub kind: Option<String>,
20    /// Set for a repository label; a space label has `space_id` instead.
21    #[serde(default)]
22    pub repo_id: Option<i64>,
23    #[serde(default)]
24    pub space_id: Option<i64>,
25    #[serde(default)]
26    pub scope: Option<i64>,
27    #[serde(default)]
28    pub value_count: Option<i64>,
29    #[serde(default)]
30    pub created: Option<i64>,
31    #[serde(default)]
32    pub updated: Option<i64>,
33}
34
35#[derive(Debug, Clone, Default, Serialize, Deserialize)]
36pub struct LabelValue {
37    #[serde(default)]
38    pub id: i64,
39    #[serde(default)]
40    pub label_id: Option<i64>,
41    #[serde(default)]
42    pub value: String,
43    #[serde(default)]
44    pub color: Option<String>,
45}
46
47/// The body for defining or updating a label. Every field is optional on an
48/// update; `key` renames the label.
49#[derive(Debug, Clone, Default, Serialize)]
50pub struct LabelInput {
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub key: Option<String>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub description: Option<String>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub color: Option<String>,
57    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
58    pub kind: Option<String>,
59}
60
61/// `GET …/pullreq/{n}/labels`: the labels that can be, or are, attached.
62#[derive(Debug, Clone, Default, Serialize, Deserialize)]
63pub struct PullRequestLabels {
64    #[serde(default)]
65    pub label_data: Vec<LabelAssignment>,
66}
67
68#[derive(Debug, Clone, Default, Serialize, Deserialize)]
69pub struct LabelAssignment {
70    #[serde(default)]
71    pub id: i64,
72    #[serde(default)]
73    pub key: String,
74    #[serde(default)]
75    pub color: Option<String>,
76    #[serde(default, rename = "type")]
77    pub kind: Option<String>,
78    #[serde(default)]
79    pub assigned: Option<bool>,
80    #[serde(default)]
81    pub assigned_value: Option<LabelValueInfo>,
82    #[serde(default)]
83    pub values: Vec<LabelValueInfo>,
84}
85
86#[derive(Debug, Clone, Default, Serialize, Deserialize)]
87pub struct LabelValueInfo {
88    #[serde(default)]
89    pub id: Option<i64>,
90    #[serde(default)]
91    pub value: Option<String>,
92    #[serde(default)]
93    pub color: Option<String>,
94}
95
96/// The colours GitFox accepts, with the RGB each one is drawn as — used to
97/// map a hex colour from a GitHub-style command onto the nearest name.
98pub const LABEL_COLORS: [(&str, [u8; 3]); 13] = [
99    ("blue", [0x3b, 0x82, 0xf6]),
100    ("brown", [0x92, 0x40, 0x0e]),
101    ("cyan", [0x06, 0xb6, 0xd4]),
102    ("green", [0x22, 0xc5, 0x5e]),
103    ("indigo", [0x63, 0x66, 0xf1]),
104    ("lime", [0x84, 0xcc, 0x16]),
105    ("mint", [0x34, 0xd3, 0x99]),
106    ("orange", [0xf9, 0x73, 0x16]),
107    ("pink", [0xec, 0x48, 0x99]),
108    ("purple", [0xa8, 0x55, 0xf7]),
109    ("red", [0xef, 0x44, 0x44]),
110    ("violet", [0x8b, 0x5c, 0xf6]),
111    ("yellow", [0xea, 0xb3, 0x08]),
112];
113
114/// A colour name GitFox accepts, from either a name or a hex triplet.
115///
116/// A hex colour becomes the nearest palette entry, so a `d73a4a` copied from
117/// a GitHub label still lands on `red`. `None` when the input is neither.
118pub fn label_color(input: &str) -> Option<&'static str> {
119    let trimmed = input.trim().trim_start_matches('#').to_ascii_lowercase();
120    if let Some((name, _)) = LABEL_COLORS.iter().find(|(name, _)| *name == trimmed) {
121        return Some(name);
122    }
123    let rgb = parse_hex(&trimmed)?;
124    LABEL_COLORS
125        .iter()
126        .min_by_key(|(_, c)| {
127            c.iter()
128                .zip(rgb.iter())
129                .map(|(a, b)| (*a as i32 - *b as i32).pow(2))
130                .sum::<i32>()
131        })
132        .map(|(name, _)| *name)
133}
134
135/// The hex triplet a palette name is drawn as, without `#`.
136pub fn label_color_hex(name: &str) -> Option<String> {
137    LABEL_COLORS
138        .iter()
139        .find(|(n, _)| n.eq_ignore_ascii_case(name))
140        .map(|(_, [r, g, b])| format!("{r:02x}{g:02x}{b:02x}"))
141}
142
143fn parse_hex(hex: &str) -> Option<[u8; 3]> {
144    let expanded: String = match hex.len() {
145        3 => hex.chars().flat_map(|c| [c, c]).collect(),
146        6 => hex.to_string(),
147        _ => return None,
148    };
149    let byte = |i: usize| u8::from_str_radix(expanded.get(i..i + 2)?, 16).ok();
150    Some([byte(0)?, byte(2)?, byte(4)?])
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn a_palette_name_passes_through_and_hex_lands_on_the_nearest_name() {
159        assert_eq!(label_color("red"), Some("red"));
160        assert_eq!(label_color("  Blue "), Some("blue"));
161        // GitHub's default `bug` colour.
162        assert_eq!(label_color("d73a4a"), Some("red"));
163        assert_eq!(label_color("#0e8a16"), Some("green"));
164        // Shorthand hex is expanded before matching.
165        assert_eq!(label_color("f44"), Some("red"));
166        assert_eq!(label_color("nonsense"), None);
167        assert_eq!(label_color_hex("red").as_deref(), Some("ef4444"));
168    }
169}