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” : “”)



50
51
52
# File 'lib/falsework/cliutils.rb', line 50

def self.debug
  @@verbose >= 2
end

.errx(exit_code = 0, msg) ⇒ Object

Print an error msg & exit if exit_code > 0.



61
62
63
64
# File 'lib/falsework/cliutils.rb', line 61

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].



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

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.



56
57
58
# File 'lib/falsework/cliutils.rb', line 56

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

.getVerboseObject

Getter.



43
44
45
# File 'lib/falsework/cliutils.rb', line 43

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.



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

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.



38
39
40
# File 'lib/falsework/cliutils.rb', line 38

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

.warnx(msg) ⇒ Object

Print a warning.



67
68
69
# File 'lib/falsework/cliutils.rb', line 67

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

.which(file) ⇒ Object

Analogue to a shell command which.



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

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