Module: Howzit::Util

Defined in:
lib/howzit/util.rb

Overview

Util class

Class Method Summary collapse

Class Method Details

.command_exist?(command) ⇒ Boolean

Test if external command exists

Parameters:

  • command (String)

    The command

Returns:

  • (Boolean)

    command exists



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/howzit/util.rb', line 40

def command_exist?(command)
  exts = ENV.fetch('PATHEXT', '').split(::File::PATH_SEPARATOR)
  command = File.expand_path(command) if command =~ /^~/
  if Pathname.new(command).absolute?
    ::File.exist?(command) || exts.any? { |ext| ::File.exist?("#{command}#{ext}") }
  else
    ENV.fetch('PATH', '').split(::File::PATH_SEPARATOR).any? do |dir|
      file = ::File.join(dir, command)
      ::File.exist?(file) || exts.any? { |ext| ::File.exist?("#{file}#{ext}") }
    end
  end
end

.os_copy(string) ⇒ Object

Platform-agnostic copy-to-clipboard

Parameters:

  • string (String)

    The string to copy



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/howzit/util.rb', line 189

def os_copy(string)
  os = RbConfig::CONFIG['target_os']
  out = "{bg}Copying {bw}#{string}".c
  case os
  when /darwin.*/i
    Howzit.console.debug("#{out} (macOS){x}".c)
    `echo #{Shellwords.escape(string)}'\\c'|pbcopy`
  when /mingw|mswin/i
    Howzit.console.debug("#{out} (Windows){x}".c)
    `echo #{Shellwords.escape(string)} | clip`
  else
    if 'xsel'.available?
      Howzit.console.debug("#{out} (Linux, xsel){x}".c)
      `echo #{Shellwords.escape(string)}'\\c'|xsel -i`
    elsif 'xclip'.available?
      Howzit.console.debug("#{out} (Linux, xclip){x}".c)
      `echo #{Shellwords.escape(string)}'\\c'|xclip -i`
    else
      Howzit.console.debug(out)
      Howzit.console.warn('Unable to determine executable for clipboard.')
    end
  end
end

.os_open(command) ⇒ Object

Platform-agnostic open command

Parameters:

  • command (String)

    The command



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/howzit/util.rb', line 245

def os_open(command)
  os = RbConfig::CONFIG['target_os']
  out = "{bg}Opening {bw}#{command}".c
  case os
  when /darwin.*/i
    Howzit.console.debug "#{out} (macOS){x}".c if Howzit.options[:log_level] < 2
    `open #{Shellwords.escape(command)}`
  when /mingw|mswin/i
    Howzit.console.debug "#{out} (Windows){x}".c if Howzit.options[:log_level] < 2
    `start #{Shellwords.escape(command)}`
  else
    if 'xdg-open'.available?
      Howzit.console.debug "#{out} (Linux){x}".c if Howzit.options[:log_level] < 2
      `xdg-open #{Shellwords.escape(command)}`
    else
      Howzit.console.debug out if Howzit.options[:log_level] < 2
      Howzit.console.debug 'Unable to determine executable for `open`.'
    end
  end
end

.os_pasteObject

Platform-agnostic paste-from-clipboard



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/howzit/util.rb', line 216

def os_paste
  os = RbConfig::CONFIG['target_os']
  out = "{bg}Pasting from clipboard".c
  case os
  when /darwin.*/i
    Howzit.console.debug("#{out} (macOS){x}".c)
    `pbpaste`
  when /mingw|mswin/i
    Howzit.console.debug("#{out} (Windows){x}".c)
    `cat /dev/clipboard`
  else
    if 'xsel'.available?
      Howzit.console.debug("#{out} (Linux, xsel){x}".c)
      `xsel --clipboard --output`
    elsif 'xclip'.available?
      Howzit.console.debug("#{out} (Linux, xclip){x}".c)
      `xclip -selection clipboard -o`
    else
      Howzit.console.debug(out)
      Howzit.console.warn('Unable to determine executable for clipboard.')
    end
  end
end

.page(text) ⇒ Object

Paginate the output



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/howzit/util.rb', line 119

def page(text)
  unless $stdout.isatty
    puts text
    return
  end

  read_io, write_io = IO.pipe

  input = $stdin

  pid = Kernel.fork do
    write_io.close
    input.reopen(read_io)
    read_io.close

    # Wait until we have input before we start the pager
    IO.select [input]

    pager = which_pager

    begin
      exec(pager)
    rescue SystemCallError => e
      Howzit.console.error(e)
      exit 1
    end
  end

  read_io.close
  write_io.write(text)
  write_io.close

  _, status = Process.waitpid2(pid)

  status.success?
end

.read_file(path) ⇒ String

Read a file with UTF-8 encoding and leading/trailing whitespace removed

Parameters:

  • path (String)

    The path to read

Returns:

  • (String)

    UTF-8 encoded string



15
16
17
# File 'lib/howzit/util.rb', line 15

def read_file(path)
  IO.read(path).force_encoding('utf-8').strip
end

.show(string, opts = {}) ⇒ Object

print output to terminal



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/howzit/util.rb', line 157

def show(string, opts = {})
  options = {
    color: true,
    highlight: false,
    paginate: true,
    wrap: 0
  }

  options.merge!(opts)

  string = string.uncolor unless options[:color]

  pipes = ''
  if options[:highlight]
    hl = which_highlighter
    pipes = "|#{hl}" if hl
  end

  output = `echo #{Shellwords.escape(string.strip)}#{pipes}`.strip

  if options[:paginate] && Howzit.options[:paginate]
    page(output)
  else
    puts output
  end
end

.valid_command?(command) ⇒ Boolean

Test if an external command exists and is executable. Removes additional arguments and passes just the executable to #command_exist?

Parameters:

  • command (String)

    The command

Returns:

  • (Boolean)

    command is valid



28
29
30
31
# File 'lib/howzit/util.rb', line 28

def valid_command?(command)
  cmd = command.split(' ')[0]
  command_exist?(cmd)
end

.which_highlighterObject

If either mdless or mdcat are installed, use that for highlighting markdown



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/howzit/util.rb', line 55

def which_highlighter
  if Howzit.options[:highlighter] =~ /auto/i
    highlighters = %w[mdcat mdless]
    highlighters.delete_if(&:nil?).select!(&:available?)
    return nil if highlighters.empty?

    hl = highlighters.first
    args = case hl
           when 'mdless'
             '--no-pager'
           end

    [hl, args].join(' ')
  else
    hl = Howzit.options[:highlighter].split(/ /)[0]
    if hl.available?
      Howzit.options[:highlighter]
    else
      Howzit.console.error Color.template("{Rw}Error:{xbw} Specified highlighter (#{Howzit.options[:highlighter]}) not found, switching to auto")
      Howzit.options[:highlighter] = 'auto'
      which_highlighter
    end
  end
end

.which_pagerObject

When pagination is enabled, find the best (in my opinion) option, favoring environment settings



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/howzit/util.rb', line 82

def which_pager
  if Howzit.options[:pager] =~ /auto/i
    pagers = [ENV['PAGER'], ENV['GIT_PAGER'],
              'bat', 'less', 'more', 'pager']
    pagers.delete_if(&:nil?).select!(&:available?)
    return nil if pagers.empty?

    pg = pagers.first
    args = case pg
           when 'delta'
             '--pager="less -FXr"'
           when 'less'
             '-FXr'
           when 'bat'
             if Howzit.options[:highlight]
               '--language Markdown --style plain --pager="less -FXr"'
             else
               '--style plain --pager="less -FXr"'
             end
           else
             ''
           end

    [pg, args].join(' ')
  else
    pg = Howzit.options[:pager].split(/ /)[0]
    if pg.available?
      Howzit.options[:pager]
    else
      Howzit.console.error Color.template("{Rw}Error:{xbw} Specified pager (#{Howzit.options[:pager]}) not found, switching to auto")
      Howzit.options[:pager] = 'auto'
      which_pager
    end
  end
end