Skip to content

Commit

Permalink
Rubocop!
Browse files Browse the repository at this point in the history
1. Add rubocop to dev dependencies.
2. Fix most errors.
3. Add .rubocop.yml for the rest.
  • Loading branch information
glebm committed Dec 26, 2016
1 parent 9949bdf commit 678f301
Show file tree
Hide file tree
Showing 98 changed files with 1,253 additions and 1,118 deletions.
1 change: 1 addition & 0 deletions .rubocop
@@ -0,0 +1 @@
-D
54 changes: 54 additions & 0 deletions .rubocop.yml
@@ -0,0 +1,54 @@
AllCops:
TargetRubyVersion: 2.3
Exclude:
- 'tmp/**/*'
- 'spec/fixtures/**/*'

Metrics/AbcSize:
Max: 28

Metrics/ClassLength:
Max: 125
Exclude:
- 'lib/i18n/tasks/cli.rb'

Metrics/CyclomaticComplexity:
Max: 10

Metrics/BlockLength:
Max: 30

Metrics/LineLength:
Max: 120

Metrics/MethodLength:
Max: 25

Metrics/PerceivedComplexity:
Max: 9

Style/Documentation:
Enabled: false

Style/ClassAndModuleChildren:
Enabled: false

Style/GuardClause:
Enabled: false

Style/MultilineBlockChain:
Enabled: false

Style/SafeNavigation:
# TODO(glebm): Remove this when we update the minimum Ruby version to 2.3+.
Enabled: false

Style/SpecialGlobalVars:
Enabled: false

Style/SignalException:
EnforcedStyle: semantic


Style/SingleLineBlockParams:
Enabled: false
1 change: 1 addition & 0 deletions Gemfile
@@ -1,3 +1,4 @@
# frozen_string_literal: true
source 'https://rubygems.org'

# Specify your gem's dependencies in i18n-tasks.gemspec
Expand Down
3 changes: 2 additions & 1 deletion Rakefile
@@ -1,7 +1,8 @@
# frozen_string_literal: true
require 'bundler/gem_tasks'
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:rspec)
task :default => :rspec
task default: :rspec

task :irb do
# $: << File.expand_path('lib', __FILE__)
Expand Down
1 change: 1 addition & 0 deletions bin/i18n-tasks
@@ -1,4 +1,5 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

if ENV['I18N_TASKS_BIN_SIMPLECOV_COVERAGE']
require_relative '../spec/bin_simplecov_helper'
Expand Down
16 changes: 8 additions & 8 deletions i18n-tasks.gemspec
@@ -1,14 +1,15 @@
# frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'i18n/tasks/version'

Gem::Specification.new do |s|
Gem::Specification.new do |s| # rubocop:disable Metrics/BlockLength
s.name = 'i18n-tasks'
s.version = I18n::Tasks::VERSION
s.authors = ['glebm']
s.email = ['glex.spb@gmail.com']
s.license = 'MIT'
s.summary = %q{Manage localization and translation with the awesome power of static analysis}
s.summary = 'Manage localization and translation with the awesome power of static analysis'
s.description = <<-TEXT
i18n-tasks helps you find and manage missing and unused translations.
Expand All @@ -21,16 +22,14 @@ cp $(i18n-tasks gem-path)/templates/config/i18n-tasks.yml config/
# Add an RSpec for missing and unused keys:
cp $(i18n-tasks gem-path)/templates/rspec/i18n_spec.rb spec/
TEXT
s.homepage = 'https://github.com/glebm/i18n-tasks'
s.homepage = 'https://github.com/glebm/i18n-tasks'
if s.respond_to?(:metadata=)
s.metadata = { 'issue_tracker' => 'https://github.com/glebm/i18n-tasks' }
end
if s.respond_to?(:required_ruby_version=)
s.required_ruby_version = '~> 2.1'
end
s.required_ruby_version = '~> 2.1' if s.respond_to?(:required_ruby_version=)

s.files = `git ls-files`.split($/)
s.files -= s.files.grep(%r{^(doc/|\.|spec/)}) + %w(CHANGES.md config/i18n-tasks.yml Gemfile)
s.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR)
s.files -= s.files.grep(%r{^(doc/|\.|spec/)}) + %w(CHANGES.md config/i18n-tasks.yml Gemfile)
s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } - %w(i18n-tasks.cmd)
s.test_files = s.files.grep(%r{^(test|spec|features)/})
s.require_paths = ['lib']
Expand All @@ -48,5 +47,6 @@ TEXT
s.add_development_dependency 'bundler', '~> 1.3'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec', '~> 3.3'
s.add_development_dependency 'rubocop'
s.add_development_dependency 'yard'
end
7 changes: 2 additions & 5 deletions lib/i18n/tasks.rb
Expand Up @@ -11,9 +11,7 @@ def verbose?
@verbose
end

def verbose=(value)
@verbose = value
end
attr_writer :verbose

# Add a scanner to the default configuration.
#
Expand All @@ -37,14 +35,13 @@ def add_commands(commands_module)
end
end

@verbose = !!ENV['VERBOSE']
@verbose = !ENV['VERBOSE'].nil?

module Data
end
end
end


require 'active_support/inflector'
require 'active_support/core_ext/hash'
require 'active_support/core_ext/array/access'
Expand Down
32 changes: 14 additions & 18 deletions lib/i18n/tasks/cli.rb
Expand Up @@ -10,16 +10,13 @@ def self.start(argv)
new.start(argv)
end

def initialize
end
def initialize; end

def start(argv)
I18n.with_locale(base_task.internal_locale) do
auto_output_coloring do
begin
if run(argv) == :exit_1
exit 1
end
exit 1 if run(argv) == :exit_1
rescue OptionParser::ParseError => e
error e.message, 64
rescue I18n::Tasks::CommandError => e
Expand Down Expand Up @@ -51,7 +48,7 @@ def context
def commands
# load base task to initialize plugins
base_task
@commands ||= ::I18n::Tasks::Commands.cmds.transform_keys { |k| k.to_s.tr('_'.freeze, '-'.freeze) }
@commands ||= ::I18n::Tasks::Commands.cmds.transform_keys { |k| k.to_s.tr('_', '-') }
end

private
Expand All @@ -64,7 +61,7 @@ def parse!(argv)
command = parse_command! argv
options = optparse! command, argv
parse_options! options, command, argv
[command.tr('-'.freeze, '_'.freeze), options.update(arguments: argv)]
[command.tr('-', '_'), options.update(arguments: argv)]
end

def optparse!(command, argv)
Expand Down Expand Up @@ -103,14 +100,14 @@ def optparse_no_command!(argv)

def allow_help_arg_first!(argv)
# allow `i18n-tasks --help command` in addition to `i18n-tasks command --help`
if %w(-h --help).include?(argv[0]) && argv[1] && !argv[1].start_with?('-'.freeze)
if %w(-h --help).include?(argv[0]) && argv[1] && !argv[1].start_with?('-')
argv[0], argv[1] = argv[1], argv[0]
end
end

def parse_command!(argv)
allow_help_arg_first! argv
if argv[0] && !argv[0].start_with?('-'.freeze)
if argv[0] && !argv[0].start_with?('-')
if commands.keys.include?(argv[0])
argv.shift
else
Expand All @@ -120,9 +117,9 @@ def parse_command!(argv)
end

def verbose_option(op)
op.on('--verbose', 'Verbose output') {
op.on('--verbose', 'Verbose output') do
::I18n::Tasks.verbose = true
}
end
end

def help_option(op)
Expand Down Expand Up @@ -157,24 +154,24 @@ def optparse_args(flag)
def parse_options!(options, command, argv)
commands[command][:args].each do |flag|
name = option_name flag
options[name] = parse_option flag, options[name], argv, self.context
options[name] = parse_option flag, options[name], argv, context
end
end

def parse_option(flag, val, argv, context)
conf = flag.last.is_a?(Hash) ? flag.last : {}
if conf[:consume_positional]
val = Array(val) + Array(flag.include?(Array) ? argv.flat_map { |x| x.split(','.freeze) } : argv)
val = Array(val) + Array(flag.include?(Array) ? argv.flat_map { |x| x.split(',') } : argv)
end
val = conf[:default] if val.nil? && conf.key?(:default)
val = conf[:parser].call(val, context) if conf.key?(:parser)
val
end

def option_name(flag)
flag.detect { |f|
f.start_with?('--'.freeze)
}.sub(/\A--(\[no-\])?/, ''.freeze).sub(/[^\-\w].*\z/, ''.freeze).to_sym
flag.detect do |f|
f.start_with?('--')
end.sub(/\A--(\[no-\])?/, '').sub(/[^\-\w].*\z/, '').to_sym
end

def try_call(v)
Expand All @@ -190,7 +187,7 @@ def error(message, exit_code)
fail ExecutionError.new(message, exit_code)
end

class ExecutionError < Exception
class ExecutionError < RuntimeError
attr_reader :exit_code

def initialize(message, exit_code)
Expand All @@ -206,5 +203,4 @@ def auto_output_coloring(coloring = ENV['I18N_TASKS_COLOR'] || STDOUT.isatty)
ensure
Term::ANSIColor.coloring = coloring_was
end

end
5 changes: 2 additions & 3 deletions lib/i18n/tasks/command/commander.rb
Expand Up @@ -10,16 +10,15 @@ class Commander

attr_reader :i18n


# @param [I18n::Tasks::BaseTask] i18n
def initialize(i18n)
@i18n = i18n
end

def run(name, opts = {})
name = name.to_sym
public_name = name.to_s.tr '_'.freeze, '-'.freeze
log_verbose "task: #{public_name}(#{opts.map { |k, v| "#{k}: #{v.inspect}" } * ', '.freeze})"
public_name = name.to_s.tr '_', '-'
log_verbose "task: #{public_name}(#{opts.map { |k, v| "#{k}: #{v.inspect}" } * ', '})"
if opts.empty? || method(name).arity.zero?
send name
else
Expand Down
2 changes: 1 addition & 1 deletion lib/i18n/tasks/command/commands/health.rb
Expand Up @@ -14,7 +14,7 @@ def health(opt = {})
forest = i18n.data_forest(opt[:locales])
stats = i18n.forest_stats(forest)
if stats[:key_count].zero?
raise CommandError.new t('i18n_tasks.health.no_keys_detected')
fail CommandError, t('i18n_tasks.health.no_keys_detected')
end
terminal_report.forest_stats forest, stats
[missing(opt), unused(opt)].detect { |result| result == :exit_1 }
Expand Down
4 changes: 2 additions & 2 deletions lib/i18n/tasks/command/commands/meta.rb
Expand Up @@ -13,8 +13,8 @@ def config(opts = {})
cfg = i18n.config_for_inspect
cfg = cfg.slice(*opts[:arguments]) if opts[:arguments].present?
cfg = cfg.to_yaml
cfg.sub! /\A---\n/, ''
cfg.gsub! /^([^\s-].+?:)/, Term::ANSIColor.cyan(Term::ANSIColor.bold('\1'))
cfg.sub!(/\A---\n/, '')
cfg.gsub!(/^([^\s-].+?:)/, Term::ANSIColor.cyan(Term::ANSIColor.bold('\1')))
puts cfg
end

Expand Down
21 changes: 12 additions & 9 deletions lib/i18n/tasks/command/commands/missing.rb
Expand Up @@ -14,9 +14,12 @@ module Missing
Array,
t('i18n_tasks.cmd.args.desc.missing_types', valid: missing_types * ', '),
parser: OptionParsers::Enum::ListParser.new(
missing_types,
proc { |invalid, valid| I18n.t('i18n_tasks.cmd.errors.invalid_missing_type',
invalid: invalid * ', ', valid: valid * ', ', count: invalid.length) })
missing_types,
proc do |invalid, valid|
I18n.t('i18n_tasks.cmd.errors.invalid_missing_type',
invalid: invalid * ', ', valid: valid * ', ', count: invalid.length)
end
)

cmd :missing,
pos: '[locale ...]',
Expand Down Expand Up @@ -45,23 +48,23 @@ def translate_missing(opt = {})
cmd :add_missing,
pos: '[locale ...]',
desc: t('i18n_tasks.cmd.desc.add_missing'),
args: [:locales, :out_format, arg(:value) + [{default: '%{value_or_default_or_human_key}'}],
args: [:locales, :out_format, arg(:value) + [{ default: '%{value_or_default_or_human_key}' }],
['--nil-value', 'Set value to nil. Takes precedence over the value argument.']]

def add_missing(opt = {})
def add_missing(opt = {}) # rubocop:disable Metrics/AbcSize
added = i18n.empty_forest
locales = (opt[:locales] || i18n.locales)
value = opt[:'nil-value'] ? nil : opt[:value]
if locales[0] == i18n.base_locale
# Merge base locale first, as this may affect the value for the other locales
forest = i18n.missing_keys({locales: [locales[0]]}.update(opt.slice(:types, :base_locale))).
set_each_value!(value)
forest = i18n.missing_keys({ locales: [locales[0]] }.update(opt.slice(:types, :base_locale)))
.set_each_value!(value)
i18n.data.merge! forest
added.merge! forest
locales = locales[1..-1]
end
forest = i18n.missing_keys({locales: locales}.update(opt.slice(:types, :base_locale))).
set_each_value!(value)
forest = i18n.missing_keys({ locales: locales }.update(opt.slice(:types, :base_locale)))
.set_each_value!(value)
i18n.data.merge! forest
added.merge! forest
log_stderr t('i18n_tasks.add_missing.added', count: added.leaves.count)
Expand Down
6 changes: 3 additions & 3 deletions lib/i18n/tasks/command/commands/tree.rb
Expand Up @@ -50,8 +50,8 @@ def tree_rename_key(opt = {})
key = arg_or_pos! :key, opt
name = arg_or_pos! :name, opt
forest = forest_pos_or_stdin! opt
raise CommandError.new('pass full key to rename (-k, --key)') if key.blank?
raise CommandError.new('pass new name (-n, --name)') if name.blank?
fail CommandError, 'pass full key to rename (-k, --key)' if key.blank?
fail CommandError, 'pass new name (-n, --name)' if name.blank?
forest.rename_each_key!(key, name)
print_forest forest, opt
end
Expand All @@ -76,7 +76,7 @@ def tree_set_value(opt = {})
value = arg_or_pos! :value, opt
forest = forest_pos_or_stdin!(opt)
key_pattern = opt[:pattern]
raise CommandError.new('pass value (-v, --value)') if value.blank?
fail CommandError, 'pass value (-v, --value)' if value.blank?
forest.set_each_value!(value, key_pattern)
print_forest forest, opt
end
Expand Down
11 changes: 6 additions & 5 deletions lib/i18n/tasks/command/commands/usages.rb
Expand Up @@ -16,7 +16,8 @@ module Usages

def find(opt = {})
opt[:filter] ||= opt.delete(:pattern) || opt[:arguments].try(:first)
print_forest i18n.used_tree(strict: opt[:strict], key_filter: opt[:filter].presence, include_raw_references: true), opt, :used_keys
result = i18n.used_tree(strict: opt[:strict], key_filter: opt[:filter].presence, include_raw_references: true)
print_forest result, opt, :used_keys
end

cmd :unused,
Expand Down Expand Up @@ -54,10 +55,10 @@ def confirm_remove_unused!(unused_keys, opt)
return if ENV['CONFIRM'] || opt[:confirm]
locales = bold(unused_keys.flat_map { |root| root.key.split('+') }.sort.uniq * ', ')
msg = [
red(t('i18n_tasks.remove_unused.confirm', count: unused_keys.leaves.count, locales: locales)),
yellow(t('i18n_tasks.common.continue_q')),
yellow('(yes/no)')
] * ' '
red(t('i18n_tasks.remove_unused.confirm', count: unused_keys.leaves.count, locales: locales)),
yellow(t('i18n_tasks.common.continue_q')),
yellow('(yes/no)')
].join(' ')
exit 1 unless agree msg
end
end
Expand Down

0 comments on commit 678f301

Please sign in to comment.