middleman/middleman-core/lib/middleman-core/extensions/external_pipeline.rb

89 lines
2.3 KiB
Ruby
Raw Normal View History

2014-07-11 23:24:22 +02:00
class Middleman::Extensions::ExternalPipeline < ::Middleman::Extension
self.supports_multiple_instances = true
2014-07-24 06:08:20 +02:00
option :name, nil, 'The name of the pipeline', required: true
option :command, nil, 'The command to initialize', required: true
option :source, nil, 'Path to merge into sitemap', required: true
2014-07-11 23:24:22 +02:00
option :latency, 0.25, 'Latency between refreshes of source'
option :disable_background_execution, false, "Don't run the command in a separate background thread"
2014-07-11 23:24:22 +02:00
def initialize(app, config={}, &block)
super
return if app.mode?(:config)
require 'servolux'
2014-07-11 23:24:22 +02:00
require 'thread'
2016-03-25 18:16:54 +01:00
require 'fileutils'
source_path = File.expand_path(options[:source], app.root)
# Make sure it exists, or `listen` will explode.
::FileUtils.mkdir_p(source_path)
2014-07-11 23:24:22 +02:00
2015-12-08 23:46:03 +01:00
@watcher = app.files.watch :source,
2016-03-25 18:16:54 +01:00
path: source_path,
latency: options[:latency],
frontmatter: false
2014-07-11 23:24:22 +02:00
@current_thread = nil
app.reload(&method(:reload!))
2015-12-08 23:46:03 +01:00
logger.info "== Executing: `#{options[:command]}`"
if app.build? || options[:disable_background_execution]
watch_command!(false)
@watcher.poll_once!
2015-12-10 02:03:55 +01:00
else
watch_command!(true)
end
end
def reload!
if @current_thread
logger.info "== Stopping: `#{options[:command]}`"
@current_thread.stop
@current_thread = nil
2014-07-11 23:24:22 +02:00
end
end
def watch_command!(async)
@current_thread = ::Servolux::Child.new(
command: options[:command],
suspend: 2
)
@current_thread.start
watch_thread = Thread.new do
while buf = @current_thread.io.gets
2014-07-24 06:08:20 +02:00
without_newline = buf.sub(/\n$/, '')
logger.info "== External: #{without_newline}" unless without_newline.empty?
2014-07-11 23:24:22 +02:00
end
@current_thread.wait
if !@current_thread.exitstatus.nil? && @current_thread.exitstatus != 0
logger.error '== External: Command failed with non-zero exit status'
exit(1)
end
end
watch_thread.join unless async
rescue ::Errno::ENOENT => e
logger.error "== External: Command failed with message: #{e.message}"
exit(1)
2014-07-11 23:24:22 +02:00
end
private
def print_command(stdout)
while buf = stdout.gets
without_newline = buf.sub(/\n$/, '')
logger.info "== External: #{without_newline}" unless without_newline.empty?
end
end
2014-07-11 23:24:22 +02:00
end