'how to use escape sequences in strings in github actions expressions

the goal is to write a github actions expression to match "there is /command on a line by itself" -- as such a few edge cases need to be handled (exactly at the beginning, exactly at the end, and somewhere in the middle).

the github actions expressions provide a few helpful expressions -- notably contains(haystack, needle), format(fmt, var0, var1, ...)

using these I should be able to construct something like:

    if: contains(format('\r\n{0}\r\n', github.event.comment.body), '\r\n/command\r\n')

however this doesn't seem to work as expected -- it is always skipped unless the comment is exactly /command



Solution 1:[1]

it appears that github takes strings very literally!

this little demo:

- run: python3 -c 'print(os.environ["TEST"])'
  env:
    TEST: ${{ format('\r\n{0}\r\n', '/command') }}

produces the following output:

'\\r\\n/command\\r\\n'

the double backslashes being a literal \ when printed

fortunately there's a bit of hack you can do by utilizing fromJSON (which will process escape sequences)

using our little demo:

- run: python3 -c 'print(os.environ["TEST"])'
  env:
    TEST: ${{ format(fromJSON('"\r\n{0}\r\n"'), '/command') }}

(note that you have to have double-quotes embedded in the single quotes, we're parsing a json string)

now produces:

'\r\n/command\r\n'

success \o/

adapting that to the original question:

    if: contains(format(fromJSON('"\r\n{0}\r\n"'), github.event.comment.body), fromJSON('"\r\n/command\r\n"'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anthony Sottile