ForgeCredoChecks.WithResultTag (forge_credo_checks v0.4.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

<- clauses in a with chain should use a consistent vocabulary of result tags. The default is :ok | {:error, reason} or {:ok, value} | {:error, reason} - every step in the chain returns one of those shapes, so a non-match falls through cleanly without needing an else block to sort by step-specific tags.

How to fix

Two options when this fires:

Option 1 - change the called function to return an allowed shape (typically {:ok, _} | {:error, _}):

# BEFORE - returns {:found, user} | nil
def lookup(id), do: Repo.get(User, id) |> wrap_found()

# AFTER - returns {:ok, user} | {:error, :not_found}
def lookup(id) do
  case Repo.get(User, id) do
    nil -> {:error, :not_found}
    user -> {:ok, user}
  end
end

Then the with clause becomes {:ok, user} <- lookup(id) and falls through cleanly.

Option 2 - add the atom to :allowed_atoms in .credo.exs if it's part of this codebase's intentional vocabulary (e.g. a domain-specific control-flow tag like :found, :retry, :locked):

{ForgeCredoChecks.WithResultTag,
 allowed_atoms: [:ok, :error, :found, :retry]}

What NOT to do

Do not bypass this check by switching the LHS to a variable or wildcard just to silence it:

# STILL BAD - loses the contract entirely
with result <- lookup(id), ...
with _ <- lookup(id), ...

Pick option 1 (normalize the return) or option 2 (extend the allowlist) - both are accepted; the variable-shrug is not.

Scope

Only atom-tagged shapes are checked: bare atoms (:foo <-), 2-tuples ({:foo, _} <-), and 3+-tuples ({:foo, a, b} <-). Variables, pinned variables, struct matches, list patterns, and other complex patterns are not checked.

Check-Specific Parameters

Use the following parameters to configure this check:

:allowed_atoms

Atoms permitted as a <- LHS or as the tag of a {tag, _} LHS. Default: [:ok, :error].

This parameter defaults to [:ok, :error].

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.