Skip to content

Instantly share code, notes, and snippets.

@paulo-ferraz-oliveira
Last active January 8, 2024 18:42
Show Gist options
  • Save paulo-ferraz-oliveira/61e243a67186788c56f8e8ee7bfdb6d3 to your computer and use it in GitHub Desktop.
Save paulo-ferraz-oliveira/61e243a67186788c56f8e8ee7bfdb6d3 to your computer and use it in GitHub Desktop.
Read .tool-versions to GitHub env. and use it in between jobs

I recently made a cross-platform GitHub action out of this (using outputs instead of environment variables) Check it out at https://github.com/paulo-ferraz-oliveira/parse-tool-versions/.

The script

In e.g. .github/parse-tool-versions.sh, do:

#!/bin/bash

TOOL_VERSIONS=".tool-versions"
TOOLS=(erlang elixir)
echo "##[group] Parsing .tool-versions"
while read -r LINE; do
  for tool in "${TOOLS[@]}"; do
    LOWER=$tool # e.g. erlang
    UPPER=${LOWER^^} # e.g. ERLANG
    REGEX="^$LOWER ([^ #]+)" # e.g. erlang ([^ #]+)
    VARNAME=${UPPER}_VERSION
    if [[ $LINE =~ $REGEX ]]; then
      VERSION=$VARNAME # dynamic variable: e.g. ERLANG_VERSION
      declare "$VERSION"="${BASH_REMATCH[1]}" # e.g. ERLANG_VERSION=25.1.1
      echo "${LOWER^} version ($VARNAME) set to ${!VERSION}"
      echo "$VARNAME=${!VERSION}" >> "$GITHUB_ENV"
    fi
  done
done < $TOOL_VERSIONS
echo "##[endgroup]"

The YAML

In e.g. .github/workflows/ci.yml, do:

jobs:
  setup_env:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
      - name: Parse .tool-versions
        run: ./.github/parse-tool-versions.sh
    outputs:
      ERLANG_VERSION: ${{ env.ERLANG_VERSION }}
      ELIXIR_VERSION: ${{ env.ELIXIR_VERSION }}
  build:
    needs:
      - setup_env
    ... # Refer to outputs of previous job as ${{ needs.setup_env.outputs.ERLANG_VERSION }} and ${{ needs.setup_env.outputs.ELIXIR_VERSION }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment