Support hierarchical loading of the config file

This commit is contained in:
Sijawusz Pur Rahnama 2023-03-06 05:32:55 +01:00
parent 6f05df4006
commit 9534104942
4 changed files with 32 additions and 15 deletions

View file

@ -21,7 +21,7 @@ module Ameba::Cli
%w(-c --config).each do |f|
it "accepts #{f} flag" do
c = Cli.parse_args [f, "config.yml"]
c.config.should eq "config.yml"
c.config.should eq Path["config.yml"]
end
end
@ -82,12 +82,6 @@ module Ameba::Cli
c.colors?.should be_true
end
it "ignores --config if --gen-config flag passed" do
c = Cli.parse_args %w(--gen-config --config my_config.yml)
c.formatter.should eq :todo
c.config.should eq ""
end
describe "-e/--explain" do
it "configures file/line/column" do
c = Cli.parse_args %w(--explain src/file.cr:3:5)
@ -166,7 +160,7 @@ module Ameba::Cli
c.globs.should be_nil
c.only.should be_nil
c.except.should be_nil
c.config.should eq Config::PATH
c.config.should be_nil
end
end
end

View file

@ -45,7 +45,7 @@ module Ameba
s = Source.new "a = 1", "source.cr"
s.add_issue DummyRule.new, {1, 2}, "message"
formatter.finished([s])
io.to_s.should contain "Created .ameba.yml"
io.to_s.should contain "Created #{Config::PATH}"
end
end

View file

@ -44,7 +44,7 @@ module Ameba::Cli
end
private class Opts
property config = Config::PATH
property config : Path?
property formatter : Symbol | String | Nil
property globs : Array(String)?
property only : Array(String)?
@ -76,7 +76,7 @@ module Ameba::Cli
parser.on("-c", "--config PATH",
"Specify a configuration file") do |path|
opts.config = path unless opts.config.empty?
opts.config = Path[path] unless path.empty?
end
parser.on("-f", "--format FORMATTER",
@ -105,7 +105,6 @@ module Ameba::Cli
parser.on("--gen-config",
"Generate a configuration file acting as a TODO list") do
opts.formatter = :todo
opts.config = ""
end
parser.on("--fail-level SEVERITY",

View file

@ -24,7 +24,12 @@ class Ameba::Config
json: Formatter::JSONFormatter,
}
PATH = ".ameba.yml"
DEFAULT_PATHS = {
"~/.ameba.yml",
"~/.config/ameba/config.yml",
}
FILENAME = ".ameba.yml"
PATH = Path[Dir.current] / FILENAME
DEFAULT_GLOBS = %w(
**/*.cr
@ -77,14 +82,33 @@ class Ameba::Config
# ```
# config = Ameba::Config.load
# ```
def self.load(path = PATH, colors = true)
def self.load(path = nil, colors = true)
Colorize.enabled = colors
content = File.exists?(path) ? File.read path : "{}"
content = read_config(path) || "{}"
Config.new YAML.parse(content)
rescue e
raise "Config file is invalid: #{e.message}"
end
protected def self.read_config(path) : String?
if path
return File.exists?(path) ? File.read(path) : nil
end
path = Path[PATH].expand(home: true)
search_paths = path
.parents
.map! { |search_path| search_path / FILENAME }
search_paths.reverse_each do |search_path|
return File.read(search_path) if File.exists?(search_path)
end
DEFAULT_PATHS.each do |default_path|
return File.read(default_path) if File.exists?(default_path)
end
end
def self.formatter_names
AVAILABLE_FORMATTERS.keys.join('|')
end