CI/CD - Formatting

Automated Code Formatting

Automated code formatting is a great way to keep your code consistent and readable. It helps avoid arguments about code style, a phenomenon often referred to as “bikeshedding”.

Why Use Automated Code Formatting?

  • Consistency: Ensures that code is uniformly styled throughout the project.
  • Readability: Properly formatted code is easier to read and understand.
  • Focus: Allows developers to focus on actual code logic and functionality instead of debating over style issues.

Personal Anecdote

Many developers prefer to enforce automated code formatting from the start of a project. For example, in the Go programming language, a built-in, opinionated code formatter called go fmt is widely used. Most serious Go projects use this formatter to maintain consistency across the codebase.

Example: Unformatted vs. Formatted Code

Here’s an example of technically valid, but poorly formatted Go code:

func main() {
 fmt.Println("hello world!") }

Formatted correctly, it would look like this:

func main() {
    fmt.Println("hello world!")
}

Using go fmt

The go fmt command is a built-in Go tool that automatically formats Go code. Since it is part of the Go toolchain, you don’t need to install anything additional to use it.

Command Syntax

To format a Go file or an entire project, simply run:

go fmt ./...

This command formats all .go files in the current directory and its subdirectories.

VS Code Integration

Many developers configure their code editors to format code automatically on save. For example, in VS Code, you can set up auto-formatting for Go (or any other language) to ensure your code always follows the proper style conventions.

Benefits of Auto-Formatting on Save

  • Saves Time: Developers don’t have to manually run formatting commands.
  • Reduces Errors: Automatically corrects minor formatting mistakes.
  • Prevents Style Debates: Eliminates subjective discussions around code styling.

Application in Projects

In most projects, formatting is enforced as part of the Continuous Integration (CI) pipeline, where code is checked and formatted before merging into the main branch. This ensures that all code meets the project’s styling guidelines.

Incorporating automated formatting tools is a recommended practice, whether you’re working alone or in a team environment, as it promotes cleaner and more maintainable codebases.

Checking Code Formatting

Automated code formatting tools are essential for maintaining code consistency and readability across various programming languages. However, some formatting tools may not indicate formatting issues via their exit status.

Ensuring Proper Formatting in CI

To ensure that your code is properly formatted, you can use a command that checks whether any files need formatting. If the output is empty, it indicates that the code is correctly formatted.

Example Command

Here’s a generic way to check formatting in many programming environments:

test -z "$(<formatter_command>)"

For Go, that’s:

test -z "$(gofmt -l .)"

Breakdown of the Command

  1. <formatter_command>: This command runs the formatting tool in list mode on the current directory and all its subdirectories (e.g. gofmt -l .). If any files need formatting, the tool will print their names without changing them. Don’t use go fmt here: it rewrites the files (so the check would always pass), and ./... is go tool syntax that gofmt doesn’t accept.

  2. **”()syntax is used for command substitution. It runs the command inside the parentheses and replaces$()with its output. Keep the quotes: unquoted, two or more file names become separate arguments andtest` fails with “too many arguments”.

  3. test -z ”$(<formatter_command>)”: The test command checks if the output from the formatting tool is an empty string:

    • -z option returns 0 (true) if the string is empty, indicating that the code is formatted correctly.
    • Returns 1 (false) if there are any files that need formatting.

Practical Steps

  1. Edit a File: Make an intentional formatting mistake in your code to test the formatting check.

  2. Run the Formatting Check: Execute the formatting check command:

    test -z "$(<formatter_command>)"
  3. Check the Exit Code: Use the following command to print the exit code of the last command:

    echo $?
    • You should see 1, indicating that the code is not formatted properly.
  4. Fix Formatting: Run the formatting command again to automatically fix the formatting:

    go fmt ./...   # or: gofmt -w .
  5. Re-check the Formatting: Run the formatting check command again:

    test -z "$(<formatter_command>)"
    echo $?
    • This time, you should see 0, confirming that the code is now properly formatted.

Conclusion

Implementing code formatting checks as part of the CI/CD pipeline helps maintain code quality and consistency across different programming languages. Automating this process can significantly improve the code review process and reduce formatting-related discussions among team members.