Add derivation for the convert script by itself

This commit is contained in:
Danila Fedorin 2022-03-27 16:41:32 -07:00
parent 7915e20ed0
commit e533c204fa
2 changed files with 61 additions and 8 deletions

36
convert.rb Normal file
View File

@ -0,0 +1,36 @@
require "open3"
require "nokogiri"
require "net/http"
require "json"
def render_cached(cache, display, string, render_comment = nil)
cache.fetch(string) do |new|
puts " Rendering #{render_comment || new}"
res = Net::HTTP.post URI("http://localhost:8000/render"),
{ :equations => [ { :str => string, :display => display } ] }.to_json,
"Content-Type" => "application/json"
cache[string] = JSON.parse(res.body)[0]
end
end
def perform_katex_sub(inline_cache, display_cache, content)
rendered = content.gsub /\\\(((?:[^\\]|\\[^\)])*)\\\)/ do |match|
render_cached(inline_cache, false, $~[1])
end
rendered = rendered.gsub /\$\$((?:[^\$]|$[^\$])*)\$\$/ do |match|
render_cached(display_cache, true, $~[1], "display")
end
return rendered
end
files = ARGV[0..-1]
inline_cache, display_cache = {}, {}
files.each do |file|
puts "Rendering file: #{file}"
document = Nokogiri::HTML.parse(File.open(file))
document.search('//*[not(ancestor-or-self::code)]/text()').each do |t|
t.replace(perform_katex_sub(inline_cache, display_cache, t.content))
end
File.write(file, document.to_html(encoding: 'UTF-8'))
end

View File

@ -1,10 +1,27 @@
{ bundlerEnv, ruby }:
{ bundlerEnv, ruby, stdenv }:
bundlerEnv {
inherit ruby;
let
env = bundlerEnv {
inherit ruby;
name = "render-test";
gemfile = ./Gemfile;
lockfile = ./Gemfile.lock;
gemset = ./gemset.nix;
}
name = "render-test";
gemfile = ./Gemfile;
lockfile = ./Gemfile.lock;
gemset = ./gemset.nix;
};
in
stdenv.mkDerivation {
name = "katex-converter";
src = ./convert.rb;
buildInputs = [ env ruby ];
unpackPhase = "echo 'Skipping unpack phase (nothing to unpack)'";
installPhase = ''
mkdir -p $out/{bin,share/katex-converter}
cp $src $out/share/katex-converter/convert.rb
cat > $out/bin/katex-converter <<EOF
#!/bin/sh -e
exec ${env}/bin/bundle exec ${ruby}/bin/ruby $out/share/katex-converter/convert.rb \$@
EOF
chmod +x $out/bin/katex-converter
'';
}