Invalid cache path on Windows runners

Take the following .gitlab-ci.yml as an example:

cache:
  key: "${CI_COMMIT_REF_SLUG}_${CI_JOB_NAME}"
  paths:
    - build/

build:app:
  tags:
    - windows
  script:
    - # run some build script

The cache path generated from the dynamic name is invalid on Windows. That is, because the $CI_JOB_NAME includes a colon (:), which is invalid as part of paths on Windows. This also applies to matrix jobs, because they will likely include square brackets [ (e.g. build:app ["node-lts"]).

Hence you will receive the following error:

FATAL: mkdir ..\..\..\..\..\cache\jdoubleu\my-project\main_build:app: The filename, directory name, or volume label syntax is incorrect.

The obvious solution would be to drop the usage of ${CI_JOB_NAME} in cache names. However, that is usually a good way to build a cache on a per-job basis. Instead I suggest to provide a CI_JOB_NAME_SLUG, similar to the CI_COMMIT_REF_SLUG variable, which is a sanitized version of its original.

According to the Microsoft documentation, the paths may or may not contain the following characters:

Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

  • The following reserved characters:
    • < (less than)
    • > (greater than)
    • : (colon)
    • " (double quote)
    • / (forward slash)
    • \ (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk)
  • Integer value zero, sometimes referred to as the ASCII NUL character.
  • Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
  • Any other character that the target file system does not allow.