svg_render.rb (1787B)
1 #!/usr/bin/ruby 2 3 INKSCAPE = '/Applications/Inkscape.app/Contents/MacOS/inkscape' 4 5 require 'nokogiri' 6 7 def read_xml(fn) 8 Nokogiri::XML(File.open(fn)) do |config| 9 config.norecover.strict 10 end 11 end 12 13 if ARGV.empty? 14 STDERR.puts "Usage: #{$0} <res-pp/MODULE-pp.svg> [...more files...]" 15 exit 1 16 end 17 18 svg_filenames = {} 19 svg_files = [] 20 ARGV.each do |file| 21 unless File.readable?(file) 22 STDERR.puts "No such file: #{file}" 23 exit 1 24 end 25 26 name = nil 27 if File.basename(file) =~ /^(.*)(-\w+)?-pp.svg$/ 28 name = $1 29 else 30 STDERR.puts "Input file #{file} must be named *-pp.svg" 31 exit 1 32 end 33 34 Dir.glob(File.join(File.dirname(file), "#{name}-*pp.svg")).each do |fn| 35 unless svg_filenames.key?(fn) 36 svg_filenames[fn] = true 37 38 puts "Preparing #{fn}..." 39 doc = read_xml(fn) 40 doc.css('use, svg svg').each do |n| 41 id = n.attribute('id') 42 n.remove if id && id.to_s =~ /_(PARAM|INPUT|OUTPUT|LIGHT|WIDGET)$/ 43 end 44 tmp_name = File.join('/tmp', "svg_render_#{File.basename(fn)}") 45 File.write(tmp_name, doc.to_xml) 46 47 svg_files << { 48 name: fn, 49 out_name: File.join(File.dirname(fn).sub(/-pp\/?$/, ''), File.basename(fn).sub(/-pp.svg$/, '.svg')), 50 tmp_name: tmp_name 51 } 52 end 53 end 54 end 55 56 puts 'Calling Inkscape...' 57 files = svg_files.map { |f| "'#{f[:tmp_name]}'" }.join(' ') 58 out = `#{INKSCAPE} -g --batch-process --actions='EditSelectAll;SelectionUnGroup;EditSelectAll;EditUnlinkClone;EditSelectAll;ObjectToPath;FileSave' #{files} 2>&1` 59 unless $?.success? 60 STDERR.puts "Calling Inkscape failed:\n#{out}" 61 exit 1 62 end 63 64 puts 'Cleaning up...' 65 svg_files.each do |sf| 66 fn = sf[:tmp_name] 67 doc = read_xml(fn) 68 doc.css('style').each(&:remove) 69 File.write(sf[:out_name], doc.to_xml) 70 File.unlink(fn) 71 end