Class: Rundoc::CodeCommand::BashRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/rundoc/code_command/bash.rb,
lib/rundoc/code_command/bash/cd.rb

Direct Known Subclasses

Cd, BashRunnerFailOk

Defined Under Namespace

Classes: Cd

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user_args:, render_command:, render_result:, io:, contents: nil) ⇒ BashRunner

Returns a new instance of BashRunner.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rundoc/code_command/bash.rb', line 14

def initialize(user_args:, render_command:, render_result:, io:, contents: nil)
  @io = io
  @contents = contents.dup if contents && !contents.empty?
  @line = user_args.line
  @delegate = case @line.split(" ").first.downcase
  when "cd"
    Cd.new(@line, io: io)
  else
    false
  end
end

Instance Attribute Details

#contentsObject (readonly)

Returns the value of attribute contents.



12
13
14
# File 'lib/rundoc/code_command/bash.rb', line 12

def contents
  @contents
end

#ioObject (readonly)

Returns the value of attribute io.



12
13
14
# File 'lib/rundoc/code_command/bash.rb', line 12

def io
  @io
end

Instance Method Details

#call(env = {}) ⇒ Object



36
37
38
39
40
# File 'lib/rundoc/code_command/bash.rb', line 36

def call(env = {})
  return @delegate.call(env) if @delegate

  shell(@line, @contents)
end

#raise_on_error?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/rundoc/code_command/bash.rb', line 26

def raise_on_error?
  true
end

#sanitize_escape_chars(input) ⇒ Object

markdown doesn’t understand bash color codes



43
44
45
# File 'lib/rundoc/code_command/bash.rb', line 43

def sanitize_escape_chars(input)
  input.gsub(/\e\[(\d+)m/, "")
end

#shell(cmd, stdin = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rundoc/code_command/bash.rb', line 47

def shell(cmd, stdin = nil)
  cmd = "(#{cmd}) 2>&1"
  msg = "Running: $ '#{cmd}'"
  msg << " with stdin: '#{stdin.inspect}'" if stdin && !stdin.empty?
  io.puts msg

  result = +""
  IO.popen(cmd, "w+") do |pipe|
    pipe << stdin if stdin
    pipe.close_write

    until pipe.eof?
      buffer = pipe.gets
      io.puts "    #{buffer}"

      result << sanitize_escape_chars(buffer)
    end
  end

  if raise_on_error? && !$?.success?
    raise "Command `#{@line}` exited with non zero status: #{result}"
  end
  result
end

#to_md(env = {}) ⇒ Object



30
31
32
33
34
# File 'lib/rundoc/code_command/bash.rb', line 30

def to_md(env = {})
  return @delegate.to_md(env) if @delegate

  "$ #{@line}"
end