Module: CLAide::Executable

Included in:
TemplateRunner
Defined in:
lib/claide/executable.rb

Overview

Module which provides support for running executables.

In a class it can be used as:

extend Executable
executable :git

This will create two methods ‘git` and `git!` both accept a command but the latter will raise on non successful executions. The methods return the output of the command.

Defined Under Namespace

Classes: Indenter

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.execute_command(exe, command, raise_on_failure) ⇒ String

TODO:

Find a way to display the live output of the commands.

Executes the given command. Displays output if in verbose mode.

Parameters:

  • bin (String)

    The binary to use.

  • command (Array<#to_s>)

    The command to send to the binary.

  • raise_on_failure (Bool)

    Whether it should raise if the command fails.

Returns:

  • (String)

    the output of the command (STDOUT and STDERR).

Raises:

  • If the executable could not be located.

  • If the command fails and the ‘raise_on_failure` is set to true.



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
# File 'lib/claide/executable.rb', line 50

def self.execute_command(exe, command, raise_on_failure)
  bin = `which #{exe}`.strip
  raise Informative, "Unable to locate `#{exe}`" if bin.empty?

  require 'open4'
  require 'shellwords'

  command = command.map(&:to_s)
  full_command = \
    "#{bin.shellescape} #{command.map(&:shellescape).join(' ')}"

  # if Config.instance.verbose?
  # UI.message("$ #{full_command}")
  # stdout, stderr = Indenter.new(STDOUT), Indenter.new(STDERR)
  # else
  stdout, stderr = Indenter.new, Indenter.new
  # end

  options = { :stdout => stdout, :stderr => stderr, :status => true }
  status  = Open4.spawn(bin, command, options)
  output  = stdout.join("\n") + stderr.join("\n")
  unless status.success?
    if raise_on_failure
      raise Informative, "#{full_command}\n\n#{output}"
    else
      UI.message("[!] Failed: #{full_command}".red)
    end
  end
  output
end

Instance Method Details

#executable(name) ⇒ void

This method returns an undefined value.

Creates the methods for the executable with the given name.

Parameters:

  • name (Symbol)

    the name of the executable.



21
22
23
24
25
26
27
28
29
# File 'lib/claide/executable.rb', line 21

def executable(name)
  define_method(name) do |*command|
    Executable.execute_command(name, Array(command).flatten, false)
  end

  define_method(name.to_s + '!') do |*command|
    Executable.execute_command(name, Array(command).flatten, true)
  end
end