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
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
//! Issue labels: listing, create/update/delete, and the
//! [`LabelsService::ensure`] find-or-create convenience.

use bon::Builder;
use futures::Stream;
use serde::{Deserialize, Serialize};

use crate::client::LinearClient;
use crate::error::{Error, LinearErrorType, Result};
use crate::filter::{IdComparator, IssueLabelFilter, StringComparator, TeamFilter};
use crate::ids::{LabelId, TeamId};
use crate::pagination::{Page, PageInfo, paginate};
use crate::types::{LabelRef, TeamRef, Undefinable, ensure_success};

/// Appends the label fragments to an operation. The `LabelRefFields` and
/// `TeamRefFields` texts are the canonical fragments from `src/types.rs`.
macro_rules! doc_with_label_fields {
    ($op:literal) => {
        concat!(
            $op,
            " fragment LabelFields on IssueLabel { id name color description isGroup \
             parent { ...LabelRefFields } team { ...TeamRefFields } }",
            " fragment LabelRefFields on IssueLabel { id name color }",
            " fragment TeamRefFields on Team { id key name }"
        )
    };
}

const LABEL_LIST: &str = doc_with_label_fields!(
    "query LabelList($filter: IssueLabelFilter, $first: Int, $after: String) { \
     issueLabels(filter: $filter, first: $first, after: $after) { \
     nodes { ...LabelFields } \
     pageInfo { hasNextPage hasPreviousPage startCursor endCursor } } }"
);

const LABEL_CREATE: &str = doc_with_label_fields!(
    "mutation LabelCreate($input: IssueLabelCreateInput!) { \
     issueLabelCreate(input: $input) { success issueLabel { ...LabelFields } } }"
);

const LABEL_UPDATE: &str = doc_with_label_fields!(
    "mutation LabelUpdate($id: String!, $input: IssueLabelUpdateInput!) { \
     issueLabelUpdate(id: $id, input: $input) { success issueLabel { ...LabelFields } } }"
);

const LABEL_DELETE: &str =
    "mutation LabelDelete($id: String!) { issueLabelDelete(id: $id) { success } }";

pub(crate) const DOCUMENTS: &[(&str, &str)] = &[
    ("LabelList", LABEL_LIST),
    ("LabelCreate", LABEL_CREATE),
    ("LabelUpdate", LABEL_UPDATE),
    ("LabelDelete", LABEL_DELETE),
];

/// An issue label.
///
/// `team == None` means the label is a **workspace-level** label, available
/// to every team; otherwise it is scoped to the given team.
///
/// Wire fragment:
/// `fragment LabelFields on IssueLabel { id name color description isGroup
/// parent { ...LabelRefFields } team { ...TeamRefFields } }`
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Label {
    /// Label ID.
    pub id: LabelId,
    /// Label name.
    pub name: String,
    /// Label color as a hex string, e.g. `"#BB87FC"`.
    pub color: String,
    /// Optional description.
    pub description: Option<String>,
    /// Whether the label is a group (a container for child labels).
    pub is_group: bool,
    /// The group this label belongs to, when nested.
    pub parent: Option<LabelRef>,
    /// The owning team; `None` for workspace-level labels.
    pub team: Option<TeamRef>,
}

/// Variables for [`LabelsService::list`].
///
/// # Example
///
/// ```no_run
/// # async fn run() -> linear_api::Result<()> {
/// use linear_api::labels::ListLabelsRequest;
///
/// let client = linear_api::LinearClient::from_env()?;
/// let page = client
///     .labels()
///     .list(ListLabelsRequest::builder().first(10).build())
///     .await?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, Default, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ListLabelsRequest {
    /// Filter the returned labels.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<IssueLabelFilter>,
    /// Page size (server default 50). Page size multiplies query complexity;
    /// prefer modest values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first: Option<i32>,
    /// Cursor to paginate forward from (a previous page's `end_cursor`).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub after: Option<String>,
}

/// Input for [`LabelsService::create`] (`IssueLabelCreateInput`).
///
/// # Example
///
/// ```no_run
/// # async fn run() -> linear_api::Result<()> {
/// use linear_api::TeamId;
/// use linear_api::labels::LabelCreateInput;
///
/// let client = linear_api::LinearClient::from_env()?;
/// let label = client
///     .labels()
///     .create(
///         LabelCreateInput::builder()
///             .name("bug")
///             .color("#BB87FC")
///             .team_id(TeamId::new("9c2c88a6-99d3-4a63-a201-8ee5c7dcc374"))
///             .build(),
///     )
///     .await?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LabelCreateInput {
    /// Label name (required).
    #[builder(into)]
    pub name: String,
    /// Label color as a hex string like `"#BB87FC"`. Server-assigned when
    /// omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub color: Option<String>,
    /// Optional description.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub description: Option<String>,
    /// Owning team. `None` creates a **workspace-level** label.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub team_id: Option<TeamId>,
    /// Parent group to nest the label under.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub parent_id: Option<LabelId>,
    /// Whether the label is a group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_group: Option<bool>,
}

/// Input for [`LabelsService::update`] (`IssueLabelUpdateInput`).
///
/// `description` and `parent_id` are clearable: [`Undefinable::Undefined`]
/// (the default) leaves the field unchanged, [`Undefinable::Null`] clears it,
/// and a value sets it.
///
/// # Example
///
/// ```no_run
/// # async fn run() -> linear_api::Result<()> {
/// use linear_api::{LabelId, Undefinable};
/// use linear_api::labels::LabelUpdateInput;
///
/// let client = linear_api::LinearClient::from_env()?;
/// let label = client
///     .labels()
///     .update(
///         &LabelId::new("3d5a8ea4-9e4b-4caf-8d6f-1d914a518790"),
///         LabelUpdateInput::builder()
///             .name("triage")
///             .description(Undefinable::Null) // clear the description
///             .build(),
///     )
///     .await?;
/// # Ok(()) }
/// ```
#[derive(Debug, Clone, Default, Serialize, Builder)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct LabelUpdateInput {
    /// New label name.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub name: Option<String>,
    /// New color as a hex string like `"#BB87FC"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[builder(into)]
    pub color: Option<String>,
    /// Description: set, clear (`Null`), or leave unchanged (`Undefined`).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub description: Undefinable<String>,
    /// Parent group: set, clear (`Null`), or leave unchanged (`Undefined`).
    #[serde(skip_serializing_if = "Undefinable::is_undefined", default)]
    #[builder(default, into)]
    pub parent_id: Undefinable<LabelId>,
}

/// The `IssueLabelPayload` shape shared by the create and update mutations.
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct LabelPayload {
    success: bool,
    issue_label: Option<Label>,
}

fn unwrap_payload(operation: &'static str, payload: LabelPayload) -> Result<Label> {
    ensure_success(operation, payload.success)?;
    payload.issue_label.ok_or(Error::MissingData { operation })
}

/// `true` for the create-failure shapes a concurrent duplicate produces: an
/// [`Error::Api`] mentioning a duplicate or typed `InvalidInput`.
fn create_conflict(err: &Error) -> bool {
    let Error::Api { errors, .. } = err else {
        return false;
    };
    errors
        .iter()
        .any(|e| e.message.to_ascii_lowercase().contains("duplicate"))
        || err.error_types().contains(&LinearErrorType::InvalidInput)
}

/// Issue label operations. Obtain via [`LinearClient::labels`].
#[derive(Clone, Copy)]
pub struct LabelsService<'a> {
    client: &'a LinearClient,
}

impl LinearClient {
    /// Issue label operations: listing, CRUD, and
    /// [find-or-create](LabelsService::ensure).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// let client = linear_api::LinearClient::from_env()?;
    /// let labels = client.labels().list(Default::default()).await?;
    /// # Ok(()) }
    /// ```
    pub fn labels(&self) -> LabelsService<'_> {
        LabelsService { client: self }
    }
}

impl<'a> LabelsService<'a> {
    /// Fetches one page of issue labels (`issueLabels`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use linear_api::labels::ListLabelsRequest;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let page = client
    ///     .labels()
    ///     .list(ListLabelsRequest::builder().first(25).build())
    ///     .await?;
    /// for label in &page.nodes {
    ///     println!("{} ({})", label.name, label.color);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn list(&self, req: ListLabelsRequest) -> Result<Page<Label>> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_labels: Connection,
        }
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Connection {
            nodes: Vec<Label>,
            page_info: PageInfo,
        }
        let data: Data = self.client.query("LabelList", LABEL_LIST, req).await?;
        Ok(Page {
            nodes: data.issue_labels.nodes,
            page_info: data.issue_labels.page_info,
        })
    }

    /// Lazily streams every label matching the request across pages,
    /// starting from `req.after` when set (see [`paginate`] for the
    /// complexity note).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use futures::TryStreamExt;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let labels = client.labels();
    /// let mut stream = labels.list_stream(Default::default());
    /// futures::pin_mut!(stream);
    /// while let Some(label) = stream.try_next().await? {
    ///     println!("{}", label.name);
    /// }
    /// # Ok(()) }
    /// ```
    pub fn list_stream(&self, req: ListLabelsRequest) -> impl Stream<Item = Result<Label>> + 'a {
        let service = *self;
        paginate(move |cursor| {
            let mut req = req.clone();
            // The first call keeps a caller-seeded `req.after`; later calls
            // advance to each page's end cursor.
            if cursor.is_some() {
                req.after = cursor;
            }
            async move { service.list(req).await }
        })
    }

    /// Creates a label (`issueLabelCreate`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use linear_api::labels::LabelCreateInput;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// // No `team_id`: a workspace-level label.
    /// let label = client
    ///     .labels()
    ///     .create(LabelCreateInput::builder().name("infra").build())
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn create(&self, input: LabelCreateInput) -> Result<Label> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_label_create: LabelPayload,
        }
        let data: Data = self
            .client
            .mutation(
                "LabelCreate",
                LABEL_CREATE,
                serde_json::json!({ "input": input }),
            )
            .await?;
        unwrap_payload("LabelCreate", data.issue_label_create)
    }

    /// Updates a label (`issueLabelUpdate`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use linear_api::{LabelId, Undefinable};
    /// use linear_api::labels::LabelUpdateInput;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let label = client
    ///     .labels()
    ///     .update(
    ///         &LabelId::new("3d5a8ea4-9e4b-4caf-8d6f-1d914a518790"),
    ///         LabelUpdateInput::builder().color("#26B5CE").build(),
    ///     )
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn update(&self, id: &LabelId, input: LabelUpdateInput) -> Result<Label> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_label_update: LabelPayload,
        }
        let data: Data = self
            .client
            .mutation(
                "LabelUpdate",
                LABEL_UPDATE,
                serde_json::json!({ "id": id, "input": input }),
            )
            .await?;
        unwrap_payload("LabelUpdate", data.issue_label_update)
    }

    /// Deletes a label (`issueLabelDelete`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use linear_api::LabelId;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// client
    ///     .labels()
    ///     .delete(&LabelId::new("3d5a8ea4-9e4b-4caf-8d6f-1d914a518790"))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub async fn delete(&self, id: &LabelId) -> Result<()> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Data {
            issue_label_delete: Payload,
        }
        #[derive(Deserialize)]
        struct Payload {
            success: bool,
        }
        let data: Data = self
            .client
            .mutation("LabelDelete", LABEL_DELETE, serde_json::json!({ "id": id }))
            .await?;
        ensure_success("LabelDelete", data.issue_label_delete.success)
    }

    /// Finds a label by name (case-insensitive) or creates it — the
    /// find-or-create primitive behind "labels found or created on the team"
    /// in plan-apply flows.
    ///
    /// With `team == Some(_)` the lookup is scoped to that team and a created
    /// label is team-scoped. With `team == None` the lookup is
    /// workspace-wide: a workspace-level match (label with no team) is
    /// preferred, any exact-name match is accepted otherwise, and a created
    /// label is workspace-level.
    ///
    /// # Race tolerance
    ///
    /// Linear has no idempotency keys, so two concurrent `ensure` calls can
    /// both miss the lookup and race the create. When the create fails with
    /// a duplicate-name/`InvalidInput` API error, the lookup is re-run once
    /// and the winner's label is returned; if that re-lookup still finds
    /// nothing, the original create error is surfaced.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn run() -> linear_api::Result<()> {
    /// use linear_api::TeamId;
    ///
    /// let client = linear_api::LinearClient::from_env()?;
    /// let team = TeamId::new("9c2c88a6-99d3-4a63-a201-8ee5c7dcc374");
    /// let label = client.labels().ensure(Some(&team), "bug").await?;
    /// # Ok(()) }
    /// ```
    pub async fn ensure(&self, team: Option<&TeamId>, name: &str) -> Result<Label> {
        if let Some(label) = self.find_by_name(team, name).await? {
            return Ok(label);
        }
        let input = LabelCreateInput {
            name: name.to_owned(),
            color: None,
            description: None,
            team_id: team.cloned(),
            parent_id: None,
            is_group: None,
        };
        match self.create(input).await {
            Ok(label) => Ok(label),
            Err(err) if create_conflict(&err) => match self.find_by_name(team, name).await? {
                Some(label) => Ok(label),
                None => Err(err),
            },
            Err(err) => Err(err),
        }
    }

    /// Looks up a label by exact name, case-insensitively. Scoped to `team`
    /// when given; workspace-wide otherwise, preferring a workspace-level
    /// (team-less) match over team-scoped ones.
    async fn find_by_name(&self, team: Option<&TeamId>, name: &str) -> Result<Option<Label>> {
        let filter = IssueLabelFilter {
            name: Some(StringComparator {
                eq_ignore_case: Some(name.to_owned()),
                ..Default::default()
            }),
            team: team.map(|team| TeamFilter {
                id: Some(IdComparator {
                    eq: Some(team.to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        let page = self
            .list(ListLabelsRequest {
                filter: Some(filter),
                first: None,
                after: None,
            })
            .await?;
        let mut team_scoped_match = None;
        for label in page.nodes {
            // The server filter is already exact-and-case-insensitive; this
            // guard keeps the invariant even if the filter loosens.
            if !label.name.eq_ignore_ascii_case(name) {
                continue;
            }
            if team.is_some() || label.team.is_none() {
                return Ok(Some(label));
            }
            if team_scoped_match.is_none() {
                team_scoped_match = Some(label);
            }
        }
        Ok(team_scoped_match)
    }
}