Class: Facter::Core::Execution::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/facter/custom_facts/core/execution/base.rb

Overview

Since:

  • 2.0.0

Direct Known Subclasses

Posix, Windows

Constant Summary collapse

STDERR_MESSAGE =

Since:

  • 2.0.0

'Command %s resulted with the following stderr message: %s'

Instance Method Summary collapse

Instance Method Details

#execute(command, options = {}) ⇒ Object

Since:

  • 2.0.0



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/facter/custom_facts/core/execution/base.rb', line 38

def execute(command, options = {})
  on_fail = options.fetch(:on_fail, :raise)
  expand = options.fetch(:expand, true)
  logger = options[:logger]

  expanded_command = if !expand && builtin_command?(command) || logger
                       command
                     else
                       expand_command(command)
                     end

  if expanded_command.nil?
    if on_fail == :raise
      raise Facter::Core::Execution::ExecutionFailure.new,
            "Could not execute '#{command}': command not found"
    end

    return on_fail
  end

  execute_command(expanded_command, on_fail, logger)
end

#with_env(values) ⇒ Object

This is part of the public API. No race condition can happen here because custom facts are executed sequentially

Since:

  • 2.0.0



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/facter/custom_facts/core/execution/base.rb', line 11

def with_env(values)
  old = {}
  values.each do |var, value|
    # save the old value if it exists
    if (old_val = ENV[var])
      old[var] = old_val
    end
    # set the new (temporary) value for the environment variable
    ENV[var] = value
  end
  # execute the caller's block, capture the return value
  rv = yield
# use an ensure block to make absolutely sure we restore the variables
ensure
  # restore the old values
  values.each do |var, _value|
    if old.include?(var)
      ENV[var] = old[var]
    else
      # if there was no old value, delete the key from the current environment variables hash
      ENV.delete(var)
    end
  end
  # return the captured return value
  rv
end