config_comment_finder.ex (1324B)
1 defmodule Credo.Check.ConfigCommentFinder do 2 @moduledoc false 3 4 # This check is used internally by Credo. 5 # 6 # It traverses the given codebase to find `Credo.Check.ConfigComment` 7 # compatible comments, which control Credo's behaviour. 8 9 @config_comment_format ~r/#\s*credo\:([\w-\:]+)\s*(.*)/im 10 11 alias Credo.Check.ConfigComment 12 alias Credo.SourceFile 13 14 @doc false 15 def run(source_files) when is_list(source_files) do 16 source_files 17 |> Enum.map(&find_and_set_in_source_file/1) 18 |> Enum.reject(&is_nil/1) 19 end 20 21 def find_and_set_in_source_file(source_file) do 22 case find_config_comments(source_file) do 23 [] -> 24 nil 25 26 config_comments -> 27 {source_file.filename, config_comments} 28 end 29 end 30 31 defp find_config_comments(source_file) do 32 source = SourceFile.source(source_file) 33 34 if source =~ @config_comment_format do 35 source 36 |> Credo.Code.clean_charlists_strings_and_sigils() 37 |> Credo.Code.to_lines() 38 |> Enum.reduce([], &find_config_comment/2) 39 else 40 [] 41 end 42 end 43 44 defp find_config_comment({line_no, string}, memo) do 45 case Regex.run(@config_comment_format, string) do 46 nil -> 47 memo 48 49 [_, instruction, param_string] -> 50 memo ++ [ConfigComment.new(instruction, param_string, line_no)] 51 end 52 end 53 end