Skip to content

Commit bb54b0f

Browse files
committed
Fix false negative for ModuleDoc
Refs #1168
1 parent 91502ce commit bb54b0f

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

lib/credo/code/module.ex

+19
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,25 @@ defmodule Credo.Code.Module do
7474
end
7575

7676
@doc "Reads an attribute from a module's `ast`"
77+
def attribute({:defmodule, _, _arguments} = ast, attr_name) do
78+
arguments =
79+
case Credo.Code.Block.do_block_for!(ast) do
80+
{:__block__, [], arguments} -> arguments
81+
value -> List.wrap(value)
82+
end
83+
84+
attr_value =
85+
Enum.find_value(arguments, fn
86+
{:@, _meta, [{^attr_name, _, [value]} | _tail]} -> {:ok, value}
87+
_ -> nil
88+
end)
89+
90+
case attr_value do
91+
{:ok, value} -> value
92+
error -> {:error, error}
93+
end
94+
end
95+
7796
def attribute(ast, attr_name) do
7897
case Credo.Code.postwalk(ast, &find_attribute(&1, &2, attr_name), {:error, nil}) do
7998
{:ok, value} ->

test/credo/code/module_test.exs

+41
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,47 @@ defmodule Credo.Code.ModuleTest do
2828
assert false == Module.attribute(ast, :moduledoc)
2929
end
3030

31+
test "should return the given module attribute for the top module in the given AST" do
32+
{:ok, ast} =
33+
"""
34+
defmodule CredoExample do
35+
@attr_list [:atom1, :atom2]
36+
@attr_string "This is a String"
37+
@attr_number 42
38+
39+
@moduledoc false
40+
41+
defmodule Foo do
42+
@attr_list [:atom3, :atom4]
43+
@attr_string "This is another String"
44+
@attr_number -1
45+
46+
@moduledoc "test"
47+
end
48+
end
49+
"""
50+
|> Code.string_to_quoted()
51+
52+
assert [:atom1, :atom2] == Module.attribute(ast, :attr_list)
53+
assert "This is a String" == Module.attribute(ast, :attr_string)
54+
assert 42 == Module.attribute(ast, :attr_number)
55+
assert false == Module.attribute(ast, :moduledoc)
56+
end
57+
58+
test "should return the given module attribute, if found" do
59+
ast =
60+
{:defmodule, [line: 2, column: 3],
61+
[
62+
{:__aliases__, [line: 2, column: 13], [:SubModule]},
63+
[do: {:__block__, [], []}]
64+
]}
65+
66+
assert {:error, nil} == Module.attribute(ast, :attr_list)
67+
assert {:error, nil} == Module.attribute(ast, :attr_string)
68+
assert {:error, nil} == Module.attribute(ast, :attr_number)
69+
assert {:error, nil} == Module.attribute(ast, :moduledoc)
70+
end
71+
3172
#
3273
# def_count
3374
#

0 commit comments

Comments
 (0)