scratch/lib/mpost.rb

67 lines
2.4 KiB
Ruby
Raw Normal View History

2012-10-13 16:42:26 +00:00
class MPost < Nanoc3::Filter
identifier :mpost
2012-10-19 12:57:47 +00:00
@@tmp="/tmp/mp/"
2012-10-13 16:42:26 +00:00
@@name=["Zero","One","Two","Three"]
def solarized(str)
str.gsub(
2012-10-18 10:27:46 +00:00
%r{base0([0123])},'base'+@@name[0]+@@name[$1.to_i]
2012-10-13 16:42:26 +00:00
).gsub(
2012-10-18 10:27:46 +00:00
%r{base([0123])},'base'+@@name[$1.to_i]
2012-10-13 16:42:26 +00:00
).gsub(
%{red},'s_red'
).gsub(
%{blue},'s_blue'
).gsub(
%{green},'s_green'
)
end
2012-10-18 10:27:46 +00:00
def run(content, params={})
2012-10-12 15:12:09 +00:00
content.gsub(%r{<mpost( title="([^"]*)")?>(.+?)</mpost>}m) do |full|
title=$2
str=$3
filename=title.gsub(/[^a-zA-Z0-9_]/,"_")
2012-10-20 09:00:56 +00:00
# write the mp file using the code
code=File.read('lib/graph.mp')
code<<=%{beginfig(1)
drawoptions (withcolor base01);}
code <<= str
code <<= %{\nendfig;\nbye;\n}
# create the directory to compile metapost files
2012-10-20 07:56:19 +00:00
FileUtils.mkdir_p(@@tmp)
2012-10-20 09:00:56 +00:00
# write the code into a temporary file
2012-10-19 12:57:47 +00:00
File.open(@@tmp+filename+'.mp','w') do |f|
2012-10-18 10:27:46 +00:00
f.write solarized(code)
2012-10-12 15:12:09 +00:00
end
2012-10-20 09:00:56 +00:00
# write the URL of the image
imgurl=@item.path + 'mpost/' + filename + '.png'
# We compile only if the source changed
if not (File.exists?(@@tmp+filename+'.old') and
FileUtils.cmp(@@tmp+filename+'.mp', @@tmp+filename+'.old'))
2012-10-19 12:57:47 +00:00
then
2012-10-20 09:00:56 +00:00
print %{\t[mpost] updating: #{filename}}
fspath=FileUtils.pwd+'/output'+imgurl
# create the directory for the output file
FileUtils.mkdir_p(File.dirname(fspath))
# Launch the metapost compilation and update
# the cache in case of success
cmd="cd #{@@tmp} && mpost #{filename}.mp >/dev/null 2>&1 && convert -density 180 #{filename}.1 #{fspath} >/dev/null"
2012-10-19 12:57:47 +00:00
if system(cmd)
2012-10-20 09:00:56 +00:00
if FileUtils.copy(@@tmp+filename+'.mp',@@tmp+filename+'.old')
puts " [SUCCESS]"
else
puts " [ERROR: couldn't copy]"
end
else
puts " [ERROR: compilation error; check #{@@tmp}#{filename}.log ]"
2012-10-19 12:57:47 +00:00
end
end
2012-10-20 09:00:56 +00:00
# replace the code by the image
%{<figure><img alt="#{title}" src="#{imgurl}"/><figcaption>#{title}</figcaption></figure>}
2012-10-12 15:12:09 +00:00
end
end
end