linear-api 0.1.0

Unofficial async Rust client for the Linear GraphQL API (API-key auth)
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
//! Shared scalar types, server enums, three-state input support
//! ([`Undefinable`]), and the canonical Ref/Stub structs used across modules.

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::ids::{
    IssueId, LabelId, ProjectId, ProjectMilestoneId, TeamId, UserId, WorkflowStateId,
};

const TIMELESS_DATE_FORMAT: &[time::format_description::BorrowedFormatItem<'static>] =
    time::macros::format_description!("[year]-[month]-[day]");

/// Linear's `TimelessDate` scalar: a calendar date with no time component,
/// serialized as `"YYYY-MM-DD"`.
///
/// A newtype (rather than a serde `with` module) so it composes inside
/// `Option<_>`, [`Undefinable<_>`], and `Vec<_>` without field attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimelessDate(pub time::Date);

impl std::fmt::Display for TimelessDate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let formatted = self
            .0
            .format(TIMELESS_DATE_FORMAT)
            .map_err(|_| std::fmt::Error)?;
        f.write_str(&formatted)
    }
}

impl std::str::FromStr for TimelessDate {
    type Err = time::error::Parse;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        time::Date::parse(s, TIMELESS_DATE_FORMAT).map(Self)
    }
}

impl From<time::Date> for TimelessDate {
    fn from(date: time::Date) -> Self {
        Self(date)
    }
}

impl Serialize for TimelessDate {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for TimelessDate {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

/// GraphQL nullable-input tri-state: absent (leave unchanged) / `null`
/// (clear) / value (set).
///
/// Input convention across this crate: **create inputs** use `Option<T>` with
/// `#[serde(skip_serializing_if = "Option::is_none")]` (absent-when-`None`);
/// **update inputs** use `Undefinable<T>` for clearable fields, with
/// `#[serde(skip_serializing_if = "Undefinable::is_undefined", default)]` and
/// `#[builder(default, into)]`.
#[derive(Debug, Clone, Default, PartialEq)]
pub enum Undefinable<T> {
    /// Field is omitted from the request: leave unchanged.
    #[default]
    Undefined,
    /// Field is sent as `null`: clear the value.
    Null,
    /// Field is sent with a concrete value: set it.
    Value(T),
}

impl<T> Undefinable<T> {
    /// `true` when the field should be omitted from serialization entirely.
    pub fn is_undefined(&self) -> bool {
        matches!(self, Undefinable::Undefined)
    }
}

impl<T> From<T> for Undefinable<T> {
    fn from(value: T) -> Self {
        Undefinable::Value(value)
    }
}

impl<T: Serialize> Serialize for Undefinable<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            // `Undefined` is never reached when fields carry
            // `#[serde(skip_serializing_if = "Undefinable::is_undefined")]`;
            // serializing it as `null` is the safe fallback.
            Undefinable::Undefined | Undefinable::Null => serializer.serialize_none(),
            Undefinable::Value(value) => value.serialize(serializer),
        }
    }
}

/// Issue priority. On the wire this is an integer `0..=4`:
/// 0 = no priority, 1 = urgent, 2 = high, 3 = medium, 4 = low.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "u8", into = "u8")]
#[non_exhaustive]
pub enum Priority {
    /// No priority set (0).
    None,
    /// Urgent (1).
    Urgent,
    /// High (2).
    High,
    /// Medium (3).
    Medium,
    /// Low (4).
    Low,
    /// A numeric value outside `0..=4` (future-proofing).
    Other(u8),
}

impl From<u8> for Priority {
    fn from(value: u8) -> Self {
        match value {
            0 => Priority::None,
            1 => Priority::Urgent,
            2 => Priority::High,
            3 => Priority::Medium,
            4 => Priority::Low,
            other => Priority::Other(other),
        }
    }
}

impl From<Priority> for u8 {
    fn from(value: Priority) -> Self {
        match value {
            Priority::None => 0,
            Priority::Urgent => 1,
            Priority::High => 2,
            Priority::Medium => 3,
            Priority::Low => 4,
            Priority::Other(other) => other,
        }
    }
}

/// Sort order for paginated list queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum PaginationOrderBy {
    /// Order by creation time (`"createdAt"`).
    CreatedAt,
    /// Order by last update time (`"updatedAt"`).
    UpdatedAt,
}

macro_rules! string_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $($(#[$vmeta:meta])* $variant:ident => $wire:literal,)+
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
        #[serde(from = "String", into = "String")]
        #[non_exhaustive]
        pub enum $name {
            $($(#[$vmeta])* $variant,)+
            /// A wire value this crate does not know about (server-added
            /// variants deserialize here instead of failing).
            Unrecognized(String),
        }

        impl From<String> for $name {
            fn from(s: String) -> Self {
                match s.as_str() {
                    $($wire => Self::$variant,)+
                    _ => Self::Unrecognized(s),
                }
            }
        }

        impl From<$name> for String {
            fn from(v: $name) -> String {
                match v {
                    $($name::$variant => $wire.to_string(),)+
                    $name::Unrecognized(s) => s,
                }
            }
        }
    };
}

string_enum! {
    /// The kind of a workflow state (column category on a Linear board).
    WorkflowStateType {
        /// Triage inbox.
        Triage => "triage",
        /// Backlog.
        Backlog => "backlog",
        /// Not started yet.
        Unstarted => "unstarted",
        /// In progress.
        Started => "started",
        /// Done.
        Completed => "completed",
        /// Canceled.
        Canceled => "canceled",
    }
}

string_enum! {
    /// The kind of an issue relation.
    ///
    /// There is **no** `blockedBy` value — direction is positional:
    /// `issueId` *blocks* `relatedIssueId` in `issueRelationCreate`.
    IssueRelationType {
        /// The issue blocks the related issue.
        Blocks => "blocks",
        /// The issue duplicates the related issue.
        Duplicate => "duplicate",
        /// The issues are related.
        Related => "related",
        /// The issues are similar.
        Similar => "similar",
    }
}

string_enum! {
    /// The kind of a project status.
    ProjectStatusType {
        /// Backlog.
        Backlog => "backlog",
        /// Planned.
        Planned => "planned",
        /// In progress.
        Started => "started",
        /// Paused.
        Paused => "paused",
        /// Done.
        Completed => "completed",
        /// Canceled.
        Canceled => "canceled",
    }
}

string_enum! {
    /// Project health as reported in project updates.
    ProjectHealth {
        /// On track (`"onTrack"`).
        OnTrack => "onTrack",
        /// At risk (`"atRisk"`).
        AtRisk => "atRisk",
        /// Off track (`"offTrack"`).
        OffTrack => "offTrack",
    }
}

/// Minimal reference to a user.
///
/// Canonical fragment:
/// `fragment UserRefFields on User { id name displayName }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UserRef {
    /// User ID.
    pub id: UserId,
    /// Full name.
    pub name: String,
    /// Display (handle) name.
    pub display_name: String,
}

/// Minimal reference to a team.
///
/// Canonical fragment:
/// `fragment TeamRefFields on Team { id key name }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct TeamRef {
    /// Team ID.
    pub id: TeamId,
    /// Team key, e.g. `"ENG"`.
    pub key: String,
    /// Team name.
    pub name: String,
}

/// Minimal reference to a project.
///
/// Canonical fragment:
/// `fragment ProjectRefFields on Project { id name }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProjectRef {
    /// Project ID.
    pub id: ProjectId,
    /// Project name.
    pub name: String,
}

/// Minimal reference to an issue.
///
/// Canonical fragment:
/// `fragment IssueStubFields on Issue { id identifier title }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct IssueStub {
    /// Issue ID.
    pub id: IssueId,
    /// Human identifier, e.g. `"ENG-123"`.
    pub identifier: String,
    /// Issue title.
    pub title: String,
}

/// Minimal reference to an issue label.
///
/// Canonical fragment:
/// `fragment LabelRefFields on IssueLabel { id name color }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LabelRef {
    /// Label ID.
    pub id: LabelId,
    /// Label name.
    pub name: String,
    /// Label color as a hex string.
    pub color: String,
}

/// Minimal reference to a workflow state.
///
/// Canonical fragment:
/// `fragment StateRefFields on WorkflowState { id name type color }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct StateRef {
    /// Workflow state ID.
    pub id: WorkflowStateId,
    /// State name, e.g. `"In Progress"`.
    pub name: String,
    /// State category.
    #[serde(rename = "type")]
    pub state_type: WorkflowStateType,
    /// State color as a hex string.
    pub color: String,
}

/// Minimal reference to a project milestone.
///
/// Canonical fragment:
/// `fragment MilestoneRefFields on ProjectMilestone { id name }`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct MilestoneRef {
    /// Milestone ID.
    pub id: ProjectMilestoneId,
    /// Milestone name.
    pub name: String,
}

/// Deserializes a GraphQL connection object `{"nodes": [...]}` directly into
/// a `Vec<T>`.
///
/// Use as `#[serde(deserialize_with = "crate::types::nodes")]` on embedded
/// connection fields such as an issue's `labels`.
pub fn nodes<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    #[derive(Deserialize)]
    struct Nodes<T> {
        nodes: Vec<T>,
    }
    Ok(Nodes::deserialize(deserializer)?.nodes)
}

/// Maps a mutation payload's `success: false` (with no GraphQL errors) to
/// [`Error::MutationFailed`](crate::Error::MutationFailed).
pub(crate) fn ensure_success(operation: &'static str, success: bool) -> crate::Result<()> {
    if success {
        Ok(())
    } else {
        Err(crate::Error::MutationFailed { operation })
    }
}

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

    #[test]
    fn timeless_date_roundtrip() {
        let date: TimelessDate = "2026-07-05".parse().unwrap();
        assert_eq!(date.to_string(), "2026-07-05");
        assert_eq!(serde_json::to_string(&date).unwrap(), "\"2026-07-05\"");
        let back: TimelessDate = serde_json::from_str("\"2026-07-05\"").unwrap();
        assert_eq!(back, date);
        assert!("not-a-date".parse::<TimelessDate>().is_err());
    }

    #[test]
    fn undefinable_serializes_null_and_value() {
        #[derive(Serialize)]
        struct Input {
            #[serde(skip_serializing_if = "Undefinable::is_undefined")]
            a: Undefinable<u32>,
            #[serde(skip_serializing_if = "Undefinable::is_undefined")]
            b: Undefinable<u32>,
            #[serde(skip_serializing_if = "Undefinable::is_undefined")]
            c: Undefinable<u32>,
        }
        let value = serde_json::to_value(Input {
            a: Undefinable::Undefined,
            b: Undefinable::Null,
            c: Undefinable::Value(7),
        })
        .unwrap();
        assert_eq!(value, serde_json::json!({ "b": null, "c": 7 }));
    }

    #[test]
    fn priority_maps_ints_both_ways() {
        assert_eq!(
            serde_json::from_str::<Priority>("1").unwrap(),
            Priority::Urgent
        );
        assert_eq!(serde_json::to_string(&Priority::Low).unwrap(), "4");
        assert_eq!(
            serde_json::from_str::<Priority>("9").unwrap(),
            Priority::Other(9)
        );
    }

    #[test]
    fn string_enums_keep_unrecognized_values() {
        let state: WorkflowStateType = serde_json::from_str("\"started\"").unwrap();
        assert_eq!(state, WorkflowStateType::Started);
        let novel: WorkflowStateType = serde_json::from_str("\"paused\"").unwrap();
        assert_eq!(novel, WorkflowStateType::Unrecognized("paused".into()));
        assert_eq!(
            serde_json::to_string(&ProjectHealth::OnTrack).unwrap(),
            "\"onTrack\""
        );
    }

    #[test]
    fn nodes_unwraps_connections() {
        #[derive(Deserialize)]
        struct Holder {
            #[serde(deserialize_with = "crate::types::nodes")]
            labels: Vec<String>,
        }
        let holder: Holder =
            serde_json::from_value(serde_json::json!({ "labels": { "nodes": ["a", "b"] } }))
                .unwrap();
        assert_eq!(holder.labels, vec!["a", "b"]);
    }

    #[test]
    fn ensure_success_maps_false() {
        assert!(ensure_success("Test", true).is_ok());
        assert!(matches!(
            ensure_success("Test", false),
            Err(crate::Error::MutationFailed { operation: "Test" })
        ));
    }
}