Skip to content

Commit

Permalink
(FACT-2320) added warnonce method
Browse files Browse the repository at this point in the history
  • Loading branch information
Filipovici-Andrei committed Sep 14, 2020
1 parent fe98e99 commit a8f7a4b
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 3 deletions.
18 changes: 18 additions & 0 deletions lib/facter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class ResolveCustomFactError < StandardError; end
Options.init
Log.output(STDOUT)
@already_searched = {}
@warn_once = []

class << self
def clear_messages
Expand Down Expand Up @@ -54,6 +55,7 @@ def add(name, options = {}, &block)
# @api public
def clear
@already_searched = {}
@warn_once = []
LegacyFacter.clear
Options[:custom_dir] = []
LegacyFacter.collection.invalidate_custom_facts
Expand Down Expand Up @@ -262,6 +264,22 @@ def log_exception(exception, message = :default)
logger.error(arr.flatten.join("\n"))
end

# Logs only once the same warning message.
#
# @param message [Object] the warning message object
#
# @return [nil]
#
# @api public
def warnonce(message)
message_string = message.to_s
return if @warn_once.include? message_string

@warn_once << message_string
logger.warn(message_string)
nil
end

private

def logger
Expand Down
4 changes: 1 addition & 3 deletions lib/facter/framework/logging/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,7 @@ def info(msg)
end

def warn(msg)
if msg.nil? || msg.empty?
empty_message_error(msg)
elsif @@message_callback
if @@message_callback
@@message_callback.call(:warn, msg)
else
msg = colorize(msg, YELLOW) if Options[:color]
Expand Down
41 changes: 41 additions & 0 deletions spec/facter/facter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -380,4 +380,45 @@ def mock_collection(method, os_name = nil, error = nil)
end
end
end

describe '#warnonce' do
before do
allow(logger).to receive(:warn)
end

it 'calls logger with the warning message' do
message = 'Some error message'

Facter.warnonce(message)

expect(logger).to have_received(:warn).with(message)
end

it 'writes the same warning message only once' do
message = 'Some error message'

Facter.warnonce(message)
Facter.warnonce(message)

expect(logger).to have_received(:warn).once.with(message)
end

it 'writes empty message when message is nil' do
Facter.warnonce(nil)

expect(logger).to have_received(:warn).with('')
end

it 'when message is a hash' do
Facter.warnonce({ warn: 'message' })

expect(logger).to have_received(:warn).with('{:warn=>"message"}')
end

it 'returns nil' do
result = Facter.warnonce({ warn: 'message' })

expect(result).to be_nil
end
end
end

0 comments on commit a8f7a4b

Please sign in to comment.