Module: BSV::Wallet::CLI::Output

Defined in:
lib/bsv/wallet/cli.rb

Overview

Output formatting for CLI tools.

Binary data goes to stdout as binary when piped, hex when interactive. JSON data goes to stdout as formatted JSON when interactive, compact when piped. Human-readable summaries always go to stderr.

Class Method Summary collapse

Class Method Details

.write_binary(data, output_file: nil, binary: false) ⇒ Object

Write binary data to stdout or file.

Parameters:

  • data (String)

    binary data

  • output_file (String, nil) (defaults to: nil)

    write to file instead of stdout

  • binary (Boolean) (defaults to: false)

    force binary output even to TTY



147
148
149
150
151
152
153
154
155
156
# File 'lib/bsv/wallet/cli.rb', line 147

def write_binary(data, output_file: nil, binary: false)
  if output_file
    File.binwrite(output_file, data)
  elsif binary || !$stdout.tty?
    $stdout.binmode
    $stdout.write(data)
  else
    $stdout.puts data.unpack1('H*')
  end
end

.write_json(obj, output_file: nil) ⇒ Object

Write a hash/array as JSON to stdout.

Parameters:

  • obj (Hash, Array)

    JSON-serializable object

  • output_file (String, nil) (defaults to: nil)

    write to file instead of stdout



162
163
164
165
166
167
168
169
170
# File 'lib/bsv/wallet/cli.rb', line 162

def write_json(obj, output_file: nil)
  require 'json'
  json = $stdout.tty? ? JSON.pretty_generate(obj) : JSON.generate(obj)
  if output_file
    File.write(output_file, json)
  else
    $stdout.puts json
  end
end