Skip to content
Permalink
Browse files

Add check for alias as

resolves #684
  • Loading branch information...
sasa1977 committed Aug 7, 2019
1 parent 7f51b45 commit cb95dca7f1427d5041058187039868e90c3b4804
Showing with 98 additions and 0 deletions.
  1. +1 −0 .credo.exs
  2. +50 −0 lib/credo/check/readability/alias_as.ex
  3. +47 −0 test/credo/check/readability/alias_as_test.exs
@@ -142,6 +142,7 @@
{Credo.Check.Consistency.MultiAliasImportRequireUse, false},
{Credo.Check.Consistency.UnusedVariableNames, false},
{Credo.Check.Design.DuplicatedCode, false},
{Credo.Check.Readability.AliasAs, false},
{Credo.Check.Readability.MultiAlias, false},
{Credo.Check.Readability.Specs, false},
{Credo.Check.Readability.SinglePipe, false},
@@ -0,0 +1,50 @@
defmodule Credo.Check.Readability.AliasAs do
@moduledoc false

@checkdoc """
Aliases which are not completely renamed using the `:as` option are easier to follow.
# preferred
alias MyApp.Module1
# NOT preferred
alias MyApp.Module1, as: M1
Like all `Readability` issues, this one is not a technical concern.
But you can improve the odds of others reading and liking your code by making
it easier to follow.
"""
@explanation [check: @checkdoc]

use Credo.Check, base_priority: :low

alias Credo.Code

@doc false
def run(source_file, params \\ []) do
source_file
|> Code.prewalk(&traverse(&1, &2, IssueMeta.for(source_file, params)))
|> Enum.reverse()
end

defp traverse(ast, issues, issue_meta), do: {ast, add_issue(issues, issue(ast, issue_meta))}

defp add_issue(issues, nil), do: issues
defp add_issue(issues, issue), do: [issue | issues]

defp issue({:alias, _, [{_, _, original}, [as: {_, meta, _}]]}, issue_meta),
do: issue_for(issue_meta, meta[:line], inspect(Module.concat(original)))

defp issue(_ast, _issue_meta), do: nil

defp issue_for(issue_meta, line_no, trigger) do
format_issue(
issue_meta,
message: "Avoid using the :as option with alias.",
trigger: trigger,
line_no: line_no
)
end
end
@@ -0,0 +1,47 @@
defmodule Credo.Check.Readability.AliasAsTest do
use Credo.TestHelper

@described_check Credo.Check.Readability.AliasAs

test "it should NOT report violation" do
"""
defmodule Test do
alias App.Module1
alias App.Module2
end
"""
|> to_source_file
|> refute_issues(@described_check)
end

test "it should report a violation" do
[issue] =
"""
defmodule Test do
alias App.Module1, as: M1
end
"""
|> to_source_file
|> assert_issue(@described_check)

assert issue.trigger == "App.Module1"
end

test "it should report multiple violations" do
[issue1, issue2, issue3] =
"""
defmodule Test do
alias App.Module1, as: M1
alias App.Module2
alias App.Module3, as: M3
alias App.Module4, as: M4
end
"""
|> to_source_file
|> assert_issues(@described_check)

assert issue1.trigger == "App.Module1"
assert issue2.trigger == "App.Module3"
assert issue3.trigger == "App.Module4"
end
end

0 comments on commit cb95dca

Please sign in to comment.
You can’t perform that action at this time.