Sha256: cc6e8b9ce19dc6b8411b2fb7bceb9f368d5cf574c4bb2e5a90f2d9b80e489e7f

Contents?: true

Size: 1.24 KB

Versions: 2

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

module Nanoc::Tidy
  class Filter < Nanoc::Filter
    require "fileutils"
    require_relative "spawn"
    include Spawn
    include FileUtils

    identifier :tidy
    type text: :text

    ##
    # @example
    #   Nanoc::Tidy.default_argv.concat ["-upper"]
    #
    # @return [Array<String>]
    #  The default command line options forwarded to tidy-html5.
    def self.default_argv
      @default_argv ||= ["-wrap", "120", "-indent"]
    end

    def run(content, options = {})
      path = temporary_file(content).path
      spawn tidy,
            [*default_argv, *(options[:argv] || []), "-modify", path],
            log: File.join(tmpdir, "tidy-html5.log")
      File.read(path).tap { rm(path) }
    end

    private

    def default_argv
      self.class.default_argv
    end

    def temporary_file(content)
      mkdir_p(tmpdir)
      file = Tempfile.new(File.basename(item.identifier.to_s), tmpdir)
      file.write(content)
      file.tap(&:flush)
    end

    def tidy
      case
      when system("which tidy > /dev/null 2>&1") then "tidy"
      when system("which tidy5 > /dev/null 2>&1") then "tidy5"
      else nil
      end
    end

    def tmpdir
      File.join(Dir.getwd, "tmp", "nanoc-tidy.rb")
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nanoc-tidy.rb-0.5.2 lib/nanoc/tidy/filter.rb
nanoc-tidy.rb-0.5.1 lib/nanoc/tidy/filter.rb