Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding option for output format #763

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/foreman/cli.rb
Expand Up @@ -25,6 +25,8 @@ class Foreman::CLI < Foreman::Thor
method_option :port, :type => :numeric, :aliases => "-p"
method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5."
method_option :timestamp, :type => :boolean, :default => true, :desc => "Include timestamp in output"
method_option :output_format, :type => :string, :default => "text", :desc => "Specify the output format you wish, text or json. Default: text"
method_option :json_message_key, :type => :string, :default => "message", :desc => "The key used to put a text based output from your process. Default: message"

class << self
# Hackery. Take the run method away from Thor so that we can redefine it.
Expand Down
36 changes: 28 additions & 8 deletions lib/foreman/engine/cli.rb
Expand Up @@ -55,14 +55,34 @@ def startup

def output(name, data)
data.to_s.lines.map(&:chomp).each do |message|
output = ""
output += $stdout.color(@colors[name.split(".").first].to_sym)
output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp]
output += "#{pad_process_name(name)} | "
output += $stdout.color(:reset)
output += message
$stdout.puts output
$stdout.flush
case options[:output_format]
when "text"
output = ""
output += $stdout.color(@colors[name.split(".").first].to_sym)
output += "#{Time.now.strftime("%H:%M:%S")} " if options[:timestamp]
output += "#{pad_process_name(name)} | "
output += $stdout.color(:reset)
output += message
$stdout.puts output
$stdout.flush
when "json"
require 'json'
json_data = {foreman_process: name}
begin
result = JSON.parse(message)
if result.is_a?(Hash)
json_data.merge!(result)
else
json_data[options[:json_message_key]] = message
end
rescue JSON::ParserError, TypeError
json_data[options[:json_message_key]] = message
end
$stdout.puts json_data.to_json
$stdout.flush
else
raise "Invalid output format: #{options[:output_format]}"
end
end
rescue Errno::EPIPE
terminate_gracefully
Expand Down