Class: Falsework::CliUtils

Inherits:
Object
  • Object
show all
Defined in:
lib/falsework/cliutils.rb

Overview

Common routines useful in any CLI program.

Constant Summary collapse

DIR_LIB_SRC =

Physical location of program libraries.

Pathname.new File.dirname(__FILE__)
NNL_MARK =

veputs uses this to decide to put a newline or not to put.

'__NNL__'
@@verbose =

Class-wide verbosity level.

0

Class Method Summary collapse

Class Method Details

.debugObject

A handy check. Use it like:

puts (CliUtils.debug ? “DEBUG mode” : “”)



52
53
54
# File 'lib/falsework/cliutils.rb', line 52

def self.debug
  @@verbose >= 2
end

.errx(exit_code = 0, msg) ⇒ Object

Print an error msg & exit if exit_code > 0.



63
64
65
66
# File 'lib/falsework/cliutils.rb', line 63

def self.errx(exit_code = 0, msg)
  $stderr.puts File.basename($0) + ' error: ' + msg.to_s
  exit exit_code if exit_code > 0
end

.exec(cmd) ⇒ Object

Execute cmd and return an array [exit_status, stderr, stdout].



102
103
104
105
106
107
108
109
# File 'lib/falsework/cliutils.rb', line 102

def self.exec(cmd)
  so = sr = ''
  status = Open4::popen4(cmd) { |pid, stdin, stdout, stderr|
    so = stdout.read
    sr = stderr.read
  }
  [status.exitstatus, sr, so]
end

.getBacktraceObject

A handy method that return a nicely formatted current global backtrace.



58
59
60
# File 'lib/falsework/cliutils.rb', line 58

def self.getBacktrace
  "#{$!}\n\nBacktrace:\n\n#{$!.backtrace.join("\n")}"
end

.getVerboseObject

Getter.



45
46
47
# File 'lib/falsework/cliutils.rb', line 45

def self.getVerbose
  @@verbose
end

.veputs(level, msg) ⇒ Object

level

Verbosity level.

msg

A message to print.

Don’t print msg with a newline if it contains NNL_MARK at the end.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/falsework/cliutils.rb', line 77

def self.veputs(level, msg)
  t = msg.dup
  
  nnl = false
  if t.match(/#{NNL_MARK}$/)
    t.sub!(/#{$&}/, '')
    nnl = true
  end

  if @@verbose >= level
    nnl ? print(t) : print("#{t}\n")
    $stdout.flush
  end
end

.verbose=(val) ⇒ Object

Setter.



40
41
42
# File 'lib/falsework/cliutils.rb', line 40

def self.verbose=(val)
  @@verbose = val
end

.warnx(msg) ⇒ Object

Print a warning.



69
70
71
# File 'lib/falsework/cliutils.rb', line 69

def self.warnx(msg)
  $stderr.puts File.basename($0) + ' warning: ' + msg.to_s
end

.which(file) ⇒ Object

Analogue to a shell command which.



93
94
95
96
97
98
99
# File 'lib/falsework/cliutils.rb', line 93

def self.which(file)
  return true if file =~ %r%\A/% and File.exist? file
  
  ENV['PATH'].split(File::PATH_SEPARATOR).any? do |path|
    File.exist? File.join(path, file)
  end
end