/
serve.rb
387 lines (330 loc) · 13.2 KB
/
serve.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# frozen_string_literal: true
require "thread"
module Jekyll
module Commands
class Serve < Command
# Similar to the pattern in Utils::ThreadEvent except we are maintaining the
# state of @running instead of just signaling an event. We have to maintain this
# state since Serve is just called via class methods instead of an instance
# being created each time.
@mutex = Mutex.new
@run_cond = ConditionVariable.new
@running = false
class << self
COMMAND_OPTIONS = {
"ssl_cert" => ["--ssl-cert [CERT]", "X.509 (SSL) certificate."],
"host" => ["host", "-H", "--host [HOST]", "Host to bind to"],
"open_url" => ["-o", "--open-url", "Launch your site in a browser"],
"detach" => ["-B", "--detach",
"Run the server in the background",],
"ssl_key" => ["--ssl-key [KEY]", "X.509 (SSL) Private Key."],
"port" => ["-P", "--port [PORT]", "Port to listen on"],
"show_dir_listing" => ["--show-dir-listing",
"Show a directory listing instead of loading your index file.",],
"skip_initial_build" => ["skip_initial_build", "--skip-initial-build",
"Skips the initial site build which occurs before the server is started.",],
"livereload" => ["-l", "--livereload",
"Use LiveReload to automatically refresh browsers",],
"livereload_ignore" => ["--livereload-ignore ignore GLOB1[,GLOB2[,...]]",
Array,
"Files for LiveReload to ignore. Remember to quote the values so your shell "\
"won't expand them",],
"livereload_min_delay" => ["--livereload-min-delay [SECONDS]",
"Minimum reload delay",],
"livereload_max_delay" => ["--livereload-max-delay [SECONDS]",
"Maximum reload delay",],
"livereload_port" => ["--livereload-port [PORT]", Integer,
"Port for LiveReload to listen on",],
}.freeze
DIRECTORY_INDEX = %w(
index.htm
index.html
index.rhtml
index.cgi
index.xml
index.json
).freeze
LIVERELOAD_PORT = 35_729
LIVERELOAD_DIR = File.join(__dir__, "serve", "livereload_assets")
attr_reader :mutex, :run_cond, :running
alias_method :running?, :running
def init_with_program(prog)
prog.command(:serve) do |cmd|
cmd.description "Serve your site locally"
cmd.syntax "serve [options]"
cmd.alias :server
cmd.alias :s
add_build_options(cmd)
COMMAND_OPTIONS.each do |key, val|
cmd.option key, *val
end
cmd.action do |_, opts|
opts["livereload_port"] ||= LIVERELOAD_PORT
opts["serving"] = true
opts["watch" ] = true unless opts.key?("watch")
start(opts)
end
end
end
#
def start(opts)
# Set the reactor to nil so any old reactor will be GCed.
# We can't unregister a hook so in testing when Serve.start is
# called multiple times we don't want to inadvertently keep using
# a reactor created by a previous test when our test might not
@reload_reactor = nil
register_reload_hooks(opts) if opts["livereload"]
config = configuration_from_options(opts)
if Jekyll.env == "development"
config["url"] = default_url(config)
end
[Build, Serve].each { |klass| klass.process(config) }
end
#
def process(opts)
opts = configuration_from_options(opts)
destination = opts["destination"]
setup(destination)
start_up_webrick(opts, destination)
end
def shutdown
@server.shutdown if running?
end
# Perform logical validation of CLI options
private
def validate_options(opts)
if opts["livereload"]
if opts["detach"]
Jekyll.logger.warn "Warning:",
"--detach and --livereload are mutually exclusive. Choosing --livereload"
opts["detach"] = false
end
if opts["ssl_cert"] || opts["ssl_key"]
# This is not technically true. LiveReload works fine over SSL, but
# EventMachine's SSL support in Windows requires building the gem's
# native extensions against OpenSSL and that proved to be a process
# so tedious that expecting users to do it is a non-starter.
Jekyll.logger.abort_with "Error:", "LiveReload does not support SSL"
end
unless opts["watch"]
# Using livereload logically implies you want to watch the files
opts["watch"] = true
end
elsif %w(livereload_min_delay
livereload_max_delay
livereload_ignore
livereload_port).any? { |o| opts[o] }
Jekyll.logger.abort_with "--livereload-min-delay, "\
"--livereload-max-delay, --livereload-ignore, and "\
"--livereload-port require the --livereload option."
end
end
#
private
# rubocop:disable Metrics/AbcSize
def register_reload_hooks(opts)
require_relative "serve/live_reload_reactor"
@reload_reactor = LiveReloadReactor.new
Jekyll::Hooks.register(:site, :post_render) do |site|
regenerator = Jekyll::Regenerator.new(site)
@changed_pages = site.pages.select do |p|
regenerator.regenerate?(p)
end
end
# A note on ignoring files: LiveReload errs on the side of reloading when it
# comes to the message it gets. If, for example, a page is ignored but a CSS
# file linked in the page isn't, the page will still be reloaded if the CSS
# file is contained in the message sent to LiveReload. Additionally, the
# path matching is very loose so that a message to reload "/" will always
# lead the page to reload since every page starts with "/".
Jekyll::Hooks.register(:site, :post_write) do
if @changed_pages && @reload_reactor && @reload_reactor.running?
ignore, @changed_pages = @changed_pages.partition do |p|
Array(opts["livereload_ignore"]).any? do |filter|
File.fnmatch(filter, Jekyll.sanitized_path(p.relative_path))
end
end
Jekyll.logger.debug "LiveReload:", "Ignoring #{ignore.map(&:relative_path)}"
@reload_reactor.reload(@changed_pages)
end
@changed_pages = nil
end
end
# Do a base pre-setup of WEBRick so that everything is in place
# when we get ready to party, checking for an setting up an error page
# and making sure our destination exists.
private
def setup(destination)
require_relative "serve/servlet"
FileUtils.mkdir_p(destination)
if File.exist?(File.join(destination, "404.html"))
WEBrick::HTTPResponse.class_eval do
def create_error_page
@header["Content-Type"] = "text/html; charset=UTF-8"
@body = IO.read(File.join(@config[:DocumentRoot], "404.html"))
end
end
end
end
#
private
def webrick_opts(opts)
opts = {
:JekyllOptions => opts,
:DoNotReverseLookup => true,
:MimeTypes => mime_types,
:DocumentRoot => opts["destination"],
:StartCallback => start_callback(opts["detach"]),
:StopCallback => stop_callback(opts["detach"]),
:BindAddress => opts["host"],
:Port => opts["port"],
:DirectoryIndex => DIRECTORY_INDEX,
}
opts[:DirectoryIndex] = [] if opts[:JekyllOptions]["show_dir_listing"]
enable_ssl(opts)
enable_logging(opts)
opts
end
#
private
def start_up_webrick(opts, destination)
if opts["livereload"]
@reload_reactor.start(opts)
end
@server = WEBrick::HTTPServer.new(webrick_opts(opts)).tap { |o| o.unmount("") }
@server.mount(opts["baseurl"].to_s, Servlet, destination, file_handler_opts)
Jekyll.logger.info "Server address:", server_address(@server, opts)
launch_browser @server, opts if opts["open_url"]
boot_or_detach @server, opts
end
# Recreate NondisclosureName under utf-8 circumstance
private
def file_handler_opts
WEBrick::Config::FileHandler.merge({
:FancyIndexing => true,
:NondisclosureName => [
".ht*", "~*",
],
})
end
#
private
def server_address(server, options = {})
format_url(
server.config[:SSLEnable],
server.config[:BindAddress],
server.config[:Port],
options["baseurl"]
)
end
private
def format_url(ssl_enabled, address, port, baseurl = nil)
format("%<prefix>s://%<address>s:%<port>i%<baseurl>s", {
:prefix => ssl_enabled ? "https" : "http",
:address => address,
:port => port,
:baseurl => baseurl ? "#{baseurl}/" : "",
})
end
#
private
def default_url(opts)
config = configuration_from_options(opts)
format_url(
config["ssl_cert"] && config["ssl_key"],
config["host"] == "127.0.0.1" ? "localhost" : config["host"],
config["port"]
)
end
#
private
def launch_browser(server, opts)
address = server_address(server, opts)
return system "start", address if Utils::Platforms.windows?
return system "xdg-open", address if Utils::Platforms.linux?
return system "open", address if Utils::Platforms.osx?
Jekyll.logger.error "Refusing to launch browser; " \
"Platform launcher unknown."
end
# Keep in our area with a thread or detach the server as requested
# by the user. This method determines what we do based on what you
# ask us to do.
private
def boot_or_detach(server, opts)
if opts["detach"]
pid = Process.fork do
server.start
end
Process.detach(pid)
Jekyll.logger.info "Server detached with pid '#{pid}'.", \
"Run `pkill -f jekyll' or `kill -9 #{pid}' to stop the server."
else
t = Thread.new { server.start }
trap("INT") { server.shutdown }
t.join
end
end
# Make the stack verbose if the user requests it.
private
def enable_logging(opts)
opts[:AccessLog] = []
level = WEBrick::Log.const_get(opts[:JekyllOptions]["verbose"] ? :DEBUG : :WARN)
opts[:Logger] = WEBrick::Log.new($stdout, level)
end
# Add SSL to the stack if the user triggers --enable-ssl and they
# provide both types of certificates commonly needed. Raise if they
# forget to add one of the certificates.
private
def enable_ssl(opts)
cert, key, src =
opts[:JekyllOptions].values_at("ssl_cert", "ssl_key", "source")
return if cert.nil? && key.nil?
raise "Missing --ssl_cert or --ssl_key. Both are required." unless cert && key
require "openssl"
require "webrick/https"
opts[:SSLCertificate] = OpenSSL::X509::Certificate.new(read_file(src, cert))
opts[:SSLPrivateKey ] = OpenSSL::PKey::RSA.new(read_file(src, key))
opts[:SSLEnable] = true
end
private
def start_callback(detached)
unless detached
proc do
mutex.synchronize do
# Block until EventMachine reactor starts
@reload_reactor.started_event.wait unless @reload_reactor.nil?
@running = true
Jekyll.logger.info("Server running...", "press ctrl-c to stop.")
@run_cond.broadcast
end
end
end
end
private
def stop_callback(detached)
unless detached
proc do
mutex.synchronize do
unless @reload_reactor.nil?
@reload_reactor.stop
@reload_reactor.stopped_event.wait
end
@running = false
@run_cond.broadcast
end
end
end
end
private
def mime_types
file = File.expand_path("../mime.types", __dir__)
WEBrick::HTTPUtils.load_mime_types(file)
end
private
def read_file(source_dir, file_path)
File.read(Jekyll.sanitized_path(source_dir, file_path))
end
end
end
end
end