Class: Rundoc::CodeCommand::Bash

Inherits:
Rundoc::CodeCommand show all
Defined in:
lib/rundoc/code_command/bash.rb,
lib/rundoc/code_command/bash/cd.rb

Direct Known Subclasses

Cd

Defined Under Namespace

Classes: Cd

Constant Summary

Constants inherited from Rundoc::CodeCommand

NEWLINE

Instance Attribute Summary

Attributes inherited from Rundoc::CodeCommand

#command, #contents, #keyword, #original_args, #render_command, #render_result

Instance Method Summary collapse

Methods inherited from Rundoc::CodeCommand

#hidden?, #not_hidden?, #push

Constructor Details

#initialize(line) ⇒ Bash

line = “cd ..”“ line = ”pwd“ line = ”ls“



5
6
7
8
9
10
11
12
13
14
# File 'lib/rundoc/code_command/bash.rb', line 5

def initialize(line)
  @line = line
  @contents = ""
  @delegate = case @line.split(" ").first.downcase
  when "cd"
    Cd.new(@line)
  else
    false
  end
end

Instance Method Details

#call(env = {}) ⇒ Object



22
23
24
25
26
# File 'lib/rundoc/code_command/bash.rb', line 22

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

  shell(@line, @contents)
end

#sanitize_escape_chars(input) ⇒ Object

markdown doesn’t understand bash color codes



29
30
31
# File 'lib/rundoc/code_command/bash.rb', line 29

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

#shell(cmd, stdin = nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rundoc/code_command/bash.rb', line 33

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

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

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

      result << sanitize_escape_chars(buffer)
    end
  end

  unless $?.success?
    raise "Command `#{@line}` exited with non zero status: #{result}" unless keyword.to_s.include?("fail")
  end
  result
end

#to_md(env = {}) ⇒ Object



16
17
18
19
20
# File 'lib/rundoc/code_command/bash.rb', line 16

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

  "$ #{@line}"
end