Sha256: 5be45b3f3b81c0f092aca194ac5575e50b7da45882fb363cf3e3c4ae8efac819

Contents?: true

Size: 1.78 KB

Versions: 2

Compression:

Stored size: 1.78 KB

Contents

require 'pathname'
require 'yaml'

module SlimLint
  # Manages configuration file loading.
  class ConfigurationLoader
    DEFAULT_CONFIG_PATH = File.join(SlimLint::HOME, 'config', 'default.yml')
    CONFIG_FILE_NAME = '.slim-lint.yml'

    class << self
      def load_applicable_config
        directory = File.expand_path(Dir.pwd)
        config_file = possible_config_files(directory).find(&:file?)

        if config_file
          load_file(config_file.to_path)
        else
          default_configuration
        end
      end

      def default_configuration
        @default_config ||= load_from_file(DEFAULT_CONFIG_PATH)
      end

      # Loads a configuration, ensuring it extends the default configuration.
      def load_file(file)
        config = load_from_file(file)

        default_configuration.merge(config)
      rescue => error
        raise SlimLint::Exceptions::ConfigurationError,
              "Unable to load configuration from '#{file}': #{error}",
              error.backtrace
      end

      def load_hash(hash)
        config = SlimLint::Configuration.new(hash)

        default_configuration.merge(config)
      rescue => error
        raise SlimLint::Exceptions::ConfigurationError,
              "Unable to load configuration from '#{file}': #{error}",
              error.backtrace
      end

      private

      def load_from_file(file)
        hash =
          if yaml = YAML.load_file(file)
            yaml.to_hash
          else
            {}
          end

        SlimLint::Configuration.new(hash)
      end

      def possible_config_files(directory)
        files = Pathname.new(directory)
                        .enum_for(:ascend)
                        .map { |path| path + CONFIG_FILE_NAME }
        files << Pathname.new(CONFIG_FILE_NAME)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
slim_lint-0.2.0 lib/slim_lint/configuration_loader.rb
slim_lint-0.1.0 lib/slim_lint/configuration_loader.rb