Sha256: cde0ae7ac1bc42831dbc25b38f26d66a8dbe47673dcafe0b2e2ec07f3cfabd61

Contents?: true

Size: 1.55 KB

Versions: 12

Compression:

Stored size: 1.55 KB

Contents

require 'open3'
require 'thread'

module Kuby
  class CLIBase
    def last_status
      Thread.current[status_key]
    end

    def before_execute(&block)
      @before_execute ||= []
      @before_execute << block
    end

    def after_execute(&block)
      @after_execute ||= []
      @after_execute << block
    end

    private

    def open3_w(env, cmd, opts = {}, &block)
      run_before_callbacks(cmd)
      cmd_s = cmd.join(' ')

      Open3.pipeline_w([env, cmd_s], opts) do |stdin, wait_threads|
        yield(stdin, wait_threads).tap do
          stdin.close
          self.last_status = wait_threads.last.value
          run_after_callbacks(cmd)
        end
      end
    end

    def execc(cmd)
      run_before_callbacks(cmd)
      cmd_s = cmd.join(' ')
      exec(cmd_s)
    end

    def systemm(cmd)
      run_before_callbacks(cmd)
      cmd_s = cmd.join(' ')
      system(cmd_s).tap do
        self.last_status = $?
        run_after_callbacks(cmd)
      end
    end

    def backticks(cmd)
      run_before_callbacks(cmd)
      cmd_s = cmd.join(' ')
      `#{cmd_s}`.tap do
        self.last_status = $?
        run_after_callbacks(cmd)
      end
    end

    def run_before_callbacks(cmd)
      (@before_execute || []).each { |cb| cb.call(cmd) }
    end

    def run_after_callbacks(cmd)
      (@after_execute || []).each { |cb| cb.call(cmd, last_status) }
    end

    def last_status=(status)
      Thread.current[status_key] = status
    end

    def status_key
      raise NotImplementedError, "#{__method__} must be defined in derived classes"
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
kuby-core-0.8.1 lib/kuby/cli_base.rb
kuby-core-0.8.0 lib/kuby/cli_base.rb
kuby-core-0.7.2 lib/kuby/cli_base.rb
kuby-core-0.7.1 lib/kuby/cli_base.rb
kuby-core-0.7.0 lib/kuby/cli_base.rb
kuby-core-0.6.1 lib/kuby/cli_base.rb
kuby-core-0.6.0 lib/kuby/cli_base.rb
kuby-core-0.5.0 lib/kuby/cli_base.rb
kuby-core-0.4.0 lib/kuby/cli_base.rb
kuby-core-0.3.0 lib/kuby/cli_base.rb
kuby-core-0.2.0 lib/kuby/cli_base.rb
kuby-core-0.1.0 lib/kuby/cli_base.rb