/
check.ex
883 lines (729 loc) · 22.1 KB
/
check.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
defmodule Credo.Check do
@moduledoc """
`Check` modules represent the checks which are run during Credo's analysis.
Example:
defmodule MyCheck do
use Credo.Check, category: :warning, base_priority: :high
def run(%SourceFile{} = source_file, params) do
#
end
end
The check can be configured by passing the following
options to `use Credo.Check`:
- `:base_priority` Sets the checks's base priority (`:low`, `:normal`, `:high`, `:higher` or `:ignore`).
- `:category` Sets the check's category (`:consistency`, `:design`, `:readability`, `:refactor` or `:warning`).
- `:elixir_version` Sets the check's version requirement for Elixir (defaults to `>= 0.0.1`).
- `:explanations` Sets explanations displayed for the check, e.g.
```elixir
[
check: "...",
params: [
param1: "Your favorite number",
param2: "Online/Offline mode"
]
]
```
- `:param_defaults` Sets the default values for the check's params (e.g. `[param1: 42, param2: "offline"]`)
- `:tags` Sets the tags for this check (list of atoms, e.g. `[:tag1, :tag2]`)
Please also note that these options to `use Credo.Check` are just a convenience to implement the `Credo.Check`
behaviour. You can implement any of these by hand:
defmodule MyCheck do
use Credo.Check
def category, do: :warning
def base_priority, do: :high
def explanations do
[
check: "...",
params: [
param1: "Your favorite number",
param2: "Online/Offline mode"
]
]
end
def param_defaults, do: [param1: 42, param2: "offline"]
def run(%SourceFile{} = source_file, params) do
#
end
end
The `run/2` function of a Check module takes two parameters: a source file and a list of parameters for the check.
It has to return a list of found issues.
"""
@doc """
Runs the current check on all `source_files` by calling `run_on_source_file/3`.
If you are developing a check that has to run on all source files, you can overwrite `run_on_all_source_files/3`:
defmodule MyCheck do
use Credo.Check
def run_on_all_source_files(exec, source_files, params) do
issues =
source_files
|> do_something_crazy()
|> do_something_crazier()
append_issues_and_timings(exec, issues)
:ok
end
end
Check out Credo's checks from the consistency category for examples of these kinds of checks.
"""
@callback run_on_all_source_files(
exec :: Credo.Execution.t(),
source_files :: list(Credo.SourceFile.t()),
params :: Keyword.t()
) :: :ok
@doc """
Runs the current check on a single `source_file` and appends the resulting issues to the current `exec`.
"""
@callback run_on_source_file(
exec :: Credo.Execution.t(),
source_file :: Credo.SourceFile.t(),
params :: Keyword.t()
) :: :ok
@callback run(source_file :: Credo.SourceFile.t(), params :: Keyword.t()) ::
list(Credo.Issue.t())
@doc """
Returns the base priority for the check.
This can be one of `:higher`, `:high`, `:normal`, `:low` or `:ignore`
(technically it can also be or an integer, but these are internal representations although that is not recommended).
"""
@callback base_priority() :: :higher | :high | :normal | :low | :ignore | integer
@doc """
Returns the category for the check.
"""
@callback category() :: atom
@doc """
Returns the required Elixir version for the check.
"""
@callback elixir_version() :: String.t()
@doc """
Returns the exit status for the check.
"""
@callback exit_status() :: integer
@doc """
Returns the explanations for the check and params as a keyword list.
"""
@callback explanations() :: Keyword.t()
@doc """
Returns the default values for the check's params as a keyword list.
"""
@callback param_defaults() :: Keyword.t()
# @callback run(source_file :: Credo.SourceFile.t, params :: Keyword.t) :: list()
@doc """
Returns whether or not this check runs on all source files.
"""
@callback run_on_all?() :: boolean
@doc """
Returns the tags for the check.
"""
@callback tags() :: list(atom)
@doc """
Returns the docs URL for the check.
"""
@callback docs_uri() :: binary()
@doc """
Returns an ID that can be used to identify the check.
"""
@callback id() :: binary()
@doc false
@callback format_issue(issue_meta :: Credo.IssueMeta.t(), opts :: Keyword.t()) ::
Credo.Issue.t()
@base_category_exit_status_map %{
consistency: 1,
design: 2,
readability: 4,
refactor: 8,
warning: 16
}
alias Credo.Service.SourceFileScopePriorities
alias Credo.Check
alias Credo.Check.Params
alias Credo.Code.Scope
alias Credo.Issue
alias Credo.IssueMeta
alias Credo.Priority
alias Credo.Service.SourceFileScopes
alias Credo.Severity
alias Credo.SourceFile
@valid_use_opts [
:base_priority,
:category,
:docs_uri,
:elixir_version,
:exit_status,
:explanations,
:id,
:param_defaults,
:run_on_all,
:tags
]
{config, _binding} = Code.eval_file(".credo.exs")
%{:name => "default", :checks => %{:enabled => check_tuples}} = List.first(config[:configs])
@__default_checks__ Enum.map(check_tuples, fn {check, _params} -> check end)
@doc false
defmacro __using__(opts) do
Enum.each(opts, fn
{key, _name} when key not in @valid_use_opts ->
raise "Could not find key `#{key}` in #{inspect(@valid_use_opts)}"
_ ->
nil
end)
def_base_priority =
if opts[:base_priority] do
quote do
@impl true
def base_priority, do: unquote(opts[:base_priority])
end
else
quote do
@impl true
def base_priority, do: 0
end
end
def_category =
if opts[:category] do
quote do
@impl true
def category, do: unquote(category_body(opts[:category]))
end
else
quote do
@impl true
def category, do: unquote(category_body(nil))
end
end
def_elixir_version =
if opts[:elixir_version] do
quote do
@impl true
def elixir_version do
unquote(opts[:elixir_version])
end
end
else
quote do
@impl true
def elixir_version, do: ">= 0.0.1"
end
end
def_exit_status =
if opts[:exit_status] do
quote do
@impl true
def exit_status do
unquote(opts[:exit_status])
end
end
else
quote do
@impl true
def exit_status, do: Credo.Check.to_exit_status(category())
end
end
def_run_on_all? =
if opts[:run_on_all] do
quote do
@impl true
def run_on_all?, do: unquote(opts[:run_on_all] == true)
end
else
quote do
@impl true
def run_on_all?, do: false
end
end
def_param_defaults =
if opts[:param_defaults] do
quote do
@impl true
def param_defaults, do: unquote(opts[:param_defaults])
end
end
def_explanations =
if opts[:explanations] do
quote do
@impl true
def explanations do
unquote(opts[:explanations])
end
end
end
def_tags =
quote do
@impl true
def tags do
unquote(opts[:tags] || [])
end
end
docs_uri =
if opts[:docs_uri] do
quote do
@impl true
def docs_uri do
unquote(opts[:docs_uri])
end
end
else
quote do
@impl true
def docs_uri do
"https://hexdocs.pm/credo/#{Credo.Code.Name.full(__MODULE__)}.html"
end
end
end
id =
if opts[:id] do
quote do
@impl true
def id do
unquote(opts[:id])
end
end
else
quote do
@impl true
def id do
Credo.Code.Name.full(__MODULE__)
end
end
end
module_doc = moduledoc(opts, __CALLER__.module)
quote do
@moduledoc unquote(module_doc)
@behaviour Credo.Check
@before_compile Credo.Check
@use_deprecated_run_on_all? false
alias Credo.Check
alias Credo.Check.Params
alias Credo.CLI.ExitStatus
alias Credo.CLI.Output.UI
alias Credo.Execution
alias Credo.Execution.ExecutionTiming
alias Credo.Issue
alias Credo.IssueMeta
alias Credo.Priority
alias Credo.Severity
alias Credo.SourceFile
unquote(def_base_priority)
unquote(def_category)
unquote(def_elixir_version)
unquote(def_exit_status)
unquote(def_run_on_all?)
unquote(def_param_defaults)
unquote(def_explanations)
unquote(def_tags)
unquote(docs_uri)
unquote(id)
@impl true
def format_issue(issue_meta, issue_options) do
Check.format_issue(
issue_meta,
issue_options,
__MODULE__
)
end
@doc false
@impl true
def run_on_all_source_files(exec, source_files, params \\ [])
@impl true
def run_on_all_source_files(exec, source_files, params) do
if function_exported?(__MODULE__, :run, 3) do
IO.warn(
"Defining `run(source_files, exec, params)` for checks that run on all source files is deprecated. " <>
"Define `run_on_all_source_files(exec, source_files, params)` instead."
)
apply(__MODULE__, :run, [source_files, exec, params])
else
do_run_on_all_source_files(exec, source_files, params)
end
end
defp do_run_on_all_source_files(exec, source_files, params) do
source_files
|> Task.async_stream(fn source -> run_on_source_file(exec, source, params) end,
max_concurrency: exec.max_concurrent_check_runs,
timeout: :infinity,
ordered: false
)
|> Stream.run()
:ok
end
@doc false
@impl true
def run_on_source_file(exec, source_file, params \\ [])
def run_on_source_file(%Execution{debug: true} = exec, source_file, params) do
ExecutionTiming.run(&do_run_on_source_file/3, [exec, source_file, params])
|> ExecutionTiming.append(exec,
task: exec.current_task,
check: __MODULE__,
filename: source_file.filename
)
end
def run_on_source_file(exec, source_file, params) do
do_run_on_source_file(exec, source_file, params)
end
defp do_run_on_source_file(exec, source_file, params) do
issues =
try do
run(source_file, params)
rescue
error ->
UI.warn("Error while running #{__MODULE__} on #{source_file.filename}")
if exec.crash_on_error do
reraise error, __STACKTRACE__
else
[]
end
end
append_issues_and_timings(issues, exec)
:ok
end
@doc false
@impl true
def run(source_file, params)
def run(%SourceFile{} = source_file, params) do
throw("Implement me")
end
defoverridable Credo.Check
defp append_issues_and_timings([] = _issues, exec) do
exec
end
defp append_issues_and_timings([_ | _] = issues, exec) do
Credo.Execution.ExecutionIssues.append(exec, issues)
end
end
end
@doc false
defmacro __before_compile__(env) do
quote do
unquote(deprecated_def_default_params(env))
unquote(deprecated_def_explanations(env))
@doc false
def param_names do
Keyword.keys(param_defaults())
end
@deprecated "Use param_defaults/1 instead"
@doc false
def params_defaults do
# deprecated - remove module attribute
param_defaults()
end
@deprecated "Use param_names/1 instead"
@doc false
def params_names do
param_names()
end
@deprecated "Use explanations()[:check] instead"
@doc false
def explanation do
# deprecated - remove module attribute
explanations()[:check]
end
@deprecated "Use explanations()[:params] instead"
@doc false
def explanation_for_params do
# deprecated - remove module attribute
explanations()[:params]
end
end
end
defp moduledoc(opts, module) do
explanations = opts[:explanations]
base_priority = opts_to_string(opts[:base_priority]) || 0
default_check? = module in @__default_checks__
tags = opts[:tags] || []
elixir_version_hint =
if opts[:elixir_version] do
elixir_version = opts_to_string(opts[:elixir_version])
"requires Elixir `#{elixir_version}`"
else
"works with any version of Elixir"
end
default_check_hint =
if default_check? do
"""
> #### This check is enabled by default. {: .tip}
>
> [Learn how to disable it](config_file.html#checks) via `.credo.exs`.
"""
else
"""
> #### This check is disabled by default. {: .neutral}
>
> [Learn how to enable it](config_file.html#checks) via `.credo.exs`.
"""
end
# TODO: list all tags
tag_hint =
if :formatter in tags do
"""
> #### This check is tagged `:formatter` {: .info}
>
> This means you can disable this check when also using Elixir's formatter.
"""
else
if :controversial in tags do
"""
> #### This check is tagged `:controversial` {: .warning}
>
> This means that this check is more opinionated than others and not for everyone's taste.
"""
else
"""
"""
end
end
check_doc = opts_to_string(explanations[:check])
params = explanations[:params] |> opts_to_string() |> List.wrap()
param_defaults = opts_to_string(opts[:param_defaults])
params_doc =
if params == [] do
"*There are no specific parameters for this check.*"
else
param_explanation =
Enum.map(params, fn {key, value} ->
default_value = inspect(param_defaults[key], limit: :infinity)
default_hint =
if default_value do
"*This parameter defaults to* `#{default_value}`."
end
value = value |> String.split("\n") |> Enum.map_join("\n", &" #{&1}")
"""
### `:#{key}`
#{value}
#{default_hint}
"""
end)
"""
Use the following parameters to configure this check:
#{param_explanation}
"""
end
"""
## Basics
#{String.trim(default_check_hint)}
#{String.trim(tag_hint)}
This check has a base priority of `#{base_priority}` and #{elixir_version_hint}.
## Explanation
#{check_doc}
## Check-Specific Parameters
#{params_doc}
## General Parameters
Like with all checks, [general params](check_params.html) can be applied.
Parameters can be configured via the [`.credo.exs` config file](config_file.html).
"""
end
defp opts_to_string(value) do
{result, _} =
value
|> Macro.to_string()
|> Code.eval_string()
result
end
defp deprecated_def_default_params(env) do
default_params = Module.get_attribute(env.module, :default_params)
if is_nil(default_params) do
if not Module.defines?(env.module, {:param_defaults, 0}) do
quote do
@impl true
def param_defaults, do: []
end
end
else
# deprecated - remove once we ditch @default_params
quote do
@impl true
def param_defaults do
@default_params
end
end
end
end
defp deprecated_def_explanations(env) do
defines_deprecated_explanation_module_attribute? =
!is_nil(Module.get_attribute(env.module, :explanation))
defines_deprecated_explanations_fun? = Module.defines?(env.module, {:explanations, 0})
if defines_deprecated_explanation_module_attribute? do
# deprecated - remove once we ditch @explanation
quote do
@impl true
def explanations do
@explanation
end
end
else
if !defines_deprecated_explanations_fun? do
quote do
@impl true
def explanations, do: []
end
end
end
end
def explanation_for(nil, _), do: nil
def explanation_for(keywords, key), do: keywords[key]
@doc """
format_issue takes an issue_meta and returns an issue.
The resulting issue can be made more explicit by passing the following
options to `format_issue/2`:
- `:priority` Sets the issue's priority.
- `:trigger` Sets the issue's trigger, i.e. the text causing the issue (see `Credo.Check.Warning.IoInspect`).
- `:line_no` Sets the issue's line number. Tries to find `column` if `:trigger` is supplied.
- `:column` Sets the issue's column.
- `:exit_status` Sets the issue's exit_status.
- `:severity` Sets the issue's severity.
"""
def format_issue(issue_meta, opts, check) do
params = IssueMeta.params(issue_meta)
issue_category = Params.category(params, check)
issue_base_priority = Params.priority(params, check)
format_issue(issue_meta, opts, issue_category, issue_base_priority, check)
end
@doc false
def format_issue(issue_meta, opts, issue_category, issue_priority, check) do
source_file = IssueMeta.source_file(issue_meta)
params = IssueMeta.params(issue_meta)
priority = Priority.to_integer(issue_priority)
exit_status_or_category = Params.exit_status(params, check) || issue_category
exit_status = Check.to_exit_status(exit_status_or_category)
line_no = opts[:line_no]
column = opts[:column]
severity = opts[:severity] || Severity.default_value()
trigger = opts[:trigger]
trigger =
if trigger == Issue.no_trigger() do
trigger
else
to_string(trigger)
end
%Issue{
priority: priority,
filename: source_file.filename,
message: opts[:message],
trigger: trigger,
line_no: line_no,
column: column,
severity: severity,
exit_status: exit_status
}
|> add_line_no_options(line_no, source_file)
|> add_column_if_missing(trigger, line_no, column, source_file)
|> add_check_and_category(check, issue_category)
end
defp add_check_and_category(issue, check, issue_category) do
%Issue{
issue
| check: check,
category: issue_category
}
end
defp add_column_if_missing(issue, trigger, line_no, column, source_file) do
if trigger && line_no && !column do
%Issue{
issue
| column: SourceFile.column(source_file, line_no, trigger)
}
else
issue
end
end
defp add_line_no_options(issue, line_no, source_file) do
if line_no do
{_def, scope} = scope_for(source_file, line: line_no)
%Issue{
issue
| priority: issue.priority + priority_for(source_file, scope),
scope: scope
}
else
issue
end
end
# Returns the scope for the given line as a tuple consisting of the call to
# define the scope (`:defmodule`, `:def`, `:defp` or `:defmacro`) and the
# name of the scope.
#
# Examples:
#
# {:defmodule, "Foo.Bar"}
# {:def, "Foo.Bar.baz"}
#
@doc false
def scope_for(source_file, line: line_no) do
source_file
|> scope_list
|> Enum.at(line_no - 1)
end
# Returns all scopes for the given source_file per line of source code as tuple
# consisting of the call to define the scope
# (`:defmodule`, `:def`, `:defp` or `:defmacro`) and the name of the scope.
#
# Examples:
#
# [
# {:defmodule, "Foo.Bar"},
# {:def, "Foo.Bar.baz"},
# {:def, "Foo.Bar.baz"},
# {:def, "Foo.Bar.baz"},
# {:def, "Foo.Bar.baz"},
# {:defmodule, "Foo.Bar"}
# ]
defp scope_list(%SourceFile{} = source_file) do
case SourceFileScopes.get(source_file) do
{:ok, value} ->
value
:notfound ->
ast = SourceFile.ast(source_file)
lines = SourceFile.lines(source_file)
scope_info_list = Scope.scope_info_list(ast)
result =
Enum.map(lines, fn {line_no, _} ->
Scope.name_from_scope_info_list(scope_info_list, line_no)
end)
SourceFileScopes.put(source_file, result)
result
end
end
defp priority_for(source_file, scope) do
# Caching scope priorities, because these have to be computed only once per file. This
# significantly speeds up the execution time when a large number of issues are generated.
scope_prio_map =
case SourceFileScopePriorities.get(source_file) do
{:ok, value} ->
value
:notfound ->
result = Priority.scope_priorities(source_file)
SourceFileScopePriorities.put(source_file, result)
result
end
scope_prio_map[scope] || 0
end
defp category_body(nil) do
quote do
name =
__MODULE__
|> Module.split()
|> Enum.at(2)
safe_name = name || :unknown
safe_name
|> to_string
|> String.downcase()
|> String.to_atom()
end
end
defp category_body(value), do: value
@doc "Converts a given category to an exit status"
def to_exit_status(nil), do: 0
def to_exit_status(atom) when is_atom(atom) do
to_exit_status(@base_category_exit_status_map[atom])
end
def to_exit_status(value) when is_number(value), do: value
@doc false
def defined?(check)
def defined?({atom, _params}), do: defined?(atom)
def defined?(binary) when is_binary(binary) do
binary |> String.to_atom() |> defined?()
end
def defined?(module) when is_atom(module) do
case Code.ensure_compiled(module) do
{:module, _} -> true
{:error, _} -> false
end
end
end