# Expressions and variables

> The ${{ }} expression language, its contexts and functions, and the environment variables every job gets.
> **Available** in repositories branchd reads pipeline files for. It is switching repositories on one at a time: until yours is, it keeps running its `.forge-ci.yaml` or `.xeonr-ci.yaml`. See [What is available](https://docs.branchd.run/branchd/pipelines#what-is-available).

## Where expressions go

- **`if:`** is one expression, with or without `${{ }}` around it.
- **`${{ … }}` inside any string** substitutes its value: in `env:`, `image:`,
  `run:`, `with:`, `services:`, `environment:`, `concurrency:`, cache keys,
  `outputs:` and the rest.
- **Decided when the run is compiled**, from branchd's facts, so
  `branchd ci plan` gives the reason each job is in or out. Only outputs
  (`steps.*`, `needs.*`) wait until the job runs, and those are allowed only
  in `run:`, `env:`, `image:`, `with:` and a job's `outputs:`, never in `if:`.

## Syntax

|              |                                                                                                                                                |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Literals     | `'text'` (a quote inside is `''`), numbers, `true`, `false`, `null`                                                                            |
| Comparison   | `==`, `!=`, `<`, `<=`, `>`, `>=`. Strings compare case-sensitively; anything compared with a number or a boolean is compared as a number.      |
| Logic        | `!`, `&&`, `\|\|`, parentheses. `&&` and `\|\|` short-circuit and return one operand, so `branch == 'main' && 'prod' \|\| 'stage'` is a value. |
| False values | `false`, `null`, `0` and `''`                                                                                                                  |
| Nesting      | Parentheses, `!` and calls nest at most 64 deep.                                                                                               |

## Contexts

| Context                               | Value                                                                                  |
| ------------------------------------- | -------------------------------------------------------------------------------------- |
| `branch`                              | The branch pushed; for a pull request, its source branch. `''` for a tag.              |
| `tag`                                 | The tag pushed, else `''`.                                                             |
| `event`                               | `push`, `pull_request`, `schedule`, `manual` or `trigger`.                             |
| `sha`                                 | The commit.                                                                            |
| `ref`                                 | The full ref, `refs/heads/main` or `refs/tags/v1.0.0`.                                 |
| `repository`                          | The repository's path, `<team>/<group>/<name>`.                                        |
| `default_branch`                      | The repository's default branch.                                                       |
| `protected`                           | Whether the ref is protected.                                                          |
| `pr.number`, `pr.source`, `pr.target` | The pull request's number, source and target branches; `null` outside a pull request.  |
| `inputs.<name>`                       | An input of `on: manual`, `on: trigger` or `on: call`.                                 |
| `matrix.<key>`                        | The cell's value; `''` for a key this cell has no value for.                           |
| `vars.<NAME>`                         | A settings variable of the repository or its groups.                                   |
| `env.<NAME>`                          | The file's, job's and step's `env:`, as written. `NAME` must be a shell variable name. |
| `steps.<id>.outputs.<name>`           | A step's output, known while the job runs.                                             |
| `needs.<job>.outputs.<name>`          | A needed job's output, known while the job runs. The job must be in `needs`.           |
| `jobs.<id>.outputs.<name>`            | Only in `on.call.outputs`: a job of the called pipeline.                               |

## Functions

| Function                             | True when                                                                                                                                                                    |
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `changed('glob', …)`                 | Any changed path matches any glob. A new branch, a tag, or a push with more changes than branchd lists counts as everything changed.                                         |
| `exists('glob', …)`                  | A file of the commit matches, at any depth (`exists('src/**/*.go')`). Same globs as `changed()`.                                                                             |
| `contains(a, b)`                     | `a` contains `b`.                                                                                                                                                            |
| `startsWith(a, b)`, `endsWith(a, b)` | `a` starts or ends with `b`.                                                                                                                                                 |
| `always()`                           | Always. In a job's `if:`, the job runs even after a failed need; in a step's, after a failed step.                                                                           |
| `success()`                          | Nothing has failed.                                                                                                                                                          |
| `failure()`                          | In a step's `if:` only: an earlier step failed.                                                                                                                              |
| `cancelled()`                        | In a step's `if:` only: the job was cancelled. Such a step, and an `always()` one, runs after a cancel; see [Cancelled jobs](https://docs.branchd.run/branchd/pipelines/expressions#cancelled-jobs). |

Globs: `*` within one path segment, `**` across segments, `?`, `[…]`,
`{a,b}`, and a leading `!` to exclude; the last pattern that matches
decides. A file uses at most 1,000 different globs.

## In a run: script

`${{ }}` in a `run:` is never pasted into the script. Each expression becomes
an environment variable of the job, and the script reads it:

- `${{ inputs.version }}` is `${BRANCHD_INPUTS_VERSION}`; another expression is
  `${BRANCHD_EXPR_<n>}`; `${{ env.X }}` is `${X}`.
- So it expands where the shell expands variables, and not inside single
  quotes: write `echo "${{ inputs.version }}"`, not
  `echo '${{ inputs.version }}'`.
- A value that would hold `${{` is refused.

## $NAME in values

In `env:`, `image:`, `with:` and other values, `$NAME` of a variable known
when the run is compiled (the `CI_*` variables below, and `env:`) expands,
and `$$` is a literal `$`. In `run:`, the shell expands `$NAME` as usual.

## Variables every job gets

| Variable                                                                                                          | Value                                                                                                    |
| ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `CI`                                                                                                              | `true`                                                                                                   |
| `CI_COMMIT_SHA`, `CI_COMMIT_SHORT_SHA`                                                                            | The commit.                                                                                              |
| `CI_COMMIT_BEFORE_SHA`                                                                                            | The previous head of the branch, else forty zeros.                                                       |
| `CI_COMMIT_REF_NAME`, `CI_COMMIT_REF_SLUG`                                                                        | The branch or tag, and a lower-case form safe in URLs and host names.                                    |
| `CI_COMMIT_BRANCH`                                                                                                | The branch (a pull request's source branch too).                                                         |
| `CI_COMMIT_TAG`                                                                                                   | The tag, for a tag.                                                                                      |
| `CI_COMMIT_REF_PROTECTED`                                                                                         | `true` or `false`.                                                                                       |
| `CI_DEFAULT_BRANCH`                                                                                               | The default branch.                                                                                      |
| `CI_PIPELINE_SOURCE`                                                                                              | What started the run.                                                                                    |
| `CI_PIPELINE_IID`                                                                                                 | The run's number in the repository.                                                                      |
| `CI_PROJECT_PATH`, `CI_PROJECT_PATH_SLUG`, `CI_PROJECT_NAME`, `CI_PROJECT_NAMESPACE`, `CI_PROJECT_ROOT_NAMESPACE` | The repository's path, its slug, its name, its group path and its team.                                  |
| `CI_SERVER_URL`, `CI_SERVER_HOST`, `CI_PROJECT_URL`                                                               | branchd's address and the repository's page.                                                             |
| `CI_REGISTRY`, `CI_REGISTRY_IMAGE`                                                                                | The registry, and this repository's image path in it.                                                    |
| `CI_MERGE_REQUEST_IID`, `CI_MERGE_REQUEST_SOURCE_BRANCH_NAME`, `CI_MERGE_REQUEST_TARGET_BRANCH_NAME`              | In a pull request's run.                                                                                 |
| `BRANCHD_OUTPUT`                                                                                                  | In each step: the file to write `name=value` outputs to.                                                 |
| `BRANCHD_TOKEN`, `BRANCHD_TOKEN_COMMAND`                                                                          | The job token, and a command that prints a fresh one. See [The job token](https://docs.branchd.run/branchd/pipelines/job-token). |
| `BRANCHD_API_URL`, `BRANCHD_REPOSITORY`, `BRANCHD_PR`                                                             | branchd's API; this repository's path; the pull request's number, in a pull request's run.               |
| `FORGE_REPOSITORY_URL`                                                                                            | This repository's HTTPS URL as the runner reaches it, with no credential; the checkout's `origin`.       |
| `FORGE_SHA`, `FORGE_RUN_NUMBER`                                                                                   | The commit and the run's number.                                                                         |

There is no `CI_JOB_STAGE`: there are no stages.

## if: on outputs

An `if:` may read outputs, which are known only while the run runs:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
on: push
jobs:
  api:
    image: alpine:3.20
    outputs:
      changed: ${{ steps.changes.outputs.api }}
    steps:
      - id: changes
        run: echo "api=$(git diff --quiet HEAD~1 -- api || echo true)" >> "$BRANCHD_OUTPUT"
      - if: steps.changes.outputs.api == 'true' && branch == 'main'
        run: make build-api
  deploy:
    needs: [api]
    if: needs.api.outputs.changed == 'true'
    image: alpine:3.20
    steps:
      - run: make deploy-api
```

- **A step's `if:`** may read `steps.<id>.outputs.<name>` of an earlier step
  and `needs.<job>.outputs.<name>` of a needed job. It is decided when the
  step's turn comes; the log says when a step is skipped.
- **A job's `if:`** may read `needs.<job>.outputs.<name>`. It is decided when
  the jobs it needs have run. A job whose `if:` is false then is **skipped**,
  and so are the jobs that need it (unless they use `always()`). A manual
  job's `if:` cannot read outputs.
- **What is decided first.** The parts known when the run is compiled are
  decided then: off `main`, `branch == 'main' && …` is false, and the step or
  job never runs.
- **What reads an output.** An output is a string. `==` and `!=` against a
  string (`'true'`) or another output, `contains`, `startsWith` and
  `endsWith` with a string, the output on its own (true when not empty: as
  on GitHub, `'false'` is true), and `!`, `&&`, `||` over these. `<`, `>`,
  `== true` (write `== 'true'`) and other functions of an output are refused.
- **An output never set** reads as `''`. An output's value is never run as
  shell code.

## Cancelled jobs

When a job is cancelled (its run cancelled or superseded, or a fail-fast
matrix stopping it), its steps with `if: always()` or `if: cancelled()` still
run, as GitLab's `after_script` does: after the cancel, in a fresh shell, with
up to 30 seconds by default. Each runs in its own subshell, with its `env:` and
`working-directory:`, in the job's working directory; a failure is reported
and the next one runs. They do not see earlier steps' outputs or what the
script exported, and a step whose `if:` reads an output does not run after a
cancel. `failure()` steps do not run after a cancel. This is how a host job
removes its temporary files when it is stopped:

```yaml title=".branchd/pipelines/ci.yaml"
# .branchd/pipelines/ci.yaml
on: push
jobs:
  ios:
    host: true
    runs-on: [macos]
    steps:
      - run: eas build --local --platform ios
      - if: always()
        run: rm -rf "$TMPDIR/eas-build"
```

Source: https://docs.branchd.run/branchd/pipelines/expressions
