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:

Article content
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:

Article content

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.

To view or add a comment, sign in

Others also viewed

Explore content categories