Skip to main content

orch/plan/
mod.rs

1//! Roadmap files and the issue plan `orch plan import` applies.
2//!
3//! A milestone is `## M1. Title`. A task is `### M1-03 Title` with Goal, Scope,
4//! Acceptance, Depends on and Owner lines. Later milestones may be a table with
5//! those columns. An unknown table column or a task with no title is an error.
6//! `none` is no dependency.
7
8use std::collections::{HashMap, HashSet};
9use std::error;
10use std::fmt;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fmt::Write as _;
14use std::hash::BuildHasher;
15
16pub const PLAN_LABEL: &str = "orch-plan";
17pub const HUMAN_LABEL: &str = "owner:human";
18pub const NO_AGENT_LABEL: &str = "no-agent";
19/// Marks the `no-agent` that an import adds while it links blocked-by, so a later import releases
20/// that hold and never a `no-agent` the owner set by hand
21pub const HOLD_LABEL: &str = "orch-plan-hold";
22pub const CI_BOOTSTRAP_ID: &str = "CI-01";
23pub const CI_BOOTSTRAP_MARKER: &str = "<!-- orch-ci-bootstrap -->";
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PlanError {
27    pub message: String,
28}
29
30impl Display for PlanError {
31    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
32        f.write_str(&self.message)
33    }
34}
35
36impl error::Error for PlanError {}
37
38impl PlanError {
39    fn new(message: impl Into<String>) -> Self {
40        Self {
41            message: message.into(),
42        }
43    }
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Milestone {
48    pub id: String,
49    pub title: String,
50    /// Text after `## `, used for the GitHub heading anchor
51    pub heading: String,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Task {
56    pub id: String,
57    pub title: String,
58    pub milestone_id: String,
59    pub milestone_title: String,
60    pub milestone_heading: String,
61    /// Full `###` heading. Empty for a table row, which links to the milestone heading
62    pub anchor_heading: String,
63    pub goal: String,
64    pub scope: String,
65    pub acceptance: Vec<String>,
66    pub depends_on: Vec<String>,
67    pub owner_human: bool,
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Roadmap {
72    pub milestones: Vec<Milestone>,
73    pub tasks: Vec<Task>,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum ChangeKind {
78    Create,
79    Update,
80    Unchanged,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct ExistingIssue {
85    pub task_id: String,
86    pub number: u64,
87    pub database_id: u64,
88    pub title: String,
89    pub body: String,
90    pub labels: Vec<String>,
91    pub state: String,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct TaskPlan {
96    pub task: Task,
97    pub kind: ChangeKind,
98    pub number: Option<u64>,
99    pub database_id: Option<u64>,
100    pub existing_labels: Vec<String>,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct RemovedTask {
105    pub task_id: String,
106    pub number: u64,
107    pub state: String,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct PlanDiff {
112    pub tasks: Vec<TaskPlan>,
113    pub removed: Vec<RemovedTask>,
114}
115
116/// A selected task depends on a roadmap id outside the import that has no issue yet
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct UnmetExternal {
119    pub task_id: String,
120    pub blocking_task_id: String,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct Binding {
125    pub task_id: String,
126    pub number: Option<u64>,
127    pub database_id: Option<u64>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct DepRef {
132    pub number: u64,
133    pub database_id: u64,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum LinkEdit {
138    Add {
139        task_id: String,
140        issue_number: Option<u64>,
141        blocking_task_id: String,
142        blocking_number: Option<u64>,
143        blocking_database_id: Option<u64>,
144    },
145    Remove {
146        task_id: String,
147        issue_number: u64,
148        blocking_number: u64,
149        blocking_database_id: u64,
150    },
151}
152
153struct Draft {
154    id: String,
155    title: String,
156    milestone_id: String,
157    milestone_title: String,
158    milestone_heading: String,
159    anchor_heading: String,
160    goal: String,
161    scope: String,
162    acceptance: Vec<String>,
163    depends_raw: Option<String>,
164    owner_human: bool,
165    in_acceptance: bool,
166    line: usize,
167}
168
169#[derive(Clone, Copy)]
170struct TableCols {
171    task: usize,
172    goal: Option<usize>,
173    scope: Option<usize>,
174    acceptance: Option<usize>,
175    depends: Option<usize>,
176    owner: Option<usize>,
177}
178
179pub fn parse_roadmap(markdown: &str) -> Result<Roadmap, PlanError> {
180    parse_roadmap_for(markdown, None).map(|(roadmap, _)| roadmap)
181}
182
183/// With a milestone, errors that belong to other milestones come back as warnings
184pub fn parse_roadmap_for(
185    markdown: &str,
186    milestone: Option<&str>,
187) -> Result<(Roadmap, Vec<String>), PlanError> {
188    let mut milestones = Vec::new();
189    let mut tasks = Vec::new();
190    let mut errors = Vec::new();
191    let mut current: Option<Milestone> = None;
192    let mut draft: Option<Draft> = None;
193    let mut table: Option<TableCols> = None;
194    let mut seen = HashSet::new();
195    let mut tags: Vec<Option<String>> = Vec::new();
196    let mut tag: Option<String> = None;
197
198    for (idx, raw) in markdown.lines().enumerate() {
199        tags.resize(errors.len(), tag.clone());
200        tag = current.as_ref().map(|item| item.id.clone());
201        let line = raw.trim_end_matches('\r');
202        let line_no = idx + 1;
203
204        if let Some(cols) = table {
205            if line.trim().starts_with('|') {
206                if !is_separator_row(line)
207                    && let Some(milestone) = current.as_ref()
208                {
209                    match task_from_row(line, &cols, milestone, line_no) {
210                        Ok(Some(task)) => {
211                            push_task(task, &mut tasks, &mut seen, &mut errors);
212                        }
213                        Ok(None) => {}
214                        Err(err) => errors.push(err),
215                    }
216                }
217                continue;
218            }
219            table = None;
220        }
221
222        if let Some(rest) = line.strip_prefix("### ") {
223            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
224            let Some(milestone) = current.as_ref() else {
225                errors.push(format!(
226                    "line {line_no}: task heading is outside a milestone"
227                ));
228                continue;
229            };
230            if let Some((id, title)) = parse_task_heading(rest) {
231                if title.is_empty() {
232                    errors.push(format!("line {line_no}: {id} has no title"));
233                } else {
234                    draft = Some(Draft::new(id, title, milestone, rest.trim(), line_no));
235                }
236            }
237            continue;
238        }
239
240        if let Some(rest) = line.strip_prefix("## ") {
241            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
242            if let Some((id, title)) = parse_milestone_heading(rest) {
243                let milestone = Milestone {
244                    id,
245                    title,
246                    heading: rest.trim().to_string(),
247                };
248                current = Some(milestone.clone());
249                milestones.push(milestone);
250            } else {
251                current = None;
252            }
253            continue;
254        }
255
256        if let Some((cols, unknown)) = table_cols(line) {
257            flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
258            if current.is_some() {
259                if !unknown.is_empty() {
260                    errors.push(format!(
261                        "line {line_no}: unknown table column {}",
262                        unknown.join(", ")
263                    ));
264                }
265                table = Some(cols);
266            }
267            continue;
268        }
269
270        if let Some(draft) = draft.as_mut() {
271            if let Some((name, value)) = top_level_field(line) {
272                apply_field(draft, name, value);
273                continue;
274            }
275            if draft.in_acceptance && is_acceptance_line(line) {
276                draft.acceptance.push(unindent(line));
277            }
278        }
279    }
280
281    flush_draft(&mut draft, &mut tasks, &mut seen, &mut errors);
282    tags.resize(errors.len(), tag);
283    check_dependencies(&tasks, &mut errors);
284    for message in &errors[tags.len()..] {
285        let id = message
286            .split_whitespace()
287            .next()
288            .and_then(task_milestone_id);
289        tags.push(id.map(str::to_string));
290    }
291
292    let (mut fatal, mut warnings) = (Vec::new(), Vec::new());
293    for (message, tag) in errors.into_iter().zip(tags) {
294        let elsewhere = match (milestone, tag) {
295            (Some(wanted), Some(id)) => !id.eq_ignore_ascii_case(wanted),
296            _ => false,
297        };
298        if elsewhere {
299            warnings.push(message);
300        } else {
301            fatal.push(message);
302        }
303    }
304    if fatal.is_empty() {
305        Ok((Roadmap { milestones, tasks }, warnings))
306    } else {
307        Err(PlanError::new(fatal.join("\n")))
308    }
309}
310
311pub fn select<'a>(
312    roadmap: &'a Roadmap,
313    milestone: Option<&str>,
314) -> Result<Vec<&'a Task>, PlanError> {
315    let Some(wanted) = milestone else {
316        return Ok(roadmap.tasks.iter().collect());
317    };
318    if !roadmap
319        .milestones
320        .iter()
321        .any(|item| item.id.eq_ignore_ascii_case(wanted))
322    {
323        return Err(PlanError::new(format!("no milestone {wanted}")));
324    }
325    Ok(roadmap
326        .tasks
327        .iter()
328        .filter(|task| {
329            task.milestone_id.eq_ignore_ascii_case(wanted) || is_ci_bootstrap_id(&task.id)
330        })
331        .collect())
332}
333
334pub fn issue_title(task: &Task) -> String {
335    if task.title.is_empty() {
336        task.id.clone()
337    } else {
338        format!("{} {}", task.id, task.title)
339    }
340}
341
342pub fn task_anchor(task: &Task) -> String {
343    if task.anchor_heading.is_empty() {
344        github_anchor(&task.milestone_heading)
345    } else {
346        github_anchor(&task.anchor_heading)
347    }
348}
349
350pub fn issue_body(task: &Task, repo: &str, branch: &str, rel_path: &str) -> String {
351    issue_body_with(task, repo, branch, rel_path, &[])
352}
353
354pub fn issue_body_with(
355    task: &Task,
356    repo: &str,
357    branch: &str,
358    rel_path: &str,
359    blocked_external: &[String],
360) -> String {
361    let mut out = String::new();
362    if is_ci_bootstrap_id(&task.id) {
363        out.push_str(CI_BOOTSTRAP_MARKER);
364        out.push('\n');
365    }
366    if !task.goal.is_empty() {
367        out.push_str("## Goal\n\n");
368        out.push_str(task.goal.trim());
369        out.push_str("\n\n");
370    }
371    if !task.scope.is_empty() {
372        out.push_str("## Scope\n\n");
373        out.push_str(task.scope.trim());
374        out.push_str("\n\n");
375    }
376    if !task.acceptance.is_empty() {
377        out.push_str("## Acceptance\n\n");
378        for item in &task.acceptance {
379            let item = item.trim_end();
380            if item.starts_with('-') || item.starts_with('*') || item.starts_with(' ') {
381                out.push_str(item);
382            } else {
383                out.push_str("- ");
384                out.push_str(item);
385            }
386            out.push('\n');
387        }
388        out.push('\n');
389    }
390    if !blocked_external.is_empty() {
391        out.push_str("blocked-external: ");
392        out.push_str(&blocked_external.join(", "));
393        out.push_str(" (no issue yet)\n\n");
394    }
395    if !is_ci_bootstrap_id(&task.id) {
396        let url = format!(
397            "https://github.com/{repo}/blob/{branch}/{path}#{anchor}",
398            branch = encode_git_path(branch),
399            path = encode_git_path(rel_path),
400            anchor = urlencoding::encode(&task_anchor(task)),
401        );
402        let _ = write!(out, "[{rel_path}]({url})\n\n");
403    }
404    if !blocked_external.is_empty() {
405        out.push_str("<!-- orch-blocked-external: ");
406        out.push_str(&blocked_external.join(", "));
407        out.push_str(" -->\n");
408    }
409    out.push_str(&marker_for(&task.id));
410    out.push('\n');
411    out
412}
413
414pub fn marker_for(id: &str) -> String {
415    format!("<!-- orch-plan: {id} -->")
416}
417
418pub fn marker_id(body: &str) -> Option<String> {
419    let start = body.find("<!-- orch-plan:")?;
420    let rest = &body[start + "<!-- orch-plan:".len()..];
421    let end = rest.find("-->")?;
422    let id = rest[..end].trim();
423    is_task_id(id).then(|| id.to_string())
424}
425
426pub fn is_ci_bootstrap_id(id: &str) -> bool {
427    id.eq_ignore_ascii_case(CI_BOOTSTRAP_ID)
428}
429
430pub fn is_ci_bootstrap_body(body: &str) -> bool {
431    body.contains(CI_BOOTSTRAP_MARKER)
432}
433
434/// True when import should add CI-01, because the default branch has no workflow or CI-01 is still open
435pub fn needs_ci_bootstrap(has_workflow: bool, ci_issue_open: bool) -> bool {
436    !has_workflow || ci_issue_open
437}
438
439/// Prepend the CI bootstrap task and make every other task wait on it
440pub fn inject_ci_bootstrap(roadmap: &mut Roadmap, include_shipcheck: bool) {
441    if !roadmap
442        .tasks
443        .iter()
444        .any(|task| is_ci_bootstrap_id(&task.id))
445    {
446        if !roadmap
447            .milestones
448            .iter()
449            .any(|milestone| milestone.id.eq_ignore_ascii_case("CI"))
450        {
451            roadmap.milestones.insert(
452                0,
453                Milestone {
454                    id: "CI".to_string(),
455                    title: "CI bootstrap".to_string(),
456                    heading: "CI. CI bootstrap".to_string(),
457                },
458            );
459        }
460        roadmap
461            .tasks
462            .insert(0, ci_bootstrap_task(include_shipcheck));
463    }
464    for task in &mut roadmap.tasks {
465        if is_ci_bootstrap_id(&task.id) {
466            continue;
467        }
468        if !task.depends_on.iter().any(|dep| is_ci_bootstrap_id(dep)) {
469            task.depends_on.insert(0, CI_BOOTSTRAP_ID.to_string());
470        }
471    }
472}
473
474pub(crate) fn ci_bootstrap_task(include_shipcheck: bool) -> Task {
475    let mut scope = String::from(
476        "Add the smallest project layout that can run tests for this repository's language.\n\
477         Add at least one test that fails if that layout is broken.\n\
478         Add a GitHub Actions workflow under `.github/workflows/` that runs those tests on every push to the default branch.\n\
479         Do not add product features.",
480    );
481    let mut acceptance = vec![
482        "A workflow file exists on the default branch after merge.".to_string(),
483        "Pushing to the default branch runs the workflow.".to_string(),
484        "The workflow reports a passing check.".to_string(),
485        "Tests fail when the skeleton is broken.".to_string(),
486    ];
487    if include_shipcheck {
488        scope.push_str("\nAdd or keep `shipcheck.toml` so local checks match the workflow jobs.");
489        acceptance.push("`shipcheck.toml` lists the same checks the workflow runs.".to_string());
490    }
491    Task {
492        id: CI_BOOTSTRAP_ID.to_string(),
493        title: "Set up CI and tests".to_string(),
494        milestone_id: "CI".to_string(),
495        milestone_title: "CI bootstrap".to_string(),
496        milestone_heading: "CI. CI bootstrap".to_string(),
497        anchor_heading: "CI-01 Set up CI and tests".to_string(),
498        goal: "Give this repository a project skeleton, tests, and a GitHub Actions workflow that runs on every push to the default branch, so later tasks can rely on required checks.".to_string(),
499        scope,
500        acceptance,
501        depends_on: Vec::new(),
502        owner_human: false,
503    }
504}
505
506/// Labels for a plan issue. Human tasks also get `no-agent`, which the dispatcher already skips
507pub fn labels_for(existing: &[String], human: bool) -> Vec<String> {
508    let drop_no_agent = existing.iter().any(|label| label == HUMAN_LABEL);
509    let mut labels = vec![PLAN_LABEL.to_string()];
510    if human {
511        labels.push(HUMAN_LABEL.to_string());
512        labels.push(NO_AGENT_LABEL.to_string());
513    }
514    for label in existing {
515        if label == PLAN_LABEL || label == HUMAN_LABEL {
516            continue;
517        }
518        if label == NO_AGENT_LABEL && (human || drop_no_agent) {
519            continue;
520        }
521        if !labels.iter().any(|have| have == label) {
522            labels.push(label.clone());
523        }
524    }
525    labels
526}
527
528pub fn diff_import(
529    roadmap: &Roadmap,
530    existing: &[ExistingIssue],
531    milestone: Option<&str>,
532    mut body_for: impl FnMut(&Task) -> String,
533) -> Result<PlanDiff, PlanError> {
534    let selected = select(roadmap, milestone)?;
535    let mut by_id: HashMap<&str, &ExistingIssue> = HashMap::new();
536    let mut errors = Vec::new();
537    for issue in existing {
538        if by_id.insert(issue.task_id.as_str(), issue).is_some() {
539            errors.push(format!(
540                "more than one issue is marked as {}",
541                issue.task_id
542            ));
543        }
544    }
545    if !errors.is_empty() {
546        return Err(PlanError::new(errors.join("\n")));
547    }
548
549    let mut tasks = Vec::new();
550    let mut selected_ids = HashSet::new();
551    for task in selected {
552        selected_ids.insert(task.id.as_str());
553        let title = issue_title(task);
554        let body = body_for(task);
555        let kind = if let Some(issue) = by_id.get(task.id.as_str()) {
556            let same = issue.title == title
557                && normalize_body(&issue.body) == normalize_body(&body)
558                && same_labels(&issue.labels, &labels_for(&issue.labels, task.owner_human));
559            if same {
560                ChangeKind::Unchanged
561            } else {
562                ChangeKind::Update
563            }
564        } else {
565            ChangeKind::Create
566        };
567        let issue = by_id.get(task.id.as_str()).copied();
568        tasks.push(TaskPlan {
569            task: task.clone(),
570            kind,
571            number: issue.map(|item| item.number),
572            database_id: issue.map(|item| item.database_id),
573            existing_labels: issue.map(|item| item.labels.clone()).unwrap_or_default(),
574        });
575    }
576
577    let mut removed = Vec::new();
578    for issue in existing {
579        if selected_ids.contains(issue.task_id.as_str()) || is_ci_bootstrap_id(&issue.task_id) {
580            continue;
581        }
582        if let Some(wanted) = milestone {
583            let Some(prefix) = task_milestone_id(&issue.task_id) else {
584                continue;
585            };
586            if !prefix.eq_ignore_ascii_case(wanted) {
587                continue;
588            }
589        }
590        removed.push(RemovedTask {
591            task_id: issue.task_id.clone(),
592            number: issue.number,
593            state: issue.state.clone(),
594        });
595    }
596
597    Ok(PlanDiff { tasks, removed })
598}
599
600/// Dependencies outside the selected set that have no GitHub issue yet.
601///
602/// An id that is not in the roadmap is an error. An id in the roadmap is reported
603pub fn unmet_externals<S: BuildHasher>(
604    tasks: &[Task],
605    roadmap: &Roadmap,
606    known_ids: &HashSet<String, S>,
607) -> Result<Vec<UnmetExternal>, PlanError> {
608    let selected: HashSet<&str> = tasks.iter().map(|task| task.id.as_str()).collect();
609    let roadmap_ids: HashSet<&str> = roadmap.tasks.iter().map(|task| task.id.as_str()).collect();
610    let mut unmet = Vec::new();
611    let mut errors = Vec::new();
612    for task in tasks {
613        for dep in &task.depends_on {
614            if selected.contains(dep.as_str()) || known_ids.contains(dep) {
615                continue;
616            }
617            if roadmap_ids.contains(dep.as_str()) {
618                unmet.push(UnmetExternal {
619                    task_id: task.id.clone(),
620                    blocking_task_id: dep.clone(),
621                });
622            } else {
623                errors.push(format!("{} depends on unknown task {dep}", task.id));
624            }
625        }
626    }
627    if errors.is_empty() {
628        Ok(unmet)
629    } else {
630        Err(PlanError::new(errors.join("\n")))
631    }
632}
633
634/// Task ids to omit when `--skip-unmet` is set, including tasks that depend on a skipped task
635pub fn skip_unmet_ids(tasks: &[Task], unmet: &[UnmetExternal]) -> HashSet<String> {
636    let mut skip: HashSet<String> = unmet.iter().map(|item| item.task_id.clone()).collect();
637    loop {
638        let mut added = false;
639        for task in tasks {
640            if skip.contains(&task.id) {
641                continue;
642            }
643            if task.depends_on.iter().any(|dep| skip.contains(dep)) {
644                skip.insert(task.id.clone());
645                added = true;
646            }
647        }
648        if !added {
649            break;
650        }
651    }
652    skip
653}
654
655pub fn blocked_external_ids<'a>(unmet: &'a [UnmetExternal], task_id: &str) -> Vec<&'a str> {
656    unmet
657        .iter()
658        .filter(|item| item.task_id == task_id)
659        .map(|item| item.blocking_task_id.as_str())
660        .collect()
661}
662
663pub fn diff_links<S: BuildHasher>(
664    tasks: &[Task],
665    bindings: &[Binding],
666    current: &HashMap<u64, Vec<DepRef>, S>,
667) -> Result<Vec<LinkEdit>, PlanError> {
668    let mut edits = Vec::new();
669    let mut errors = Vec::new();
670    let managed: HashSet<u64> = bindings.iter().filter_map(|item| item.number).collect();
671    for task in tasks {
672        let Some(binding) = bindings.iter().find(|item| item.task_id == task.id) else {
673            errors.push(format!("{} has no issue binding", task.id));
674            continue;
675        };
676        let blocked = binding
677            .number
678            .and_then(|number| current.get(&number))
679            .cloned()
680            .unwrap_or_default();
681        let mut desired_numbers = Vec::new();
682        for dep_id in &task.depends_on {
683            let Some(dep) = bindings.iter().find(|item| item.task_id == dep_id.as_str()) else {
684                continue;
685            };
686            if let Some(number) = dep.number {
687                desired_numbers.push(number);
688            }
689            let already = dep
690                .number
691                .is_some_and(|number| blocked.iter().any(|item| item.number == number));
692            if !already {
693                edits.push(LinkEdit::Add {
694                    task_id: task.id.clone(),
695                    issue_number: binding.number,
696                    blocking_task_id: dep_id.clone(),
697                    blocking_number: dep.number,
698                    blocking_database_id: dep.database_id,
699                });
700            }
701        }
702        if let Some(issue_number) = binding.number {
703            for item in &blocked {
704                // Only drop links to other plan issues, a link a person added by hand stays
705                if desired_numbers.contains(&item.number) || !managed.contains(&item.number) {
706                    continue;
707                }
708                edits.push(LinkEdit::Remove {
709                    task_id: task.id.clone(),
710                    issue_number,
711                    blocking_number: item.number,
712                    blocking_database_id: item.database_id,
713                });
714            }
715        }
716    }
717    if errors.is_empty() {
718        Ok(edits)
719    } else {
720        Err(PlanError::new(errors.join("\n")))
721    }
722}
723
724pub fn render(diff: &PlanDiff, links: &[LinkEdit], dry_run: bool) -> String {
725    render_report(diff, links, &[], &[], dry_run)
726}
727
728pub fn render_report(
729    diff: &PlanDiff,
730    links: &[LinkEdit],
731    unmet: &[UnmetExternal],
732    skipped: &[String],
733    dry_run: bool,
734) -> String {
735    let mut out = render_tasks(diff);
736    out.push_str(&render_unmet(unmet, skipped));
737    out.push_str(&render_links(links));
738    out.push_str(&render_summary(diff, links, dry_run));
739    out
740}
741
742fn render_unmet(unmet: &[UnmetExternal], skipped: &[String]) -> String {
743    let skip: HashSet<&str> = skipped.iter().map(String::as_str).collect();
744    let mut out = String::new();
745    for id in skipped {
746        let deps = blocked_external_ids(unmet, id);
747        if deps.is_empty() {
748            let _ = writeln!(out, "skip {id}");
749        } else {
750            let _ = writeln!(
751                out,
752                "skip {id} depends on {}, which has no issue yet",
753                deps.join(", ")
754            );
755        }
756    }
757    let mut seen = HashSet::new();
758    for item in unmet {
759        if skip.contains(item.task_id.as_str()) || !seen.insert(item.task_id.as_str()) {
760            continue;
761        }
762        let deps = blocked_external_ids(unmet, &item.task_id);
763        let _ = writeln!(
764            out,
765            "blocked-external {} depends on {}, which has no issue yet",
766            item.task_id,
767            deps.join(", ")
768        );
769    }
770    out
771}
772
773pub fn render_outline(roadmap: &Roadmap) -> String {
774    let mut out = String::new();
775    for milestone in &roadmap.milestones {
776        let _ = writeln!(out, "{} {}", milestone.id, milestone.title);
777        for task in roadmap
778            .tasks
779            .iter()
780            .filter(|task| task.milestone_id == milestone.id)
781        {
782            let human = if task.owner_human { " [human]" } else { "" };
783            let deps = if task.depends_on.is_empty() {
784                "none".to_string()
785            } else {
786                task.depends_on.join(", ")
787            };
788            let _ = writeln!(out, "  {} {}{human}", task.id, task.title);
789            let _ = writeln!(out, "    depends on: {deps}");
790        }
791        out.push('\n');
792    }
793    out
794}
795
796pub fn render_tasks(diff: &PlanDiff) -> String {
797    let mut out = String::new();
798    for plan in &diff.tasks {
799        let human = if plan.task.owner_human {
800            " [human]"
801        } else {
802            ""
803        };
804        let deps = if plan.task.depends_on.is_empty() {
805            "none".to_string()
806        } else {
807            plan.task.depends_on.join(", ")
808        };
809        let _ = writeln!(
810            out,
811            "{kind} {title}{human}\n  depends on: {deps}",
812            kind = kind_word(plan.kind),
813            title = issue_title(&plan.task),
814        );
815    }
816    for removed in &diff.removed {
817        let _ = writeln!(
818            out,
819            "removed {} issue #{} ({}), not closed",
820            removed.task_id, removed.number, removed.state
821        );
822    }
823    out
824}
825
826pub fn render_links(links: &[LinkEdit]) -> String {
827    let mut out = String::new();
828    for link in links {
829        match link {
830            LinkEdit::Add {
831                task_id,
832                issue_number,
833                blocking_task_id,
834                blocking_number,
835                ..
836            } => {
837                let _ = writeln!(
838                    out,
839                    "link {task_id}{issue} blocked by {blocking_task_id}{blocking}",
840                    issue = number_suffix(*issue_number),
841                    blocking = number_suffix(*blocking_number),
842                );
843            }
844            LinkEdit::Remove {
845                task_id,
846                blocking_number,
847                ..
848            } => {
849                let _ = writeln!(out, "unlink {task_id} blocked by #{blocking_number}");
850            }
851        }
852    }
853    out
854}
855
856pub fn render_summary(diff: &PlanDiff, links: &[LinkEdit], dry_run: bool) -> String {
857    let creates = diff
858        .tasks
859        .iter()
860        .filter(|plan| plan.kind == ChangeKind::Create)
861        .count();
862    let updates = diff
863        .tasks
864        .iter()
865        .filter(|plan| plan.kind == ChangeKind::Update)
866        .count();
867    let unchanged = diff
868        .tasks
869        .iter()
870        .filter(|plan| plan.kind == ChangeKind::Unchanged)
871        .count();
872    let prefix = if dry_run { "dry run: " } else { "" };
873    format!(
874        "{prefix}create {creates}, update {updates}, unchanged {unchanged}, link {}, removed {}\n",
875        links.len(),
876        diff.removed.len()
877    )
878}
879
880pub fn github_anchor(heading: &str) -> String {
881    let mut out = String::new();
882    let mut prev_hyphen = false;
883    for ch in heading.chars() {
884        if ch.is_whitespace() {
885            if !out.is_empty() && !prev_hyphen {
886                out.push('-');
887                prev_hyphen = true;
888            }
889            continue;
890        }
891        if ch == '-' || ch == '_' {
892            if !out.is_empty() && !prev_hyphen {
893                out.push(ch);
894                prev_hyphen = true;
895            }
896            continue;
897        }
898        if ch.is_alphanumeric() {
899            for lower in ch.to_lowercase() {
900                out.push(lower);
901            }
902            prev_hyphen = false;
903        }
904    }
905    while out.ends_with('-') || out.ends_with('_') {
906        out.pop();
907    }
908    out
909}
910
911fn encode_git_path(path: &str) -> String {
912    path.split('/')
913        .map(|segment| urlencoding::encode(segment).into_owned())
914        .collect::<Vec<_>>()
915        .join("/")
916}
917
918fn kind_word(kind: ChangeKind) -> &'static str {
919    match kind {
920        ChangeKind::Create => "create",
921        ChangeKind::Update => "update",
922        ChangeKind::Unchanged => "unchanged",
923    }
924}
925
926fn number_suffix(number: Option<u64>) -> String {
927    match number {
928        Some(number) if number > 0 => format!(" (#{number})"),
929        _ => String::new(),
930    }
931}
932
933fn normalize_body(body: &str) -> String {
934    body.replace("\r\n", "\n").trim().to_string()
935}
936
937fn same_labels(left: &[String], right: &[String]) -> bool {
938    let left: HashSet<&str> = left.iter().map(String::as_str).collect();
939    let right: HashSet<&str> = right.iter().map(String::as_str).collect();
940    left == right
941}
942
943fn task_milestone_id(task_id: &str) -> Option<&str> {
944    if !is_task_id(task_id) {
945        return None;
946    }
947    task_id.split_once('-').map(|(prefix, _)| prefix)
948}
949
950fn push_task(
951    task: Task,
952    tasks: &mut Vec<Task>,
953    seen: &mut HashSet<String>,
954    errors: &mut Vec<String>,
955) {
956    if !seen.insert(task.id.clone()) {
957        errors.push(format!("duplicate task id {}", task.id));
958        return;
959    }
960    tasks.push(task);
961}
962
963fn flush_draft(
964    draft: &mut Option<Draft>,
965    tasks: &mut Vec<Task>,
966    seen: &mut HashSet<String>,
967    errors: &mut Vec<String>,
968) {
969    let Some(draft) = draft.take() else {
970        return;
971    };
972    match draft.into_task() {
973        Ok(task) => push_task(task, tasks, seen, errors),
974        Err(err) => errors.push(err),
975    }
976}
977
978fn check_dependencies(tasks: &[Task], errors: &mut Vec<String>) {
979    let ids: HashSet<&str> = tasks.iter().map(|task| task.id.as_str()).collect();
980    for task in tasks {
981        for dep in &task.depends_on {
982            if dep == &task.id {
983                errors.push(format!("{} depends on itself", task.id));
984            } else if !ids.contains(dep.as_str()) {
985                errors.push(format!("{} depends on unknown task {dep}", task.id));
986            }
987        }
988    }
989}
990
991fn apply_field(draft: &mut Draft, name: &str, value: &str) {
992    if name.eq_ignore_ascii_case("goal") {
993        draft.in_acceptance = false;
994        draft.goal = value.to_string();
995    } else if name.eq_ignore_ascii_case("scope") {
996        draft.in_acceptance = false;
997        draft.scope = value.to_string();
998    } else if name.eq_ignore_ascii_case("acceptance") {
999        draft.in_acceptance = true;
1000        if !value.is_empty() {
1001            draft.acceptance.push(acceptance_item(value));
1002        }
1003    } else if name.eq_ignore_ascii_case("depends on") {
1004        draft.in_acceptance = false;
1005        draft.depends_raw = Some(value.to_string());
1006    } else if name.eq_ignore_ascii_case("owner") {
1007        draft.in_acceptance = false;
1008        draft.owner_human = is_human_owner(value);
1009    }
1010}
1011
1012fn acceptance_item(value: &str) -> String {
1013    if value.starts_with('-') || value.starts_with('*') {
1014        value.to_string()
1015    } else {
1016        format!("- {value}")
1017    }
1018}
1019
1020fn is_acceptance_line(line: &str) -> bool {
1021    let trimmed = line.trim();
1022    !trimmed.is_empty()
1023        && (line.starts_with(' ')
1024            || line.starts_with('\t')
1025            || trimmed.starts_with("- ")
1026            || trimmed.starts_with("* "))
1027}
1028
1029fn unindent(line: &str) -> String {
1030    let line = line.trim_end();
1031    line.strip_prefix("  ")
1032        .or_else(|| line.strip_prefix('\t'))
1033        .unwrap_or(line)
1034        .to_string()
1035}
1036
1037fn top_level_field(line: &str) -> Option<(&str, &str)> {
1038    let rest = line.strip_prefix("- ")?;
1039    let (name, value) = rest.split_once(':')?;
1040    let name = name.trim();
1041    is_known_field(name).then_some((name, value.trim()))
1042}
1043
1044fn is_known_field(name: &str) -> bool {
1045    name.eq_ignore_ascii_case("goal")
1046        || name.eq_ignore_ascii_case("scope")
1047        || name.eq_ignore_ascii_case("acceptance")
1048        || name.eq_ignore_ascii_case("depends on")
1049        || name.eq_ignore_ascii_case("owner")
1050}
1051
1052fn is_human_owner(value: &str) -> bool {
1053    let Some(word) = value.split_whitespace().next() else {
1054        return false;
1055    };
1056    word.trim_matches(|ch: char| matches!(ch, '.' | ',' | ';' | ':'))
1057        .eq_ignore_ascii_case("human")
1058}
1059
1060fn parse_depends(raw: &str) -> Result<Vec<String>, String> {
1061    let trimmed = raw.trim().trim_end_matches('.').trim();
1062    if trimmed.is_empty() {
1063        return Ok(Vec::new());
1064    }
1065    let first = trimmed.split_whitespace().next().unwrap_or("");
1066    let first = first.trim_matches(|ch: char| matches!(ch, '.' | ',' | ';' | ':'));
1067    // A leading none is no dependency, even when the rest of the line names a task
1068    if first.eq_ignore_ascii_case("none") {
1069        return Ok(Vec::new());
1070    }
1071    let ids = extract_ids(trimmed);
1072    if ids.is_empty() {
1073        Err(format!("depends on value \"{trimmed}\" has no task id"))
1074    } else {
1075        Ok(ids)
1076    }
1077}
1078
1079fn extract_ids(raw: &str) -> Vec<String> {
1080    let bytes = raw.as_bytes();
1081    let mut ids = Vec::new();
1082    let mut index = 0;
1083    while index < bytes.len() {
1084        if bytes[index].is_ascii_alphabetic() {
1085            let start = index;
1086            index += 1;
1087            while index < bytes.len()
1088                && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'-')
1089            {
1090                index += 1;
1091            }
1092            let token = &raw[start..index];
1093            if is_task_id(token) && !ids.iter().any(|id| id == token) {
1094                ids.push(token.to_string());
1095            }
1096            continue;
1097        }
1098        index += 1;
1099    }
1100    ids
1101}
1102
1103fn is_task_id(token: &str) -> bool {
1104    if is_ci_bootstrap_id(token) {
1105        return true;
1106    }
1107    let Some((milestone, rest)) = token.split_once('-') else {
1108        return false;
1109    };
1110    if !is_milestone_id(milestone) || rest.is_empty() || !rest.as_bytes()[0].is_ascii_digit() {
1111        return false;
1112    }
1113    rest.bytes().all(|byte| byte.is_ascii_alphanumeric())
1114}
1115
1116fn is_milestone_id(token: &str) -> bool {
1117    let mut chars = token.chars();
1118    let Some(first) = chars.next() else {
1119        return false;
1120    };
1121    if !first.is_ascii_alphabetic() {
1122        return false;
1123    }
1124    let mut saw_digit = false;
1125    for ch in chars {
1126        if ch.is_ascii_digit() {
1127            saw_digit = true;
1128        } else if !ch.is_ascii_alphabetic() {
1129            return false;
1130        }
1131    }
1132    saw_digit
1133}
1134
1135pub(crate) fn is_milestone_heading(line: &str) -> bool {
1136    line.trim_start()
1137        .strip_prefix("## ")
1138        .and_then(parse_milestone_heading)
1139        .is_some()
1140}
1141
1142fn parse_milestone_heading(rest: &str) -> Option<(String, String)> {
1143    let rest = rest.trim();
1144    let (first, title) = rest.split_once(char::is_whitespace)?;
1145    let id = first.trim_end_matches('.');
1146    is_milestone_id(id).then(|| (id.to_string(), title.trim().to_string()))
1147}
1148
1149fn parse_task_heading(rest: &str) -> Option<(String, String)> {
1150    let rest = rest.trim();
1151    let (id, title) = match rest.split_once(char::is_whitespace) {
1152        Some((id, title)) => (id, title.trim()),
1153        None => (rest, ""),
1154    };
1155    is_task_id(id).then(|| (id.to_string(), title.to_string()))
1156}
1157
1158fn table_cols(line: &str) -> Option<(TableCols, Vec<String>)> {
1159    if !line.trim().starts_with('|') {
1160        return None;
1161    }
1162    let cells = split_cells(line);
1163    let names: Vec<String> = cells.iter().map(|cell| cell.to_ascii_lowercase()).collect();
1164    let task = names.iter().position(|name| name == "task")?;
1165    if !names.iter().any(|name| name == "depends on") {
1166        return None;
1167    }
1168    let unknown = cells
1169        .iter()
1170        .zip(names.iter())
1171        .filter(|(_, name)| !name.is_empty() && !is_known_table_column(name))
1172        .map(|(cell, _)| cell.clone())
1173        .collect();
1174    let pos = |label: &str| names.iter().position(|name| name == label);
1175    Some((
1176        TableCols {
1177            task,
1178            goal: pos("goal"),
1179            scope: pos("scope"),
1180            acceptance: pos("acceptance"),
1181            depends: pos("depends on"),
1182            owner: pos("owner"),
1183        },
1184        unknown,
1185    ))
1186}
1187
1188fn is_known_table_column(name: &str) -> bool {
1189    name.eq_ignore_ascii_case("task") || is_known_field(name)
1190}
1191
1192fn is_separator_row(line: &str) -> bool {
1193    let cells = split_cells(line);
1194    !cells.is_empty()
1195        && cells.iter().all(|cell| {
1196            let token = cell.trim_matches(':');
1197            !token.is_empty() && token.chars().all(|ch| ch == '-')
1198        })
1199}
1200
1201fn split_cells(line: &str) -> Vec<String> {
1202    line.trim()
1203        .trim_matches('|')
1204        .split('|')
1205        .map(|cell| cell.trim().to_string())
1206        .collect()
1207}
1208
1209fn cell(cells: &[String], index: Option<usize>) -> &str {
1210    index
1211        .and_then(|index| cells.get(index))
1212        .map_or("", String::as_str)
1213}
1214
1215fn task_from_row(
1216    line: &str,
1217    cols: &TableCols,
1218    milestone: &Milestone,
1219    line_no: usize,
1220) -> Result<Option<Task>, String> {
1221    let cells = split_cells(line);
1222    let task_cell = cell(&cells, Some(cols.task));
1223    let Some((id, title)) = parse_task_heading(task_cell) else {
1224        return Ok(None);
1225    };
1226    if title.is_empty() {
1227        return Err(format!("line {line_no}: {id} has no title"));
1228    }
1229    let depends_raw = cell(&cells, cols.depends);
1230    let depends_on =
1231        parse_depends(depends_raw).map_err(|err| format!("line {line_no}: {id} {err}"))?;
1232    let owner = cell(&cells, cols.owner);
1233    Ok(Some(Task {
1234        id,
1235        title,
1236        milestone_id: milestone.id.clone(),
1237        milestone_title: milestone.title.clone(),
1238        milestone_heading: milestone.heading.clone(),
1239        anchor_heading: String::new(),
1240        goal: cell(&cells, cols.goal).to_string(),
1241        scope: cell(&cells, cols.scope).to_string(),
1242        acceptance: {
1243            let value = cell(&cells, cols.acceptance);
1244            if value.is_empty() {
1245                Vec::new()
1246            } else {
1247                vec![acceptance_item(value)]
1248            }
1249        },
1250        depends_on,
1251        owner_human: is_human_owner(owner),
1252    }))
1253}
1254
1255impl Draft {
1256    fn new(
1257        id: String,
1258        title: String,
1259        milestone: &Milestone,
1260        anchor_heading: &str,
1261        line: usize,
1262    ) -> Self {
1263        Self {
1264            id,
1265            title,
1266            milestone_id: milestone.id.clone(),
1267            milestone_title: milestone.title.clone(),
1268            milestone_heading: milestone.heading.clone(),
1269            anchor_heading: anchor_heading.to_string(),
1270            goal: String::new(),
1271            scope: String::new(),
1272            acceptance: Vec::new(),
1273            depends_raw: None,
1274            owner_human: false,
1275            in_acceptance: false,
1276            line,
1277        }
1278    }
1279
1280    fn into_task(self) -> Result<Task, String> {
1281        let depends_on = match self.depends_raw {
1282            Some(raw) => parse_depends(&raw)
1283                .map_err(|err| format!("line {}: {} {err}", self.line, self.id))?,
1284            None => Vec::new(),
1285        };
1286        Ok(Task {
1287            id: self.id,
1288            title: self.title,
1289            milestone_id: self.milestone_id,
1290            milestone_title: self.milestone_title,
1291            milestone_heading: self.milestone_heading,
1292            anchor_heading: self.anchor_heading,
1293            goal: self.goal,
1294            scope: self.scope,
1295            acceptance: self.acceptance,
1296            depends_on,
1297            owner_human: self.owner_human,
1298        })
1299    }
1300}
1301
1302#[cfg(test)]
1303mod tests;