Credo and Elixir: Add linting and analysis
This post is part of the Elixir Setup Series, covering essential tools and practices for Elixir projects.
Adding Credo to Your Elixir Project
Credo automates and enforces team-wide standards through linting and code analysis, checking for style consistency, readability, and potential bugs. Integrating Credo into your workflow ensures that your codebase adheres to best practices, making it easier to maintain and reducing the likelihood of introducing errors.
Add credo
to Mix Dependencies
First, add Credo to the list of dependencies in the mix.exs
file:
defp deps do
[
{:credo, "~> 1.6", only: [:dev, :test], runtime: false}
]
end
Limit Credo to the development and test environments, and then update your dependencies:
mix deps.get
Generate a Credo Configuration
To customize Credo’s behavior, generate a .credo.exs
configuration file:
mix credo.gen.config
The .credo.exs
file can be edited to fit your project’s needs.
Integrating Credo into the Makefile
While you can use the mix
file’s aliases
, I prefer using a Makefile to manage tasks.
lint:
@echo "Linting code..."
MIX_ENV=dev mix credo --strict
Running Credo in --strict
mode provides additional feedback.
Check for Lint Errors
To check for lint errors, run:
make lint
This will run Credo locally, ensuring that your code meets style and readability standards.
Add a Git Hook to Run Credo on Push
To automate code analysis when pushing changes to your repository, add a pre-push hook:
-
Create the Pre-Push Hook Script:
Create or modify the
pre-push
file:nano .git/hooks/pre-push
-
Add the Following Script to the
pre-push
File:#!/bin/sh echo "Running Credo to check for code consistency..." mix credo --strict # Capture the exit status of Credo CREDO_EXIT_CODE=$? # Check if Credo found any problems if [ $CREDO_EXIT_CODE -ne 0 ]; then echo "Credo found issues." echo "Please fix them before pushing!" exit 1 fi echo "No issues found by Credo. Proceeding with push." exit 0
-
Make the Pre-Push Script Executable:
chmod +x .git/hooks/pre-push
Now, whenever you push changes to your repository, Credo will run automatically to check for code consistency and style issues.
Add an Extension to Your Editor
I recommend using the Credo (Elixir Linter) extension for your editor.