Module: Kplay::System::ClassMethods

Defined in:
lib/kplay/system.rb

Overview

Class level methods

Constant Summary collapse

DEFAULT_SH_OPTS =
{
  echo: true,
  output: true,
  tty: false
}.freeze

Instance Method Summary collapse

Instance Method Details

#assert_program_presence!(name) ⇒ Object

Checks if program with given name is present. Raises an error if the program is not found.



47
48
49
50
51
# File 'lib/kplay/system.rb', line 47

def assert_program_presence!(name)
  sh(['which', name], echo: false, output: false)
rescue
  raise "Failed to find required program: #{name}"
end

#host_osSymbol

Returns the OS identifier

Returns:

  • (Symbol)

    :linux, :macosx or :unknown



66
67
68
69
70
71
72
73
74
75
76
# File 'lib/kplay/system.rb', line 66

def host_os
  name = `uname`.split(' ').first.downcase.to_sym
  case name
  when :linux
    :linux
  when :darwin
    :macosx
  else
    :unknown
  end
end

Outputs a string to STDOUT without adding a line break

Parameters:

  • text (String)


57
58
59
60
# File 'lib/kplay/system.rb', line 57

def print(text)
  Kernel.print(text)
  $stdout.flush
end

#sh(cmd, opts = {}) ⇒ Object

Executes a shell command on the host

Parameters:

  • cmd (String)

    command to execute

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :echo (true, false)

    echo command to stdout (default: true)

  • :output (true, false)

    display (true) or suppress (false) commands output (default: true)

  • :tty (true, false)

    attach a TTY (stdin is preserved and output is never suppressed), (default: false)



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/kplay/system.rb', line 30

def sh(cmd, opts = {})
  opts = DEFAULT_SH_OPTS.merge(opts)
  cmd = [cmd] if cmd.is_a?(String)
  puts cmd.join(' ') if opts[:echo]
  exit_status = nil
  if opts[:tty]
    exit_status = system(*cmd) ? 0 : -1
  else
    out, status = Open3.capture2(*cmd)
    puts out if opts[:output]
    exit_status = status.exitstatus
  end
  raise "Failed to execute '#{cmd.join(' ')}' (#{exit_status})" unless exit_status == 0
end