Module: SL::Util

Defined in:
lib/searchlink/util.rb

Overview

Utilities

Class Method Summary collapse

Class Method Details

.cache_file_for(filename) ⇒ String

Get the path for a cache file



84
85
86
87
88
# File 'lib/searchlink/util.rb', line 84

def cache_file_for(filename)
  cache_folder = File.expand_path("~/.config/searchlink/cache")
  FileUtils.mkdir_p(cache_folder) unless File.directory?(cache_folder)
  File.join(cache_folder, filename.sub(/(\.cache)?$/, ".cache"))
end

.exec_with_timeout(cmd, timeout) ⇒ String



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/searchlink/util.rb', line 17

def exec_with_timeout(cmd, timeout)
  begin
    # stdout, stderr pipes
    rout, wout = IO.pipe
    rerr, werr = IO.pipe
    stdout, stderr = nil

    pid = Process.spawn(cmd, pgroup: true, out: wout, err: werr)

    Timeout.timeout(timeout) do
      Process.waitpid(pid)

      # close write ends so we can read from them
      wout.close
      werr.close

      stdout = rout.readlines.join
      stderr = rerr.readlines.join
    end
  rescue Timeout::Error
    Process.kill(-9, pid)
    Process.detach(pid)
  ensure
    wout.close unless wout.closed?
    werr.close unless werr.closed?
    # dispose the read ends of the pipes
    rout.close
    rerr.close
  end

  stdout&.strip
end

Checks if the Preview URL.workflow exists, return path if it does.



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/searchlink/util.rb', line 91

def popup_path
  begin
    path = File.expand_path(File.join(__dir__, "../../helpers/Preview URL.workflow"))
    path = File.expand_path("~/Library/Services/Preview URL.workflow") unless File.exist?(path)
  rescue
    path = File.expand_path("~/Library/Services/Preview URL.workflow")
  end
  return false unless File.exist?(path)

  path
end

.search_with_timeout(search, timeout) ⇒ Array

Execute a search with deadman’s switch



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/searchlink/util.rb', line 58

def search_with_timeout(search, timeout)
  if SL.config["skip_timeout"] || SL.config["confirm"]
    url, title, link_text = search.call
    return [url, title, link_text]
  end

  begin
    Timeout.timeout(timeout) do
      url, title, link_text = search.call
    end
  rescue Timeout::Error
    SL.add_error("Timeout", "Search timed out")
    url, title, link_text = false
  end

  [url, title, link_text]
end