bridgetown-core 0.7.0 → 0.7.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (107) hide show
  1. checksums.yaml +4 -4
  2. data/Rakefile +42 -0
  3. data/bridgetown-core.gemspec +46 -0
  4. data/lib/bridgetown-core.rb +202 -0
  5. data/lib/bridgetown-core/cache.rb +190 -0
  6. data/lib/bridgetown-core/cleaner.rb +111 -0
  7. data/lib/bridgetown-core/collection.rb +279 -0
  8. data/lib/bridgetown-core/command.rb +106 -0
  9. data/lib/bridgetown-core/commands/build.rb +96 -0
  10. data/lib/bridgetown-core/commands/clean.rb +43 -0
  11. data/lib/bridgetown-core/commands/console.rb +56 -0
  12. data/lib/bridgetown-core/commands/doctor.rb +172 -0
  13. data/lib/bridgetown-core/commands/help.rb +34 -0
  14. data/lib/bridgetown-core/commands/new.rb +148 -0
  15. data/lib/bridgetown-core/commands/serve.rb +273 -0
  16. data/lib/bridgetown-core/commands/serve/servlet.rb +68 -0
  17. data/lib/bridgetown-core/configuration.rb +323 -0
  18. data/lib/bridgetown-core/converter.rb +54 -0
  19. data/lib/bridgetown-core/converters/identity.rb +39 -0
  20. data/lib/bridgetown-core/converters/markdown.rb +108 -0
  21. data/lib/bridgetown-core/converters/markdown/kramdown_parser.rb +132 -0
  22. data/lib/bridgetown-core/converters/smartypants.rb +69 -0
  23. data/lib/bridgetown-core/convertible.rb +237 -0
  24. data/lib/bridgetown-core/deprecator.rb +50 -0
  25. data/lib/bridgetown-core/document.rb +475 -0
  26. data/lib/bridgetown-core/drops/bridgetown_drop.rb +32 -0
  27. data/lib/bridgetown-core/drops/collection_drop.rb +20 -0
  28. data/lib/bridgetown-core/drops/document_drop.rb +69 -0
  29. data/lib/bridgetown-core/drops/drop.rb +215 -0
  30. data/lib/bridgetown-core/drops/excerpt_drop.rb +19 -0
  31. data/lib/bridgetown-core/drops/page_drop.rb +14 -0
  32. data/lib/bridgetown-core/drops/site_drop.rb +62 -0
  33. data/lib/bridgetown-core/drops/static_file_drop.rb +14 -0
  34. data/lib/bridgetown-core/drops/unified_payload_drop.rb +26 -0
  35. data/lib/bridgetown-core/drops/url_drop.rb +132 -0
  36. data/lib/bridgetown-core/entry_filter.rb +108 -0
  37. data/lib/bridgetown-core/errors.rb +20 -0
  38. data/lib/bridgetown-core/excerpt.rb +202 -0
  39. data/lib/bridgetown-core/external.rb +62 -0
  40. data/lib/bridgetown-core/filters.rb +467 -0
  41. data/lib/bridgetown-core/filters/date_filters.rb +110 -0
  42. data/lib/bridgetown-core/filters/grouping_filters.rb +64 -0
  43. data/lib/bridgetown-core/filters/url_filters.rb +79 -0
  44. data/lib/bridgetown-core/frontmatter_defaults.rb +238 -0
  45. data/lib/bridgetown-core/generator.rb +5 -0
  46. data/lib/bridgetown-core/hooks.rb +103 -0
  47. data/lib/bridgetown-core/layout.rb +57 -0
  48. data/lib/bridgetown-core/liquid_extensions.rb +22 -0
  49. data/lib/bridgetown-core/liquid_renderer.rb +71 -0
  50. data/lib/bridgetown-core/liquid_renderer/file.rb +67 -0
  51. data/lib/bridgetown-core/liquid_renderer/table.rb +75 -0
  52. data/lib/bridgetown-core/log_adapter.rb +151 -0
  53. data/lib/bridgetown-core/log_writer.rb +60 -0
  54. data/lib/bridgetown-core/mime.types +867 -0
  55. data/lib/bridgetown-core/page.rb +214 -0
  56. data/lib/bridgetown-core/page_without_a_file.rb +14 -0
  57. data/lib/bridgetown-core/path_manager.rb +31 -0
  58. data/lib/bridgetown-core/plugin.rb +80 -0
  59. data/lib/bridgetown-core/plugin_manager.rb +60 -0
  60. data/lib/bridgetown-core/publisher.rb +23 -0
  61. data/lib/bridgetown-core/reader.rb +185 -0
  62. data/lib/bridgetown-core/readers/collection_reader.rb +22 -0
  63. data/lib/bridgetown-core/readers/data_reader.rb +75 -0
  64. data/lib/bridgetown-core/readers/layout_reader.rb +48 -0
  65. data/lib/bridgetown-core/readers/page_reader.rb +24 -0
  66. data/lib/bridgetown-core/readers/post_reader.rb +74 -0
  67. data/lib/bridgetown-core/readers/static_file_reader.rb +24 -0
  68. data/lib/bridgetown-core/regenerator.rb +195 -0
  69. data/lib/bridgetown-core/related_posts.rb +52 -0
  70. data/lib/bridgetown-core/renderer.rb +261 -0
  71. data/lib/bridgetown-core/site.rb +469 -0
  72. data/lib/bridgetown-core/static_file.rb +205 -0
  73. data/lib/bridgetown-core/tags/component.rb +34 -0
  74. data/lib/bridgetown-core/tags/highlight.rb +111 -0
  75. data/lib/bridgetown-core/tags/include.rb +220 -0
  76. data/lib/bridgetown-core/tags/link.rb +41 -0
  77. data/lib/bridgetown-core/tags/post_url.rb +107 -0
  78. data/lib/bridgetown-core/url.rb +164 -0
  79. data/lib/bridgetown-core/utils.rb +367 -0
  80. data/lib/bridgetown-core/utils/ansi.rb +57 -0
  81. data/lib/bridgetown-core/utils/exec.rb +26 -0
  82. data/lib/bridgetown-core/utils/internet.rb +37 -0
  83. data/lib/bridgetown-core/utils/platforms.rb +80 -0
  84. data/lib/bridgetown-core/utils/thread_event.rb +31 -0
  85. data/lib/bridgetown-core/utils/win_tz.rb +75 -0
  86. data/lib/bridgetown-core/version.rb +5 -0
  87. data/lib/bridgetown-core/watcher.rb +139 -0
  88. data/lib/site_template/.gitignore +6 -0
  89. data/lib/site_template/bridgetown.config.yml +21 -0
  90. data/lib/site_template/frontend/javascript/index.js +3 -0
  91. data/lib/site_template/frontend/styles/index.scss +17 -0
  92. data/lib/site_template/package.json +23 -0
  93. data/lib/site_template/src/404.html +9 -0
  94. data/lib/site_template/src/_data/site_metadata.yml +11 -0
  95. data/lib/site_template/src/_includes/footer.html +3 -0
  96. data/lib/site_template/src/_includes/head.html +9 -0
  97. data/lib/site_template/src/_includes/navbar.html +4 -0
  98. data/lib/site_template/src/_layouts/default.html +15 -0
  99. data/lib/site_template/src/_layouts/home.html +7 -0
  100. data/lib/site_template/src/_layouts/page.html +7 -0
  101. data/lib/site_template/src/_layouts/post.html +7 -0
  102. data/lib/site_template/src/_posts/0000-00-00-welcome-to-bridgetown.md.erb +26 -0
  103. data/lib/site_template/src/about.md +11 -0
  104. data/lib/site_template/src/index.md +7 -0
  105. data/lib/site_template/webpack.config.js +60 -0
  106. data/rake/release.rake +30 -0
  107. metadata +106 -1
@@ -0,0 +1,273 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bridgetown
4
+ module Commands
5
+ class Serve < Command
6
+ # Similar to the pattern in Utils::ThreadEvent except we are maintaining the
7
+ # state of @running instead of just signaling an event. We have to maintain this
8
+ # state since Serve is just called via class methods instead of an instance
9
+ # being created each time.
10
+ @mutex = Mutex.new
11
+ @run_cond = ConditionVariable.new
12
+ @running = false
13
+
14
+ class << self
15
+ COMMAND_OPTIONS = {
16
+ "ssl_cert" => ["--ssl-cert [CERT]", "X.509 (SSL) certificate."],
17
+ "host" => ["host", "-H", "--host [HOST]", "Host to bind to"],
18
+ "open_url" => ["-o", "--open-url", "Launch your site in a browser"],
19
+ "detach" => ["-B", "--detach",
20
+ "Run the server in the background",],
21
+ "ssl_key" => ["--ssl-key [KEY]", "X.509 (SSL) Private Key."],
22
+ "port" => ["-P", "--port [PORT]", "Port to listen on"],
23
+ "show_dir_listing" => ["--show-dir-listing",
24
+ "Show a directory listing instead of loading" \
25
+ " your index file.",],
26
+ "skip_initial_build" => ["skip_initial_build", "--skip-initial-build",
27
+ "Skips the initial site build which occurs before" \
28
+ " the server is started.",],
29
+ }.freeze
30
+
31
+ DIRECTORY_INDEX = %w(
32
+ index.htm
33
+ index.html
34
+ index.rhtml
35
+ index.xht
36
+ index.xhtml
37
+ index.cgi
38
+ index.xml
39
+ index.json
40
+ ).freeze
41
+
42
+ attr_reader :mutex, :run_cond, :running
43
+ alias_method :running?, :running
44
+
45
+ def init_with_program(prog)
46
+ prog.command(:serve) do |cmd|
47
+ cmd.description "Serve your site locally"
48
+ cmd.syntax "serve [options]"
49
+ cmd.alias :server
50
+ cmd.alias :s
51
+
52
+ add_build_options(cmd)
53
+ COMMAND_OPTIONS.each do |key, val|
54
+ cmd.option key, *val
55
+ end
56
+
57
+ cmd.action do |_, opts|
58
+ opts["serving"] = true
59
+ opts["watch"] = true unless opts.key?("watch")
60
+
61
+ config = configuration_from_options(opts)
62
+ config["url"] = default_url(config) if Bridgetown.env == "development"
63
+
64
+ process_with_graceful_fail(cmd, config, Build, Serve)
65
+ end
66
+ end
67
+ end
68
+
69
+ #
70
+
71
+ def process(opts)
72
+ opts = configuration_from_options(opts)
73
+ destination = opts["destination"]
74
+ setup(destination)
75
+
76
+ start_up_webrick(opts, destination)
77
+ end
78
+
79
+ def shutdown
80
+ @server.shutdown if running?
81
+ end
82
+
83
+ private
84
+
85
+ # Do a base pre-setup of WEBRick so that everything is in place
86
+ # when we get ready to party, checking for an setting up an error page
87
+ # and making sure our destination exists.
88
+
89
+ def setup(destination)
90
+ require_relative "serve/servlet"
91
+
92
+ FileUtils.mkdir_p(destination)
93
+ if File.exist?(File.join(destination, "404.html"))
94
+ WEBrick::HTTPResponse.class_eval do
95
+ def create_error_page
96
+ @header["Content-Type"] = "text/html; charset=UTF-8"
97
+ @body = IO.read(File.join(@config[:DocumentRoot], "404.html"))
98
+ end
99
+ end
100
+ end
101
+ end
102
+
103
+ def webrick_opts(opts)
104
+ opts = {
105
+ :BridgetownOptions => opts,
106
+ :DoNotReverseLookup => true,
107
+ :MimeTypes => mime_types,
108
+ :DocumentRoot => opts["destination"],
109
+ :StartCallback => start_callback(opts["detach"]),
110
+ :StopCallback => stop_callback(opts["detach"]),
111
+ :BindAddress => opts["host"],
112
+ :Port => opts["port"],
113
+ :DirectoryIndex => DIRECTORY_INDEX,
114
+ }
115
+
116
+ opts[:DirectoryIndex] = [] if opts[:BridgetownOptions]["show_dir_listing"]
117
+
118
+ enable_ssl(opts)
119
+ enable_logging(opts)
120
+ opts
121
+ end
122
+
123
+ def start_up_webrick(opts, destination)
124
+ @reload_reactor.start(opts) if opts["livereload"]
125
+
126
+ @server = WEBrick::HTTPServer.new(webrick_opts(opts)).tap { |o| o.unmount("") }
127
+ @server.mount(opts["baseurl"].to_s, Servlet, destination, file_handler_opts)
128
+
129
+ Bridgetown.logger.info "Server address:", server_address(@server, opts)
130
+ launch_browser @server, opts if opts["open_url"]
131
+ boot_or_detach @server, opts
132
+ end
133
+
134
+ # Recreate NondisclosureName under utf-8 circumstance
135
+ def file_handler_opts
136
+ WEBrick::Config::FileHandler.merge(
137
+ :FancyIndexing => true,
138
+ :NondisclosureName => [
139
+ ".ht*", "~*",
140
+ ]
141
+ )
142
+ end
143
+
144
+ def server_address(server, options = {})
145
+ format_url(
146
+ server.config[:SSLEnable],
147
+ server.config[:BindAddress],
148
+ server.config[:Port],
149
+ options["baseurl"]
150
+ )
151
+ end
152
+
153
+ def format_url(ssl_enabled, address, port, baseurl = nil)
154
+ format("%<prefix>s://%<address>s:%<port>i%<baseurl>s",
155
+ :prefix => ssl_enabled ? "https" : "http",
156
+ :address => address,
157
+ :port => port,
158
+ :baseurl => baseurl ? "#{baseurl}/" : "")
159
+ end
160
+
161
+ def default_url(opts)
162
+ config = configuration_from_options(opts)
163
+ format_url(
164
+ config["ssl_cert"] && config["ssl_key"],
165
+ config["host"] == "127.0.0.1" ? "localhost" : config["host"],
166
+ config["port"]
167
+ )
168
+ end
169
+
170
+ def launch_browser(server, opts)
171
+ address = server_address(server, opts)
172
+ return system "start", address if Utils::Platforms.windows?
173
+ return system "xdg-open", address if Utils::Platforms.linux?
174
+ return system "open", address if Utils::Platforms.osx?
175
+
176
+ Bridgetown.logger.error "Refusing to launch browser; " \
177
+ "Platform launcher unknown."
178
+ end
179
+
180
+ # Keep in our area with a thread or detach the server as requested
181
+ # by the user. This method determines what we do based on what you
182
+ # ask us to do.
183
+ def boot_or_detach(server, opts)
184
+ if opts["detach"]
185
+ pid = Process.fork do
186
+ server.start
187
+ end
188
+
189
+ Process.detach(pid)
190
+ Bridgetown.logger.info "Server detached with pid '#{pid}'.", \
191
+ "Run `pkill -f bridgetown' or `kill -9 #{pid}'" \
192
+ " to stop the server."
193
+ else
194
+ t = Thread.new { server.start }
195
+ trap("INT") { server.shutdown }
196
+ t.join
197
+ end
198
+ end
199
+
200
+ # Make the stack verbose if the user requests it.
201
+ def enable_logging(opts)
202
+ opts[:AccessLog] = []
203
+ level = WEBrick::Log.const_get(opts[:BridgetownOptions]["verbose"] ? :DEBUG : :WARN)
204
+ opts[:Logger] = WEBrick::Log.new($stdout, level)
205
+ end
206
+
207
+ # Add SSL to the stack if the user triggers --enable-ssl and they
208
+ # provide both types of certificates commonly needed. Raise if they
209
+ # forget to add one of the certificates.
210
+ def enable_ssl(opts)
211
+ cert, key, src =
212
+ opts[:BridgetownOptions].values_at("ssl_cert", "ssl_key", "source")
213
+
214
+ return if cert.nil? && key.nil?
215
+ raise "Missing --ssl_cert or --ssl_key. Both are required." unless cert && key
216
+
217
+ require "openssl"
218
+ require "webrick/https"
219
+
220
+ opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(read_file(src, cert))
221
+ begin
222
+ opts[:SSLPrivateKey] = OpenSSL::PKey::RSA.new(read_file(src, key))
223
+ rescue StandardError
224
+ if defined?(OpenSSL::PKey::EC)
225
+ opts[:SSLPrivateKey] = OpenSSL::PKey::EC.new(read_file(src, key))
226
+ else
227
+ raise
228
+ end
229
+ end
230
+ opts[:SSLEnable] = true
231
+ end
232
+
233
+ def start_callback(detached)
234
+ unless detached
235
+ proc do
236
+ mutex.synchronize do
237
+ # Block until EventMachine reactor starts
238
+ @reload_reactor&.started_event&.wait
239
+ @running = true
240
+ Bridgetown.logger.info("Server running…", "press ctrl-c to stop.")
241
+ @run_cond.broadcast
242
+ end
243
+ end
244
+ end
245
+ end
246
+
247
+ def stop_callback(detached)
248
+ unless detached
249
+ proc do
250
+ mutex.synchronize do
251
+ unless @reload_reactor.nil?
252
+ @reload_reactor.stop
253
+ @reload_reactor.stopped_event.wait
254
+ end
255
+ @running = false
256
+ @run_cond.broadcast
257
+ end
258
+ end
259
+ end
260
+ end
261
+
262
+ def mime_types
263
+ file = File.expand_path("../mime.types", __dir__)
264
+ WEBrick::HTTPUtils.load_mime_types(file)
265
+ end
266
+
267
+ def read_file(source_dir, file_path)
268
+ File.read(Bridgetown.sanitized_path(source_dir, file_path))
269
+ end
270
+ end
271
+ end
272
+ end
273
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "webrick"
4
+
5
+ module Bridgetown
6
+ module Commands
7
+ class Serve
8
+ class Servlet < WEBrick::HTTPServlet::FileHandler
9
+ DEFAULTS = {
10
+ "Cache-Control" => "private, max-age=0, proxy-revalidate, " \
11
+ "no-store, no-cache, must-revalidate",
12
+ }.freeze
13
+
14
+ def initialize(server, root, callbacks)
15
+ # So we can access them easily.
16
+ @bridgetown_opts = server.config[:BridgetownOptions]
17
+ set_defaults
18
+ super
19
+ end
20
+
21
+ def search_index_file(req, res)
22
+ super ||
23
+ search_file(req, res, ".html") ||
24
+ search_file(req, res, ".xhtml")
25
+ end
26
+
27
+ # Add the ability to tap file.html the same way that Nginx does on our
28
+ # Docker images (or on GitHub Pages.) The difference is that we might end
29
+ # up with a different preference on which comes first.
30
+
31
+ def search_file(req, res, basename)
32
+ # /file.* > /file/index.html > /file.html
33
+ super ||
34
+ super(req, res, "#{basename}.html") ||
35
+ super(req, res, "#{basename}.xhtml")
36
+ end
37
+
38
+ # rubocop:disable Naming/MethodName
39
+ def do_GET(req, res)
40
+ rtn = super
41
+
42
+ validate_and_ensure_charset(req, res)
43
+ res.header.merge!(@headers)
44
+ rtn
45
+ end
46
+ # rubocop:enable Naming/MethodName
47
+
48
+ private
49
+
50
+ def validate_and_ensure_charset(_req, res)
51
+ key = res.header.keys.grep(%r!content-type!i).first
52
+ typ = res.header[key]
53
+
54
+ unless %r!;\s*charset=!.match?(typ)
55
+ res.header[key] = "#{typ}; charset=#{@bridgetown_opts["encoding"]}"
56
+ end
57
+ end
58
+
59
+ def set_defaults
60
+ hash_ = @bridgetown_opts.fetch("webrick", {}).fetch("headers", {})
61
+ DEFAULTS.each_with_object(@headers = hash_) do |(key, val), hash|
62
+ hash[key] = val unless hash.key?(key)
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,323 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Bridgetown
4
+ class Configuration < Hash
5
+ # Default options. Overridden by values in bridgetown.config.yml.
6
+ # Strings rather than symbols are used for compatibility with YAML.
7
+ DEFAULTS = {
8
+ # Where things are
9
+ "root_dir" => Dir.pwd,
10
+ "plugins_dir" => "plugins",
11
+ "source" => File.join(Dir.pwd, "src"),
12
+ "destination" => File.join(Dir.pwd, "output"),
13
+ "collections_dir" => "",
14
+ "cache_dir" => ".bridgetown-cache",
15
+ "layouts_dir" => "_layouts",
16
+ "data_dir" => "_data",
17
+ "includes_dir" => "_includes",
18
+ "collections" => {},
19
+
20
+ # Handling Reading
21
+ "include" => [".htaccess", "_redirects", ".well-known"],
22
+ "exclude" => [],
23
+ "keep_files" => [".git", ".svn", "_bridgetown"],
24
+ "encoding" => "utf-8",
25
+ "markdown_ext" => "markdown,mkdown,mkdn,mkd,md",
26
+ "strict_front_matter" => false,
27
+
28
+ # Filtering Content
29
+ "limit_posts" => 0,
30
+ "future" => false,
31
+ "unpublished" => false,
32
+
33
+ # Conversion
34
+ "markdown" => "kramdown",
35
+ "highlighter" => "rouge",
36
+ "lsi" => false,
37
+ "excerpt_separator" => "\n\n",
38
+ "incremental" => false,
39
+
40
+ # Serving
41
+ "detach" => false, # default to not detaching the server
42
+ "port" => "4000",
43
+ "host" => "127.0.0.1",
44
+ "baseurl" => nil, # this mounts at /, i.e. no subdirectory
45
+ "show_dir_listing" => false,
46
+
47
+ # Output Configuration
48
+ "permalink" => "date",
49
+ "paginate_path" => "/page:num",
50
+ "timezone" => nil, # use the local timezone
51
+
52
+ "quiet" => false,
53
+ "verbose" => false,
54
+ "defaults" => [],
55
+
56
+ "liquid" => {
57
+ "error_mode" => "warn",
58
+ "strict_filters" => false,
59
+ "strict_variables" => false,
60
+ },
61
+
62
+ "kramdown" => {
63
+ "auto_ids" => true,
64
+ "toc_levels" => (1..6).to_a,
65
+ "entity_output" => "as_char",
66
+ "smart_quotes" => "lsquo,rsquo,ldquo,rdquo",
67
+ "input" => "GFM",
68
+ "hard_wrap" => false,
69
+ "guess_lang" => true,
70
+ "footnote_nr" => 1,
71
+ "show_warnings" => false,
72
+ },
73
+ }.each_with_object(Configuration.new) { |(k, v), hsh| hsh[k] = v.freeze }.freeze
74
+
75
+ # The modern default config file name is bridgetown.config.EXT, but we also
76
+ # need to check for _config.EXT as a backward-compatibility nod to our
77
+ # progenitor
78
+ CONFIG_FILE_PREFIXES = %w(bridgetown.config _config).freeze
79
+ CONFIG_FILE_EXTS = %w(yml yaml toml).freeze
80
+
81
+ class << self
82
+ # Static: Produce a Configuration ready for use in a Site.
83
+ # It takes the input, fills in the defaults where values do not exist.
84
+ #
85
+ # user_config - a Hash or Configuration of overrides.
86
+ #
87
+ # Returns a Configuration filled with defaults.
88
+ def from(user_config)
89
+ Utils.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys)
90
+ .add_default_collections.add_default_excludes
91
+ end
92
+ end
93
+
94
+ # Public: Turn all keys into string
95
+ #
96
+ # Return a copy of the hash where all its keys are strings
97
+ def stringify_keys
98
+ each_with_object({}) { |(k, v), hsh| hsh[k.to_s] = v }
99
+ end
100
+
101
+ def get_config_value_with_override(config_key, override)
102
+ override[config_key] || self[config_key] || DEFAULTS[config_key]
103
+ end
104
+
105
+ # Public: Directory of the top-level root where config files are located
106
+ #
107
+ # override - the command-line options hash
108
+ #
109
+ # Returns the path to the Bridgetown root directory
110
+ def root_dir(override)
111
+ get_config_value_with_override("root_dir", override)
112
+ end
113
+
114
+ # Public: Directory of the Bridgetown source folder
115
+ #
116
+ # override - the command-line options hash
117
+ #
118
+ # Returns the path to the Bridgetown source directory
119
+ def source(override)
120
+ get_config_value_with_override("source", override)
121
+ end
122
+
123
+ def quiet(override = {})
124
+ get_config_value_with_override("quiet", override)
125
+ end
126
+ alias_method :quiet?, :quiet
127
+
128
+ def verbose(override = {})
129
+ get_config_value_with_override("verbose", override)
130
+ end
131
+ alias_method :verbose?, :verbose
132
+
133
+ def safe_load_file(filename)
134
+ case File.extname(filename)
135
+ when %r!\.toml!i
136
+ Bridgetown::External.require_with_graceful_fail("tomlrb") unless defined?(Tomlrb)
137
+ Tomlrb.load_file(filename)
138
+ when %r!\.ya?ml!i
139
+ SafeYAML.load_file(filename) || {}
140
+ else
141
+ raise ArgumentError,
142
+ "No parser for '#{filename}' is available. Use a .y(a)ml or .toml file instead."
143
+ end
144
+ end
145
+
146
+ # Public: Generate list of configuration files from the override
147
+ #
148
+ # override - the command-line options hash
149
+ #
150
+ # Returns an Array of config files
151
+ def config_files(override)
152
+ # Adjust verbosity quickly
153
+ Bridgetown.logger.adjust_verbosity(
154
+ :quiet => quiet?(override),
155
+ :verbose => verbose?(override)
156
+ )
157
+
158
+ # Get configuration from <root_dir>/<matching_default_config>
159
+ # or <root_dir>/<config_file> if there's a command line override.
160
+ # By default only the first matching config file will be loaded, but
161
+ # multiple configs can be specified via command line.
162
+ config_files = override["config"]
163
+ if config_files.to_s.empty?
164
+ file_lookups = CONFIG_FILE_PREFIXES.map do |prefix|
165
+ CONFIG_FILE_EXTS.map do |ext|
166
+ Bridgetown.sanitized_path(root_dir(override), "#{prefix}.#{ext}")
167
+ end
168
+ end.flatten.freeze
169
+
170
+ found_file = file_lookups.find do |path|
171
+ File.exist?(path)
172
+ end
173
+
174
+ config_files = found_file || file_lookups.first
175
+ @default_config_file = true
176
+ end
177
+ Array(config_files)
178
+ end
179
+
180
+ # Public: Read configuration and return merged Hash
181
+ #
182
+ # file - the path to the YAML file to be read in
183
+ #
184
+ # Returns this configuration, overridden by the values in the file
185
+ def read_config_file(file)
186
+ file = File.expand_path(file)
187
+ next_config = safe_load_file(file)
188
+
189
+ unless next_config.is_a?(Hash)
190
+ raise ArgumentError, "Configuration file: (INVALID) #{file}".yellow
191
+ end
192
+
193
+ Bridgetown.logger.info "Configuration file:", file
194
+ next_config
195
+ rescue SystemCallError
196
+ if @default_config_file ||= nil
197
+ Bridgetown.logger.warn "Configuration file:", "none"
198
+ {}
199
+ else
200
+ Bridgetown.logger.error "Fatal:", "The configuration file '#{file}' could not be found."
201
+ raise LoadError, "The Configuration file '#{file}' could not be found."
202
+ end
203
+ end
204
+
205
+ # Public: Read in a list of configuration files and merge with this hash
206
+ #
207
+ # files - the list of configuration file paths
208
+ #
209
+ # Returns the full configuration, with the defaults overridden by the values in the
210
+ # configuration files
211
+ def read_config_files(files)
212
+ configuration = clone
213
+
214
+ begin
215
+ files.each do |config_file|
216
+ next if config_file.nil? || config_file.empty?
217
+
218
+ new_config = read_config_file(config_file)
219
+ configuration = Utils.deep_merge_hashes(configuration, new_config)
220
+ end
221
+ rescue ArgumentError => e
222
+ Bridgetown.logger.warn "WARNING:", "Error reading configuration. Using defaults" \
223
+ " (and options)."
224
+ warn e
225
+ end
226
+
227
+ configuration.validate.add_default_collections
228
+ end
229
+
230
+ # Public: Split a CSV string into an array containing its values
231
+ #
232
+ # csv - the string of comma-separated values
233
+ #
234
+ # Returns an array of the values contained in the CSV
235
+ def csv_to_array(csv)
236
+ csv.split(",").map(&:strip)
237
+ end
238
+
239
+ # Public: Ensure the proper options are set in the configuration
240
+ #
241
+ # Returns the configuration Hash
242
+ def validate
243
+ config = clone
244
+
245
+ check_include_exclude(config)
246
+
247
+ config
248
+ end
249
+
250
+ def add_default_collections
251
+ config = clone
252
+
253
+ # It defaults to `{}`, so this is only if someone sets it to null manually.
254
+ return config if config["collections"].nil?
255
+
256
+ # Ensure we have a hash.
257
+ if config["collections"].is_a?(Array)
258
+ config["collections"] = config["collections"].each_with_object({}) do |collection, hash|
259
+ hash[collection] = {}
260
+ end
261
+ end
262
+
263
+ config["collections"] = Utils.deep_merge_hashes(
264
+ { "posts" => {} }, config["collections"]
265
+ ).tap do |collections|
266
+ collections["posts"]["output"] = true
267
+ if config["permalink"]
268
+ collections["posts"]["permalink"] ||= style_to_permalink(config["permalink"])
269
+ end
270
+ end
271
+
272
+ config
273
+ end
274
+
275
+ DEFAULT_EXCLUDES = %w(
276
+ .sass-cache .bridgetown-cache
277
+ gemfiles Gemfile Gemfile.lock
278
+ node_modules
279
+ vendor/bundle/ vendor/cache/ vendor/gems/ vendor/ruby/
280
+ ).freeze
281
+
282
+ def add_default_excludes
283
+ config = clone
284
+ return config if config["exclude"].nil?
285
+
286
+ config["exclude"].concat(DEFAULT_EXCLUDES).uniq!
287
+ config
288
+ end
289
+
290
+ private
291
+
292
+ # rubocop:disable Metrics/CyclomaticComplexity #
293
+ def style_to_permalink(permalink_style)
294
+ case permalink_style.to_sym
295
+ when :pretty
296
+ "/:categories/:year/:month/:day/:title/"
297
+ when :simple
298
+ "/:categories/:title/"
299
+ when :none
300
+ "/:categories/:title:output_ext"
301
+ when :date
302
+ "/:categories/:year/:month/:day/:title:output_ext"
303
+ when :ordinal
304
+ "/:categories/:year/:y_day/:title:output_ext"
305
+ when :weekdate
306
+ "/:categories/:year/W:week/:short_day/:title:output_ext"
307
+ else
308
+ permalink_style.to_s
309
+ end
310
+ end
311
+ # rubocop:enable Metrics/CyclomaticComplexity #
312
+
313
+ def check_include_exclude(config)
314
+ %w(include exclude).each do |option|
315
+ next unless config.key?(option)
316
+ next if config[option].is_a?(Array)
317
+
318
+ raise Bridgetown::Errors::InvalidConfigurationError,
319
+ "'#{option}' should be set as an array, but was: #{config[option].inspect}."
320
+ end
321
+ end
322
+ end
323
+ end