local-ci 0.6.2

Run the GitHub Actions jobs a branch would trigger, locally, in an isolated worktree, and print a short report
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
//! A small evaluator for GitHub Actions expressions (`${{ ... }}` and `if:`).
//!
//! Values are JSON values. Anything the evaluator does not know (an unknown
//! context, an unknown function) is an error, never a silent `false`, so the
//! caller can report the job as unsupported instead of quietly skipping it.

use anyhow::{bail, Result};
use serde_json::{Map, Value};
use std::cell::Cell;

/// Job status the status functions (`success()`, `failure()`, ...) answer from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    Success,
    Failure,
    Cancelled,
}

pub struct Ctx<'a> {
    /// Top-level contexts: github, env, matrix, steps, needs, job, runner, inputs, vars, strategy.
    pub contexts: &'a Map<String, Value>,
    pub status: Status,
    /// Set when the expression touched `secrets.*`.
    pub used_secrets: Cell<bool>,
}

impl<'a> Ctx<'a> {
    pub fn new(contexts: &'a Map<String, Value>, status: Status) -> Self {
        Ctx {
            contexts,
            status,
            used_secrets: Cell::new(false),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
enum Tok {
    Num(f64),
    Str(String),
    Ident(String),
    Op(&'static str),
}

fn lex(src: &str) -> Result<Vec<Tok>> {
    let c: Vec<char> = src.chars().collect();
    let mut i = 0;
    let mut out = Vec::new();
    while i < c.len() {
        let ch = c[i];
        if ch.is_whitespace() {
            i += 1;
            continue;
        }
        if ch == '\'' {
            let mut s = String::new();
            i += 1;
            loop {
                if i >= c.len() {
                    bail!("unterminated string in `{src}`");
                }
                if c[i] == '\'' {
                    if i + 1 < c.len() && c[i + 1] == '\'' {
                        s.push('\'');
                        i += 2;
                        continue;
                    }
                    i += 1;
                    break;
                }
                s.push(c[i]);
                i += 1;
            }
            out.push(Tok::Str(s));
            continue;
        }
        if ch.is_ascii_digit()
            || (ch == '-'
                && i + 1 < c.len()
                && c[i + 1].is_ascii_digit()
                && prev_allows_number(&out))
        {
            let start = i;
            i += 1;
            while i < c.len() && (c[i].is_ascii_alphanumeric() || c[i] == '.') {
                i += 1;
            }
            let text: String = c[start..i].iter().collect();
            let n = if let Some(hex) = text.strip_prefix("0x") {
                i64::from_str_radix(hex, 16).map(|v| v as f64).ok()
            } else {
                text.parse::<f64>().ok()
            };
            match n {
                Some(n) => out.push(Tok::Num(n)),
                None => bail!("bad number `{text}` in `{src}`"),
            }
            continue;
        }
        if ch.is_alphabetic() || ch == '_' {
            let start = i;
            while i < c.len() && (c[i].is_alphanumeric() || c[i] == '_' || c[i] == '-') {
                i += 1;
            }
            out.push(Tok::Ident(c[start..i].iter().collect()));
            continue;
        }
        let two: String = c[i..(i + 2).min(c.len())].iter().collect();
        let op2 = ["==", "!=", "<=", ">=", "&&", "||"]
            .into_iter()
            .find(|o| *o == two);
        if let Some(o) = op2 {
            out.push(Tok::Op(o));
            i += 2;
            continue;
        }
        let op1 = ["!", "<", ">", "(", ")", "[", "]", ".", ",", "*"]
            .into_iter()
            .find(|o| o.starts_with(ch));
        match op1 {
            Some(o) => {
                out.push(Tok::Op(o));
                i += 1;
            }
            None => bail!("unexpected `{ch}` in `{src}`"),
        }
    }
    Ok(out)
}

fn prev_allows_number(out: &[Tok]) -> bool {
    !matches!(
        out.last(),
        Some(Tok::Num(_))
            | Some(Tok::Str(_))
            | Some(Tok::Ident(_))
            | Some(Tok::Op(")"))
            | Some(Tok::Op("]"))
    )
}

#[derive(Debug, Clone)]
enum Ast {
    Lit(Value),
    Ctx(String),
    Prop(Box<Ast>, Box<Ast>),
    Star(Box<Ast>),
    Call(String, Vec<Ast>),
    Not(Box<Ast>),
    Bin(&'static str, Box<Ast>, Box<Ast>),
}

struct Parser<'s> {
    toks: Vec<Tok>,
    pos: usize,
    src: &'s str,
}

impl Parser<'_> {
    fn peek(&self) -> Option<&Tok> {
        self.toks.get(self.pos)
    }
    fn eat_op(&mut self, op: &str) -> bool {
        if let Some(Tok::Op(o)) = self.peek() {
            if *o == op {
                self.pos += 1;
                return true;
            }
        }
        false
    }
    fn expect_op(&mut self, op: &str) -> Result<()> {
        if !self.eat_op(op) {
            bail!("expected `{op}` in `{}`", self.src);
        }
        Ok(())
    }
    fn binary(&mut self, level: usize) -> Result<Ast> {
        const LEVELS: [&[&str]; 4] = [&["||"], &["&&"], &["==", "!="], &["<", "<=", ">", ">="]];
        if level == LEVELS.len() {
            return self.unary();
        }
        let mut lhs = self.binary(level + 1)?;
        loop {
            let op = match self.peek() {
                Some(Tok::Op(o)) if LEVELS[level].contains(o) => *o,
                _ => break,
            };
            self.pos += 1;
            let rhs = self.binary(level + 1)?;
            lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs));
        }
        Ok(lhs)
    }
    fn unary(&mut self) -> Result<Ast> {
        if self.eat_op("!") {
            return Ok(Ast::Not(Box::new(self.unary()?)));
        }
        self.postfix()
    }
    fn postfix(&mut self) -> Result<Ast> {
        let mut e = self.primary()?;
        loop {
            if self.eat_op(".") {
                match self.toks.get(self.pos).cloned() {
                    Some(Tok::Ident(name)) => {
                        self.pos += 1;
                        e = Ast::Prop(Box::new(e), Box::new(Ast::Lit(Value::String(name))));
                    }
                    Some(Tok::Op("*")) => {
                        self.pos += 1;
                        e = Ast::Star(Box::new(e));
                    }
                    _ => bail!("expected a property name after `.` in `{}`", self.src),
                }
            } else if self.eat_op("[") {
                if self.eat_op("*") {
                    self.expect_op("]")?;
                    e = Ast::Star(Box::new(e));
                } else {
                    let idx = self.binary(0)?;
                    self.expect_op("]")?;
                    e = Ast::Prop(Box::new(e), Box::new(idx));
                }
            } else {
                break;
            }
        }
        Ok(e)
    }
    fn primary(&mut self) -> Result<Ast> {
        let t = self.toks.get(self.pos).cloned();
        self.pos += 1;
        match t {
            Some(Tok::Num(n)) => Ok(Ast::Lit(num(n))),
            Some(Tok::Str(s)) => Ok(Ast::Lit(Value::String(s))),
            Some(Tok::Ident(id)) => match id.as_str() {
                "true" => Ok(Ast::Lit(Value::Bool(true))),
                "false" => Ok(Ast::Lit(Value::Bool(false))),
                "null" => Ok(Ast::Lit(Value::Null)),
                _ => {
                    if self.eat_op("(") {
                        let mut args = Vec::new();
                        if !self.eat_op(")") {
                            loop {
                                args.push(self.binary(0)?);
                                if self.eat_op(")") {
                                    break;
                                }
                                self.expect_op(",")?;
                            }
                        }
                        Ok(Ast::Call(id.to_ascii_lowercase(), args))
                    } else {
                        Ok(Ast::Ctx(id))
                    }
                }
            },
            Some(Tok::Op("(")) => {
                let e = self.binary(0)?;
                self.expect_op(")")?;
                Ok(e)
            }
            _ => bail!("unexpected end or token in `{}`", self.src),
        }
    }
}

fn parse(src: &str) -> Result<Ast> {
    let mut p = Parser {
        toks: lex(src)?,
        pos: 0,
        src,
    };
    let e = p.binary(0)?;
    if p.pos != p.toks.len() {
        bail!("trailing tokens in `{src}`");
    }
    Ok(e)
}

fn num(n: f64) -> Value {
    if n.fract() == 0.0 && n.abs() < 9e15 {
        Value::from(n as i64)
    } else {
        serde_json::Number::from_f64(n)
            .map(Value::Number)
            .unwrap_or(Value::Null)
    }
}

pub fn truthy(v: &Value) -> bool {
    match v {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(n) => n.as_f64().map(|f| f != 0.0 && !f.is_nan()).unwrap_or(false),
        Value::String(s) => !s.is_empty(),
        _ => true,
    }
}

fn to_num(v: &Value) -> f64 {
    match v {
        Value::Null => 0.0,
        Value::Bool(b) => *b as i32 as f64,
        Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
        Value::String(s) => {
            let t = s.trim();
            if t.is_empty() {
                0.0
            } else if let Some(h) = t.strip_prefix("0x") {
                i64::from_str_radix(h, 16)
                    .map(|v| v as f64)
                    .unwrap_or(f64::NAN)
            } else {
                t.parse().unwrap_or(f64::NAN)
            }
        }
        _ => f64::NAN,
    }
}

/// GitHub's loose equality: same type compares directly (strings ignore case),
/// different primitive types compare as numbers, objects/arrays by identity
/// (here: never equal unless both are the same JSON).
fn loose_eq(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::String(x), Value::String(y)) => x.eq_ignore_ascii_case(y),
        (Value::Array(_), _)
        | (Value::Object(_), _)
        | (_, Value::Array(_))
        | (_, Value::Object(_)) => a == b,
        _ if std::mem::discriminant(a) == std::mem::discriminant(b) => a == b,
        _ => to_num(a) == to_num(b),
    }
}

fn cmp(op: &str, a: &Value, b: &Value) -> bool {
    if let (Value::String(x), Value::String(y)) = (a, b) {
        let (x, y) = (x.to_ascii_lowercase(), y.to_ascii_lowercase());
        return match op {
            "<" => x < y,
            "<=" => x <= y,
            ">" => x > y,
            _ => x >= y,
        };
    }
    let (x, y) = (to_num(a), to_num(b));
    match op {
        "<" => x < y,
        "<=" => x <= y,
        ">" => x > y,
        _ => x >= y,
    }
}

pub fn to_string(v: &Value) -> String {
    match v {
        Value::Null => String::new(),
        Value::String(s) => s.clone(),
        Value::Bool(b) => b.to_string(),
        Value::Number(n) => n.to_string(),
        other => serde_json::to_string_pretty(other).unwrap_or_default(),
    }
}

fn get_prop(base: &Value, key: &Value) -> Value {
    match base {
        Value::Object(m) => {
            let k = to_string(key);
            m.iter()
                .find(|(name, _)| name.eq_ignore_ascii_case(&k))
                .map(|(_, v)| v.clone())
                .unwrap_or(Value::Null)
        }
        Value::Array(a) => {
            if let Value::Number(_) = key {
                let i = to_num(key);
                if i >= 0.0 {
                    return a.get(i as usize).cloned().unwrap_or(Value::Null);
                }
                return Value::Null;
            }
            // property of a filtered array (`foo.*.bar`) maps over the elements
            Value::Array(
                a.iter()
                    .map(|e| get_prop(e, key))
                    .filter(|v| !v.is_null())
                    .collect(),
            )
        }
        _ => Value::Null,
    }
}

fn eval(ast: &Ast, ctx: &Ctx) -> Result<Value> {
    Ok(match ast {
        Ast::Lit(v) => v.clone(),
        Ast::Ctx(name) => {
            let lower = name.to_ascii_lowercase();
            if lower == "secrets" {
                ctx.used_secrets.set(true);
                return Ok(Value::Object(Map::new()));
            }
            match ctx.contexts.get(&lower) {
                Some(v) => v.clone(),
                None => bail!("unsupported context `{name}`"),
            }
        }
        Ast::Prop(b, k) => {
            let base = eval(b, ctx)?;
            let key = eval(k, ctx)?;
            // `github.token` is a credential, like `secrets.GITHUB_TOKEN`
            if matches!(b.as_ref(), Ast::Ctx(n) if n.eq_ignore_ascii_case("github"))
                && to_string(&key).eq_ignore_ascii_case("token")
            {
                ctx.used_secrets.set(true);
            }
            get_prop(&base, &key)
        }
        Ast::Star(b) => match eval(b, ctx)? {
            Value::Object(m) => Value::Array(m.values().cloned().collect()),
            Value::Array(a) => Value::Array(a),
            _ => Value::Array(vec![]),
        },
        Ast::Not(e) => Value::Bool(!truthy(&eval(e, ctx)?)),
        Ast::Bin(op, l, r) => {
            let lv = eval(l, ctx)?;
            match *op {
                "&&" => {
                    if !truthy(&lv) {
                        lv
                    } else {
                        eval(r, ctx)?
                    }
                }
                "||" => {
                    if truthy(&lv) {
                        lv
                    } else {
                        eval(r, ctx)?
                    }
                }
                "==" => Value::Bool(loose_eq(&lv, &eval(r, ctx)?)),
                "!=" => Value::Bool(!loose_eq(&lv, &eval(r, ctx)?)),
                o => Value::Bool(cmp(o, &lv, &eval(r, ctx)?)),
            }
        }
        Ast::Call(name, args) => call(name, args, ctx)?,
    })
}

fn call(name: &str, args: &[Ast], ctx: &Ctx) -> Result<Value> {
    let a: Vec<Value> = args.iter().map(|e| eval(e, ctx)).collect::<Result<_>>()?;
    let s = |i: usize| a.get(i).map(to_string).unwrap_or_default();
    Ok(match name {
        "success" => Value::Bool(ctx.status == Status::Success),
        "failure" => Value::Bool(ctx.status == Status::Failure),
        "cancelled" => Value::Bool(ctx.status == Status::Cancelled),
        "always" => Value::Bool(true),
        // Cache keys only; every cache step is skipped locally.
        "hashfiles" => Value::String(String::new()),
        "contains" => match a.first() {
            Some(Value::Array(items)) => Value::Bool(
                items
                    .iter()
                    .any(|i| loose_eq(i, a.get(1).unwrap_or(&Value::Null))),
            ),
            _ => Value::Bool(s(0).to_lowercase().contains(&s(1).to_lowercase())),
        },
        "startswith" => Value::Bool(s(0).to_lowercase().starts_with(&s(1).to_lowercase())),
        "endswith" => Value::Bool(s(0).to_lowercase().ends_with(&s(1).to_lowercase())),
        "format" => {
            let mut out = s(0);
            for i in 1..a.len() {
                out = out.replace(&format!("{{{}}}", i - 1), &s(i));
            }
            Value::String(out.replace("{{", "{").replace("}}", "}"))
        }
        "join" => {
            let sep = if a.len() > 1 { s(1) } else { ",".into() };
            match a.first() {
                Some(Value::Array(items)) => {
                    Value::String(items.iter().map(to_string).collect::<Vec<_>>().join(&sep))
                }
                _ => Value::String(s(0)),
            }
        }
        "tojson" => Value::String(serde_json::to_string_pretty(
            a.first().unwrap_or(&Value::Null),
        )?),
        "fromjson" => serde_json::from_str(&s(0)).map_err(|e| anyhow::anyhow!("fromJSON: {e}"))?,
        other => bail!("unsupported function `{other}()`"),
    })
}

/// Evaluate a bare expression (the inside of `${{ }}`).
pub fn evaluate(src: &str, ctx: &Ctx) -> Result<Value> {
    eval(&parse(src)?, ctx)
}

/// Replace every `${{ expr }}` in `s`.
pub fn interpolate(s: &str, ctx: &Ctx) -> Result<String> {
    let mut out = String::new();
    let mut rest = s;
    while let Some(start) = rest.find("${{") {
        out.push_str(&rest[..start]);
        let after = &rest[start + 3..];
        let end =
            find_close(after).ok_or_else(|| anyhow::anyhow!("unterminated `${{{{` in `{s}`"))?;
        out.push_str(&to_string(&evaluate(&after[..end], ctx)?));
        rest = &after[end + 2..];
    }
    out.push_str(rest);
    Ok(out)
}

/// Like `interpolate`, but a string that is exactly one `${{ expr }}` keeps the
/// expression's type (needed for `strategy.matrix: ${{ fromJSON(...) }}`).
pub fn interpolate_value(s: &str, ctx: &Ctx) -> Result<Value> {
    let t = s.trim();
    if let Some(inner) = t.strip_prefix("${{").and_then(|r| r.strip_suffix("}}")) {
        if !inner.contains("${{") && find_close(inner).is_none() {
            return evaluate(inner, ctx);
        }
    }
    Ok(Value::String(interpolate(s, ctx)?))
}

/// Find the `}}` that closes an expression, skipping over quoted strings.
fn find_close(s: &str) -> Option<usize> {
    let b = s.as_bytes();
    let mut i = 0;
    let mut in_str = false;
    while i < b.len() {
        if in_str {
            if b[i] == b'\'' {
                if i + 1 < b.len() && b[i + 1] == b'\'' {
                    i += 2;
                    continue;
                }
                in_str = false;
            }
        } else if b[i] == b'\'' {
            in_str = true;
        } else if b[i] == b'}' && i + 1 < b.len() && b[i + 1] == b'}' {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Does an `if:` condition call a status function? If not, GitHub wraps it in `success() && (...)`.
fn has_status_fn(src: &str) -> bool {
    let l = src.to_ascii_lowercase();
    ["success(", "failure(", "always(", "cancelled("]
        .iter()
        .any(|f| l.contains(f))
}

/// Evaluate an `if:` value (with or without `${{ }}`); `None` means the default `success()`.
pub fn condition(raw: Option<&str>, ctx: &Ctx) -> Result<bool> {
    let raw = match raw {
        None => return Ok(ctx.status == Status::Success),
        Some(r) => r.trim(),
    };
    let inner = match raw.strip_prefix("${{").and_then(|r| r.strip_suffix("}}")) {
        Some(i) if find_close(i).is_none() => i.trim().to_string(),
        _ if raw.contains("${{") => interpolate(raw, ctx)?,
        _ => raw.to_string(),
    };
    if inner.is_empty() {
        return Ok(ctx.status == Status::Success);
    }
    let v = truthy(&evaluate(&inner, ctx)?);
    if has_status_fn(&inner) {
        Ok(v)
    } else {
        Ok(ctx.status == Status::Success && v)
    }
}

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

    fn ctx_map() -> Map<String, Value> {
        let v = json!({
            "github": {"event_name": "pull_request", "event": {"pull_request": {"draft": false}}, "sha": "abc"},
            "matrix": {"type": "e2e", "port": 33306, "check_generated": true, "shard": "1/2"},
            "steps": {"prepare": {"outcome": "success"}},
            "env": {"node-version": "22.1.0"},
            "needs": {"list": {"outputs": {"shards": "{\"project\":[\"a\",\"b\"]}"}}}
        });
        v.as_object().unwrap().clone()
    }

    #[test]
    fn job_level_draft_check() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        assert!(condition(Some("github.event.pull_request.draft == false"), &c).unwrap());
        assert!(condition(Some("${{ github.event_name == 'pull_request' }}"), &c).unwrap());
    }

    #[test]
    fn status_functions_and_steps() {
        let m = ctx_map();
        let failed = Ctx::new(&m, Status::Failure);
        assert!(condition(
            Some("${{ !cancelled() && steps.prepare.outcome == 'success' }}"),
            &failed
        )
        .unwrap());
        assert!(!condition(Some("matrix.type == 'e2e'"), &failed).unwrap());
        assert!(condition(Some("always()"), &failed).unwrap());
        assert!(!condition(None, &failed).unwrap());
    }

    #[test]
    fn matrix_bools_and_numbers() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        assert!(condition(Some("${{ matrix.check_generated }}"), &c).unwrap());
        assert_eq!(
            interpolate("DB_PORT=${{ matrix.port }} x", &c).unwrap(),
            "DB_PORT=33306 x"
        );
        assert_eq!(
            interpolate("${{ env.node-version }}", &c).unwrap(),
            "22.1.0"
        );
        assert!(condition(Some("matrix.type == 'E2E'"), &c).unwrap());
    }

    #[test]
    fn from_json_keeps_type() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        let v = interpolate_value("${{ fromJSON(needs.list.outputs.shards) }}", &c).unwrap();
        assert_eq!(v, json!({"project": ["a", "b"]}));
    }

    #[test]
    fn functions_and_operators() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        let t = |s: &str| truthy(&evaluate(s, &c).unwrap());
        assert!(t("contains('Hello', 'ell')"));
        assert!(t("contains(fromJSON('[\"a\",\"b\"]'), 'b')"));
        assert!(t("startsWith('refs/heads/x', 'refs/')"));
        assert!(t("format('{0}-{1}', 'a', 1) == 'a-1'"));
        assert!(t("1 < 2 && '' == 0 && null == 0"));
        assert!(!t("'a' && ''"));
        assert_eq!(
            interpolate("${{ github.head_ref || 'main' }}", &c).unwrap(),
            "main"
        );
        assert_eq!(interpolate("k-${{ hashFiles('a/**') }}", &c).unwrap(), "k-");
    }

    #[test]
    fn unknown_things_are_errors() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        assert!(evaluate("nope.x", &c).is_err());
        assert!(evaluate("frob(1)", &c).is_err());
        assert!(evaluate("1 +", &c).is_err());
    }

    #[test]
    fn secrets_are_flagged() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        assert_eq!(interpolate("${{ secrets.TOKEN }}", &c).unwrap(), "");
        assert!(c.used_secrets.get());
        let c = Ctx::new(&m, Status::Success);
        interpolate("${{ github.token }}", &c).unwrap();
        assert!(c.used_secrets.get());
        let c = Ctx::new(&m, Status::Success);
        interpolate("${{ github.sha }}", &c).unwrap();
        assert!(!c.used_secrets.get());
    }

    #[test]
    fn strings_with_braces() {
        let m = ctx_map();
        let c = Ctx::new(&m, Status::Success);
        assert_eq!(interpolate("${{ format('{{x}}') }}", &c).unwrap(), "{x}");
    }
}