xbp 10.38.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
//! Linear metadata lookups (teams, states, labels, users).

use crate::commands::linear::{linear_graphql_errors, linear_graphql_request};
use serde::Deserialize;
use serde_json::{json, Value as JsonValue};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinearTeam {
    pub id: String,
    pub key: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinearWorkflowState {
    pub id: String,
    pub name: String,
    pub state_type: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinearLabel {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinearUser {
    pub id: String,
    pub name: String,
    pub email: Option<String>,
    pub display_name: Option<String>,
}

#[derive(Debug, Deserialize)]
struct TeamsPage {
    nodes: Vec<TeamNode>,
    #[serde(rename = "pageInfo")]
    page_info: PageInfo,
}

#[derive(Debug, Deserialize)]
struct TeamNode {
    id: String,
    key: String,
    name: String,
}

#[derive(Debug, Deserialize)]
struct PageInfo {
    #[serde(rename = "hasNextPage")]
    has_next_page: bool,
    #[serde(rename = "endCursor")]
    end_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
struct StatesPage {
    nodes: Vec<StateNode>,
}

#[derive(Debug, Deserialize)]
struct StateNode {
    id: String,
    name: String,
    #[serde(rename = "type")]
    state_type: String,
}

#[derive(Debug, Deserialize)]
struct LabelsPage {
    nodes: Vec<LabelNode>,
    #[serde(rename = "pageInfo")]
    page_info: PageInfo,
}

#[derive(Debug, Deserialize)]
struct LabelNode {
    id: String,
    name: String,
}

#[derive(Debug, Deserialize)]
struct UsersPage {
    nodes: Vec<UserNode>,
    #[serde(rename = "pageInfo")]
    page_info: PageInfo,
}

#[derive(Debug, Deserialize)]
struct UserNode {
    id: String,
    name: String,
    #[serde(default)]
    email: Option<String>,
    #[serde(default, rename = "displayName")]
    display_name: Option<String>,
}

pub async fn list_teams(api_key: &str) -> Result<Vec<LinearTeam>, String> {
    let mut teams = Vec::new();
    let mut after: Option<String> = None;
    loop {
        let body = linear_graphql_request(
            api_key,
            &json!({
                "query": r#"
                    query XbpLinearTeams($after: String) {
                      teams(first: 50, after: $after, includeArchived: false) {
                        nodes { id key name }
                        pageInfo { hasNextPage endCursor }
                      }
                    }
                "#,
                "variables": { "after": after }
            }),
        )
        .await?;
        let page: TeamsPage = extract_data(body, "teams")?;
        teams.extend(page.nodes.into_iter().map(|n| LinearTeam {
            id: n.id,
            key: n.key,
            name: n.name,
        }));
        if !page.page_info.has_next_page {
            break;
        }
        after = page.page_info.end_cursor;
        if after.is_none() {
            break;
        }
    }
    Ok(teams)
}

pub async fn resolve_team_id(api_key: &str, team: &str) -> Result<String, String> {
    let team = team.trim();
    if team.is_empty() {
        return Err("Team is required.".into());
    }
    // UUID-looking values are used as-is.
    if team.len() >= 32 && team.contains('-') {
        return Ok(team.to_string());
    }
    let teams = list_teams(api_key).await?;
    let lower = team.to_ascii_lowercase();
    if let Some(found) = teams.iter().find(|t| {
        t.id == team
            || t.key.eq_ignore_ascii_case(team)
            || t.name.eq_ignore_ascii_case(team)
            || t.key.to_ascii_lowercase() == lower
            || t.name.to_ascii_lowercase() == lower
    }) {
        return Ok(found.id.clone());
    }
    Err(format!(
        "No Linear team matching `{team}`. Use a team key, name, or id."
    ))
}

pub async fn list_workflow_states(
    api_key: &str,
    team_id: &str,
) -> Result<Vec<LinearWorkflowState>, String> {
    let body = linear_graphql_request(
        api_key,
        &json!({
            "query": r#"
                query XbpLinearStates($teamId: String!) {
                  team(id: $teamId) {
                    states {
                      nodes { id name type }
                    }
                  }
                }
            "#,
            "variables": { "teamId": team_id }
        }),
    )
    .await?;
    linear_graphql_errors(&body)?;
    let states = body
        .get("data")
        .and_then(|d| d.get("team"))
        .and_then(|t| t.get("states"))
        .cloned()
        .ok_or_else(|| "Linear team states query returned no data.".to_string())?;
    let page: StatesPage = serde_json::from_value(states)
        .map_err(|e| format!("Failed to decode Linear states: {e}"))?;
    Ok(page
        .nodes
        .into_iter()
        .map(|n| LinearWorkflowState {
            id: n.id,
            name: n.name,
            state_type: n.state_type,
        })
        .collect())
}

pub async fn resolve_state_id(
    api_key: &str,
    team_id: &str,
    state: &str,
) -> Result<String, String> {
    let state = state.trim();
    if state.is_empty() {
        return Err("State is required.".into());
    }
    if state.len() >= 32 && state.contains('-') {
        return Ok(state.to_string());
    }
    let states = list_workflow_states(api_key, team_id).await?;
    let lower = state.to_ascii_lowercase();
    if let Some(found) = states.iter().find(|s| {
        s.id == state
            || s.name.eq_ignore_ascii_case(state)
            || s.state_type.eq_ignore_ascii_case(state)
            || s.name.to_ascii_lowercase() == lower
    }) {
        return Ok(found.id.clone());
    }
    Err(format!(
        "No workflow state matching `{state}` on this team."
    ))
}

pub async fn list_labels(api_key: &str, team_id: Option<&str>) -> Result<Vec<LinearLabel>, String> {
    let mut labels = Vec::new();
    let mut after: Option<String> = None;
    loop {
        let body = if let Some(team_id) = team_id {
            linear_graphql_request(
                api_key,
                &json!({
                    "query": r#"
                        query XbpLinearTeamLabels($teamId: String!, $after: String) {
                          team(id: $teamId) {
                            labels(first: 50, after: $after) {
                              nodes { id name }
                              pageInfo { hasNextPage endCursor }
                            }
                          }
                        }
                    "#,
                    "variables": { "teamId": team_id, "after": after }
                }),
            )
            .await?
        } else {
            linear_graphql_request(
                api_key,
                &json!({
                    "query": r#"
                        query XbpLinearLabels($after: String) {
                          issueLabels(first: 50, after: $after) {
                            nodes { id name }
                            pageInfo { hasNextPage endCursor }
                          }
                        }
                    "#,
                    "variables": { "after": after }
                }),
            )
            .await?
        };

        linear_graphql_errors(&body)?;
        let page_value = if team_id.is_some() {
            body.get("data")
                .and_then(|d| d.get("team"))
                .and_then(|t| t.get("labels"))
                .cloned()
        } else {
            body.get("data")
                .and_then(|d| d.get("issueLabels"))
                .cloned()
        }
        .ok_or_else(|| "Linear labels query returned no data.".to_string())?;

        let page: LabelsPage = serde_json::from_value(page_value)
            .map_err(|e| format!("Failed to decode Linear labels: {e}"))?;
        labels.extend(page.nodes.into_iter().map(|n| LinearLabel {
            id: n.id,
            name: n.name,
        }));
        if !page.page_info.has_next_page {
            break;
        }
        after = page.page_info.end_cursor;
        if after.is_none() {
            break;
        }
    }
    Ok(labels)
}

pub async fn resolve_label_ids(
    api_key: &str,
    team_id: Option<&str>,
    labels: &[String],
) -> Result<Vec<String>, String> {
    if labels.is_empty() {
        return Ok(Vec::new());
    }
    let known = list_labels(api_key, team_id).await?;
    let mut ids = Vec::new();
    for label in labels {
        let label = label.trim();
        if label.is_empty() {
            continue;
        }
        if label.len() >= 32 && label.contains('-') {
            ids.push(label.to_string());
            continue;
        }
        if let Some(found) = known
            .iter()
            .find(|l| l.id == label || l.name.eq_ignore_ascii_case(label))
        {
            ids.push(found.id.clone());
        } else {
            return Err(format!("No Linear label matching `{label}`."));
        }
    }
    Ok(ids)
}

/// Resolve label ids, creating missing labels on the team when possible.
pub async fn ensure_label_ids(
    api_key: &str,
    team_id: Option<&str>,
    labels: &[String],
) -> Result<Vec<String>, String> {
    if labels.is_empty() {
        return Ok(Vec::new());
    }
    let mut known = list_labels(api_key, team_id).await?;
    let mut ids = Vec::new();
    for label in labels {
        let label = label.trim();
        if label.is_empty() {
            continue;
        }
        if label.len() >= 32 && label.contains('-') {
            ids.push(label.to_string());
            continue;
        }
        if let Some(found) = known
            .iter()
            .find(|l| l.id == label || l.name.eq_ignore_ascii_case(label))
        {
            ids.push(found.id.clone());
            continue;
        }
        // Create when we have a team context.
        if let Some(team_id) = team_id {
            match create_issue_label(api_key, team_id, label).await {
                Ok(created) => {
                    known.push(created.clone());
                    ids.push(created.id);
                }
                Err(err) => {
                    // Soft-fail: skip unknown labels rather than aborting the whole sync.
                    eprintln!(
                        "warning: could not create Linear label `{label}`: {err}"
                    );
                }
            }
        } else {
            eprintln!("warning: Linear label `{label}` not found and no team to create it on");
        }
    }
    Ok(ids)
}

async fn create_issue_label(
    api_key: &str,
    team_id: &str,
    name: &str,
) -> Result<LinearLabel, String> {
    let body = linear_graphql_request(
        api_key,
        &json!({
            "query": r#"
                mutation XbpLinearLabelCreate($input: IssueLabelCreateInput!) {
                  issueLabelCreate(input: $input) {
                    success
                    issueLabel { id name }
                  }
                }
            "#,
            "variables": {
                "input": {
                    "name": name,
                    "teamId": team_id
                }
            }
        }),
    )
    .await?;
    linear_graphql_errors(&body)?;
    let label = body
        .get("data")
        .and_then(|d| d.get("issueLabelCreate"))
        .and_then(|c| c.get("issueLabel"))
        .cloned()
        .ok_or_else(|| "Linear issueLabelCreate returned no label.".to_string())?;
    let id = label
        .get("id")
        .and_then(JsonValue::as_str)
        .ok_or_else(|| "Linear label missing id.".to_string())?
        .to_string();
    let name = label
        .get("name")
        .and_then(JsonValue::as_str)
        .unwrap_or(name)
        .to_string();
    Ok(LinearLabel { id, name })
}

/// Prefer configured team, else the only accessible team, else error.
pub async fn resolve_team_id_auto(
    api_key: &str,
    preferred: Option<&str>,
) -> Result<String, String> {
    if let Some(preferred) = preferred.map(str::trim).filter(|s| !s.is_empty()) {
        return resolve_team_id(api_key, preferred).await;
    }
    let teams = list_teams(api_key).await?;
    if teams.len() == 1 {
        return Ok(teams[0].id.clone());
    }
    if teams.is_empty() {
        return Err("No Linear teams available for this API key.".into());
    }
    Err(
        "Multiple Linear teams found. Pass `--team KEY` or set `linear.default_team_key` in `.xbp/xbp.yaml`."
            .into(),
    )
}

pub async fn list_users(api_key: &str) -> Result<Vec<LinearUser>, String> {
    let mut users = Vec::new();
    let mut after: Option<String> = None;
    loop {
        let body = linear_graphql_request(
            api_key,
            &json!({
                "query": r#"
                    query XbpLinearUsers($after: String) {
                      users(first: 50, after: $after, includeDisabled: false) {
                        nodes { id name email displayName }
                        pageInfo { hasNextPage endCursor }
                      }
                    }
                "#,
                "variables": { "after": after }
            }),
        )
        .await?;
        let page: UsersPage = extract_data(body, "users")?;
        users.extend(page.nodes.into_iter().map(|n| LinearUser {
            id: n.id,
            name: n.name,
            email: n.email,
            display_name: n.display_name,
        }));
        if !page.page_info.has_next_page {
            break;
        }
        after = page.page_info.end_cursor;
        if after.is_none() {
            break;
        }
    }
    Ok(users)
}

pub async fn resolve_assignee_id(api_key: &str, assignee: &str) -> Result<Option<String>, String> {
    let assignee = assignee.trim();
    if assignee.is_empty() || assignee.eq_ignore_ascii_case("none") {
        return Ok(None);
    }
    if assignee.eq_ignore_ascii_case("me") {
        return Ok(Some(viewer_id(api_key).await?));
    }
    if assignee.len() >= 32 && assignee.contains('-') {
        return Ok(Some(assignee.to_string()));
    }
    let users = list_users(api_key).await?;
    let lower = assignee.to_ascii_lowercase();
    if let Some(found) = users.iter().find(|u| {
        u.id == assignee
            || u.name.eq_ignore_ascii_case(assignee)
            || u.email
                .as_deref()
                .is_some_and(|e| e.eq_ignore_ascii_case(assignee))
            || u.display_name
                .as_deref()
                .is_some_and(|d| d.eq_ignore_ascii_case(assignee))
            || u.name.to_ascii_lowercase() == lower
    }) {
        return Ok(Some(found.id.clone()));
    }
    Err(format!("No Linear user matching `{assignee}`."))
}

async fn viewer_id(api_key: &str) -> Result<String, String> {
    let body = linear_graphql_request(
        api_key,
        &json!({
            "query": r#"query XbpLinearViewer { viewer { id } }"#
        }),
    )
    .await?;
    linear_graphql_errors(&body)?;
    body.get("data")
        .and_then(|d| d.get("viewer"))
        .and_then(|v| v.get("id"))
        .and_then(JsonValue::as_str)
        .map(str::to_string)
        .ok_or_else(|| "Linear viewer query returned no id.".to_string())
}

fn extract_data<T: for<'de> Deserialize<'de>>(body: JsonValue, field: &str) -> Result<T, String> {
    linear_graphql_errors(&body)?;
    let value = body
        .get("data")
        .and_then(|d| d.get(field))
        .cloned()
        .ok_or_else(|| format!("Linear query returned no `{field}` data."))?;
    serde_json::from_value(value).map_err(|e| format!("Failed to decode Linear `{field}`: {e}"))
}