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)


5
6
7
# File 'lib/headless/cli_util.rb', line 5

def self.application_exists?(app)
  !!path_to(app)
end

.ensure_application_exists!(app, error_message) ⇒ Object



9
10
11
12
13
# File 'lib/headless/cli_util.rb', line 9

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



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/headless/cli_util.rb', line 44

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



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/headless/cli_util.rb', line 56

def self.kill_process(pid_filename, options={})
  if pid = read_pid(pid_filename)
    begin
      Process.kill 'TERM', 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

  unless options[:preserve_pid_file]
    begin
      FileUtils.rm pid_filename
    rescue Errno::ENOENT
      # pid file already removed
    end
  end
end

.path_to(app) ⇒ Object



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

def self.path_to(app)
  exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
  ENV['PATH'].split(File::PATH_SEPARATOR).each do |path|
    exts.each { |ext|
      exe = File.join(path, "#{app}#{ext}")
      return exe if File.executable?(exe) && !File.directory?(exe)
    }
  end
  return nil
end

.process_mine?(pid) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
# File 'lib/headless/cli_util.rb', line 27

def self.process_mine?(pid)
  Process.kill(0, pid) && true
rescue Errno::EPERM, Errno::ESRCH
  false
end

.process_running?(pid) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
# File 'lib/headless/cli_util.rb', line 33

def self.process_running?(pid)
  Process.getpgid(pid) && true
rescue Errno::ESRCH
  false
end

.read_pid(pid_filename) ⇒ Object



39
40
41
42
# File 'lib/headless/cli_util.rb', line 39

def self.read_pid(pid_filename)
  pid = (File.read(pid_filename) rescue "").strip
  pid.empty? ? nil : pid.to_i
end