release-kit 0.2.23

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
//! What a target's own workflows say about the job `--required-check` names.
//!
//! The trunk protection requires exactly two status-check contexts: the
//! named check and the title check. Every other job the project's workflow
//! reports on a pull request gates nothing, and under the trunk style's
//! standing arm nobody reads the check list before the merge. This reader
//! finds those jobs so `rk setup check` can name them as a limitation on
//! `protect-trunk`. It reads the workflow text line by line, in the same
//! spirit as the landing invariants: where a value sits somewhere this
//! reader does not follow, it says so rather than guessing.

use camino::Utf8Path;

use crate::landing::invariants::before_comment;
use crate::setup::context::TRUNK_BRANCH;
use crate::setup::observe::TITLE_CHECK;

/// What the workflows say about the required check.
#[derive(Debug, PartialEq, Eq)]
pub enum GateReading {
    /// No workflow runs on a pull request, so no job reports the check.
    NoRequestWorkflows,
    /// Every request-reporting context is the check, the title check, or a
    /// job the check needs.
    Gated,
    /// No job reports the required check's context on a pull request.
    NoSuchJob {
        /// The contexts that do report, in file order.
        contexts: Vec<String>,
    },
    /// A job carries the check's id, but names itself by an expression or
    /// runs a reusable workflow, so the context it reports is not in the
    /// file.
    UnprovenGateName {
        /// The job id.
        job: String,
    },
    /// The check's `needs` value is one this reader does not follow.
    OpaqueNeeds {
        /// The workflow file that carries it.
        workflow: String,
    },
    /// Contexts that report on a pull request and gate nothing.
    Ungated {
        /// Their names, in file order.
        jobs: Vec<String>,
    },
}

/// The gate job's `if` condition, as far as the reader proves it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Condition {
    /// No `if` key: the job is skipped when a needed job fails.
    Absent,
    /// A bare `always()`: the job runs whatever the needed jobs report.
    Always,
    /// Any other expression, carried verbatim: not proven to run on a
    /// failed dependency.
    Other(String),
}

/// The reading and what the reader judges beside it.
#[derive(Debug, PartialEq, Eq)]
pub struct GateReport {
    /// What the workflows say.
    pub reading: GateReading,
    /// The gate job's condition, where a gate job was found.
    pub gate_condition: Option<Condition>,
    /// What the gate's workflow filters its pull-request trigger by.
    pub gate_trigger: Trigger,
    /// Workflow files that could not be read, so their jobs are unjudged.
    pub unreadable: Vec<String>,
}

/// One job as the line reader sees it.
#[derive(Debug, PartialEq, Eq)]
struct Job {
    id: String,
    name: Name,
    /// The job calls a reusable workflow, whose jobs report their own
    /// contexts, named after both the caller and the callee.
    reusable: bool,
    needs: Needs,
    condition: Condition,
}

/// How a job's status-check context is known.
#[derive(Debug, PartialEq, Eq)]
enum Name {
    /// No `name` key: the context is the id.
    Id,
    /// A literal `name` value.
    Fixed(String),
    /// A name built from an expression: not in this file.
    Unproven,
}

impl Job {
    /// The status-check context the job reports, where the file states it.
    fn context(&self) -> Option<&str> {
        if self.reusable {
            return None;
        }
        match &self.name {
            Name::Id => Some(&self.id),
            Name::Fixed(name) => Some(name),
            Name::Unproven => None,
        }
    }

    /// How the job is listed: its context, or its id marked as unresolved.
    fn listing(&self) -> String {
        self.context().map_or_else(
            || format!("{} (a context this reader cannot resolve)", self.id),
            str::to_owned,
        )
    }
}

/// A job's `needs` value.
#[derive(Debug, PartialEq, Eq)]
enum Needs {
    /// The key is absent.
    None,
    /// The job ids named, in a scalar, a flow list, or a block list.
    Listed(Vec<String>),
    /// An expression, an anchor, or a folded scalar: not followed.
    Opaque,
}

/// What a workflow's pull-request trigger filters by.
///
/// Every filter can keep the gate from reporting on a request the trunk
/// protection covers, and a required context that never appears leaves
/// the merge hanging.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Trigger {
    /// The trigger carries `paths` or `paths-ignore`.
    pub paths_filtered: bool,
    /// The trigger's branch filter leaves the trunk out, quoted.
    pub misses_trunk: Option<String>,
    /// The trigger's activity types leave out an opened, reopened, or
    /// synchronized request, quoted.
    pub types_filtered: Option<String>,
}

impl Trigger {
    /// Read the filters one request event carries.
    fn from_filters(filters: &[(String, Vec<String>)]) -> Self {
        let mut trigger = Self::default();
        for (key, items) in filters {
            match key.as_str() {
                "paths" | "paths-ignore" => trigger.paths_filtered = true,
                // A negative pattern later in the list can take the trunk
                // back out, so a list carrying one is not proven either way.
                "branches" => {
                    let negated = items.iter().any(|item| item.starts_with('!'));
                    if negated || !items.iter().any(|item| covers_trunk(item)) {
                        trigger.misses_trunk = Some(format!("branches: [{}]", items.join(", ")));
                    }
                }
                // A glob here may match the trunk, and the reader does not
                // run the forge's matcher, so only a literal other name is
                // proven harmless.
                "branches-ignore" => {
                    if items.iter().any(|item| covers_trunk(item) || is_glob(item)) {
                        trigger.misses_trunk =
                            Some(format!("branches-ignore: [{}]", items.join(", ")));
                    }
                }
                "types" => {
                    let needed = ["opened", "synchronize", "reopened"];
                    if !needed
                        .iter()
                        .all(|kind| items.iter().any(|item| item == kind))
                    {
                        trigger.types_filtered = Some(format!("types: [{}]", items.join(", ")));
                    }
                }
                _ => {}
            }
        }
        trigger
    }

    /// Fold a second request event's filters in: a filter on either event
    /// is reported.
    fn merge(&mut self, other: Self) {
        self.paths_filtered |= other.paths_filtered;
        if self.misses_trunk.is_none() {
            self.misses_trunk = other.misses_trunk;
        }
        if self.types_filtered.is_none() {
            self.types_filtered = other.types_filtered;
        }
    }
}

/// Whether a branch pattern names the trunk: its exact name, or a glob
/// that matches every branch. Any other glob is not proven to.
fn covers_trunk(pattern: &str) -> bool {
    pattern == TRUNK_BRANCH || pattern == "*" || pattern == "**"
}

/// Whether a branch pattern carries a glob or negation character, so its
/// matches are the forge's to decide, not this reader's.
fn is_glob(pattern: &str) -> bool {
    pattern.contains(['*', '?', '[', ']', '+', '!'])
}

/// One workflow file that runs on a pull request.
struct Workflow {
    name: String,
    trigger: Trigger,
    jobs: Vec<Job>,
}

/// Read every workflow under the target's `.github/workflows` and judge
/// the named check against the jobs that report on a pull request.
#[must_use]
pub fn read_gate(target: &Utf8Path, required_check: &str) -> GateReport {
    let (workflows, unreadable) = read_workflows(&target.join(".github/workflows"));
    let mut report = GateReport {
        reading: GateReading::NoRequestWorkflows,
        gate_condition: None,
        gate_trigger: Trigger::default(),
        unreadable,
    };
    if workflows.iter().all(|workflow| workflow.jobs.is_empty()) {
        return report;
    }
    judge(&mut report, &workflows, required_check);
    report
}

/// Every request-running workflow under the directory, in name order, and
/// every path that could not be read. A missing directory is neither: a
/// target with no workflows reads as none, not as unreadable.
fn read_workflows(dir: &Utf8Path) -> (Vec<Workflow>, Vec<String>) {
    let mut unreadable: Vec<String> = Vec::new();
    let mut workflows: Vec<Workflow> = Vec::new();
    match std::fs::read_dir(dir) {
        Ok(entries) => {
            let mut names: Vec<String> = Vec::new();
            for entry in entries {
                match entry {
                    Ok(entry) => names.push(entry.file_name().to_string_lossy().into_owned()),
                    Err(_) => unreadable.push(dir.to_string()),
                }
            }
            names.sort();
            for name in names {
                let is_workflow = std::path::Path::new(&name)
                    .extension()
                    .is_some_and(|ext| ext == "yml" || ext == "yaml");
                if !is_workflow {
                    continue;
                }
                let Ok(text) = std::fs::read_to_string(dir.join(&name)) else {
                    unreadable.push(name);
                    continue;
                };
                if let Some(trigger) = request_trigger(&text) {
                    workflows.push(Workflow {
                        name,
                        trigger,
                        jobs: jobs(&text),
                    });
                }
            }
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
        Err(_) => unreadable.push(dir.to_string()),
    }
    (workflows, unreadable)
}

/// The gate judgment over workflows that declare at least one job.
fn judge(report: &mut GateReport, workflows: &[Workflow], required_check: &str) {
    let Some((workflow, gate)) = workflows.iter().find_map(|workflow| {
        workflow
            .jobs
            .iter()
            .find(|job| job.context() == Some(required_check))
            .map(|job| (workflow, job))
    }) else {
        let unproven = workflows
            .iter()
            .flat_map(|workflow| &workflow.jobs)
            .find(|job| job.id == required_check && job.context().is_none());
        report.reading = unproven.map_or_else(
            || GateReading::NoSuchJob {
                contexts: workflows
                    .iter()
                    .flat_map(|workflow| workflow.jobs.iter().map(Job::listing))
                    .collect(),
            },
            |job| GateReading::UnprovenGateName {
                job: job.id.clone(),
            },
        );
        return;
    };
    report.gate_condition = Some(gate.condition.clone());
    report.gate_trigger = workflow.trigger.clone();
    // A `needs` entry is a job id, and ids are per workflow file, so the
    // gated jobs resolve inside the gate's own file.
    let gated: Vec<&Job> = match &gate.needs {
        Needs::Opaque => {
            report.reading = GateReading::OpaqueNeeds {
                workflow: workflow.name.clone(),
            };
            return;
        }
        Needs::None => Vec::new(),
        Needs::Listed(ids) => ids
            .iter()
            .filter_map(|id| workflow.jobs.iter().find(|job| &job.id == id))
            .collect(),
    };
    let mut ungated: Vec<String> = Vec::new();
    for job in workflows.iter().flat_map(|workflow| &workflow.jobs) {
        if std::ptr::eq(job, gate)
            || job.context() == Some(TITLE_CHECK)
            || gated.iter().any(|needed| std::ptr::eq(*needed, job))
        {
            continue;
        }
        let listing = job.listing();
        if !ungated.contains(&listing) {
            ungated.push(listing);
        }
    }
    report.reading = if ungated.is_empty() {
        GateReading::Gated
    } else {
        GateReading::Ungated { jobs: ungated }
    };
}

/// The one-line limitation a report earns, or nothing where the check
/// stands for every request-reporting job.
#[must_use]
pub fn limitation(report: &GateReport, required_check: &str) -> Option<String> {
    let mut parts: Vec<String> = Vec::new();
    match &report.reading {
        GateReading::Gated => {}
        GateReading::NoRequestWorkflows => parts.push(format!(
            "no workflow in .github/workflows runs on a pull request, so the required check {required_check} cannot be satisfied"
        )),
        GateReading::NoSuchJob { contexts } => parts.push(format!(
            "no job in .github/workflows reports the context {required_check} on a pull request, so the required check cannot be satisfied; the request-reporting contexts are [{}]",
            contexts.join(", ")
        )),
        GateReading::UnprovenGateName { job } => parts.push(format!(
            "the job {job} names itself by an expression or runs a reusable workflow, so the context it reports is not in the file and the required check {required_check} is not proven to exist"
        )),
        GateReading::OpaqueNeeds { workflow } => parts.push(format!(
            "the needs value of {required_check} in {workflow} is one this reader does not follow; whether every request-reporting job is gated could not be read"
        )),
        GateReading::Ungated { jobs } => parts.push(format!(
            "the required check {required_check} gates nothing from [{}]: those jobs report on a pull request but the gate does not need them, so a failure there does not hold the merge",
            jobs.join(", ")
        )),
    }
    match &report.gate_condition {
        None | Some(Condition::Always) => {}
        Some(Condition::Absent) => parts.push(format!(
            "the job {required_check} runs without if: always(), so a needed job that fails skips it and the skip reports success"
        )),
        Some(Condition::Other(expression)) => parts.push(format!(
            "the job {required_check} runs under the condition {expression}, which this reader cannot prove holds when a needed job fails; a bare always() is the proven form"
        )),
    }
    if report.gate_trigger.paths_filtered {
        parts.push(format!(
            "the pull_request trigger of the workflow carrying {required_check} filters by paths, so a request outside them never reports the check and its merge hangs"
        ));
    }
    if let Some(filter) = &report.gate_trigger.misses_trunk {
        parts.push(format!(
            "the pull_request trigger of the workflow carrying {required_check} reads {filter}, which does not prove it runs for a request against {TRUNK_BRANCH}, so the check would never report there"
        ));
    }
    if let Some(filter) = &report.gate_trigger.types_filtered {
        parts.push(format!(
            "the pull_request trigger of the workflow carrying {required_check} reads {filter}, so an opened, reopened, or synchronized request outside those types never reports the check"
        ));
    }
    if !report.unreadable.is_empty() {
        parts.push(format!(
            "[{}] could not be read, so the jobs there are not judged",
            report.unreadable.join(", ")
        ));
    }
    (!parts.is_empty()).then(|| parts.join("; "))
}

/// The workflow's pull-request trigger, in the block, the flow, the
/// scalar, or the block-list form of `on`, where it has one, with the
/// filters a block-form event carries under it.
///
/// The landing invariant reads it too, to ask whether a generated
/// workflow reports on a request at all: one reader owns the forms `on`
/// takes, so a form one of them learns is a form both know.
pub(crate) fn request_trigger(workflow: &str) -> Option<Trigger> {
    let mut in_on = false;
    let mut event_indent: Option<usize> = None;
    let mut in_request_event = false;
    let mut filter_indent: Option<usize> = None;
    let mut filters: Vec<(String, Vec<String>)> = Vec::new();
    let mut found: Option<Trigger> = None;
    let close_event = |filters: &mut Vec<(String, Vec<String>)>, found: &mut Option<Trigger>| {
        if let Some(trigger) = found {
            trigger.merge(Trigger::from_filters(filters));
        }
        filters.clear();
    };
    for line in workflow.lines() {
        if is_blank(line) {
            continue;
        }
        let depth = indent(line);
        if depth == 0 {
            if in_request_event {
                close_event(&mut filters, &mut found);
            }
            in_on = false;
            in_request_event = false;
            event_indent = None;
            let Some((key, value)) = key_value(line) else {
                continue;
            };
            if key != "on" {
                continue;
            }
            if value.is_empty() {
                in_on = true;
                continue;
            }
            if list_items(value).iter().any(|item| is_request_event(item)) {
                found.get_or_insert_with(Trigger::default);
            }
            continue;
        }
        if !in_on {
            continue;
        }
        let event_depth = *event_indent.get_or_insert(depth);
        if depth == event_depth {
            if in_request_event {
                close_event(&mut filters, &mut found);
            }
            filter_indent = None;
            let item = line.trim_start();
            let item = item.strip_prefix("- ").map_or(item, str::trim_start);
            let key = key_value(item).map_or_else(|| before_comment(item).trim(), |(key, _)| key);
            in_request_event = is_request_event(key);
            if in_request_event {
                found.get_or_insert_with(Trigger::default);
            }
            continue;
        }
        if !in_request_event || depth <= event_depth {
            continue;
        }
        let filter_depth = *filter_indent.get_or_insert(depth);
        if depth == filter_depth {
            if let Some((key, value)) = key_value(line) {
                let items = if value.is_empty() {
                    Vec::new()
                } else {
                    list_items(value).into_iter().map(str::to_owned).collect()
                };
                filters.push((key.to_owned(), items));
            }
            continue;
        }
        // A block-list item under the last filter key.
        if let Some(item) = line.trim_start().strip_prefix("- ") {
            if let Some((_, items)) = filters.last_mut() {
                items.push(unquote(before_comment(item).trim()).to_owned());
            }
        }
    }
    if in_request_event {
        close_event(&mut filters, &mut found);
    }
    found
}

fn is_request_event(name: &str) -> bool {
    matches!(name, "pull_request" | "pull_request_target")
}

/// The jobs the workflow declares under its top-level `jobs` key, with
/// the properties the gate judgment reads. Steps and every deeper mapping
/// are passed over, so a `jobs` key nested in a reusable-workflow call or
/// a matrix opens no job.
fn jobs(workflow: &str) -> Vec<Job> {
    let mut found: Vec<Job> = Vec::new();
    let mut in_jobs = false;
    let mut job_indent: Option<usize> = None;
    let mut property_indent: Option<usize> = None;
    let mut reading_needs_list = false;
    for line in workflow.lines() {
        if is_blank(line) {
            continue;
        }
        let depth = indent(line);
        if depth == 0 {
            in_jobs = key_value(line).is_some_and(|(key, value)| key == "jobs" && value.is_empty());
            job_indent = None;
            property_indent = None;
            reading_needs_list = false;
            continue;
        }
        if !in_jobs {
            continue;
        }
        let job_depth = *job_indent.get_or_insert(depth);
        if depth == job_depth {
            reading_needs_list = false;
            property_indent = None;
            if let Some((id, _)) = key_value(line) {
                found.push(Job {
                    id: id.to_owned(),
                    name: Name::Id,
                    reusable: false,
                    needs: Needs::None,
                    condition: Condition::Absent,
                });
            }
            continue;
        }
        if depth < job_depth {
            continue;
        }
        let Some(job) = found.last_mut() else {
            continue;
        };
        let property_depth = *property_indent.get_or_insert(depth);
        if reading_needs_list && depth > property_depth {
            if let Some(item) = line.trim_start().strip_prefix("- ") {
                if let Needs::Listed(ids) = &mut job.needs {
                    ids.push(unquote(before_comment(item).trim()).to_owned());
                }
                continue;
            }
        }
        reading_needs_list = false;
        if depth != property_depth {
            continue;
        }
        let Some((key, value)) = key_value(line) else {
            continue;
        };
        match key {
            "name" => {
                let value = unquote(before_comment(value).trim());
                // A name built from an expression resolves per run, so
                // the context it reports is not in the file.
                if value.contains("${{") || value.is_empty() {
                    job.name = Name::Unproven;
                } else {
                    job.name = Name::Fixed(value.to_owned());
                }
            }
            // A reusable-workflow call reports the called jobs' contexts,
            // named after both the caller and the callee, whatever name
            // the caller sets and in whatever key order.
            "uses" => job.reusable = true,
            "if" => job.condition = condition(value),
            "needs" => {
                let value = before_comment(value).trim();
                if value.is_empty() {
                    job.needs = Needs::Listed(Vec::new());
                    reading_needs_list = true;
                } else if value.starts_with(['|', '>', '*', '&', '$']) {
                    job.needs = Needs::Opaque;
                } else {
                    job.needs =
                        Needs::Listed(list_items(value).into_iter().map(str::to_owned).collect());
                }
            }
            _ => {}
        }
    }
    found
}

/// A job's `if` value: a bare `always()`, with or without the expression
/// braces, is the one form proven to run on a failed dependency. Anything
/// else is carried verbatim, because `always() && x` skips when `x` is
/// false and a skipped job reports success.
fn condition(value: &str) -> Condition {
    let value = unquote(before_comment(value).trim());
    let inner = value
        .strip_prefix("${{")
        .and_then(|rest| rest.strip_suffix("}}"))
        .map_or(value, str::trim);
    if inner == "always()" {
        Condition::Always
    } else if inner.is_empty() {
        Condition::Other("(a value carried on another line)".to_owned())
    } else {
        Condition::Other(inner.to_owned())
    }
}

/// A scalar or a flow list, as its items: `a`, `[a, b]`, or `"a"`. The
/// outer brackets alone delimit the list, and a comma inside a quoted
/// scalar separates nothing, so a bracketed glob such as `'ma[as]ter'`
/// stays one item and reaches the judgment whole.
fn list_items(value: &str) -> Vec<&str> {
    let value = before_comment(value).trim();
    let inner = value
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(value);
    let mut items = Vec::new();
    let mut quote: Option<char> = None;
    let mut escaped = false;
    let mut start = 0;
    for (index, character) in inner.char_indices() {
        if let Some(open) = quote {
            // A double-quoted scalar escapes with a backslash, so the
            // quote after one is content, not the close.
            if escaped {
                escaped = false;
            } else if open == QUOTES[0] && character == '\\' {
                escaped = true;
            } else if character == open {
                quote = None;
            }
        } else if QUOTES.contains(&character) {
            quote = Some(character);
        } else if character == ',' {
            items.push(&inner[start..index]);
            start = index + 1;
        }
    }
    items.push(&inner[start..]);
    items
        .into_iter()
        .map(|item| unquote(item.trim()))
        .filter(|item| !item.is_empty())
        .collect()
}

/// A `key: value` line split at its first mapping colon, the key bare or
/// quoted as YAML permits for an implicit key.
fn key_value(line: &str) -> Option<(&str, &str)> {
    let line = line.trim();
    let (key, rest) = if let Some(quoted) = line.strip_prefix(QUOTES) {
        let quote = line.chars().next()?;
        let end = quoted.find(quote)?;
        (&quoted[..end], quoted[end + 1..].trim_start())
    } else {
        let end = line.find(':')?;
        (&line[..end], &line[end..])
    };
    let value = rest.strip_prefix(':')?;
    if !(value.is_empty() || value.starts_with([' ', '\t'])) {
        return None;
    }
    let key = key.trim();
    if key.is_empty() || key.contains([' ', '\t']) {
        return None;
    }
    Some((key, value.trim()))
}

/// The two quote characters a YAML scalar is written with, named by code
/// point because the artifact-body scan reads a lone quote in these
/// sources as a literal opening.
const QUOTES: [char; 2] = ['\u{22}', '\u{27}'];

fn unquote(value: &str) -> &str {
    value
        .strip_prefix(QUOTES[0])
        .and_then(|rest| rest.strip_suffix(QUOTES[0]))
        .or_else(|| {
            value
                .strip_prefix('\'')
                .and_then(|rest| rest.strip_suffix('\''))
        })
        .unwrap_or(value)
}

fn indent(line: &str) -> usize {
    line.len() - line.trim_start_matches(' ').len()
}

fn is_blank(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.is_empty() || trimmed.starts_with('#') || trimmed == "---"
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use super::*;

    fn report(text: &str, check: &str) -> GateReport {
        let dir = tempfile::tempdir().expect("a tempdir");
        let workflows = dir.path().join(".github/workflows");
        std::fs::create_dir_all(&workflows).expect("the workflows dir");
        std::fs::write(workflows.join("ci.yml"), text).expect("the workflow writes");
        read_gate(
            Utf8Path::from_path(dir.path()).expect("utf-8 tempdir"),
            check,
        )
    }

    fn unfiltered() -> Trigger {
        Trigger::default()
    }

    #[test]
    fn the_trigger_is_read_in_every_on_form() {
        assert_eq!(
            request_trigger("on:\n  push:\n  pull_request:\n    branches: [master]\n"),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on:\n  push:\n  pull_request:\n    branches: [main]\n"),
            Some(Trigger {
                misses_trunk: Some("branches: [main]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger(
                "on:\n  pull_request:\n    branches-ignore:\n      - master\n    types: [opened]\n"
            ),
            Some(Trigger {
                misses_trunk: Some("branches-ignore: [master]".to_owned()),
                types_filtered: Some("types: [opened]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger(
                "on:\n  pull_request:\n    branches: ['**']\n    types: [opened, synchronize, reopened]\n"
            ),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches: ['**', '!master']\n"),
            Some(Trigger {
                misses_trunk: Some("branches: [**, !master]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches: ['!master', '**']\n"),
            Some(Trigger {
                misses_trunk: Some("branches: [!master, **]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches-ignore: ['mast*']\n"),
            Some(Trigger {
                misses_trunk: Some("branches-ignore: [mast*]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches-ignore: [dependabot]\n"),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches-ignore: ['ma[as]ter']\n"),
            Some(Trigger {
                misses_trunk: Some("branches-ignore: [ma[as]ter]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger(
                "on:\n  pull_request:\n    branches: [\"release/**\", 'a,b', master]\n"
            ),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    branches: [\"topic\\\",master,tail\"]\n"),
            Some(Trigger {
                misses_trunk: Some("branches: [topic\\\",master,tail]".to_owned()),
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger("on: [push, pull_request]\n"),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on: pull_request_target\n"),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("on:\n  - push\n  - pull_request\n"),
            Some(unfiltered())
        );
        assert_eq!(
            request_trigger("\"on\":\n  pull_request:\n"),
            Some(unfiltered())
        );
        assert_eq!(request_trigger("on: push\n"), None);
        assert_eq!(
            request_trigger("on:\n  push:\n  workflow_dispatch:\njobs:\n  pull_request:\n"),
            None
        );
        assert_eq!(
            request_trigger("on:\n  pull_request:\n    paths:\n      - 'docs/**'\n  push:\n"),
            Some(Trigger {
                paths_filtered: true,
                ..Trigger::default()
            })
        );
        assert_eq!(
            request_trigger(
                "on:\n  push:\n    paths: [x]\n  pull_request:\n    branches: [master]\n"
            ),
            Some(unfiltered())
        );
    }

    #[test]
    fn jobs_read_names_needs_and_conditions_in_every_form() {
        let text = "\
jobs:
  lint:
    runs-on: ubuntu-latest
  build:
    name: \"Build it\" # the context
    needs: lint
  docs:
    needs: [lint, build]
  gate:
    name: gate-${{ matrix.os }}
    if: ${{ always() }}
    needs:
      - lint
      - 'docs'
    steps:
      - uses: x@y
        with:
          needs: nothing
  odd:
    if: always() && needs.lint.result == 'success'
    needs: ${{ fromJSON(x) }}
  called:
    uses: org/repo/.github/workflows/x.yml@main
    name: called
  named-first:
    name: gate
    uses: org/repo/.github/workflows/x.yml@main
";
        let found = jobs(text);
        let ids: Vec<&str> = found.iter().map(|job| job.id.as_str()).collect();
        assert_eq!(
            ids,
            [
                "lint",
                "build",
                "docs",
                "gate",
                "odd",
                "called",
                "named-first"
            ]
        );
        assert_eq!(found[0].needs, Needs::None);
        assert_eq!(found[0].condition, Condition::Absent);
        assert_eq!(found[1].context(), Some("Build it"));
        assert_eq!(found[1].needs, Needs::Listed(vec!["lint".to_owned()]));
        assert_eq!(
            found[2].needs,
            Needs::Listed(vec!["lint".to_owned(), "build".to_owned()])
        );
        assert_eq!(found[3].name, Name::Unproven);
        assert_eq!(found[3].context(), None);
        assert_eq!(found[3].condition, Condition::Always);
        assert_eq!(
            found[3].needs,
            Needs::Listed(vec!["lint".to_owned(), "docs".to_owned()])
        );
        assert_eq!(
            found[4].condition,
            Condition::Other("always() && needs.lint.result == 'success'".to_owned())
        );
        assert_eq!(found[4].needs, Needs::Opaque);
        assert!(found[5].reusable);
        assert_eq!(found[5].context(), None);
        assert!(found[6].reusable);
        assert_eq!(found[6].context(), None);
    }

    #[test]
    fn flow_lists_keep_quoted_scalars_whole() {
        assert_eq!(list_items("[a, b]"), ["a", "b"]);
        assert_eq!(list_items("a"), ["a"]);
        assert_eq!(list_items("\"a\" # c"), ["a"]);
        assert_eq!(
            list_items("['ma[as]ter', \"x,y\", z]"),
            ["ma[as]ter", "x,y", "z"]
        );
        assert_eq!(list_items("[]"), Vec::<&str>::new());
        assert_eq!(
            list_items("[\"topic\\\",master,tail\", x]"),
            ["topic\\\",master,tail", "x"]
        );
    }

    #[test]
    fn a_nested_jobs_key_opens_no_region() {
        let text = "\
jobs:
  call:
    uses: org/repo/.github/workflows/x.yml@main
    with:
      jobs: 3
  other:
    strategy:
      matrix:
        jobs: [a, b]
";
        let ids: Vec<String> = jobs(text).into_iter().map(|job| job.id).collect();
        assert_eq!(ids, ["call", "other"]);
    }

    #[test]
    fn a_condition_is_proven_only_as_a_bare_always() {
        assert_eq!(condition("always()"), Condition::Always);
        assert_eq!(condition("${{ always() }}"), Condition::Always);
        assert_eq!(condition("'${{always()}}'"), Condition::Always);
        assert_eq!(
            condition("${{ always() && false }}"),
            Condition::Other("always() && false".to_owned())
        );
        assert_eq!(
            condition("!always()"),
            Condition::Other("!always()".to_owned())
        );
        assert_eq!(
            condition(""),
            Condition::Other("(a value carried on another line)".to_owned())
        );
    }

    #[test]
    fn read_gate_partitions_the_contexts() {
        let gated = report(
            "on: [pull_request]\njobs:\n  lint:\n  test:\n    if: always()\n    needs: [lint]\n",
            "test",
        );
        assert_eq!(gated.reading, GateReading::Gated);
        assert_eq!(gated.gate_condition, Some(Condition::Always));
        assert_eq!(gated.gate_trigger, Trigger::default());
        assert!(gated.unreadable.is_empty());

        let ungated = report(
            "on: [pull_request]\njobs:\n  lint:\n  build:\n  docs:\n  pr-title:\n  test:\n    needs: lint\n",
            "test",
        );
        assert_eq!(
            ungated.reading,
            GateReading::Ungated {
                jobs: vec!["build".to_owned(), "docs".to_owned()]
            }
        );
        assert_eq!(ungated.gate_condition, Some(Condition::Absent));

        let missing = report("on: [pull_request]\njobs:\n  lint:\n  unit:\n", "test");
        assert_eq!(
            missing.reading,
            GateReading::NoSuchJob {
                contexts: vec!["lint".to_owned(), "unit".to_owned()]
            }
        );
        assert_eq!(missing.gate_condition, None);

        let dynamic = report(
            "on: [pull_request]\njobs:\n  lint:\n  test:\n    name: test-${{ matrix.os }}\n    needs: [lint]\n",
            "test",
        );
        assert_eq!(
            dynamic.reading,
            GateReading::UnprovenGateName {
                job: "test".to_owned()
            }
        );

        let opaque = report(
            "on: [pull_request]\njobs:\n  lint:\n  test:\n    needs: *all\n",
            "test",
        );
        assert_eq!(
            opaque.reading,
            GateReading::OpaqueNeeds {
                workflow: "ci.yml".to_owned()
            }
        );

        let filtered = report(
            "on:\n  pull_request:\n    paths: ['src/**']\njobs:\n  test:\n    if: always()\n",
            "test",
        );
        assert_eq!(filtered.reading, GateReading::Gated);
        assert!(filtered.gate_trigger.paths_filtered);

        let off_trunk = report(
            "on:\n  pull_request:\n    branches: [main]\njobs:\n  test:\n    if: always()\n",
            "test",
        );
        assert_eq!(
            off_trunk.gate_trigger.misses_trunk,
            Some("branches: [main]".to_owned())
        );

        let reusable = report(
            "on: [pull_request]\njobs:\n  test:\n    uses: org/repo/.github/workflows/x.yml@main\n    name: test\n",
            "test",
        );
        assert_eq!(
            reusable.reading,
            GateReading::UnprovenGateName {
                job: "test".to_owned()
            }
        );

        let push_only = report("on: push\njobs:\n  lint:\n  test:\n", "test");
        assert_eq!(push_only.reading, GateReading::NoRequestWorkflows);

        let dir = tempfile::tempdir().expect("a tempdir");
        let empty = read_gate(Utf8Path::from_path(dir.path()).expect("utf-8"), "test");
        assert_eq!(empty.reading, GateReading::NoRequestWorkflows);
        assert!(empty.unreadable.is_empty());
    }

    #[test]
    fn an_unreadable_workflow_is_named_not_skipped() {
        let dir = tempfile::tempdir().expect("a tempdir");
        let workflows = dir.path().join(".github/workflows");
        std::fs::create_dir_all(workflows.join("broken.yml")).expect("a directory named as a file");
        std::fs::write(
            workflows.join("ci.yml"),
            "on: [pull_request]\njobs:\n  test:\n    if: always()\n",
        )
        .expect("the workflow writes");
        let report = read_gate(Utf8Path::from_path(dir.path()).expect("utf-8"), "test");
        assert_eq!(report.reading, GateReading::Gated);
        assert_eq!(report.unreadable, vec!["broken.yml".to_owned()]);
        let text = limitation(&report, "test").expect("a limitation");
        assert!(text.contains("[broken.yml] could not be read"), "{text}");
    }

    #[test]
    fn limitation_texts_are_one_line_each() {
        let base = || GateReport {
            reading: GateReading::Gated,
            gate_condition: Some(Condition::Always),
            gate_trigger: Trigger::default(),
            unreadable: Vec::new(),
        };
        assert_eq!(limitation(&base(), "test"), None);
        let cases = [
            GateReport {
                reading: GateReading::NoRequestWorkflows,
                gate_condition: None,
                ..base()
            },
            GateReport {
                reading: GateReading::NoSuchJob {
                    contexts: vec!["lint".to_owned()],
                },
                gate_condition: None,
                ..base()
            },
            GateReport {
                reading: GateReading::UnprovenGateName {
                    job: "test".to_owned(),
                },
                gate_condition: None,
                ..base()
            },
            GateReport {
                reading: GateReading::OpaqueNeeds {
                    workflow: "ci.yml".to_owned(),
                },
                gate_condition: Some(Condition::Absent),
                ..base()
            },
            GateReport {
                reading: GateReading::Ungated {
                    jobs: vec!["a".to_owned(), "b".to_owned()],
                },
                gate_condition: Some(Condition::Other("always() && x".to_owned())),
                ..base()
            },
            GateReport {
                gate_trigger: Trigger {
                    paths_filtered: true,
                    misses_trunk: Some("branches: [main]".to_owned()),
                    types_filtered: Some("types: [opened]".to_owned()),
                },
                ..base()
            },
            GateReport {
                unreadable: vec!["x.yml".to_owned()],
                ..base()
            },
        ];
        for case in &cases {
            let text = limitation(case, "test").expect("a limitation");
            assert!(!text.contains('\n'), "{text}");
            assert!(
                text.starts_with(|c: char| c.is_lowercase() || c == '['),
                "{text}"
            );
        }
    }
}