9

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
Lukasz Dynowski
  • 11,169
  • 9
  • 81
  • 124
  • 1
    You could use what is suggested here: https://stackoverflow.com/questions/2871181/replacing-some-characters-in-a-string-with-another-character on your `run` last step to substitute the `.` for something else. – GuiFalourd Apr 23 '21 at 14:24
  • Thanks. That is a general substitution with `sed` but is there any build in function for GitHub Actions ? – Lukasz Dynowski Apr 23 '21 at 15:53

2 Answers2

8

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
jidicula
  • 3,454
  • 1
  • 17
  • 38
  • 1
    I up vote the answer. It's a pity that for the moment (25 April 2021) functions doesn't include replace directive/function. Moving replace logic to run is at the moment only one solution. – Lukasz Dynowski Apr 25 '21 at 16:06
  • 4
    It's March 2022 and we still don't have a native string replace function available. – hui chen Mar 03 '22 at 08:49
8

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.

Seff
  • 1,546
  • 1
  • 17
  • 19