Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 28 additions & 12 deletions lib/mix/tasks/pre_commit.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defmodule Mix.Tasks.PreCommit do
use Mix.Task

@moduledoc """
This file contains the functions that will be run when `mix pre_commit` is
run. (we run it in the script in the `pre-commit` file in your `.git/hooks` directory but you can run it yourself if you want to see the output without committing).
Expand All @@ -12,33 +13,48 @@ defmodule Mix.Tasks.PreCommit do
@commands Application.get_env(:pre_commit, :commands) || []
@verbose Application.get_env(:pre_commit, :verbose) || false


def run(_) do
IO.puts "\e[95mPre-commit running...\e[0m"
IO.puts("\e[95mPre-commit running...\e[0m")
{_, 0} = System.cmd("git", String.split("stash push --keep-index --message pre_commit", " "))

@commands
|> Enum.each(&run_cmds/1)

{_, 0} = System.cmd("git", String.split("stash pop", " "))
IO.puts "\e[32mPre-commit passed!\e[0m"
System.cmd("git", String.split("stash pop", " "), stderr_to_stdout: true)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice. 👍

|> case do
{_, 0} ->
"\e[32mPre-commit passed!\e[0m"

{"No stash entries found.", 1} ->
"\e[32mPre-commit passed!\e[0m"

{error, _} ->
error
end
|> IO.puts()

System.halt(0)
end


defp run_cmds(cmd) do
into = case @verbose do
true -> IO.stream(:stdio, :line)
_ -> ""
end
into =
case @verbose do
true -> IO.stream(:stdio, :line)
_ -> ""
end

System.cmd("mix", String.split(cmd, " "), stderr_to_stdout: true, into: into)
|> case do
{_result, 0} ->
IO.puts "mix #{cmd} ran successfully."
IO.puts("mix #{cmd} ran successfully.")

{result, _} ->
if !@verbose, do: IO.puts result
IO.puts "\e[31mPre-commit failed on `mix #{cmd}`.\e[0m \nCommit again with --no-verify to live dangerously and skip pre-commit."
if !@verbose, do: IO.puts(result)

IO.puts(
"\e[31mPre-commit failed on `mix #{cmd}`.\e[0m \nCommit again with --no-verify to live dangerously and skip pre-commit."
)

{_, 0} = System.cmd("git", String.split("stash pop", " "))
System.halt(1)
end
Expand Down