Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run credo only on changed files
defmodule Mix.Tasks.Credo.Ci do
@shortdoc "Run Credo only on files that have changed since the last merge commit."
@moduledoc """
Runs Credo in CI with somewhat special behavior.
If the branch being tested is `master`, it runs Credo on all files. Otherwise, it only runs
Credo on the files that have changed since the last merge commit, and it will fail CI if any
check doesn't pass for those specific files.
"""
use Mix.Task
@impl true
def run(_) do
if System.cmd("git", ["rev-parse", "--abbrev-ref", "HEAD"]) == {"master", 0} do
Mix.Task.run("credo", [])
else
{last_merge, 0} =
System.cmd("git", [
"log",
"--pretty=format:%C(auto)%h",
"--grep=\(#[0-9][0-9][0-9][0-9]\)",
"--date-order",
"-1"
])
{diff, 0} = System.cmd("git", ["diff", "--name-only", last_merge])
run_files(diff, ~r/lib.*\.ex$/)
Mix.Task.clear()
run_files(diff, ~r/test.*\.exs$/)
end
end
defp run_files(diff, pattern) do
files =
diff
|> String.split("\n")
|> Enum.filter(&(&1 =~ pattern))
|> Enum.flat_map(&["--files-included", &1])
unless files == [] do
Mix.Task.run("credo", files)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment