Good practices - Automatic Code Formatting
How to maintain a Clean Code

Good practices - Automatic Code Formatting

As our team grows, maintaining clean and uniform code becomes even more crucial. To ensure that all .NET files in our repositories follow a consistent format, we've implemented a practice that helps automate this process: pre-commit hooks.

By using the task runner Husky, we've set up a pre-commit hook that automatically runs the dotnet format command on modified files just before each commit. This command applies formatting based on the preferences configured in the .editorconfig file of each repository.

This way, we not only keep the code clean and readable but also optimize our workflow and reduce the chances of format-related issues.

Configuración de Pre-Commits en .NET con Husky

If you'd like to implement a similar solution in your .NET projects, here's a quick step-by-step guide:

1- Install Husky task runner in your repository root folder by executing the following commands from console:

??if the repository doesn't have a '.config\dotnet-tools.json' file already created, then type: ???????????? ?????? ????????-????????????????.

?????????????? ???????? ?????????????? ??????????

?????????????? ?????????? ??????????????

When done we should have the .???????? folder in the project root, that contains the files we are going to use to define our Git hooks.

2-Open the .??????????\????????-????????????.???????? and define a formatter task in the tasks array, that will be executed in the pre-commit hook. Here is an example of a task to format the staged _.cs files of a .NET API:

Example of a formatter task

3-Run the following command to create a pre-commit hook: ???????????? ?????????? ?????? ??????-????????????. This will create the .??????????\??????-???????????? file. Now we just need to open it and indicate which of the tasks defined in the ????????-????????????.???????? should the pre-commit hook run. Here is an example:

Thats all it takes, now before each commit the task runner will execute a dotnet format over each of the *.cs files being committed.

??Attention to detail makes a difference in software development.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了