How can I set github action job output using conditional logic in my step?

Viewed 23

I have a simple job in my yaml that figures out the branch name, and sets it as an output

The problem that I've noticed, is that if I push a branch, then I need to read from github.event.ref. But if I push a tag, then I need to read from github.event_base_ref instead.

The code below is my best take (and it works), but I'm wondering if there's a way to simplify it so that the output is set conditionally in a single step.

setup:
      name: Setup variables
      runs-on: ubuntu-latest
      if: github.event_name == 'push'
      outputs:
        stackName: ${{steps.step3.outputs.branch}}
      steps:
        - uses: actions/checkout@v2

        - id: step1
          name: Is branch push?
          # this is the default. It assigns the branch variable to the github env
          run: |
            echo "${{ github.event.ref }}"
            raw="${{ github.event.ref }}"
            branch=$(echo ${raw/refs\/heads\/} | tr -cd '[a-zA-Z0-9-]')
            echo "Branch name is $branch."
            echo "branch=$branch" >> $GITHUB_ENV

        - id: step2
          name: Is tag push?
          # this runs conditionally.
          if: startsWith(github.ref, 'refs/tags/deploy')
          run: |
            echo "${{ github.event.base_ref }}"
            raw="${{ github.event.base_ref }}"
            branch=$(echo ${raw/refs\/heads\/} | tr -cd '[a-zA-Z0-9-]')
            echo "Branch name is $branch."
            echo "branch=$branch" >> $GITHUB_ENV

        - id: step3
          name: Set stack name
          # after both step 1 and 2 have run, see what's in the env and assign the output
          run: |
            echo "::set-output name=branch::${{env.branch}}"
1 Answers

You can use an existing action like EthanSK/git-branch-name-action, as example:

on: [push, pull_request]

jobs:
  main_job:
    runs-on: ubuntu-latest
    steps:
      - name: Git branch name
        id: git-branch-name
        uses: EthanSK/git-branch-name-action@v1
      - name: Echo the branch name
        run: echo "Branch name ${GIT_BRANCH_NAME}"

and use also like

if: ${{ env.GIT_BRANCH_NAME == 'master' }}

Link to the marketplace here

Related