How to replace string in expression with GitHub actions

Viewed 2990

This is my action that returns $TOXENV that looks like this py3.6-django2.2 I'd like to $TOXENV to look like this instead py36-django22 is there any substitute/replace function that I could use to replace . char?

name: CI
on:
  workflow_dispatch:
    branches: [ master, actions ]
jobs:
  demo:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python: [3.6, 3.7, 3.8, 3.9]
        django: ['2.2', '3.0']
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v1
        name: Set up Python ${{ matrix.python }} ${{ matrix.django }}
        with:
          python-version: ${{ matrix.python }}
      - name: python version
        env:
            TOXENV: "py${{ matrix.python }}-django${{ matrix.django }}"
        run:
          echo $TOXENV
2 Answers

I don't think there's an easy way to do this in the env directive of your step when defining the value of TOXENV. The env directive accepts expressions, but the functions that can be used in expressions are limited, with nothing that can replace arbitrary characters. The closest I could find is format(), but that unfortunately requires numbered braces in the target string, which won't work for your situation.

Instead, perhaps you could set the value of TOXENV in the run directive using sed, then add it to the environment:

      - name: python version
        run:
          RAW_TOXENV="py${{ matrix.python }}-django${{ matrix.django }}"
          TOXENV=$(echo $RAW_TOXENV | sed 's/\.//')
          echo "TOXENV=$TOXENV" >> $GITHUB_ENV

Another way by using BASH native variable substitution:

  - name: python version
    env:
        TOXENV: "py${{ matrix.python }}-django${{ matrix.django }}"
    run: |
      TOXENV=${{ env.TOXENV }}
      TOXENV=${TOXENV//.} # replace all dots
      echo TOXENV=${TOXENV} >> $GITHUB_ENV # update GitHub ENV vars
  - name: print env
    run: echo ${{ env.TOXENV }}

The idea is to read the GitHub actions expression variable into a BASH variable and do the string manipulation then export or set-output to update in GitHub actions runtime.

Related