.template.check.ex (1843B)
1 defmodule <%= @check_name %> do 2 @moduledoc """ 3 Checks all lines for a given Regex. 4 5 This is fun! 6 """ 7 8 @explanation [ 9 check: @moduledoc, 10 params: [ 11 regex: "All lines matching this Regex will yield an issue.", 12 ] 13 ] 14 @default_params [ 15 regex: ~r/Creeeedo/, # our check will find this line. 16 ] 17 18 # you can configure the basics of your check via the `use Credo.Check` call 19 use Credo.Check, base_priority: :high, category: :custom, exit_status: 0 20 21 @doc false 22 @impl true 23 def run(%SourceFile{} = source_file, params) do 24 lines = SourceFile.lines(source_file) 25 26 # IssueMeta helps us pass down both the source_file and params of a check 27 # run to the lower levels where issues are created, formatted and returned 28 issue_meta = IssueMeta.for(source_file, params) 29 30 # we use the `params` parameter and the `Params` module to extract a 31 # configuration parameter from `.credo.exs` while also providing a 32 # default value 33 line_regex = params |> Params.get(:regex, __MODULE__) 34 35 # Finally, we can run our custom made analysis. 36 # In this example, we look for lines in source code matching our regex: 37 Enum.reduce(lines, [], &process_line(&1, &2, line_regex, issue_meta)) 38 end 39 40 defp process_line({line_no, line}, issues, line_regex, issue_meta) do 41 case Regex.run(line_regex, line) do 42 nil -> issues 43 matches -> 44 trigger = matches |> List.last 45 new_issue = issue_for(issue_meta, line_no, trigger) 46 [new_issue] ++ issues 47 end 48 end 49 50 defp issue_for(issue_meta, line_no, trigger) do 51 # format_issue/2 is a function provided by Credo.Check to help us format the 52 # found issue 53 format_issue issue_meta, 54 message: "OMG! This line matches our Regexp in @default_params!", 55 line_no: line_no, 56 trigger: trigger 57 end 58 end