Class: Headless::CliUtil

Inherits:
Object
  • Object
show all
Defined in:
lib/headless/cli_util.rb

Class Method Summary collapse

Class Method Details

.application_exists?(app) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/headless/cli_util.rb', line 3

def self.application_exists?(app)
  `which #{app}`.strip != ""
end

.ensure_application_exists!(app, error_message) ⇒ Object



7
8
9
10
11
# File 'lib/headless/cli_util.rb', line 7

def self.ensure_application_exists!(app, error_message)
  if !self.application_exists?(app)
    raise Headless::Exception.new(error_message)
  end
end

.fork_process(command, pid_filename, log_filename = '/dev/null') ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/headless/cli_util.rb', line 31

def self.fork_process(command, pid_filename, log_filename='/dev/null')
  pid = fork do
    STDERR.reopen(log_filename)
    exec command
    exit! 127 # safeguard in case exec fails
  end

  File.open pid_filename, 'w' do |f|
    f.puts pid
  end
end

.kill_process(pid_filename, options = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/headless/cli_util.rb', line 43

def self.kill_process(pid_filename, options={})
  options[:sig] ||= 'TERM'
  if pid = self.read_pid(pid_filename)
    begin
      Process.kill options[:sig], pid
      Process.wait pid if options[:wait]
    rescue Errno::ESRCH
      # no such process; assume it's already killed
    rescue Errno::ECHILD
      # Process.wait tried to wait on a dead process
    end
  end
  
  begin
    FileUtils.rm pid_filename
  rescue Errno::ENOENT
    # pid file already removed
  end
end

.path_to(app) ⇒ Object



13
14
15
# File 'lib/headless/cli_util.rb', line 13

def self.path_to(app)
  `which #{app}`.strip
end

.read_pid(pid_filename) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/headless/cli_util.rb', line 17

def self.read_pid(pid_filename)
  pid = (File.read(pid_filename) rescue "").strip.to_i
  pid = nil if pid.zero?

  if pid
    begin
      Process.kill(0, pid)
      pid
    rescue Errno::ESRCH
      false
    end
  end
end

.signal_process(pid_filename, signal, options = {}) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/headless/cli_util.rb', line 63

def self.signal_process(pid_filename, signal, options={})
  if pid = self.read_pid(pid_filename)
    begin
      Process.kill signal, pid
      true
    rescue Errno::ESRCH
      # no such process; assume it's already killed
      false
    end
  end
end