Categories
Code Quality

How to use semantic release

We have a wordpress-theme and we want to use @semantic-release package to build versions of it using a Gitlab CI/CD, after creating the release we want to push the new version to the composer registry within Gitlab

Install Dependencies

npm i @semantic-release/changelog \
	@semantic-release/commit-analyzer \
	@semantic-release/exec \
	@semantic-release/git \
	@semantic-release/npm \
	@semantic-release/release-notes-generator \
        @semantic-release/gitlab

Note: Change @semantic-release/gitlab with @semantic-release/github when necessary

Configure your .gitlab-ci.yml

stages:
  - release
  - deploy

release:
  image: node:12-buster-slim
  stage: release
  variables:
    GITLAB_TOKEN: $GITLAB_TOKEN
  before_script:
    - apt-get update && apt-get install -y --no-install-recommends git-core ca-certificates
  script:
    - npm ci && npx semantic-release
  only:
    refs:
      - master
      - beta
      - alpha
    variables:
      - $CI_COMMIT_MESSAGE !~ /skip release/

deploy:
  stage: deploy
  only:
    - tags
  script:
    - 'curl --header "Job-Token: $CI_JOB_TOKEN" --data tag=$CI_COMMIT_TAG "https://gitlab.com/api/v4/projects/$CI_PROJECT_ID/packages/composer"'

We need to create a configuration file

// release.config.js
module.exports = {
    "plugins": [
        "@semantic-release/commit-analyzer",
        "@semantic-release/release-notes-generator",
        "@semantic-release/changelog",
        ["@semantic-release/npm", {
            "tarballDir": "release",
            "npmPublish": false
        }],
        ["@semantic-release/exec", {
            "prepareCmd": "bash scripts/release.sh ${nextRelease.version}",
        }],
        "@semantic-release/gitlab",
        ["@semantic-release/git", {
            "assets": ["CHANGELOG.md", "package-lock.json", "package.json", "style.css"],
            "message": "chore(release): ${nextRelease.version} [skip release]\n\n${nextRelease.notes}"
        }]
    ],
    "preset": "angular",
    "tagFormat": "${version}"
}

And create a release.sh file that will be executed to change the version in your custom files

# scripts/release.sh

export PATH="./node_modules/.bin:$PATH"

TO="Version:        "
VER=$1
TO_VER="$TO$VER"
sed -i "s/Version:\(.*\)/$TO_VER/" "style.css"