Anto Subash.

Table of contents

Introduction

In this post we will see how to automatically version and release a .Net Application using GitHub Actions. We will use the conventional commits specification to automatically version and release our application.

Conventional Commits

Conventional Commits is a specification for adding human and machine readable meaning to commit messages. It provides an easy set of rules for creating an explicit commit history; which makes it easier to write automated tools on top of. This convention dovetails with SemVer, by describing the features, fixes, and breaking changes made in commit messages. If you want to know more about conventional commits, please check this.

Libraries used

  • Versionize - To version the application
  • Husky.Net - To run git hooks in dotnet
  • Github Actions - To automatically release the application

Please note that we will use the Versionize library to version the application and Husky.Net to run git hooks in dotnet. These are amazing libraries and I highly recommend them. please check them out if you want to know more about them and give them a star. It will help the authors to keep working on them. I'm not affiliated with them in any way. I just like them and I'm using them in this post.

Versionize

Versionize is a library that can be used to version a .Net application. It uses the conventional commits specification to automatically version the application. It can also be used to automatically release the application. It can be used in any .Net application. It can be used in a console application, a web application, a web api, a library, etc. The current supported project types are: csproj, fsproj, vbproj. There is PR to support .props projects. hopefully, it will be merged soon.

Husky.Net

Husky.Net is a library that can be used to run git hooks in dotnet. It is a port of the famous Husky library. Husky is a library that can be used to run git hooks in nodejs. Husky.Net can be used to run git hooks in dotnet. It can be used in any .Net application.

Husky is not required for this but it is a nice to have. It will help us to keep the commit messages clean and consistent. If you don't want to use it you can skip this section. But I highly recommend it.

GitHub Actions

I think there is no need to explain what GitHub Actions is. If you don't know what GitHub Actions is, please check this.

Create the .Net project

Create a github repository

Create a github repository and clone it locally. You can use the following command to clone the repository.

1git clone "url of the repository"

Now, we will create a .Net project and add it to the repository.

Create the .Net project using this following command

Navigate to the your repository folder and run the following command to create a .Net project.

1dotnet new console -n VersionMe -o .

Now we have a .Net console application. We will use this application to test the versioning and releasing.

Add Version to the .Net project

To get started add version to you csproj file.

1    <Version>1.0.0</Version>

Now we can install the versionize tool.

1dotnet tool install --global Versionize

When you want to version the application, run the following command.

1versionize

This will version the application, create a tag for the release and generate a changelog. You can find the changelog in the CHANGELOG.md file. make sure you push the tag to the remote repository.

1git push --tags

For now we have versioned the application manually and tagged the release. we also have a changelog. but to create a release we need to do it manually. we need to use the GitHub UI. But we want to automate this process. We want to automatically create a release when we push a commit to the main branch. We will use GitHub Actions to do this.

Now lets automate this process using github actions.

Creating github action

We will create a github action to version and release the application. Create a new file in the .github/workflows folder and name it version-and-release.yml. In the version-and-release.yml file, add the following code.

1name: Version and Release
2
3on:
4  push:
5    branches: [ "main" ]
6
7jobs:
8  build:
9
10    runs-on: ubuntu-latest
11
12    steps:
13    - uses: actions/checkout@v3
14      with:
15        fetch-depth: 0
16    - name: Setup .NET
17      uses: actions/setup-dotnet@v3
18      with:
19        dotnet-version: 6.0.x
20    - name: Restore dependencies
21      run: dotnet restore
22    - name: Build
23      run: dotnet build --no-restore
24    - name: Install Versionize
25      run: dotnet tool install --global Versionize
26    - name: Setup git
27      run: |
28        git config --local user.email "antosubash@live.com"
29        git config --local user.name "Anto Subash"
30    - name: Versionize Release
31      id: versionize
32      run: versionize --changelog-all --exit-insignificant-commits
33      continue-on-error: true
34    - name: No release required
35      if: steps.versionize.outcome != 'success'
36      run: echo "Skipping Release. No release required."
37    - name: Push changes to GitHub
38      if: steps.versionize.outcome == 'success'
39      uses: ad-m/github-push-action@master
40      with:
41        github_token: ${{ secrets.GITHUB_TOKEN }}
42        branch: ${{ github.ref }}
43        tags: true
44    - name: "Create release"
45      if: steps.versionize.outcome == 'success'
46      uses: "actions/github-script@v5"
47      with:
48        github-token: "${{ secrets.GITHUB_TOKEN }}"
49        script: |
50          try {
51            const tags_url = context.payload.repository.tags_url + "?per_page=1"
52            const result = await github.request(tags_url)
53            const current_tag = result.data[0].name
54            await github.rest.repos.createRelease({
55              draft: false,
56              generate_release_notes: true,
57              name: current_tag,
58              owner: context.repo.owner,
59              prerelease: false,
60              repo: context.repo.repo,
61              tag_name: current_tag,
62            });
63          } catch (error) {
64            core.setFailed(error.message);
65          }

This will run when we push a commit to the main branch. It will version the application, create a tag for the release and generate a changelog. It will also create a release using the GitHub API. You can find the changelog in the CHANGELOG.md file.

If you are new to GitHub Actions, please check this to learn more about GitHub Actions. It will help you to understand the above code.

Here is a brief explanation of the above code.

1name: Version and Release

This is the name of the action.

1on:
2  push:
3    branches: [ "main" ]

This will run the action when we push a commit to the main branch.

1jobs:
2  build:
3    runs-on: ubuntu-latest

This is the job that will run. We are using ubuntu-latest as the operating system.

1- uses: actions/checkout@v3
2  with:
3    fetch-depth: 0

This will checkout the repository.

1- name: Setup .NET
2  uses: actions/setup-dotnet@v3
3  with:
4    dotnet-version: 6.0.x

This will setup the .Net environment.

1- name: Restore dependencies
2  run: dotnet restore

This will restore the dependencies.

1- name: Build
2  run: dotnet build --no-restore

This will build the application.

1- name: Install Versionize
2  run: dotnet tool install --global Versionize

This will install the versionize tool.

1- name: Setup git
2  run: |
3        git config --local user.email "antosubash@live.com"
4        git config --local user.name "Anto Subash"

This will setup the git user name and email.

1- name: Versionize Release
2  id: versionize
3  run: versionize --changelog-all --exit-insignificant-commits
4  continue-on-error: true

This will version the application, create a tag for the release and generate a changelog. You can find the changelog in the CHANGELOG.md file.

1- name: No release required
2  if: steps.versionize.outcome != 'success'
3  run: echo "Skipping Release. No release required."

This will check if the versionize command was successful. If it was successful, it will continue to the next step. If it was not successful, it will skip the release.

1- name: Push changes to GitHub
2  if: steps.versionize.outcome == 'success'
3  uses: ad-m/github-push-action@master
4  with:
5    github_token: ${{ secrets.GITHUB_TOKEN }}
6    branch: ${{ github.ref }}
7    tags: true

This will push the changes to the GitHub repository.

1- name: "Create release"
2  if: steps.versionize.outcome == 'success'
3  uses: "actions/github-script@v5"
4  with:
5    github-token: "${{ secrets.GITHUB_TOKEN }}"
6    script: |
7      try {
8        const tags_url = context.payload.repository.tags_url + "?per_page=1"
9        const result = await github.request(tags_url)
10        const current_tag = result.data[0].name
11        await github.rest.repos.createRelease({
12          draft: false,
13          generate_release_notes: true,
14          name: current_tag,
15          owner: context.repo.owner,
16          prerelease: false,
17          repo: context.repo.repo,
18          tag_name: current_tag,
19        });
20      } catch (error) {
21        core.setFailed(error.message);
22      }

This will create a release using the GitHub API.

Adding Husky.Net

We will use Husky.Net to lint the commit message. this will make the commit message follow the conventional commits standard.

As I said earlier, This is not required. But it is a nice to have. If you don't want to use it you can skip this section. But I highly recommend it.

Follow the steps here to add Husky.Net to your project. https://alirezanet.github.io/Husky.Net/guide/getting-started.html#installation

if you are new to git hooks, please check this https://githooks.com. It will help you to understand what git hooks are.

Add a pre-commit hook

We will add a pre-commit hook to lint the commit message. Husky.Net will run the pre-commit hook before the commit is made.

1dotnet husky add pre-commit

This will add a pre-commit hook to your project. You can find the hook in the .husky folder. In the pre-commit file, you can add the commands you want to run before the commit is made. In our case, we will run a group of command. This is a good example in case you want to run multiple commands before the commit is made.

1husky run -v --group "pre-commit"

Add commit-msg hook

We will add a commit msg hook to lint the commit message before the commit is made. Husky.Net will run the commit msg hook before the commit is made.

1dotnet husky add commit-msg

This will add a commit msg hook to your project. You can find the hook in the .husky folder. In the commit-msg file, you can add the commands you want to run before the commit is made. In our case, we will run commit-msg.

1husky run --name "commit-message-linter" --args "$1"
2echo
3echo Great work! 🥂
4echo

Add a commit message linter

We will add a commit message linter to lint the commit message. Husky.Net will run the commit message linter before the commit is made. Create a new folder in the .husky folder and name it csx (csx stands for C# script). In the csx folder, create a new file and name it commit-lint.csx. In the commit-lint.csx file, add the following code.

1using System.Text.RegularExpressions;
2
3private var pattern = @"^(?=.{1,90}$)(?:build|feat|ci|chore|docs|fix|perf|refactor|revert|style|test|wip)(?:\(.+\))*(?::).{4,}(?:#\d+)*(?<![\.\s])$";
4private var msg = File.ReadAllLines(Args[0])[0];
5
6if (Regex.IsMatch(msg, pattern))
7    return 0;
8
9Console.ForegroundColor = ConsoleColor.Red;
10Console.WriteLine("Invalid commit message");
11Console.ResetColor();
12Console.WriteLine("e.g: 'feat(scope): subject' or 'fix: subject'");
13Console.ForegroundColor = ConsoleColor.Gray;
14Console.WriteLine("more info: https://www.conventionalcommits.org/en/v1.0.0/");
15
16return 1;

Update the task runner

Now we have our hooks ready. We need to update the task runner to run the hooks. Open the task-runner.json file and update the tasks.

1{
2   "tasks": [
3     {
4       "name": "commit-message-linter",
5       "command": "husky",
6       "args": [
7         "exec",
8         ".husky/csx/commit-lint.csx",
9         "--args",
10         "${args}"
11       ]
12     },
13     {
14       "name": "dotnet-format",
15       "group": "pre-commit",
16       "command": "dotnet-format",
17       "args": ["--include", "${staged}"],
18       "include": ["**/*.cs"]
19     }
20   ]
21}

Commit and push

Now we are ready to commit and push our changes. Commit and push your changes. You can find the commit message linter in action.

if you followed the steps correctly, you should see the following output when you didn't follow the conventional commits standard.

1[Husky] 🚀 Loading tasks ...
2--------------------------------------------------
3--------------------------------------------------
4[Husky] ⚡ Preparing task 'dotnet-format'
5[Husky] 💤 Skipped, no matched files
6--------------------------------------------------
7[Husky] 🚀 Loading tasks ...
8--------------------------------------------------
9[Husky] ⚡ Preparing task 'commit-message-linter'
10[Husky] ⌛ Executing task 'commit-message-linter' ...
11Invalid commit message
12e.g: 'feat(scope): subject' or 'fix: subject'
13More info: https://www.conventionalcommits.org/en/v1.0.0/
14script execution failed
15
16  ❌ Task 'commit-message-linter' failed in 2.445ms
17
18husky - commit-msg hook exited with code 1 (error)

if you commit message is valid, you should see the following output.

1[Husky] 🚀 Loading tasks ...
2--------------------------------------------------
3[Husky] ⚡ Preparing task 'dotnet-format'
4[Husky] 💤 Skipped, no matched files
5--------------------------------------------------
6[Husky] 🚀 Loading tasks ...
7--------------------------------------------------
8[Husky] ⚡ Preparing task 'commit-message-linter'
9[Husky] ⌛ Executing task 'commit-message-linter' ...
10[Husky]  ✔ Successfully executed in 404ms
11--------------------------------------------------
12
13Great work! 🥂

Attach Husky.Net to your project

To make things easier for other developers, you can attach Husky.Net to your project.

1dotnet husky attach <path-to-project-file>

This will add required configuration to your project file. You can find the configuration in the PropertyGroup section.

1<Target Name="husky" BeforeTargets="Restore;CollectPackageReferences" Condition="'$(HUSKY)' != 0">
2   <Exec Command="dotnet tool restore"  StandardOutputImportance="Low" StandardErrorImportance="High"/>
3   <Exec Command="dotnet husky install" StandardOutputImportance="Low" StandardErrorImportance="High"
4         WorkingDirectory="../../" />  <!--Update this to the relative path to your project root dir -->
5</Target>

Conclusion

In this article, we have seen how to version and release a dotnet application using versionize and github actions. You can find the source code in the github repository for this article. If you have any questions or suggestions, please leave a comment below. Thanks for reading. Happy coding! 🚀 🚀 🚀

Buy Me a Coffee at ko-fi.com