Class: Bashcov::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/bashcov/runner.rb

Overview

Runs a given command with xtrace enabled then computes code coverage.

Instance Method Summary collapse

Constructor Details

#initialize(command) ⇒ Runner

Returns a new instance of Runner.

Parameters:

  • command (String)

    Command to run



17
18
19
20
# File 'lib/bashcov/runner.rb', line 17

def initialize(command)
  @command = command
  @detective = Detective.new(Bashcov.bash_path)
end

Instance Method Details

#resultHash

Note:

The result is memoized.

Returns Coverage hash of the last run.

Returns:

  • (Hash)

    Coverage hash of the last run



89
90
91
92
93
94
95
96
97
# File 'lib/bashcov/runner.rb', line 89

def result
  @result ||= begin
    find_bash_files!
    expunge_invalid_files!
    mark_relevant_lines!

    convert_coverage
  end
end

#runProcess::Status

Note:

Binds Bashcov stdin to the program being executed.

Runs the command with appropriate xtrace settings.

Returns:

  • (Process::Status)

    Status of the executed command



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/bashcov/runner.rb', line 25

def run
  # Clear out previous run
  @result = nil

  field_stream = FieldStream.new
  @xtrace = Xtrace.new(field_stream)
  fd = @xtrace.file_descriptor

  options = { in: :in }
  options[fd] = fd # bind FDs to the child process

  if Bashcov.options.mute
    options[:out] = "/dev/null"
    options[:err] = "/dev/null"
  end

  env =
    if Process.uid.zero?
      # if running as root, Bash 4.4+ does not inherit $PS4 from the environment
      # https://github.com/infertux/bashcov/issues/43#issuecomment-450605839
      write_warning "running as root is NOT recommended, Bashcov may not work properly."

      temp_file = Tempfile.new("bashcov_bash_env")
      temp_file.write("export PS4='#{Xtrace.ps4}'\n")
      temp_file.close

      { "BASH_ENV" => temp_file.path }
    else
      { "PS4" => Xtrace.ps4 }
    end

  env["BASH_XTRACEFD"] = fd.to_s

  with_xtrace_flag do
    command_pid = Process.spawn env, *@command, options # spawn the command

    begin
      # start processing the xtrace output
      xtrace_thread = Thread.new { @xtrace.read }

      Process.wait command_pid

      @xtrace.close

      @coverage = xtrace_thread.value # wait for the thread to return
    rescue XtraceError => e
      write_warning <<-WARNING
        encountered an error parsing Bash's output (error was:
        #{e.message}). This can occur if your script or its path contains
        the sequence #{Xtrace.delimiter.inspect}, or if your script unsets
        LINENO. Aborting early; coverage report will be incomplete.
      WARNING

      @coverage = e.files
    end
  end

  temp_file&.unlink

  $?
end