]> git.draconx.ca Git - homepage.git/blob - lib/scour.rb
Add filter to shrink SVG icons using scour.
[homepage.git] / lib / scour.rb
1 # Nick's web site: scour filter.  Run scour to reduce the size of SVG images.
2 #
3 # Copyright © 2021 Nick Bowler
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
18 class ScourFilter < Nanoc::Filter
19     identifier :scour
20
21     def run(content, params = {})
22         defaults = { quiet: true, id_stripping: true, shorten_ids: true }
23         args = []
24         defaults.merge(params).each do |key, val|
25             prefix = nil
26
27             # Normalize some argument names for consistency
28             case key
29             when :comment_stripping, :viewboxing, :id_stripping
30                 prefix = :enable
31             when :simplify_colors, :style_to_xml, :group_collapsing,
32                  :embed_rasters
33                 prefix = :disable
34             when :renderer_workaround, :line_breaks
35                 prefix = :no if not val
36             end
37
38             # scour does not generally have inverse options, so drop
39             # some nonsense combinations.
40             next if val and prefix == :disable
41             next if val and key == :line_breaks
42             next if !val
43
44             arg = "--"
45             if prefix then arg << "#{prefix}-" end
46             arg << key.to_s.gsub("_", "-")
47             if val != true then arg << "=#{val}" end
48
49             args << arg
50         end
51
52         content, status = Open3.capture2("scour", *args, stdin_data: content)
53         raise "scour failed" if status != 0
54
55         return content
56     end
57 end