def self.render(input, options = {}, &block)
in_place = options.delete(:in_place) || false
to_file = options.delete(:to_file)
to_dir = options.delete(:to_dir)
mkdirs = options.delete(:mkdirs) || false
monitor = options.fetch(:monitor, false)
write_in_place = in_place && input.is_a?(File)
write_to_target = to_file || to_dir
stream_output = !to_file.nil? && to_file.respond_to?(:write)
if write_in_place && write_to_target
raise ArgumentError, 'the option :in_place cannot be used with either the :to_dir or :to_file option'
end
if !options.has_key?(:header_footer) && (write_in_place || write_to_target)
options[:header_footer] = true
end
doc = Asciidoctor.load(input, options, &block)
if to_file == '/dev/null'
return doc
elsif write_in_place
to_file = File.join(File.dirname(input.path), "#{doc.attributes['docname']}#{doc.attributes['outfilesuffix']}")
elsif !stream_output && write_to_target
working_dir = options.has_key?(:base_dir) ? File.expand_path(options[:base_dir]) : File.expand_path(Dir.pwd)
jail = doc.safe >= SafeMode::SAFE ? working_dir : nil
if to_dir
to_dir = doc.normalize_system_path(to_dir, working_dir, jail, :target_name => 'to_dir', :recover => false)
if to_file
to_file = doc.normalize_system_path(to_file, to_dir, nil, :target_name => 'to_dir', :recover => false)
to_dir = File.dirname(to_file)
else
to_file = File.join(to_dir, "#{doc.attributes['docname']}#{doc.attributes['outfilesuffix']}")
end
elsif to_file
to_file = doc.normalize_system_path(to_file, working_dir, jail, :target_name => 'to_dir', :recover => false)
to_dir = File.dirname(to_file)
end
if !File.directory? to_dir
if mkdirs
Helpers.require_library 'fileutils'
FileUtils.mkdir_p to_dir
else
raise IOError, "target directory does not exist: #{to_dir}"
end
end
end
start = Time.now if monitor
output = doc.render
if monitor
render_time = Time.now - start
monitor[:render] = render_time
monitor[:load_render] = monitor[:load] + render_time
end
if to_file
start = Time.now if monitor
if stream_output
to_file.write output.rstrip
to_file.write "\n"
else
File.open(to_file, 'w') {|file| file.write output }
doc.attributes['outfile'] = outfile = File.expand_path(to_file)
doc.attributes['outdir'] = File.dirname(outfile)
end
if monitor
write_time = Time.now - start
monitor[:write] = write_time
monitor[:total] = monitor[:load_render] + write_time
end
if !stream_output && doc.attr?('basebackend-html') && doc.attr?('copycss') &&
doc.attr?('linkcss') && DEFAULT_STYLESHEET_KEYS.include?(doc.attr('stylesheet'))
Helpers.require_library 'fileutils'
outdir = doc.attr('outdir')
stylesdir = doc.normalize_system_path(doc.attr('stylesdir'), outdir,
doc.safe >= SafeMode::SAFE ? outdir : nil)
Helpers.mkdir_p stylesdir
File.open(File.join(stylesdir, DEFAULT_STYLESHEET_NAME), 'w') {|f|
f.write Asciidoctor::HTML5.default_asciidoctor_stylesheet
}
end
doc
else
output
end
end