Class: Bunto::Configuration

Inherits:
Hash
  • Object
show all
Defined in:
lib/bunto/configuration.rb

Constant Summary collapse

DEFAULTS =

Default options. Overridden by values in _config.yml. Strings rather than symbols are used for compatibility with YAML.

Configuration[{
  # Where things are
  "source"            => Dir.pwd,
  "destination"       => File.join(Dir.pwd, "_site"),
  "plugins_dir"       => "_plugins",
  "layouts_dir"       => "_layouts",
  "data_dir"          => "_data",
  "includes_dir"      => "_includes",
  "collections"       => {},

  # Handling Reading
  "safe"              => false,
  "include"           => [".htaccess"],
  "exclude"           => [],
  "keep_files"        => [".git", ".svn"],
  "encoding"          => "utf-8",
  "markdown_ext"      => "markdown,mkdown,mkdn,mkd,md",

  # Filtering Content
  "show_drafts"       => nil,
  "limit_posts"       => 0,
  "future"            => false,
  "unpublished"       => false,

  # Plugins
  "whitelist"         => [],
  "gems"              => [],

  # Conversion
  "markdown"          => "kramdown",
  "highlighter"       => "rouge",
  "lsi"               => false,
  "excerpt_separator" => "\n\n",
  "incremental"       => false,

  # Serving
  "detach"            => false, # default to not detaching the server
  "port"              => "4000",
  "host"              => "127.0.0.1",
  "baseurl"           => "",
  "show_dir_listing"  => false,

  # Output Configuration
  "permalink"         => "date",
  "paginate_path"     => "/page:num",
  "timezone"          => nil, # use the local timezone

  "quiet"             => false,
  "verbose"           => false,
  "defaults"          => [],

  "liquid"            => {
    "error_mode" => "warn"
  },

  "rdiscount"         => {
    "extensions" => []
  },

  "redcarpet"         => {
    "extensions" => []
  },

  "kramdown"          => {
    "auto_ids"      => true,
    "toc_levels"    => "1..6",
    "entity_output" => "as_char",
    "smart_quotes"  => "lsquo,rsquo,ldquo,rdquo",
    "input"         => "GFM",
    "hard_wrap"     => false,
    "footnote_nr"   => 1
  }
}.map { |k, v| [k, v.freeze] }].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from(user_config) ⇒ Object

Static: Produce a Configuration ready for use in a Site. It takes the input, fills in the defaults where values do not exist, and patches common issues including migrating options for backwards compatiblity. Except where a key or value is being fixed, the user configuration will override the defaults.

user_config - a Hash or Configuration of overrides.

Returns a Configuration filled with defaults and fixed for common problems and backwards-compatibility.



92
93
94
95
# File 'lib/bunto/configuration.rb', line 92

def from(user_config)
  Utils.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys)
    .fix_common_issues.add_default_collections
end

Instance Method Details

#add_default_collectionsObject



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/bunto/configuration.rb', line 257

def add_default_collections
  config = clone

  # It defaults to `{}`, so this is only if someone sets it to null manually.
  return config if config["collections"].nil?

  # Ensure we have a hash.
  if config["collections"].is_a?(Array)
    config["collections"] = Hash[config["collections"].map { |c| [c, {}] }]
  end

  config["collections"] = Utils.deep_merge_hashes(
    { "posts" => {} }, config["collections"]
  ).tap do |collections|
    collections["posts"]["output"] = true
    if config["permalink"]
      collections["posts"]["permalink"] ||= style_to_permalink(config["permalink"])
    end
  end

  config
end

#backwards_compatibilizeObject

Public: Ensure the proper options are set in the configuration to allow for backwards-compatibility with Bunto pre-1.0

Returns the backwards-compatible configuration



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/bunto/configuration.rb', line 224

def backwards_compatibilize
  config = clone
  # Provide backwards-compatibility
  check_auto(config)
  check_server(config)

  renamed_key "server_port", "port", config
  renamed_key "plugins", "plugins_dir", config
  renamed_key "layouts", "layouts_dir", config
  renamed_key "data_source", "data_dir", config

  check_pygments(config)
  check_include_exclude(config)
  check_coderay(config)
  check_maruku(config)

  config
end

#config_files(override) ⇒ Object

Public: Generate list of configuration files from the override

override - the command-line options hash

Returns an Array of config files



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/bunto/configuration.rb', line 146

def config_files(override)
  # Adjust verbosity quickly
  Bunto.logger.adjust_verbosity(
    :quiet   => quiet?(override),
    :verbose => verbose?(override)
  )

  # Get configuration from <source>/_config.yml or <source>/<config_file>
  config_files = override.delete("config")
  if config_files.to_s.empty?
    default = %w(yml yaml).find(-> { "yml" }) do |ext|
      File.exist?(Bunto.sanitized_path(source(override), "_config.#{ext}"))
    end
    config_files = Bunto.sanitized_path(source(override), "_config.#{default}")
    @default_config_file = true
  end
  config_files = [config_files] unless config_files.is_a? Array
  config_files
end

#csv_to_array(csv) ⇒ Object

Public: Split a CSV string into an array containing its values

csv - the string of comma-separated values

Returns an array of the values contained in the CSV



216
217
218
# File 'lib/bunto/configuration.rb', line 216

def csv_to_array(csv)
  csv.split(",").map(&:strip)
end

#fix_common_issuesObject



243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/bunto/configuration.rb', line 243

def fix_common_issues
  config = clone

  if config.key?("paginate") && (!config["paginate"].is_a?(Integer) ||
         config["paginate"] < 1)

    Bunto.logger.warn "Config Warning:", "The `paginate` key must be a positive" \
      " integer or nil. It's currently set to '#{config["paginate"].inspect}'."
    config["paginate"] = nil
  end

  config
end

#get_config_value_with_override(config_key, override) ⇒ Object



105
106
107
# File 'lib/bunto/configuration.rb', line 105

def get_config_value_with_override(config_key, override)
  override[config_key] || self[config_key] || DEFAULTS[config_key]
end

#quiet(override = {}) ⇒ Object Also known as: quiet?



118
119
120
# File 'lib/bunto/configuration.rb', line 118

def quiet(override = {})
  get_config_value_with_override("quiet", override)
end

#read_config_file(file) ⇒ Object

Public: Read configuration and return merged Hash

file - the path to the YAML file to be read in

Returns this configuration, overridden by the values in the file



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/bunto/configuration.rb', line 171

def read_config_file(file)
  next_config = safe_load_file(file)
  check_config_is_hash!(next_config, file)
  Bunto.logger.info "Configuration file:", file
  next_config
rescue SystemCallError
  if @default_config_file ||= nil
    Bunto.logger.warn "Configuration file:", "none"
    {}
  else
    Bunto.logger.error "Fatal:", "The configuration file '#{file}'
      could not be found."
    raise LoadError, "The Configuration file '#{file}' could not be found."
  end
end

#read_config_files(files) ⇒ Object

Public: Read in a list of configuration files and merge with this hash

files - the list of configuration file paths

Returns the full configuration, with the defaults overridden by the values in the configuration files



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/bunto/configuration.rb', line 193

def read_config_files(files)
  configuration = clone

  begin
    files.each do |config_file|
      next if config_file.nil? || config_file.empty?
      new_config = read_config_file(config_file)
      configuration = Utils.deep_merge_hashes(configuration, new_config)
    end
  rescue ArgumentError => err
    Bunto.logger.warn "WARNING:", "Error reading configuration. " \
                 "Using defaults (and options)."
    $stderr.puts err
  end

  configuration.fix_common_issues.backwards_compatibilize.add_default_collections
end

#renamed_key(old, new, config, _ = nil) ⇒ Object



280
281
282
283
284
285
286
287
# File 'lib/bunto/configuration.rb', line 280

def renamed_key(old, new, config, _ = nil)
  if config.key?(old)
    Bunto::Deprecator.deprecation_message "The '#{old}' configuration" \
      " option has been renamed to '#{new}'. Please update your config" \
      " file accordingly."
    config[new] = config.delete(old)
  end
end

#safe_load_file(filename) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/bunto/configuration.rb', line 128

def safe_load_file(filename)
  case File.extname(filename)
  when %r!\.toml!i
    Bunto::External.require_with_graceful_fail("toml") unless defined?(TOML)
    TOML.load_file(filename)
  when %r!\.ya?ml!i
    SafeYAML.load_file(filename) || {}
  else
    raise ArgumentError, "No parser for '#{filename}' is available.
      Use a .toml or .y(a)ml file instead."
  end
end

#source(override) ⇒ Object

Public: Directory of the Bunto source folder

override - the command-line options hash

Returns the path to the Bunto source directory



114
115
116
# File 'lib/bunto/configuration.rb', line 114

def source(override)
  get_config_value_with_override("source", override)
end

#stringify_keysObject

Public: Turn all keys into string

Return a copy of the hash where all its keys are strings



101
102
103
# File 'lib/bunto/configuration.rb', line 101

def stringify_keys
  reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }
end

#verbose(override = {}) ⇒ Object Also known as: verbose?



123
124
125
# File 'lib/bunto/configuration.rb', line 123

def verbose(override = {})
  get_config_value_with_override("verbose", override)
end