gbd 1.8.3

The Beads agent workflow on GitHub Issues and Projects
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! GitHub Projects: the board. Status is where Beads `in_progress` and
//! `deferred` live when a project is configured. Everything goes through
//! `gh project …`, which needs the `project` scope (`gh auth refresh -s project`).

use anyhow::{anyhow, bail, Context, Result};
use serde_json::Value;
use std::collections::HashMap;

use crate::gh;
use crate::repo::Repo;

pub const STATUS_READY: &str = "Ready";
pub const STATUS_IN_PROGRESS: &str = "In Progress";
/// Maintained by gbd from GitHub's open-blocker count, never set by hand:
/// project views cannot filter on `is:blocked`, so the board carries it.
pub const STATUS_BLOCKED: &str = "Blocked";
pub const STATUS_DEFERRED: &str = "Deferred";
pub const STATUS_DONE: &str = "Done";

/// The five options `gbd init` puts on the Status field, in column order
/// (what needs attention first, then what is parked, then the work), with
/// colors. Board columns follow the field's option order.
pub const STATUSES: [(&str, &str); 5] = [
    (STATUS_BLOCKED, "RED"),
    (STATUS_DEFERRED, "GRAY"),
    (STATUS_READY, "GREEN"),
    (STATUS_IN_PROGRESS, "YELLOW"),
    (STATUS_DONE, "PURPLE"),
];

/// The default view `gbd init` shapes on a new board: named Board, board
/// layout (columns are the Status options), epics filtered out since they
/// are containers, not work.
pub const VIEW_NAME: &str = "Board";
pub const VIEW_FILTER: &str = "-type:Epic";
const VIEW_LAYOUT: &str = "BOARD_LAYOUT";
/// What a new project ships with, and the only view gbd will rewrite.
const STOCK_VIEW_NAME: &str = "View 1";
const STOCK_VIEW_LAYOUT: &str = "TABLE_LAYOUT";

/// What the board's views say about the one gbd shapes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ViewState {
    /// A view named Board, board layout, filtered to `-type:Epic`.
    Configured,
    /// Still GitHub's stock "View 1" table, untouched: safe to rewrite.
    /// Carries the view's node id.
    Untouched(String),
    /// Shaped by hand; gbd leaves it alone. Says what is there.
    Custom(String),
}

/// One project view, as much of it as the stock-or-not question needs.
struct View {
    id: String,
    name: String,
    layout: String,
    filter: String,
    /// Sorted or grouped by someone.
    shaped: bool,
}

pub const SCOPE_HINT: &str = "gh auth refresh -s project";

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

/// One row of `gh project item-list`. `number` is None for draft items.
#[derive(Debug, Clone, serde::Serialize)]
pub struct BoardItem {
    pub number: Option<u64>,
    pub title: String,
    pub repo: Option<String>,
    pub status: Option<String>,
}

#[derive(Debug, Clone)]
pub struct Board {
    pub owner: String,
    pub number: u64,
    /// Project node id (`PVT_…`).
    pub id: String,
    pub title: String,
    pub url: String,
    pub status_field_id: String,
    pub status_options: Vec<StatusOption>,
}

fn scope_error(err: anyhow::Error) -> anyhow::Error {
    let msg = format!("{err:#}");
    if msg.contains("scope") || msg.contains("read:project") {
        anyhow!("{msg}\nGitHub Projects need the `project` scope. Run: {SCOPE_HINT}")
    } else {
        err
    }
}

impl Board {
    /// Two `gh project` calls: the project itself and its fields.
    pub fn load(owner: &str, number: u64) -> Result<Board> {
        let n = number.to_string();
        let view: Value =
            gh::run_json(&["project", "view", &n, "--owner", owner, "--format", "json"])
                .map_err(scope_error)?;
        let fields: Value = gh::run_json(&[
            "project",
            "field-list",
            &n,
            "--owner",
            owner,
            "--format",
            "json",
            "--limit",
            "100",
        ])
        .map_err(scope_error)?;
        let status = fields
            .get("fields")
            .and_then(Value::as_array)
            .and_then(|arr| {
                arr.iter().find(|f| {
                    f.get("name")
                        .and_then(Value::as_str)
                        .is_some_and(|s| s.eq_ignore_ascii_case("Status"))
                })
            })
            .with_context(|| format!("project #{number} has no Status field"))?;
        let status_options = status
            .get("options")
            .and_then(Value::as_array)
            .map(|arr| {
                arr.iter()
                    .filter_map(|o| {
                        Some(StatusOption {
                            id: o.get("id")?.as_str()?.to_string(),
                            name: o.get("name")?.as_str()?.to_string(),
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        let s = |key: &str| {
            view.get(key)
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string()
        };
        Ok(Board {
            owner: owner.to_string(),
            number,
            id: s("id"),
            title: s("title"),
            url: s("url"),
            status_field_id: status
                .get("id")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            status_options,
        })
    }

    /// Every item on the board with its Status, closed issues included.
    /// Every item on the board with its Status, closed issues and drafts
    /// included. Paged to the end (`gh project item-list --limit` is a cap,
    /// not a pager, and a truncated list would make `board sync` overwrite
    /// Statuses it could not see).
    pub fn items(&self) -> Result<Vec<BoardItem>> {
        const QUERY: &str = r#"query($id: ID!, $cursor: String) {
  node(id: $id) { ... on ProjectV2 { items(first: 100, after: $cursor) {
    pageInfo { hasNextPage endCursor }
    nodes {
      fieldValueByName(name: "Status") { ... on ProjectV2ItemFieldSingleSelectValue { name } }
      content {
        __typename
        ... on Issue { number title repository { nameWithOwner } }
        ... on PullRequest { number title repository { nameWithOwner } }
        ... on DraftIssue { title }
      }
    }
  } } }
}"#;
        let mut all = Vec::new();
        let mut cursor: Option<String> = None;
        let mut previous: Option<String> = None;
        loop {
            let mut vars: Vec<(&str, &str)> = vec![("id", &self.id)];
            if let Some(c) = &cursor {
                vars.push(("cursor", c));
            }
            let data = gh::graphql(QUERY, &vars).map_err(scope_error)?;
            if let Some(errors) = data.get("errors") {
                bail!("listing items of project #{}: {errors}", self.number);
            }
            let conn = data
                .pointer("/data/node/items")
                .context("GraphQL response missing node.items")?;
            all.extend(
                conn.get("nodes")
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten()
                    .map(|it| BoardItem {
                        number: it.pointer("/content/number").and_then(Value::as_u64),
                        title: it
                            .pointer("/content/title")
                            .and_then(Value::as_str)
                            .unwrap_or("")
                            .to_string(),
                        repo: it
                            .pointer("/content/repository/nameWithOwner")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                        status: it
                            .pointer("/fieldValueByName/name")
                            .and_then(Value::as_str)
                            .map(str::to_string),
                    }),
            );
            let more = conn
                .pointer("/pageInfo/hasNextPage")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            cursor = if more {
                conn.pointer("/pageInfo/endCursor")
                    .and_then(Value::as_str)
                    .map(str::to_string)
            } else {
                None
            };
            if cursor.is_none() {
                return Ok(all);
            }
            if cursor == previous {
                bail!("pagination did not advance (cursor {cursor:?} repeated)");
            }
            previous.clone_from(&cursor);
        }
    }

    pub fn has_status(&self, name: &str) -> bool {
        self.status_options
            .iter()
            .any(|o| o.name.eq_ignore_ascii_case(name))
    }

    fn option_id(&self, status: &str) -> Result<&str> {
        self.status_options
            .iter()
            .find(|o| o.name.eq_ignore_ascii_case(status))
            .map(|o| o.id.as_str())
            .ok_or_else(|| {
                anyhow!(
                    "project #{} has no Status option {status:?} (has: {}). Run: gbd init",
                    self.number,
                    self.status_options
                        .iter()
                        .map(|o| o.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
    }

    /// Add the issue to the board if it is not there (idempotent on GitHub's
    /// side) and set its Status. Two `gh project` calls.
    pub fn set_status(&self, issue_url: &str, status: &str) -> Result<()> {
        let option_id = self.option_id(status)?;
        let n = self.number.to_string();
        let item: Value = gh::run_json(&[
            "project",
            "item-add",
            &n,
            "--owner",
            &self.owner,
            "--url",
            issue_url,
            "--format",
            "json",
        ])
        .map_err(scope_error)?;
        let item_id = item
            .get("id")
            .and_then(Value::as_str)
            .context("gh project item-add returned no item id")?;
        gh::run(&[
            "project",
            "item-edit",
            "--id",
            item_id,
            "--project-id",
            &self.id,
            "--field-id",
            &self.status_field_id,
            "--single-select-option-id",
            option_id,
        ])
        .map_err(scope_error)?;
        Ok(())
    }

    /// `option id → (color, description)` for Status. `gh project
    /// field-list` returns ids and names only.
    fn option_details(&self) -> Result<HashMap<String, (String, String)>> {
        const QUERY: &str = r"query($id: ID!) {
  node(id: $id) { ... on ProjectV2SingleSelectField { options { id name color description } } }
}";
        let data = gh::graphql(QUERY, &[("id", &self.status_field_id)]).map_err(scope_error)?;
        let options = data
            .pointer("/data/node/options")
            .and_then(Value::as_array)
            .context("reading Status options")?;
        Ok(options
            .iter()
            .filter_map(|o| {
                let id = o.get("id")?.as_str()?.to_string();
                let color = o.get("color")?.as_str()?.to_string();
                let description = o
                    .get("description")
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .to_string();
                Some((id, (color, description)))
            })
            .collect())
    }

    /// The board's views, every page.
    fn views(&self) -> Result<Vec<View>> {
        const QUERY: &str = r"query($id: ID!, $cursor: String) {
  node(id: $id) { ... on ProjectV2 { views(first: 50, after: $cursor) {
    pageInfo { hasNextPage endCursor }
    nodes {
      id name layout filter
      sortByFields(first: 1) { totalCount }
      groupByFields(first: 1) { totalCount }
      verticalGroupByFields(first: 1) { totalCount }
    }
  } } }
}";
        let mut all = Vec::new();
        let mut cursor: Option<String> = None;
        let mut previous: Option<String> = None;
        loop {
            let mut vars: Vec<(&str, &str)> = vec![("id", &self.id)];
            if let Some(c) = &cursor {
                vars.push(("cursor", c));
            }
            let data = gh::graphql(QUERY, &vars).map_err(scope_error)?;
            if let Some(errors) = data.get("errors") {
                bail!("reading the views of project #{}: {errors}", self.number);
            }
            let conn = data
                .pointer("/data/node/views")
                .context("GraphQL response missing node.views")?;
            all.extend(
                conn.get("nodes")
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten()
                    .filter_map(|v| {
                        let text =
                            |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
                        let count = |k: &str| {
                            v.pointer(&format!("/{k}/totalCount"))
                                .and_then(Value::as_u64)
                                .unwrap_or(0)
                        };
                        Some(View {
                            id: v.get("id")?.as_str()?.to_string(),
                            name: text("name"),
                            layout: text("layout"),
                            filter: text("filter"),
                            shaped: count("sortByFields")
                                + count("groupByFields")
                                + count("verticalGroupByFields")
                                > 0,
                        })
                    }),
            );
            let more = conn
                .pointer("/pageInfo/hasNextPage")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            cursor = if more {
                conn.pointer("/pageInfo/endCursor")
                    .and_then(Value::as_str)
                    .map(str::to_string)
            } else {
                None
            };
            if cursor.is_none() {
                return Ok(all);
            }
            if cursor == previous {
                bail!("pagination did not advance (cursor {cursor:?} repeated)");
            }
            previous.clone_from(&cursor);
        }
    }

    /// Whether the board has the view gbd shapes, still has the stock one,
    /// or has been shaped by hand. Untouched means the stock name and table
    /// layout with no filter, sort, or grouping; which fields a view shows
    /// survives the change of layout, so that alone does not hold gbd back.
    pub fn view_state(&self) -> Result<ViewState> {
        let views = self.views()?;
        if views.iter().any(|v| {
            v.name.eq_ignore_ascii_case(VIEW_NAME)
                && v.layout == VIEW_LAYOUT
                && v.filter.trim() == VIEW_FILTER
        }) {
            return Ok(ViewState::Configured);
        }
        if let Some(v) = views.iter().find(|v| {
            v.name == STOCK_VIEW_NAME
                && v.layout == STOCK_VIEW_LAYOUT
                && v.filter.trim().is_empty()
                && !v.shaped
        }) {
            return Ok(ViewState::Untouched(v.id.clone()));
        }
        let listed: Vec<String> = views
            .iter()
            .map(|v| {
                let layout = v.layout.trim_end_matches("_LAYOUT").to_ascii_lowercase();
                if v.filter.trim().is_empty() {
                    format!("{} ({layout})", v.name)
                } else {
                    format!("{} ({layout}, {})", v.name, v.filter.trim())
                }
            })
            .collect();
        Ok(ViewState::Custom(if listed.is_empty() {
            "no views".to_string()
        } else {
            listed.join(", ")
        }))
    }

    /// Rename the stock view to Board, board layout, epics filtered out.
    fn configure_view(view_id: &str) -> Result<()> {
        const MUTATION: &str = r"mutation($view: ID!, $name: String!, $filter: String!) {
  updateProjectV2View(input: { viewId: $view, name: $name, layout: BOARD_LAYOUT, filter: $filter }) {
    projectV2View { id }
  }
}";
        let data = gh::graphql(
            MUTATION,
            &[
                ("view", view_id),
                ("name", VIEW_NAME),
                ("filter", VIEW_FILTER),
            ],
        )
        .map_err(scope_error)?;
        if let Some(errors) = data.get("errors") {
            bail!("configuring the view: {errors}");
        }
        Ok(())
    }

    /// Shape the default view if it is still the stock one. `Ok(None)`
    /// when the board has the view (already, or now); `Ok(Some(what))`
    /// when a hand-shaped view was left alone, saying what is there.
    pub fn ensure_view(&self) -> Result<Option<String>> {
        match self.view_state()? {
            ViewState::Configured => Ok(None),
            ViewState::Untouched(id) => {
                Self::configure_view(&id)?;
                Ok(None)
            }
            ViewState::Custom(what) => Ok(Some(what)),
        }
    }

    /// Make sure every option in [`STATUSES`] exists on Status, in column
    /// order.
    ///
    /// `updateProjectV2Field` replaces the option list wholesale. Existing
    /// options are carried over with their ids, colors, and descriptions:
    /// GitHub keeps an option's identity, and so every card's value, only
    /// when the id is sent. A missing option is added, and the five are put
    /// in the order of [`STATUSES`]; any other option keeps its place after
    /// them. On a board `gbd init` just created, GitHub's default `Todo` is
    /// renamed to `Ready`; on an existing board it is kept, so no item
    /// silently loses its status.
    pub fn ensure_statuses(&mut self, fresh: bool) -> Result<bool> {
        struct Opt {
            /// None for an option that does not exist yet.
            id: Option<String>,
            name: String,
            /// None: keep the board's color.
            color: Option<&'static str>,
        }
        let mut options: Vec<Opt> = self
            .status_options
            .iter()
            .map(|o| Opt {
                id: Some(o.id.clone()),
                name: o.name.clone(),
                color: None,
            })
            .collect();
        let mut changed = false;
        if fresh && !self.has_status(STATUS_READY) {
            if let Some(todo) = options
                .iter_mut()
                .find(|o| o.name.eq_ignore_ascii_case("Todo"))
            {
                todo.name = STATUS_READY.to_string();
                todo.color = Some("GREEN");
                changed = true;
            }
        }
        for (want, color) in STATUSES {
            if !options.iter().any(|o| o.name.eq_ignore_ascii_case(want)) {
                options.push(Opt {
                    id: None,
                    name: want.to_string(),
                    color: Some(color),
                });
                changed = true;
            }
        }
        // Column order: the gbd statuses as STATUSES lists them, then any
        // other option in the order the board had them (the sort is stable).
        let column = |o: &Opt| {
            STATUSES
                .iter()
                .position(|(n, _)| o.name.eq_ignore_ascii_case(n))
                .unwrap_or(STATUSES.len())
        };
        let before: Vec<String> = options.iter().map(|o| o.name.clone()).collect();
        options.sort_by_key(column);
        changed |= options.iter().map(|o| &o.name).ne(before.iter());
        if !changed {
            return Ok(false);
        }
        let current = self.option_details()?;
        // JSON string literals are valid GraphQL string literals.
        let lit = |s: &str| serde_json::to_string(s).unwrap_or_default();
        let options = options
            .iter()
            .map(|o| {
                let kept = o.id.as_deref().and_then(|id| current.get(id));
                let color = o.color.or(kept.map(|(c, _)| c.as_str())).unwrap_or("GRAY");
                let description = kept.map_or("", |(_, d)| d.as_str());
                let id =
                    o.id.as_deref()
                        .map_or(String::new(), |id| format!(r#"id: "{id}", "#));
                format!(
                    "{{{id}name: {}, color: {color}, description: {}}}",
                    lit(&o.name),
                    lit(description)
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        let mutation = format!(
            r#"mutation {{
  updateProjectV2Field(input: {{ fieldId: "{}", singleSelectOptions: [{options}] }}) {{
    projectV2Field {{ ... on ProjectV2SingleSelectField {{ id options {{ id name }} }} }}
  }}
}}"#,
            self.status_field_id
        );
        let data = gh::graphql(&mutation, &[]).map_err(scope_error)?;
        if let Some(errors) = data.get("errors") {
            bail!("updating Status options: {errors}");
        }
        *self = Board::load(&self.owner, self.number)?;
        Ok(true)
    }
}

/// Open projects linked to the repo, as `(number, title)`. Paged to the end,
/// so a decision to create a board is never made on a partial list.
pub fn linked_to(repo: &Repo) -> Result<Vec<(u64, String)>> {
    const QUERY: &str = "query($owner: String!, $name: String!, $cursor: String) { repository(owner: $owner, name: $name) { projectsV2(first: 100, after: $cursor) { pageInfo { hasNextPage endCursor } nodes { number title closed } } } }";
    let mut all = Vec::new();
    let mut cursor: Option<String> = None;
    let mut previous: Option<String> = None;
    loop {
        let mut vars: Vec<(&str, &str)> = vec![("owner", repo.owner()), ("name", repo.name())];
        if let Some(c) = &cursor {
            vars.push(("cursor", c));
        }
        let data = gh::graphql(QUERY, &vars).map_err(scope_error)?;
        if let Some(errors) = data.get("errors") {
            bail!(
                "listing projects linked to {}: {errors}",
                repo.name_with_owner
            );
        }
        let conn = data
            .pointer("/data/repository/projectsV2")
            .context("GraphQL response missing repository.projectsV2")?;
        all.extend(
            conn.get("nodes")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter(|p| p.get("closed").and_then(Value::as_bool) != Some(true))
                .filter_map(|p| {
                    Some((
                        p.get("number")?.as_u64()?,
                        p.get("title")?.as_str()?.to_string(),
                    ))
                }),
        );
        let more = conn
            .pointer("/pageInfo/hasNextPage")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        cursor = if more {
            conn.pointer("/pageInfo/endCursor")
                .and_then(Value::as_str)
                .map(str::to_string)
        } else {
            None
        };
        if cursor.is_none() {
            return Ok(all);
        }
        if cursor == previous {
            bail!("pagination did not advance (cursor {cursor:?} repeated)");
        }
        previous.clone_from(&cursor);
    }
}

/// Reuse a board already linked to the repo with this title, if any. With
/// several, the lowest number wins and the caller should warn.
pub fn find_linked(repo: &Repo, title: &str) -> Result<Vec<u64>> {
    let mut nums: Vec<u64> = linked_to(repo)?
        .into_iter()
        .filter(|(_, t)| t.eq_ignore_ascii_case(title))
        .map(|(n, _)| n)
        .collect();
    nums.sort_unstable();
    Ok(nums)
}

/// `gh project create` + Status options + link to the repo.
pub fn create(repo: &Repo, title: &str) -> Result<Board> {
    let created: Value = gh::run_json(&[
        "project",
        "create",
        "--owner",
        repo.owner(),
        "--title",
        title,
        "--format",
        "json",
    ])
    .map_err(scope_error)?;
    let number = created
        .get("number")
        .and_then(Value::as_u64)
        .context("gh project create returned no number")?;
    let mut board = Board::load(repo.owner(), number)?;
    board.ensure_statuses(true)?;
    link(&board, repo)?;
    Ok(board)
}

pub fn link(board: &Board, repo: &Repo) -> Result<()> {
    let n = board.number.to_string();
    gh::run(&[
        "project",
        "link",
        &n,
        "--owner",
        &board.owner,
        "--repo",
        &repo.name_with_owner,
    ])
    .map_err(scope_error)?;
    Ok(())
}

/// Beads status word → board Status option.
pub fn status_for(word: &str) -> Result<&'static str> {
    Ok(
        match word.trim().to_ascii_lowercase().replace('-', "_").as_str() {
            "open" | "ready" | "todo" => STATUS_READY,
            "in_progress" | "inprogress" | "claimed" => STATUS_IN_PROGRESS,
            "deferred" | "defer" => STATUS_DEFERRED,
            "done" | "closed" => STATUS_DONE,
            "blocked" => bail!(
                "blocked is not set by hand; it follows from open blockers (gbd dep add <n> <blocker>)"
            ),
            other => bail!("unknown status {other:?}; use ready, in_progress, deferred, or done"),
        },
    )
}

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

    #[test]
    fn status_words_map_to_board_options() {
        assert_eq!(status_for("in_progress").unwrap(), STATUS_IN_PROGRESS);
        assert_eq!(status_for("in-progress").unwrap(), STATUS_IN_PROGRESS);
        assert_eq!(status_for("Ready").unwrap(), STATUS_READY);
        assert_eq!(status_for("deferred").unwrap(), STATUS_DEFERRED);
        assert_eq!(status_for("done").unwrap(), STATUS_DONE);
        assert!(
            status_for("blocked").is_err(),
            "blocked is derived, never set"
        );
    }
}