html-pipeline 1.71 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/env ruby
require 'html/pipeline'

require 'optparse'

# Accept "help", too
7
.map! { |a| a == 'help' ? '--help' : a }
8

9
onParser.new do |opts|
10 11 12
  opts.banner = <<-HELP.gsub(/^    /, '')
    Usage: html-pipeline [-h] [-f]
           html-pipeline [FILTER [FILTER [...]]] < file.md
13
       cat file.md | html-pipeline [FILTER [FILTER [...]]]
14 15
  HELP

16
 opts.separator 'Options:'
17

18 19 20
  opts.on('-f', '--filters', 'List the available filters') do
    filters = HTML::Pipeline.constants.grep(/\w+Filter$/)
                            .map { |f| f.to_s.gsub(/Filter$/, '') }
21 22

    # Text filter doesn't work, no call method
23
    filters -= ['Text']
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

    abort <<-HELP.gsub(/^      /, '')
      Available filters:
        #{filters.join("\n        ")}
    HELP
  end
end.parse!

# Default to a GitHub-ish pipeline
if ARGV.empty?

  filters = [
    HTML::Pipeline::MarkdownFilter,
    HTML::Pipeline::SanitizationFilter,
    HTML::Pipeline::ImageMaxWidthFilter,
    HTML::Pipeline::EmojiFilter,
    HTML::Pipeline::AutolinkFilter,
41
    HTML::Pipeline::TableOfContentsFilter
42 43
  ]

44
  # Add syntax highlighting if rouge is present
45
  begin
46
    require 'rouge'
47 48 49 50 51 52 53 54
    filters << HTML::Pipeline::SyntaxHighlightFilter
  rescue LoadError
  end

else

  def filter_named(name)
    case name
55
    when 'Text'
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
      raise NameError # Text filter doesn't work, no call method
    end

    HTML::Pipeline.const_get("#{name}Filter")
  rescue NameError => e
    abort "Unknown filter '#{name}'. List filters with the -f option."
  end

  filters = []
  until ARGV.empty?
    name = ARGV.shift
    filters << filter_named(name)
  end

end

context = {
73 74 75
  asset_root: '/assets',
  base_url: '/',
  gfm: true
76 77 78
}

puts HTML::Pipeline.new(filters, context).call(ARGF.read)[:output]