Skip to content

Commit

Permalink
Code-Style fix.
Browse files Browse the repository at this point in the history
Helpers singletons fix.
  • Loading branch information
merqlove committed Jul 19, 2015
1 parent a668d7f commit 8a00019
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 75 deletions.
24 changes: 16 additions & 8 deletions lib/do_snapshot/cli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,10 @@ def initialize(*args)
def snap
command.snap
rescue DoSnapshot::NoTokenError, DoSnapshot::NoKeysError => e
logger.error e.message
send_error
fail e
error_simple(e)
rescue => e
command.fail_power_off(e) if [SnapshotCreateError, DropletShutdownError].include?(e.class)
logger.error e.message
backtrace(e) if options.include? 'trace'
send_error
fail e
error_with_backtrace(e)
end

desc 'version, -V', 'Shows the version of the currently installed DoSnapshot gem'
Expand All @@ -177,6 +172,19 @@ def version
end

no_commands do
def error_simple(e)
logger.error e.message
send_error
fail e
end

def error_with_backtrace(e)
logger.error e.message
backtrace(e) if options.include? 'trace'
send_error
fail e
end

def command
@command ||= Command.new(options, command_filter)
end
Expand All @@ -189,7 +197,7 @@ def command_filter
%w( log smtp mail trace digital_ocean_client_id digital_ocean_api_key digital_ocean_access_token )
end

def setup_config
def setup_config # rubocop:disable Metrics/AbcSize
DoSnapshot.configure do |config|
config.logger = ::Logger.new(options['log']) if options['log']
config.logger_level = Logger::DEBUG if config.verbose
Expand Down
4 changes: 3 additions & 1 deletion lib/do_snapshot/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
module DoSnapshot
# Configuration class. Used to share config across application.
#
class Configuration
attr_accessor :logger
attr_accessor :logger_level
Expand All @@ -14,4 +16,4 @@ def initialize
@mailer = nil
end
end
end
end
9 changes: 5 additions & 4 deletions lib/do_snapshot/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
require_relative 'mail'

module DoSnapshot
# Helpers for main class.
#
module Helpers
def logger
UniversalLogger
Expand All @@ -11,12 +13,11 @@ def logger
# Used to give classes access only for selected methods
#
module UniversalLogger
module_function
%w(debug info warn error fatal unknown).each do |name|
define_method(:"#{name}") { |*args, &block| DoSnapshot.logger.send(:"#{name}", *args, &block) }
define_singleton_method(:"#{name}") { |*args, &block| DoSnapshot.logger.send(:"#{name}", *args, &block) }
end

def close
def self.close
DoSnapshot.logger.close
end
end
Expand All @@ -25,4 +26,4 @@ def mailer
DoSnapshot.mailer
end
end
end
end
4 changes: 2 additions & 2 deletions lib/do_snapshot/log.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Log
attr_accessor :quiet, :verbose
attr_writer :buffer, :instance

def initialize(options={})
def initialize(options = {})
@verbose = DoSnapshot.config.verbose
@quiet = DoSnapshot.config.quiet
options.each { |key, option| instance_variable_set(:"@#{key}", option) }
Expand All @@ -36,7 +36,7 @@ def close
define_method(:"#{name}") { |*args, &block| log severity, *args, &block }
end

def log(severity, message = nil, progname = nil , &block)
def log(severity, message = nil, progname = nil, &block)
buffer << message
instance.add(severity, message, progname, &block) if instance

Expand Down
50 changes: 29 additions & 21 deletions lib/do_snapshot/runner.rb
Original file line number Diff line number Diff line change
@@ -1,46 +1,54 @@
require 'do_snapshot/cli'

module DoSnapshot
# CLI Runner
#
class Runner
def initialize(argv, stdin = STDIN, stdout = STDOUT, stderr = STDERR, kernel = Kernel)
@argv, @stdin, @stdout, @stderr, @kernel = argv, stdin, stdout, stderr, kernel
end

def execute!
def execute! # rubocop:disable Metrics/MethodLength
exit_code = begin
$stderr = @stderr
$stdin = @stdin
$stdout = @stdout

DoSnapshot::CLI.start(@argv)

0
run_cli
rescue DoSnapshot::NoTokenError, DoSnapshot::NoKeysError => _
clean
1
do_nothing_on_shown_error
rescue StandardError => e
b = e.backtrace
@stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
@stderr.puts(b.map{|s| "\tfrom #{s}"}.join("\n"))
1
display_backtrace_otherwise(e)
rescue SystemExit => e
e.status
ensure
clean
clean_before_exit
end

@kernel.exit(exit_code)
end

# For tests
#
def parent_instance
DoSnapshot
private

def run_cli
$stderr = @stderr
$stdin = @stdin
$stdout = @stdout

DoSnapshot::CLI.start(@argv)

0
end

def do_nothing_on_shown_error
clean_before_exit
1
end

private
def display_backtrace_otherwise(e)
b = e.backtrace
@stderr.puts("#{b.shift}: #{e.message} (#{e.class})")
@stderr.puts(b.map { |s| "\tfrom #{s}" }.join("\n"))
1
end

def clean
def clean_before_exit
DoSnapshot.cleanup

$stderr = STDERR
Expand Down
2 changes: 1 addition & 1 deletion spec/do_snapshot/configuration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
it { expect(cli.new).to respond_to(:verbose) }
it { expect(cli.new).to respond_to(:quiet) }
it { expect(cli.new).to respond_to(:mailer) }
end
end
14 changes: 7 additions & 7 deletions spec/do_snapshot/runner_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@

expect(last_command).to have_exit_status(1)
expect(all_stdout)
.to include(t_wrong_keys('digital_ocean_access_token'))
.to include(t_wrong_keys('digital_ocean_access_token'))
end
end
end
Expand All @@ -208,7 +208,7 @@

expect(last_command).to have_exit_status(1)
expect(all_stdout)
.to include(t_wrong_keys(%w( digital_ocean_client_id digital_ocean_api_key ).join(', ')))
.to include(t_wrong_keys(%w( digital_ocean_client_id digital_ocean_api_key ).join(', ')))
end
end
end
Expand All @@ -229,7 +229,7 @@
it 'shows a help message' do
run 'do_snapshot help'
expect(all_stdout)
.to match('Commands:')
.to match('Commands:')
end

it 'shows a help message for specific commands' do
Expand All @@ -243,7 +243,7 @@

expect(last_command).to have_exit_status(0)
expect(all_stdout)
.not_to include(t_wrong_keys(%w( digital_ocean_client_id digital_ocean_api_key ).join(', ')))
.not_to include(t_wrong_keys(%w( digital_ocean_client_id digital_ocean_api_key ).join(', ')))
end
end
end
Expand Down Expand Up @@ -305,14 +305,14 @@ def hash_attribute_eq_no_stub(hash)
end
end

def options_line(options = default_options_cli)
def options_line(options = default_options_cli) # rubocop:disable Metrics/PerceivedComplexity,Metrics/MethodLength,Metrics/AbcSize,Metrics/CyclomaticComplexity
options.map do |key, value|
if value.is_a?(String)
"--#{key}=#{value}"
elsif value.is_a?(FalseClass)
"--no-#{key}"
elsif value.is_a?(Numeric)
"--#{key}=#{value.to_s}"
"--#{key}=#{value}"
elsif value.is_a?(Array)
if value.size > 0
"--#{key}=#{value.join(' ')}"
Expand All @@ -321,7 +321,7 @@ def options_line(options = default_options_cli)
end
elsif value.is_a?(Hash)
if value.size > 0
items = value.map{ |param, setting| "#{param}:#{setting}" }.join(' ')
items = value.map { |param, setting| "#{param}:#{setting}" }.join(' ')
"--#{key}=#{items}"
else
nil
Expand Down
3 changes: 1 addition & 2 deletions spec/shared/api_v2_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,7 @@ def stub_with_id_name(request, id, name, fixture, type = :get, body = nil, statu
# Body Helpers
#
def stub_request_body(type, request, body)
stub_response = stub_request(type, request)
.with(headers: { 'Authorization'=>api_access_token } )
stub_response = stub_request(type, request).with(headers: { 'Authorization' => api_access_token })
return stub_response.with(body: body) if body
stub_response
end
Expand Down
58 changes: 29 additions & 29 deletions spec/shared/environment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,35 @@ def do_not_send_email
allow(Pony).to receive(:deliver) { |mail| mail }
end

let(:client_key) { 'foo' }
let(:api_key) { 'bar' }
let(:access_token) { 'sometoken' }
let(:event_id) { '7501' }
let(:droplet_id) { '100823' }
let(:image_id) { '5019770' }
let(:image_id2) { '5019903' }
let(:cli_env_nil) { Hash['DIGITAL_OCEAN_CLIENT_ID' => nil, 'DIGITAL_OCEAN_API_KEY' => nil, 'DIGITAL_OCEAN_ACCESS_TOKEN' => nil] }
let(:cli_keys) { Thor::CoreExt::HashWithIndifferentAccess.new(digital_ocean_client_id: client_key, digital_ocean_api_key: api_key, digital_ocean_access_token: access_token) }
let(:cli_keys_other) { Thor::CoreExt::HashWithIndifferentAccess.new(digital_ocean_client_id: 'NOTFOO', digital_ocean_api_key: 'NOTBAR', digital_ocean_access_token: 'NOTTOK') }
let(:snapshot_name) { "foo_#{DateTime.now.strftime('%Y_%m_%d')}" }
let(:default_options) { Hash[protocol: 1, only: %w( 100823 ), exclude: %w(), keep: 3, stop: false, trace: true, clean: true, delay: 0, timeout: 600, droplets: nil, threads: []] }
let(:default_options_cli){ default_options.reject { |key, _| %w( droplets threads ).include?(key.to_s) } }
let(:no_exclude) { [] }
let(:exclude) { %w( 100824 100825 ) }
let(:no_only) { [] }
let(:only) { %w( 100823 100824 ) }
let(:stop) { true }
let(:no_stop) { false }
let(:quiet) { true }
let(:no_quiet) { false }
let(:clean) { true }
let(:no_clean) { false }
let(:timeout) { 600 }
let(:delay) { 0 }
let(:log_path) { "#{project_path}/log/test.log" }
let(:mail_options) { Thor::CoreExt::HashWithIndifferentAccess.new(to: '[email protected]', from: '[email protected]') }
let(:smtp_options) { Thor::CoreExt::HashWithIndifferentAccess.new(address: 'smtp.gmail.com', port: '25', user_name: 'someuser', password: 'somepassword') }
let(:log) { Thor::CoreExt::HashWithIndifferentAccess.new(log: log_path) }
let(:client_key) { 'foo' }
let(:api_key) { 'bar' }
let(:access_token) { 'sometoken' }
let(:event_id) { '7501' }
let(:droplet_id) { '100823' }
let(:image_id) { '5019770' }
let(:image_id2) { '5019903' }
let(:cli_env_nil) { Hash['DIGITAL_OCEAN_CLIENT_ID' => nil, 'DIGITAL_OCEAN_API_KEY' => nil, 'DIGITAL_OCEAN_ACCESS_TOKEN' => nil] }
let(:cli_keys) { Thor::CoreExt::HashWithIndifferentAccess.new(digital_ocean_client_id: client_key, digital_ocean_api_key: api_key, digital_ocean_access_token: access_token) }
let(:cli_keys_other) { Thor::CoreExt::HashWithIndifferentAccess.new(digital_ocean_client_id: 'NOTFOO', digital_ocean_api_key: 'NOTBAR', digital_ocean_access_token: 'NOTTOK') }
let(:snapshot_name) { "foo_#{DateTime.now.strftime('%Y_%m_%d')}" }
let(:default_options) { Hash[protocol: 1, only: %w( 100823 ), exclude: %w(), keep: 3, stop: false, trace: true, clean: true, delay: 0, timeout: 600, droplets: nil, threads: []] }
let(:default_options_cli) { default_options.reject { |key, _| %w( droplets threads ).include?(key.to_s) } }
let(:no_exclude) { [] }
let(:exclude) { %w( 100824 100825 ) }
let(:no_only) { [] }
let(:only) { %w( 100823 100824 ) }
let(:stop) { true }
let(:no_stop) { false }
let(:quiet) { true }
let(:no_quiet) { false }
let(:clean) { true }
let(:no_clean) { false }
let(:timeout) { 600 }
let(:delay) { 0 }
let(:log_path) { "#{project_path}/log/test.log" }
let(:mail_options) { Thor::CoreExt::HashWithIndifferentAccess.new(to: '[email protected]', from: '[email protected]') }
let(:smtp_options) { Thor::CoreExt::HashWithIndifferentAccess.new(address: 'smtp.gmail.com', port: '25', user_name: 'someuser', password: 'somepassword') }
let(:log) { Thor::CoreExt::HashWithIndifferentAccess.new(log: log_path) }

def stub_all_api(droplets = nil, active = false)
drops = []
Expand Down

0 comments on commit 8a00019

Please sign in to comment.