Sha256: 70a60cc25576b224e9165d10922e9fe2f7e6ac0ab95a71e76da7f9781a216c0f

Contents?: true

Size: 1.31 KB

Versions: 3

Compression:

Stored size: 1.31 KB

Contents

require "open3"
require "github/markup/implementation"


module GitHub
  module Markup
    class CommandError < RuntimeError
    end

    class CommandImplementation < Implementation
      attr_reader :command, :block, :name

      def initialize(regexp, languages, command, name, &block)
        super(regexp, languages)
        @command = command.to_s
        @block = block
        @name = name
      end

      def render(filename, content, options: {})
        rendered = execute(command, content)
        rendered = rendered.to_s.empty? ? content : rendered
        call_block(rendered, content)
      end

    private
      def call_block(rendered, content)
        if block && block.arity == 2
          block.call(rendered, content)
        elsif block
          block.call(rendered)
        else
          rendered
        end
      end

      def execute(command, target)
        # capture3 blocks until both buffers are written to and the process terminates, but
        # it won't allow either buffer to fill up
        stdout, stderr, status = Open3.capture3(*command, stdin_data: target)

        raise CommandError.new(stderr) unless status.success?
        sanitize(stdout, target.encoding)
      end

      def sanitize(input, encoding)
        input.gsub("\r", '').force_encoding(encoding)
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/github-markup-5.0.1/lib/github/markup/command_implementation.rb
github-markup-5.0.1 lib/github/markup/command_implementation.rb
github-markup-5.0.0 lib/github/markup/command_implementation.rb