Use Semantic Commits to automate version generation in your PHP libraries πŸ˜πŸš€

Marcos Marcolin β€’ August 28, 2023 β€’ 2 min read

php conventional-commits semantic-versioning

Semantic Commits aren't just a way to keep a well-organized, documented history of your code (although that's fundamental), they can also trigger several essential automations.

One of the benefits, especially in the PHP context, is automatically generating tags or versions for projects, or libraries that can be installed via Composer, following the Semantic Versioning (SemVer) standard.

In CI/CD deploy processes, for example, you can automatically generate a new version of your library based on the commit that triggered the pipeline.

A few years ago, about three years back, I automated the version generation process for libraries we published on a Self Hosted GitLab. Before that, versions were released manually by each developer after a push, with commands like git tag -a v1.0.0 && git push origin v1.0.0, or similar.

To automate this process, I used the marcocesarato/php-conventional-changelog library, which can be easily installed with: composer require marcocesarato/php-conventional-changelog --dev.

Once installed, you need to create a Job in your pipeline so that, on every new push to the main branch, for example, a new version gets generated based on the semantic commit (like feat, fix, test, refactor, chore, etc.), following the Semantic Versioning standard.

For example, imagine you have a library at version 1.5.0 and make a commit with the message 'feat: add user authentication to API'. The next version automatically generated would be 1.6.0. If it were a fix commit, the generated version would be 1.5.1, and so on.

SemVer

You can also set up scripts in your composer.json file to make things easier to use in your jobs. A sample configuration:

{
...
    "scripts": {
      "changelog": "conventional-changelog",
      "release": "conventional-changelog --commit",
    },
    ...
}

In the job, you could simply run composer release, and the library would handle the release and version control. The same would apply if you just wanted to generate the changelog for the changes.

You can check out the result in this post's image, it's just an example and can be customized to fit your needs.

This approach is an excellent practice that can boost your team's productivity.

If you're interested in learning more and implementing this, you can find out more about:

  1. Semantic Commits: https://lnkd.in/dzGeMpS8
  2. Semantic Versioning: https://lnkd.in/d5JwzRbn
  3. marcocesarato/php-conventional-changelog: https://lnkd.in/dXxgnBxv
Share: