Module: Wiq::Output

Defined in:
lib/wiq/output.rb

Overview

Three output modes:

--json   full envelope (ok/data/summary/meta) for agents that want structure
--agent  bare JSON of `data` for headless scripts
default  pretty JSON to a TTY, or --agent equivalent when piped

Class Method Summary collapse

Class Method Details

.envelope(data, summary:, breadcrumbs:, meta:) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/wiq/output.rb', line 57

def envelope(data, summary:, breadcrumbs:, meta:)
  {
    "ok" => true,
    "data" => data,
    "summary" => summary,
    "breadcrumbs" => breadcrumbs,
    "meta" => meta
  }.compact
end

.pick_mode(options) ⇒ Object



50
51
52
53
54
55
# File 'lib/wiq/output.rb', line 50

def pick_mode(options)
  options ||= {}
  return :agent if options[:agent] || options["agent"]
  return :json  if options[:json]  || options["json"]
  $stdout.tty? ? :pretty : :agent
end

.render(data, summary: nil, breadcrumbs: [], meta: {}, options: {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/wiq/output.rb', line 13

def render(data, summary: nil, breadcrumbs: [], meta: {}, options: {})
  mode = pick_mode(options)
  case mode
  when :json
    puts JSON.pretty_generate(envelope(data, summary: summary, breadcrumbs: breadcrumbs, meta: meta))
  when :agent
    puts JSON.generate(data)
  when :pretty
    puts JSON.pretty_generate(data)
    puts "" unless data.nil? || (data.respond_to?(:empty?) && data.empty?)
    puts "#{summary}" if summary
    if meta && !meta.empty?
      meta_line = meta.map { |k, v| "#{k}=#{v}" }.join("  ")
      puts "  #{meta_line}"
    end
  end
end

.render_error(err, options: {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/wiq/output.rb', line 31

def render_error(err, options: {})
  mode = pick_mode(options)
  payload = {
    "ok" => false,
    "error" => err.message,
    "code" => err.respond_to?(:code) ? err.code : "error",
    "hint" => (err.respond_to?(:hint) ? err.hint : nil),
    "details" => (err.respond_to?(:details) ? err.details : nil)
  }.compact

  case mode
  when :json, :agent
    warn JSON.generate(payload)
  else
    warn "#{payload["error"]} [#{payload["code"]}]"
    warn "  hint: #{payload["hint"]}" if payload["hint"]
  end
end