GitHub Actions - How to trim a string in a condition?

Viewed 5536

How can I trim a string in a condition in GitHub actions workflow? In the following example, the comment can contains accidentally spaces and new lines. I want to trim the spaces in github.event.comment.body:

steps:
  - name: "Check CLA signed"
    if: github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA'
2 Answers

NOTE: Skip to the end for a better answer.

I believe GitHub Actions expressions are very limited to checking basic things in a workflow, rather than offering programming capabilities.

If you need to go the route of checking different ways of writing a message, your best option is to run a check against the string in a step:

steps:
  ...
  - name: Check if person has accepted and signed CLA
    shell: python
    run: |
      import sys

      def check_user_accepted_and_signed(text):
        """Some complex natural language processing will go here"""
      
      comment = '''${{ github.event.comment.body }}'''
      if not check_user_accepted_and_signed(comment):
        sys.exit(1)  # This will abort the job
  - name: Not accepted or signed
    if: ${{ failure() }}
    run: optionally do something if the check fails
  - name: Move on if the check passed
    run: ...

In the code above, you could also replace the inline Python snippet with a script call from your code base, for a cleaner code:

steps:
  - uses: actions/checkout@v3
  - name: Check if person has accepted and signed CLA
    run: ./scripts/check-accepted-signed-cla.sh '${{ toJSON(github.event.comment.body) }}'
    # Single quotes and JSON string prevents bad whitespace interpretation

Simpler is usually better

IMHO though, you'd be better off -- and safer! -- doing simple things. Here's an idea:

  1. Set up your GitHub repository with a default pull request body containing a checkbox, for example:
    Write your description.
    ---
    - [ ] I have read the CLA and hereby sign it.
    
  2. In your workflow, check for that checkbox and fail if it's not checked. Shopify/task-list-checker can be of great help here!

You can find all functions that github actions support here

I think you can use contains function for cover your case

Related