diff options
Diffstat (limited to 'lib/bundler/vendor')
31 files changed, 1391 insertions, 1262 deletions
diff --git a/lib/bundler/vendor/thor.rb b/lib/bundler/vendor/thor.rb index 6880b6d7..81f7b773 100644 --- a/lib/bundler/vendor/thor.rb +++ b/lib/bundler/vendor/thor.rb @@ -1,7 +1,7 @@ require 'set' require 'thor/base' -class Thor +class Thor # rubocop:disable ClassLength class << self # Allows for custom "Command" package naming. # @@ -9,7 +9,7 @@ class Thor # name<String> # options<Hash> # - def package_name(name, options={}) + def package_name(name, options = {}) @package_name = name.nil? || name == '' ? nil : name end @@ -18,17 +18,17 @@ class Thor # ==== Parameters # meth<Symbol>:: name of the default command # - def default_command(meth=nil) + def default_command(meth = nil) @default_command = case meth - when :none - 'help' - when nil - @default_command || from_superclass(:default_command, 'help') - else - meth.to_s - end + when :none + 'help' + when nil + @default_command || from_superclass(:default_command, 'help') + else + meth.to_s + end end - alias default_task default_command + alias_method :default_task, :default_command # Registers another Thor subclass as a command. # @@ -37,7 +37,7 @@ class Thor # command<String>:: Subcommand name to use # usage<String>:: Short usage for the subcommand # description<String>:: Description for the subcommand - def register(klass, subcommand_name, usage, description, options={}) + def register(klass, subcommand_name, usage, description, options = {}) if klass <= Thor::Group desc usage, description, options define_method(subcommand_name) { |*args| invoke(klass, args) } @@ -54,7 +54,7 @@ class Thor # description<String> # options<String> # - def desc(usage, description, options={}) + def desc(usage, description, options = {}) if options[:for] command = find_and_refresh_command(options[:for]) command.usage = usage if usage @@ -69,7 +69,7 @@ class Thor # ==== Parameters # long description<String> # - def long_desc(long_description, options={}) + def long_desc(long_description, options = {}) if options[:for] command = find_and_refresh_command(options[:for]) command.long_description = long_description if long_description @@ -91,13 +91,13 @@ class Thor # ==== Parameters # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given command. # - def map(mappings=nil) + def map(mappings = nil) @map ||= from_superclass(:map, {}) if mappings mappings.each do |key, value| if key.respond_to?(:each) - key.each {|subkey| @map[subkey] = value} + key.each { |subkey| @map[subkey] = value } else @map[key] = value end @@ -114,13 +114,13 @@ class Thor # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric # or :required (string). If you give a value, the type of the value is used. # - def method_options(options=nil) + def method_options(options = nil) @method_options ||= {} build_options(options, @method_options) if options @method_options end - alias options method_options + alias_method :options, :method_options # Adds an option to the set of method options. If :for is given as option, # it allows you to change the options from a previous defined command. @@ -148,16 +148,16 @@ class Thor # :banner - String to show on usage notes. # :hide - If you want to hide this option from the help. # - def method_option(name, options={}) + def method_option(name, options = {}) scope = if options[:for] - find_and_refresh_command(options[:for]).options - else - method_options - end + find_and_refresh_command(options[:for]).options + else + method_options + end build_option(name, options, scope) end - alias option method_option + alias_method :option, :method_option # Prints help information for the given command. # @@ -170,18 +170,18 @@ class Thor command = all_commands[meth] handle_no_command_error(meth) unless command - shell.say "Usage:" + shell.say 'Usage:' shell.say " #{banner(command)}" shell.say class_options_help(shell, nil => command.options.map { |_, o| o }) if command.long_description - shell.say "Description:" + shell.say 'Description:' shell.print_wrapped(command.long_description, :indent => 2) else shell.say command.description end end - alias task_help command_help + alias_method :task_help, :command_help # Prints help information for this class. # @@ -193,12 +193,12 @@ class Thor Thor::Util.thor_classes_in(self).each do |klass| list += klass.printable_commands(false) end - list.sort!{ |a,b| a[0] <=> b[0] } + list.sort! { |a, b| a[0] <=> b[0] } if @package_name shell.say "#{@package_name} commands:" else - shell.say "Commands:" + shell.say 'Commands:' end shell.print_table(list, :indent => 2, :truncate => true) @@ -212,34 +212,35 @@ class Thor next if command.hidden? item = [] item << banner(command, false, subcommand) - item << (command.description ? "# #{command.description.gsub(/\s+/m,' ')}" : "") + item << (command.description ? "# #{command.description.gsub(/\s+/m, ' ')}" : '') item end.compact end - alias printable_tasks printable_commands + alias_method :printable_tasks, :printable_commands def subcommands @subcommands ||= from_superclass(:subcommands, []) end - alias subtasks subcommands + alias_method :subtasks, :subcommands def subcommand(subcommand, subcommand_class) - self.subcommands << subcommand.to_s + subcommands << subcommand.to_s subcommand_class.subcommand_help subcommand define_method(subcommand) do |*args| args, opts = Thor::Arguments.split(args) + args.unshift("help") if opts.include? "--help" or opts.include? "-h" invoke subcommand_class, args, opts, :invoked_via_subcommand => true, :class_options => options end end - alias subtask subcommand + alias_method :subtask, :subcommand # Extend check unknown options to accept a hash of conditions. # # === Parameters # options<Hash>: A hash containing :only and/or :except keys - def check_unknown_options!(options={}) - @check_unknown_options ||= Hash.new + def check_unknown_options!(options = {}) + @check_unknown_options ||= {} options.each do |key, value| if value @check_unknown_options[key] = Array(value) @@ -320,7 +321,7 @@ class Thor protected # The method responsible for dispatching given the args. - def dispatch(meth, given_args, given_opts, config) #:nodoc: + def dispatch(meth, given_args, given_opts, config) #:nodoc: # rubocop:disable MethodLength # There is an edge case when dispatching from a subcommand. # A problem occurs invoking the default command. This case occurs # when arguments are passed and a default command is defined, and @@ -331,7 +332,7 @@ class Thor # the command normally. If the first item in given_args is not # a command then use the default command. The given_args will be # intact later since dup was used. - if config[:invoked_via_subcommand] && given_args.size >= 1 && default_command != "help" && given_args.first != default_command + if config[:invoked_via_subcommand] && given_args.size >= 1 && default_command != 'help' && given_args.first != default_command meth ||= retrieve_command_name(given_args.dup) command = all_commands[normalize_command_name(meth)] command ||= all_commands[normalize_command_name(default_command)] @@ -350,7 +351,7 @@ class Thor end else args, opts = given_args, nil - command = Thor::DynamicCommand.new(meth) + command = dynamic_command_class.new(meth) end opts = given_opts || opts || [] @@ -376,22 +377,26 @@ class Thor Thor end + def dynamic_command_class #:nodoc: + Thor::DynamicCommand + end + def create_command(meth) #:nodoc: if @usage && @desc base_class = @hide ? Thor::HiddenCommand : Thor::Command commands[meth] = base_class.new(meth, @desc, @long_desc, @usage, method_options) @usage, @desc, @long_desc, @method_options, @hide = nil true - elsif self.all_commands[meth] || meth == "method_missing" + elsif all_commands[meth] || meth == 'method_missing' true else puts "[WARNING] Attempted to create command #{meth.inspect} without usage or description. " << - "Call desc if you want this method to be available as command or declare it inside a " << + 'Call desc if you want this method to be available as command or declare it inside a ' << "no_commands{} block. Invoked from #{caller[1].inspect}." false end end - alias create_task create_command + alias_method :create_task, :create_command def initialize_added #:nodoc: class_options.merge!(method_options) @@ -407,7 +412,7 @@ class Thor nil end end - alias retrieve_task_name retrieve_command_name + alias_method :retrieve_task_name, :retrieve_command_name # receives a (possibly nil) command name and returns a name that is in # the commands hash. In addition to normalizing aliases, this logic @@ -421,7 +426,7 @@ class Thor possibilities = find_command_possibilities(meth) if possibilities.size > 1 - raise AmbiguousTaskError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" + fail AmbiguousTaskError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" elsif possibilities.size < 1 meth = meth || default_command elsif map[meth] @@ -430,9 +435,9 @@ class Thor meth = possibilities.first end - meth.to_s.gsub('-','_') # treat foo-bar as foo_bar + meth.to_s.gsub('-', '_') # treat foo-bar as foo_bar end - alias normalize_task_name normalize_command_name + alias_method :normalize_task_name, :normalize_command_name # this is the logic that takes the command name passed in by the user # and determines whether it is an unambiguous substrings of a command or @@ -450,23 +455,22 @@ class Thor possibilities end end - alias find_task_possibilities find_command_possibilities + alias_method :find_task_possibilities, :find_command_possibilities def subcommand_help(cmd) - desc "help [COMMAND]", "Describe subcommands or one specific subcommand" - class_eval <<-RUBY + desc 'help [COMMAND]', 'Describe subcommands or one specific subcommand' + class_eval " def help(command = nil, subcommand = true); super; end - RUBY +" end - alias subtask_help subcommand_help - + alias_method :subtask_help, :subcommand_help end include Thor::Base map HELP_MAPPINGS => :help - desc "help [COMMAND]", "Describe available commands or one specific command" + desc 'help [COMMAND]', 'Describe available commands or one specific command' def help(command = nil, subcommand = false) command ? self.class.command_help(shell, command) : self.class.help(shell, subcommand) end diff --git a/lib/bundler/vendor/thor/actions.rb b/lib/bundler/vendor/thor/actions.rb index 7e574d8b..5aaa940f 100644 --- a/lib/bundler/vendor/thor/actions.rb +++ b/lib/bundler/vendor/thor/actions.rb @@ -26,7 +26,7 @@ class Thor end # Stores and return the source root for this class - def source_root(path=nil) + def source_root(path = nil) @_source_root = path if path @_source_root end @@ -39,8 +39,8 @@ class Thor # def source_paths_for_search paths = [] - paths += self.source_paths - paths << self.source_root if self.source_root + paths += source_paths + paths << source_root if source_root paths += from_superclass(:source_paths, []) paths end @@ -48,17 +48,17 @@ class Thor # Add runtime options that help actions execution. # def add_runtime_options! - class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime, - :desc => "Overwrite files that already exist" + class_option :force, :type => :boolean, :aliases => '-f', :group => :runtime, + :desc => 'Overwrite files that already exist' - class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime, - :desc => "Run but do not make any changes" + class_option :pretend, :type => :boolean, :aliases => '-p', :group => :runtime, + :desc => 'Run but do not make any changes' - class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime, - :desc => "Suppress status output" + class_option :quiet, :type => :boolean, :aliases => '-q', :group => :runtime, + :desc => 'Suppress status output' - class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime, - :desc => "Skip files that already exist" + class_option :skip, :type => :boolean, :aliases => '-s', :group => :runtime, + :desc => 'Skip files that already exist' end end @@ -71,17 +71,16 @@ class Thor # # destination_root<String>:: The root directory needed for some actions. # - def initialize(args=[], options={}, config={}) + def initialize(args = [], options = {}, config = {}) self.behavior = case config[:behavior].to_s - when "force", "skip" - _cleanup_options_and_set(options, config[:behavior]) - :invoke - when "revoke" - :revoke - else - :invoke - end - + when 'force', 'skip' + _cleanup_options_and_set(options, config[:behavior]) + :invoke + when 'revoke' + :revoke + else + :invoke + end super self.destination_root = config[:destination_root] end @@ -113,7 +112,7 @@ class Thor # Returns the given path relative to the absolute root (ie, root where # the script started). # - def relative_to_original_destination_root(path, remove_dot=true) + def relative_to_original_destination_root(path, remove_dot = true) path = path.dup if path.gsub!(@destination_stack[0], '.') remove_dot ? (path[2..-1] || '') : path @@ -130,12 +129,15 @@ class Thor # Receives a file or directory and search for it in the source paths. # - def find_in_source_paths(file) + def find_in_source_paths(file) # rubocop:disable MethodLength + possible_files = [file, file + TEMPLATE_EXTNAME] relative_root = relative_to_original_destination_root(destination_root, false) source_paths.each do |source| - source_file = File.expand_path(file, File.join(source, relative_root)) - return source_file if File.exists?(source_file) + possible_files.each do |f| + source_file = File.expand_path(f, File.join(source, relative_root)) + return source_file if File.exist?(source_file) + end end message = "Could not find #{file.inspect} in any of your source paths. " @@ -145,12 +147,12 @@ class Thor end if source_paths.empty? - message << "Currently you have no source paths." + message << 'Currently you have no source paths.' else message << "Your current source paths are: \n#{source_paths.join("\n")}" end - raise Error, message + fail Error, message end # Do something in the root or on a provided subfolder. If a relative path @@ -162,7 +164,7 @@ class Thor # dir<String>:: the directory to move to. # config<Hash>:: give :verbose => true to log and use padding. # - def inside(dir='', config={}, &block) + def inside(dir = '', config = {}, &block) verbose = config.fetch(:verbose, false) pretend = options[:pretend] @@ -204,18 +206,18 @@ class Thor # # apply "recipes/jquery.rb" # - def apply(path, config={}) + def apply(path, config = {}) verbose = config.fetch(:verbose, true) - is_uri = path =~ /^https?\:\/\// + is_uri = path =~ %r{^https?\://} path = find_in_source_paths(path) unless is_uri say_status :apply, path, verbose shell.padding += 1 if verbose if is_uri - contents = open(path, "Accept" => "application/x-thor-template") {|io| io.read } + contents = open(path, 'Accept' => 'application/x-thor-template') { |io| io.read } else - contents = open(path) {|io| io.read } + contents = open(path) { |io| io.read } end instance_eval(contents, path) @@ -235,7 +237,7 @@ class Thor # run('ln -s ~/edge rails') # end # - def run(command, config={}) + def run(command, config = {}) return unless behavior == :invoke destination = relative_to_original_destination_root(destination_root, false) @@ -259,7 +261,7 @@ class Thor # command<String>:: the command to be executed. # config<Hash>:: give :verbose => false to not log the status. # - def run_ruby_script(command, config={}) + def run_ruby_script(command, config = {}) return unless behavior == :invoke run command, config.merge(:with => Thor::Util.ruby_command) end @@ -295,24 +297,23 @@ class Thor run command, :with => :thor, :verbose => verbose, :pretend => pretend, :capture => capture end - protected + protected - # Allow current root to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:destination_root => self.destination_root) - end + # Allow current root to be shared between invocations. + # + def _shared_configuration #:nodoc: + super.merge!(:destination_root => destination_root) + end - def _cleanup_options_and_set(options, key) #:nodoc: - case options - when Array - %w(--force -f --skip -s).each { |i| options.delete(i) } - options << "--#{key}" - when Hash - [:force, :skip, "force", "skip"].each { |i| options.delete(i) } - options.merge!(key => true) - end + def _cleanup_options_and_set(options, key) #:nodoc: + case options + when Array + %w(--force -f --skip -s).each { |i| options.delete(i) } + options << "--#{key}" + when Hash + [:force, :skip, 'force', 'skip'].each { |i| options.delete(i) } + options.merge!(key => true) end - + end end end diff --git a/lib/bundler/vendor/thor/actions/create_file.rb b/lib/bundler/vendor/thor/actions/create_file.rb index ed5973a4..0436e672 100644 --- a/lib/bundler/vendor/thor/actions/create_file.rb +++ b/lib/bundler/vendor/thor/actions/create_file.rb @@ -2,7 +2,6 @@ require 'thor/actions/empty_directory' class Thor module Actions - # Create a new file relative to the destination root with the given data, # which is the return value of a block or a data string. # @@ -25,7 +24,7 @@ class Thor data = args.first action CreateFile.new(self, destination, block || data.to_s, config) end - alias :add_file :create_file + alias_method :add_file, :create_file # CreateFile is a subset of Template, which instead of rendering a file with # ERB, it gets the content from the user. @@ -33,7 +32,7 @@ class Thor class CreateFile < EmptyDirectory #:nodoc: attr_reader :data - def initialize(base, destination, data, config={}) + def initialize(base, destination, data, config = {}) @data = data super(base, destination, config) end @@ -51,10 +50,10 @@ class Thor # def render @render ||= if data.is_a?(Proc) - data.call - else - data - end + data.call + else + data + end end def invoke! @@ -65,41 +64,40 @@ class Thor given_destination end - protected + protected - # Now on conflict we check if the file is identical or not. - # - def on_conflict_behavior(&block) - if identical? - say_status :identical, :blue - else - options = base.options.merge(config) - force_or_skip_or_conflict(options[:force], options[:skip], &block) - end - end - - # If force is true, run the action, otherwise check if it's not being - # skipped. If both are false, show the file_collision menu, if the menu - # returns true, force it, otherwise skip. - # - def force_or_skip_or_conflict(force, skip, &block) - if force - say_status :force, :yellow - block.call unless pretend? - elsif skip - say_status :skip, :yellow - else - say_status :conflict, :red - force_or_skip_or_conflict(force_on_collision?, true, &block) - end + # Now on conflict we check if the file is identical or not. + # + def on_conflict_behavior(&block) + if identical? + say_status :identical, :blue + else + options = base.options.merge(config) + force_or_skip_or_conflict(options[:force], options[:skip], &block) end + end - # Shows the file collision menu to the user and gets the result. - # - def force_on_collision? - base.shell.file_collision(destination){ render } + # If force is true, run the action, otherwise check if it's not being + # skipped. If both are false, show the file_collision menu, if the menu + # returns true, force it, otherwise skip. + # + def force_or_skip_or_conflict(force, skip, &block) + if force + say_status :force, :yellow + block.call unless pretend? + elsif skip + say_status :skip, :yellow + else + say_status :conflict, :red + force_or_skip_or_conflict(force_on_collision?, true, &block) end + end + # Shows the file collision menu to the user and gets the result. + # + def force_on_collision? + base.shell.file_collision(destination) { render } + end end end end diff --git a/lib/bundler/vendor/thor/actions/create_link.rb b/lib/bundler/vendor/thor/actions/create_link.rb index fba39151..799e5a20 100644 --- a/lib/bundler/vendor/thor/actions/create_link.rb +++ b/lib/bundler/vendor/thor/actions/create_link.rb @@ -2,7 +2,6 @@ require 'thor/actions/create_file' class Thor module Actions - # Create a new file relative to the destination root from the given source. # # ==== Parameters @@ -20,7 +19,7 @@ class Thor source = args.first action CreateLink.new(self, destination, source, config) end - alias :add_link :create_link + alias_method :add_link, :create_link # CreateLink is a subset of CreateFile, which instead of taking a block of # data, just takes a source string from the user. diff --git a/lib/bundler/vendor/thor/actions/directory.rb b/lib/bundler/vendor/thor/actions/directory.rb index 7f8fd97c..32d9c8d4 100644 --- a/lib/bundler/vendor/thor/actions/directory.rb +++ b/lib/bundler/vendor/thor/actions/directory.rb @@ -55,10 +55,10 @@ class Thor class Directory < EmptyDirectory #:nodoc: attr_reader :source - def initialize(base, source, destination=nil, config={}, &block) + def initialize(base, source, destination = nil, config = {}, &block) @source = File.expand_path(base.find_in_source_paths(source.to_s)) @block = block - super(base, destination, { :recursive => true }.merge(config)) + super(base, destination, {:recursive => true}.merge(config)) end def invoke! @@ -70,50 +70,49 @@ class Thor execute! end - protected + protected - def execute! - lookup = Util.escape_globs(source) - lookup = config[:recursive] ? File.join(lookup, '**') : lookup - lookup = file_level_lookup(lookup) + def execute! # rubocop:disable MethodLength + lookup = Util.escape_globs(source) + lookup = config[:recursive] ? File.join(lookup, '**') : lookup + lookup = file_level_lookup(lookup) - files(lookup).sort.each do |file_source| - next if File.directory?(file_source) - next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern]) - file_destination = File.join(given_destination, file_source.gsub(source, '.')) - file_destination.gsub!('/./', '/') + files(lookup).sort.each do |file_source| + next if File.directory?(file_source) + next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern]) + file_destination = File.join(given_destination, file_source.gsub(source, '.')) + file_destination.gsub!('/./', '/') - case file_source - when /\.empty_directory$/ - dirname = File.dirname(file_destination).gsub(/\/\.$/, '') - next if dirname == given_destination - base.empty_directory(dirname, config) - when /\.tt$/ - destination = base.template(file_source, file_destination[0..-4], config, &@block) - else - destination = base.copy_file(file_source, file_destination, config, &@block) - end + case file_source + when /\.empty_directory$/ + dirname = File.dirname(file_destination).gsub(/\/\.$/, '') + next if dirname == given_destination + base.empty_directory(dirname, config) + when /#{TEMPLATE_EXTNAME}$/ + base.template(file_source, file_destination[0..-4], config, &@block) + else + base.copy_file(file_source, file_destination, config, &@block) end end + end - if RUBY_VERSION < '2.0' - def file_level_lookup(previous_lookup) - File.join(previous_lookup, '{*,.[a-z]*}') - end - - def files(lookup) - Dir[lookup] - end - else - def file_level_lookup(previous_lookup) - File.join(previous_lookup, '*') - end + if RUBY_VERSION < '2.0' + def file_level_lookup(previous_lookup) + File.join(previous_lookup, '{*,.[a-z]*}') + end - def files(lookup) - Dir.glob(lookup, File::FNM_DOTMATCH) - end + def files(lookup) + Dir[lookup] + end + else + def file_level_lookup(previous_lookup) + File.join(previous_lookup, '*') end + def files(lookup) + Dir.glob(lookup, File::FNM_DOTMATCH) + end + end end end end diff --git a/lib/bundler/vendor/thor/actions/empty_directory.rb b/lib/bundler/vendor/thor/actions/empty_directory.rb index d9970aba..281d8fb2 100644 --- a/lib/bundler/vendor/thor/actions/empty_directory.rb +++ b/lib/bundler/vendor/thor/actions/empty_directory.rb @@ -1,6 +1,5 @@ class Thor module Actions - # Creates an empty directory. # # ==== Parameters @@ -11,7 +10,7 @@ class Thor # # empty_directory "doc" # - def empty_directory(destination, config={}) + def empty_directory(destination, config = {}) action EmptyDirectory.new(self, destination, config) end @@ -32,8 +31,8 @@ class Thor # destination<String>:: Relative path to the destination of this file # config<Hash>:: give :verbose => false to not log the status. # - def initialize(base, destination, config={}) - @base, @config = base, { :verbose => true }.merge(config) + def initialize(base, destination, config = {}) + @base, @config = base, {:verbose => true}.merge(config) self.destination = destination end @@ -43,7 +42,7 @@ class Thor # Boolean:: true if the file exists, false otherwise. # def exists? - ::File.exists?(destination) + ::File.exist?(destination) end def invoke! @@ -58,80 +57,79 @@ class Thor given_destination end - protected + protected - # Shortcut for pretend. - # - def pretend? - base.options[:pretend] - end + # Shortcut for pretend. + # + def pretend? + base.options[:pretend] + end - # Sets the absolute destination value from a relative destination value. - # It also stores the given and relative destination. Let's suppose our - # script is being executed on "dest", it sets the destination root to - # "dest". The destination, given_destination and relative_destination - # are related in the following way: - # - # inside "bar" do - # empty_directory "baz" - # end - # - # destination #=> dest/bar/baz - # relative_destination #=> bar/baz - # given_destination #=> baz - # - def destination=(destination) - if destination - @given_destination = convert_encoded_instructions(destination.to_s) - @destination = ::File.expand_path(@given_destination, base.destination_root) - @relative_destination = base.relative_to_original_destination_root(@destination) - end + # Sets the absolute destination value from a relative destination value. + # It also stores the given and relative destination. Let's suppose our + # script is being executed on "dest", it sets the destination root to + # "dest". The destination, given_destination and relative_destination + # are related in the following way: + # + # inside "bar" do + # empty_directory "baz" + # end + # + # destination #=> dest/bar/baz + # relative_destination #=> bar/baz + # given_destination #=> baz + # + def destination=(destination) + if destination + @given_destination = convert_encoded_instructions(destination.to_s) + @destination = ::File.expand_path(@given_destination, base.destination_root) + @relative_destination = base.relative_to_original_destination_root(@destination) end + end - # Filenames in the encoded form are converted. If you have a file: - # - # %file_name%.rb - # - # It calls #file_name from the base and replaces %-string with the - # return value (should be String) of #file_name: - # - # user.rb - # - # The method referenced can be either public or private. - # - def convert_encoded_instructions(filename) - filename.gsub(/%(.*?)%/) do |initial_string| - method = $1.strip - base.respond_to?(method, true) ? base.send(method) : initial_string - end + # Filenames in the encoded form are converted. If you have a file: + # + # %file_name%.rb + # + # It calls #file_name from the base and replaces %-string with the + # return value (should be String) of #file_name: + # + # user.rb + # + # The method referenced can be either public or private. + # + def convert_encoded_instructions(filename) + filename.gsub(/%(.*?)%/) do |initial_string| + method = $1.strip + base.respond_to?(method, true) ? base.send(method) : initial_string end + end - # Receives a hash of options and just execute the block if some - # conditions are met. - # - def invoke_with_conflict_check(&block) - if exists? - on_conflict_behavior(&block) - else - say_status :create, :green - block.call unless pretend? - end - - destination + # Receives a hash of options and just execute the block if some + # conditions are met. + # + def invoke_with_conflict_check(&block) + if exists? + on_conflict_behavior(&block) + else + say_status :create, :green + block.call unless pretend? end - # What to do when the destination file already exists. - # - def on_conflict_behavior(&block) - say_status :exist, :blue - end + destination + end - # Shortcut to say_status shell method. - # - def say_status(status, color) - base.shell.say_status status, relative_destination, color if config[:verbose] - end + # What to do when the destination file already exists. + # + def on_conflict_behavior(&block) + say_status :exist, :blue + end + # Shortcut to say_status shell method. + # + def say_status(status, color) + base.shell.say_status status, relative_destination, color if config[:verbose] + end end end end diff --git a/lib/bundler/vendor/thor/actions/file_manipulation.rb b/lib/bundler/vendor/thor/actions/file_manipulation.rb index a6effbec..6ccc345f 100644 --- a/lib/bundler/vendor/thor/actions/file_manipulation.rb +++ b/lib/bundler/vendor/thor/actions/file_manipulation.rb @@ -3,7 +3,6 @@ require 'open-uri' class Thor module Actions - # Copies the file from the relative source to the relative destination. If # the destination is not given it's assumed to be equal to the source. # @@ -79,14 +78,14 @@ class Thor config = args.last.is_a?(Hash) ? args.pop : {} destination = args.first - source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ /^https?\:\/\// - render = open(source) {|input| input.binmode.read } + source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ %r{^https?\://} + render = open(source) { |input| input.binmode.read } destination ||= if block_given? - block.arity == 1 ? block.call(render) : block.call - else - File.basename(source) - end + block.arity == 1 ? block.call(render) : block.call + else + File.basename(source) + end create_file destination, render, config end @@ -108,7 +107,7 @@ class Thor # def template(source, *args, &block) config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first || source.sub(/\.tt$/, '') + destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, '') source = File.expand_path(find_in_source_paths(source.to_s)) context = instance_eval('binding') @@ -131,7 +130,7 @@ class Thor # # chmod "script/server", 0755 # - def chmod(path, mode, config={}) + def chmod(path, mode, config = {}) return unless behavior == :invoke path = File.expand_path(path, destination_root) say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) @@ -284,14 +283,14 @@ class Thor # remove_file 'README' # remove_file 'app/controllers/application_controller.rb' # - def remove_file(path, config={}) + def remove_file(path, config = {}) return unless behavior == :invoke path = File.expand_path(path, destination_root) say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) - ::FileUtils.rm_rf(path) if !options[:pretend] && File.exists?(path) + ::FileUtils.rm_rf(path) if !options[:pretend] && File.exist?(path) end - alias :remove_dir :remove_file + alias_method :remove_dir, :remove_file attr_accessor :output_buffer private :output_buffer, :output_buffer= diff --git a/lib/bundler/vendor/thor/actions/inject_into_file.rb b/lib/bundler/vendor/thor/actions/inject_into_file.rb index c48cfab5..3cdd18b5 100644 --- a/lib/bundler/vendor/thor/actions/inject_into_file.rb +++ b/lib/bundler/vendor/thor/actions/inject_into_file.rb @@ -2,7 +2,6 @@ require 'thor/actions/empty_directory' class Thor module Actions - # Injects the given content into a file. Different from gsub_file, this # method is reversible. # @@ -36,13 +35,13 @@ class Thor attr_reader :replacement, :flag, :behavior def initialize(base, destination, data, config) - super(base, destination, { :verbose => true }.merge(config)) + super(base, destination, {:verbose => true}.merge(config)) @behavior, @flag = if @config.key?(:after) - [:after, @config.delete(:after)] - else - [:before, @config.delete(:before)] - end + [:after, @config.delete(:after)] + else + [:before, @config.delete(:before)] + end @replacement = data.is_a?(Proc) ? data.call : data @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp) @@ -52,10 +51,10 @@ class Thor say_status :invoke content = if @behavior == :after - '\0' + replacement - else - replacement + '\0' - end + '\0' + replacement + else + replacement + '\0' + end replace!(/#{flag}/, content, config[:force]) end @@ -64,46 +63,45 @@ class Thor say_status :revoke regexp = if @behavior == :after - content = '\1\2' - /(#{flag})(.*)(#{Regexp.escape(replacement)})/m - else - content = '\2\3' - /(#{Regexp.escape(replacement)})(.*)(#{flag})/m - end + content = '\1\2' + /(#{flag})(.*)(#{Regexp.escape(replacement)})/m + else + content = '\2\3' + /(#{Regexp.escape(replacement)})(.*)(#{flag})/m + end replace!(regexp, content, true) end - protected - - def say_status(behavior) - status = if behavior == :invoke - if flag == /\A/ - :prepend - elsif flag == /\z/ - :append - else - :insert - end - else - :subtract - end - - super(status, config[:verbose]) - end + protected + + def say_status(behavior) + status = if behavior == :invoke + if flag == /\A/ + :prepend + elsif flag == /\z/ + :append + else + :insert + end + else + :subtract + end + + super(status, config[:verbose]) + end - # Adds the content to the file. - # - def replace!(regexp, string, force) - unless base.options[:pretend] - content = File.binread(destination) - if force || !content.include?(replacement) - content.gsub!(regexp, string) - File.open(destination, 'wb') { |file| file.write(content) } - end + # Adds the content to the file. + # + def replace!(regexp, string, force) + unless base.options[:pretend] + content = File.binread(destination) + if force || !content.include?(replacement) + content.gsub!(regexp, string) + File.open(destination, 'wb') { |file| file.write(content) } end end - + end end end end diff --git a/lib/bundler/vendor/thor/base.rb b/lib/bundler/vendor/thor/base.rb index 272dae41..ace04d3b 100644 --- a/lib/bundler/vendor/thor/base.rb +++ b/lib/bundler/vendor/thor/base.rb @@ -5,6 +5,7 @@ require 'thor/error' require 'thor/invocation' require 'thor/parser' require 'thor/shell' +require 'thor/line_editor' require 'thor/util' class Thor @@ -19,6 +20,8 @@ class Thor THOR_RESERVED_WORDS = %w(invoke shell options behavior root destination_root relative_root action add_file create_file in_root inside run run_ruby_script) + TEMPLATE_EXTNAME = '.tt' + module Base attr_accessor :options, :parent_options, :args @@ -38,7 +41,7 @@ class Thor # # config<Hash>:: Configuration for this Thor class. # - def initialize(args=[], options={}, config={}) + def initialize(args = [], local_options = {}, config = {}) # rubocop:disable MethodLength parse_options = self.class.class_options # The start method splits inbound arguments at the first argument @@ -46,14 +49,14 @@ class Thor # new, passing in the two halves of the arguments Array as the # first two parameters. - if options.is_a?(Array) - command_options = config.delete(:command_options) # hook for start - parse_options = parse_options.merge(command_options) if command_options - array_options, hash_options = options, {} + command_options = config.delete(:command_options) # hook for start + parse_options = parse_options.merge(command_options) if command_options + if local_options.is_a?(Array) + array_options, hash_options = local_options, {} else # Handle the case where the class was explicitly instantiated # with pre-parsed options. - array_options, hash_options = [], options + array_options, hash_options = [], local_options end # Let Thor::Options parse the options first, so it can remove @@ -62,7 +65,7 @@ class Thor stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command] opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown) self.options = opts.parse(array_options) - self.options = config[:class_options].merge(self.options) if config[:class_options] + self.options = config[:class_options].merge(options) if config[:class_options] # If unknown options are disallowed, make sure that none of the # remaining arguments looks like an option. @@ -77,13 +80,13 @@ class Thor to_parse += opts.remaining unless self.class.strict_args_position?(config) thor_args = Thor::Arguments.new(self.class.arguments) - thor_args.parse(to_parse).each { |k,v| __send__("#{k}=", v) } + thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) } @args = thor_args.remaining end class << self def included(base) #:nodoc: - base.send :extend, ClassMethods + base.extend ClassMethods base.send :include, Invocation base.send :include, Shell end @@ -103,7 +106,7 @@ class Thor # Hash[path<String> => Class] # def subclass_files - @subclass_files ||= Hash.new{ |h,k| h[k] = [] } + @subclass_files ||= Hash.new { |h, k| h[k] = [] } end # Whenever a class inherits from Thor or Thor::Group, we should track the @@ -202,23 +205,23 @@ class Thor # ==== Errors # ArgumentError:: Raised if you supply a required argument after a non required one. # - def argument(name, options={}) + def argument(name, options = {}) # rubocop:disable MethodLength is_thor_reserved_word?(name, :argument) no_commands { attr_accessor name } required = if options.key?(:optional) - !options[:optional] - elsif options.key?(:required) - options[:required] - else - options[:default].nil? - end + !options[:optional] + elsif options.key?(:required) + options[:required] + else + options[:default].nil? + end remove_argument name arguments.each do |argument| next if argument.required? - raise ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << + fail ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << "the non-required argument #{argument.human_name.inspect}." end if required @@ -245,7 +248,7 @@ class Thor # ==== Parameters # Hash[Symbol => Object] # - def class_options(options=nil) + def class_options(options = nil) @class_options ||= from_superclass(:class_options, {}) build_options(options, @class_options) if options @class_options @@ -267,7 +270,7 @@ class Thor # :banner:: -- String to show on usage notes. # :hide:: -- If you want to hide this option from the help. # - def class_option(name, options={}) + def class_option(name, options = {}) build_option(name, options, class_options) end @@ -313,13 +316,13 @@ class Thor # ==== Parameters # name<String|Symbol> # - def group(name=nil) + def group(name = nil) @group = case name - when nil - @group || from_superclass(:group, 'standard') - else - name.to_s - end + when nil + @group || from_superclass(:group, 'standard') + else + name.to_s + end end # Returns the commands for this Thor class. @@ -331,7 +334,7 @@ class Thor def commands @commands ||= Thor::CoreExt::OrderedHash.new end - alias tasks commands + alias_method :tasks, :commands # Returns the commands for this Thor class and all subclasses. # @@ -343,7 +346,7 @@ class Thor @all_commands ||= from_superclass(:all_commands, Thor::CoreExt::OrderedHash.new) @all_commands.merge(commands) end - alias all_tasks all_commands + alias_method :all_tasks, :all_commands # Removes a given command from this Thor class. This is usually done if you # are inheriting from another class and don't want it to be available @@ -366,7 +369,7 @@ class Thor undef_method name if options[:undefine] end end - alias remove_task remove_command + alias_method :remove_task, :remove_command # All methods defined inside the given block are not added as commands. # @@ -393,7 +396,7 @@ class Thor ensure @no_commands = false end - alias no_tasks no_commands + alias_method :no_tasks, :no_commands # Sets the namespace for the Thor or Thor::Group class. By default the # namespace is retrieved from the class name. If your Thor class is named @@ -417,7 +420,7 @@ class Thor # # thor :my_command # - def namespace(name=nil) + def namespace(name = nil) if name @namespace = name.to_s else @@ -433,11 +436,11 @@ class Thor # script = MyScript.new(args, options, config) # script.invoke(:command, first_arg, second_arg, third_arg) # - def start(given_args=ARGV, config={}) + def start(given_args = ARGV, config = {}) config[:shell] ||= Thor::Base.shell.new dispatch(nil, given_args.dup, nil, config) rescue Thor::Error => e - ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message) + ENV['THOR_DEBUG'] == '1' ? (raise e) : config[:shell].error(e.message) exit(1) if exit_on_failure? rescue Errno::EPIPE # This happens if a thor command is piped to something like `head`, @@ -462,193 +465,192 @@ class Thor class_eval "def #{name}(*); super end" end end - alias public_task public_command + alias_method :public_task, :public_command def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc: if has_namespace - raise UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace." + fail UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace." else - raise UndefinedCommandError, "Could not find command #{command.inspect}." + fail UndefinedCommandError, "Could not find command #{command.inspect}." end end - alias handle_no_task_error handle_no_command_error + alias_method :handle_no_task_error, :handle_no_command_error def handle_argument_error(command, error, args, arity) #:nodoc: msg = "ERROR: \"#{basename} #{command.name}\" was called with " - msg << 'no arguments' if args.empty? - msg << 'arguments ' << args.inspect if !args.empty? - msg << "\nUsage: #{self.banner(command).inspect}" - raise InvocationError, msg - end - - protected - - # Prints the class options per group. If an option does not belong to - # any group, it's printed as Class option. - # - def class_options_help(shell, groups={}) #:nodoc: - # Group options by group - class_options.each do |_, value| - groups[value.group] ||= [] - groups[value.group] << value - end + msg << 'no arguments' if args.empty? + msg << 'arguments ' << args.inspect unless args.empty? + msg << "\nUsage: #{banner(command).inspect}" + fail InvocationError, msg + end - # Deal with default group - global_options = groups.delete(nil) || [] - print_options(shell, global_options) + protected - # Print all others - groups.each do |group_name, options| - print_options(shell, options, group_name) - end + # Prints the class options per group. If an option does not belong to + # any group, it's printed as Class option. + # + def class_options_help(shell, groups = {}) #:nodoc: + # Group options by group + class_options.each do |_, value| + groups[value.group] ||= [] + groups[value.group] << value end - # Receives a set of options and print them. - def print_options(shell, options, group_name=nil) - return if options.empty? + # Deal with default group + global_options = groups.delete(nil) || [] + print_options(shell, global_options) - list = [] - padding = options.collect{ |o| o.aliases.size }.max.to_i * 4 + # Print all others + groups.each do |group_name, options| + print_options(shell, options, group_name) + end + end - options.each do |option| - unless option.hide - item = [ option.usage(padding) ] - item.push(option.description ? "# #{option.description}" : "") + # Receives a set of options and print them. + def print_options(shell, options, group_name = nil) + return if options.empty? - list << item - list << [ "", "# Default: #{option.default}" ] if option.show_default? - list << [ "", "# Possible values: #{option.enum.join(', ')}" ] if option.enum - end - end + list = [] + padding = options.map { |o| o.aliases.size }.max.to_i * 4 - shell.say(group_name ? "#{group_name} options:" : "Options:") - shell.print_table(list, :indent => 2) - shell.say "" - end + options.each do |option| + unless option.hide + item = [option.usage(padding)] + item.push(option.description ? "# #{option.description}" : '') - # Raises an error if the word given is a Thor reserved word. - def is_thor_reserved_word?(word, type) #:nodoc: - return false unless THOR_RESERVED_WORDS.include?(word.to_s) - raise "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" + list << item + list << ['', "# Default: #{option.default}"] if option.show_default? + list << ['', "# Possible values: #{option.enum.join(', ')}"] if option.enum + end end - # Build an option and adds it to the given scope. - # - # ==== Parameters - # name<Symbol>:: The name of the argument. - # options<Hash>:: Described in both class_option and method_option. - # scope<Hash>:: Options hash that is being built up - def build_option(name, options, scope) #:nodoc: - scope[name] = Thor::Option.new(name, options) - end + shell.say(group_name ? "#{group_name} options:" : 'Options:') + shell.print_table(list, :indent => 2) + shell.say '' + end - # Receives a hash of options, parse them and add to the scope. This is a - # fast way to set a bunch of options: - # - # build_options :foo => true, :bar => :required, :baz => :string - # - # ==== Parameters - # Hash[Symbol => Object] - def build_options(options, scope) #:nodoc: - options.each do |key, value| - scope[key] = Thor::Option.parse(key, value) - end - end + # Raises an error if the word given is a Thor reserved word. + def is_thor_reserved_word?(word, type) #:nodoc: + return false unless THOR_RESERVED_WORDS.include?(word.to_s) + fail "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" + end - # Finds a command with the given name. If the command belongs to the current - # class, just return it, otherwise dup it and add the fresh copy to the - # current command hash. - def find_and_refresh_command(name) #:nodoc: - command = if command = commands[name.to_s] - command - elsif command = all_commands[name.to_s] - commands[name.to_s] = command.clone - else - raise ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found." - end + # Build an option and adds it to the given scope. + # + # ==== Parameters + # name<Symbol>:: The name of the argument. + # options<Hash>:: Described in both class_option and method_option. + # scope<Hash>:: Options hash that is being built up + def build_option(name, options, scope) #:nodoc: + scope[name] = Thor::Option.new(name, options) + end + + # Receives a hash of options, parse them and add to the scope. This is a + # fast way to set a bunch of options: + # + # build_options :foo => true, :bar => :required, :baz => :string + # + # ==== Parameters + # Hash[Symbol => Object] + def build_options(options, scope) #:nodoc: + options.each do |key, value| + scope[key] = Thor::Option.parse(key, value) end - alias find_and_refresh_task find_and_refresh_command + end - # Everytime someone inherits from a Thor class, register the klass - # and file into baseclass. - def inherited(klass) - Thor::Base.register_klass_file(klass) - klass.instance_variable_set(:@no_commands, false) + # Finds a command with the given name. If the command belongs to the current + # class, just return it, otherwise dup it and add the fresh copy to the + # current command hash. + def find_and_refresh_command(name) #:nodoc: + if commands[name.to_s] + commands[name.to_s] + elsif command = all_commands[name.to_s] # rubocop:disable AssignmentInCondition + commands[name.to_s] = command.clone + else + fail ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found." end + end + alias_method :find_and_refresh_task, :find_and_refresh_command - # Fire this callback whenever a method is added. Added methods are - # tracked as commands by invoking the create_command method. - def method_added(meth) - meth = meth.to_s + # Everytime someone inherits from a Thor class, register the klass + # and file into baseclass. + def inherited(klass) + Thor::Base.register_klass_file(klass) + klass.instance_variable_set(:@no_commands, false) + end - if meth == "initialize" - initialize_added - return - end + # Fire this callback whenever a method is added. Added methods are + # tracked as commands by invoking the create_command method. + def method_added(meth) + meth = meth.to_s - # Return if it's not a public instance method - return unless public_method_defined?(meth.to_sym) + if meth == 'initialize' + initialize_added + return + end - return if @no_commands || !create_command(meth) + # Return if it's not a public instance method + return unless public_method_defined?(meth.to_sym) - is_thor_reserved_word?(meth, :command) - Thor::Base.register_klass_file(self) - end + return if @no_commands || !create_command(meth) - # Retrieves a value from superclass. If it reaches the baseclass, - # returns default. - def from_superclass(method, default=nil) - if self == baseclass || !superclass.respond_to?(method, true) - default - else - value = superclass.send(method) - - # Ruby implements `dup` on Object, but raises a `TypeError` - # if the method is called on immediates. As a result, we - # don't have a good way to check whether dup will succeed - # without calling it and rescuing the TypeError. - begin - value.dup - rescue TypeError - value - end + is_thor_reserved_word?(meth, :command) + Thor::Base.register_klass_file(self) + end + # Retrieves a value from superclass. If it reaches the baseclass, + # returns default. + def from_superclass(method, default = nil) + if self == baseclass || !superclass.respond_to?(method, true) + default + else + value = superclass.send(method) + + # Ruby implements `dup` on Object, but raises a `TypeError` + # if the method is called on immediates. As a result, we + # don't have a good way to check whether dup will succeed + # without calling it and rescuing the TypeError. + begin + value.dup + rescue TypeError + value end - end - # A flag that makes the process exit with status 1 if any error happens. - def exit_on_failure? - false end + end - # - # The basename of the program invoking the thor class. - # - def basename - File.basename($0).split(' ').first - end + # A flag that makes the process exit with status 1 if any error happens. + def exit_on_failure? + false + end - # SIGNATURE: Sets the baseclass. This is where the superclass lookup - # finishes. - def baseclass #:nodoc: - end + # + # The basename of the program invoking the thor class. + # + def basename + File.basename($PROGRAM_NAME).split(' ').first + end - # SIGNATURE: Creates a new command if valid_command? is true. This method is - # called when a new method is added to the class. - def create_command(meth) #:nodoc: - end - alias create_task create_command + # SIGNATURE: Sets the baseclass. This is where the superclass lookup + # finishes. + def baseclass #:nodoc: + end - # SIGNATURE: Defines behavior when the initialize method is added to the - # class. - def initialize_added #:nodoc: - end + # SIGNATURE: Creates a new command if valid_command? is true. This method is + # called when a new method is added to the class. + def create_command(meth) #:nodoc: + end + alias_method :create_task, :create_command - # SIGNATURE: The hook invoked by start. - def dispatch(command, given_args, given_opts, config) #:nodoc: - raise NotImplementedError - end + # SIGNATURE: Defines behavior when the initialize method is added to the + # class. + def initialize_added #:nodoc: + end + # SIGNATURE: The hook invoked by start. + def dispatch(command, given_args, given_opts, config) #:nodoc: + fail NotImplementedError + end end end end diff --git a/lib/bundler/vendor/thor/command.rb b/lib/bundler/vendor/thor/command.rb index e56bd44c..cada32b1 100644 --- a/lib/bundler/vendor/thor/command.rb +++ b/lib/bundler/vendor/thor/command.rb @@ -2,7 +2,7 @@ class Thor class Command < Struct.new(:name, :description, :long_description, :usage, :options) FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/ - def initialize(name, description, long_description, usage, options=nil) + def initialize(name, description, long_description, usage, options = nil) super(name.to_s, description, long_description, usage, options || {}) end @@ -17,7 +17,7 @@ class Thor # By default, a command invokes a method in the thor class. You can change this # implementation to create custom commands. - def run(instance, args=[]) + def run(instance, args = []) arity = nil if private_method?(instance) @@ -31,11 +31,9 @@ class Thor instance.class.handle_no_command_error(name) end rescue ArgumentError => e - handle_argument_error?(instance, e, caller) ? - instance.class.handle_argument_error(self, e, args, arity) : (raise e) + handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e) rescue NoMethodError => e - handle_no_method_error?(instance, e, caller) ? - instance.class.handle_no_command_error(name) : (raise e) + handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (fail e) end # Returns the formatted usage by injecting given required arguments @@ -43,20 +41,20 @@ class Thor def formatted_usage(klass, namespace = true, subcommand = false) if namespace namespace = klass.namespace - formatted = "#{namespace.gsub(/^(default)/,'')}:" + formatted = "#{namespace.gsub(/^(default)/, '')}:" end formatted = "#{klass.namespace.split(':').last} " if subcommand - formatted ||= "" + formatted ||= '' # Add usage with required arguments formatted << if klass && !klass.arguments.empty? - usage.to_s.gsub(/^#{name}/) do |match| - match << " " << klass.arguments.map{ |a| a.usage }.compact.join(' ') - end - else - usage.to_s - end + usage.to_s.gsub(/^#{name}/) do |match| + match << ' ' << klass.arguments.map { |a| a.usage }.compact.join(' ') + end + else + usage.to_s + end # Add required options formatted << " #{required_options}" @@ -72,7 +70,7 @@ class Thor end def required_options - @required_options ||= options.map{ |_, o| o.usage if o.required? }.compact.sort.join(" ") + @required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(' ') end # Given a target, checks if this class name is a public method. @@ -90,15 +88,15 @@ class Thor end def sans_backtrace(backtrace, caller) #:nodoc: - saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) } - saned -= caller + saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) } + saned - caller end def handle_argument_error?(instance, error, caller) not_debugging?(instance) && error.message =~ /wrong number of arguments/ && begin saned = sans_backtrace(error.backtrace, caller) # Ruby 1.9 always include the called method in the backtrace - saned.empty? || (saned.size == 1 && RUBY_VERSION >= "1.9") + saned.empty? || (saned.size == 1 && RUBY_VERSION >= '1.9') end end @@ -107,7 +105,7 @@ class Thor error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ end end - Task = Command + Task = Command # rubocop:disable ConstantName # A command that is hidden in help messages but still invocable. class HiddenCommand < Command @@ -115,15 +113,15 @@ class Thor true end end - HiddenTask = HiddenCommand + HiddenTask = HiddenCommand # rubocop:disable ConstantName # A dynamic command that handles method missing scenarios. class DynamicCommand < Command - def initialize(name, options=nil) - super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options) + def initialize(name, options = nil) + super(name.to_s, 'A dynamically-generated command', name.to_s, name.to_s, options) end - def run(instance, args=[]) + def run(instance, args = []) if (instance.methods & [name.to_s, name.to_sym]).empty? super else @@ -131,6 +129,5 @@ class Thor end end end - DynamicTask = DynamicCommand - + DynamicTask = DynamicCommand # rubocop:disable ConstantName end diff --git a/lib/bundler/vendor/thor/core_ext/hash_with_indifferent_access.rb b/lib/bundler/vendor/thor/core_ext/hash_with_indifferent_access.rb index 0a583e67..35dbf070 100644 --- a/lib/bundler/vendor/thor/core_ext/hash_with_indifferent_access.rb +++ b/lib/bundler/vendor/thor/core_ext/hash_with_indifferent_access.rb @@ -1,6 +1,5 @@ class Thor module CoreExt #:nodoc: - # A hash with indifferent access and magic predicates. # # hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true @@ -10,8 +9,7 @@ class Thor # hash.foo? #=> true # class HashWithIndifferentAccess < ::Hash #:nodoc: - - def initialize(hash={}) + def initialize(hash = {}) super() hash.each do |key, value| self[convert_key(key)] = value @@ -31,7 +29,7 @@ class Thor end def values_at(*indices) - indices.collect { |key| self[convert_key(key)] } + indices.map { |key| self[convert_key(key)] } end def merge(other) @@ -50,31 +48,30 @@ class Thor Hash.new(default).merge!(self) end - protected + protected - def convert_key(key) - key.is_a?(Symbol) ? key.to_s : key - end + def convert_key(key) + key.is_a?(Symbol) ? key.to_s : key + end - # Magic predicates. For instance: - # - # options.force? # => !!options['force'] - # options.shebang # => "/usr/lib/local/ruby" - # options.test_framework?(:rspec) # => options[:test_framework] == :rspec - # - def method_missing(method, *args, &block) - method = method.to_s - if method =~ /^(\w+)\?$/ - if args.empty? - !!self[$1] - else - self[$1] == args.first - end + # Magic predicates. For instance: + # + # options.force? # => !!options['force'] + # options.shebang # => "/usr/lib/local/ruby" + # options.test_framework?(:rspec) # => options[:test_framework] == :rspec + # + def method_missing(method, *args, &block) + method = method.to_s + if method =~ /^(\w+)\?$/ + if args.empty? + !!self[$1] else - self[method] + self[$1] == args.first end + else + self[method] end - + end end end end diff --git a/lib/bundler/vendor/thor/core_ext/io_binary_read.rb b/lib/bundler/vendor/thor/core_ext/io_binary_read.rb index a824f1b2..496446f5 100644 --- a/lib/bundler/vendor/thor/core_ext/io_binary_read.rb +++ b/lib/bundler/vendor/thor/core_ext/io_binary_read.rb @@ -1,12 +1,10 @@ class IO #:nodoc: class << self - def binread(file, *args) - raise ArgumentError, "wrong number of arguments (#{1 + args.size} for 1..3)" unless args.size < 3 + fail ArgumentError, "wrong number of arguments (#{1 + args.size} for 1..3)" unless args.size < 3 File.open(file, 'rb') do |f| f.read(*args) end end unless method_defined? :binread - end end diff --git a/lib/bundler/vendor/thor/core_ext/ordered_hash.rb b/lib/bundler/vendor/thor/core_ext/ordered_hash.rb index 27fea5bb..23b7f95f 100644 --- a/lib/bundler/vendor/thor/core_ext/ordered_hash.rb +++ b/lib/bundler/vendor/thor/core_ext/ordered_hash.rb @@ -1,6 +1,5 @@ class Thor module CoreExt #:nodoc: - if RUBY_VERSION >= '1.9' class OrderedHash < ::Hash end @@ -24,7 +23,7 @@ class Thor end def []=(key, value) - if node = @hash[key] + if node = @hash[key] # rubocop:disable AssignmentInCondition node.value = value else node = Node.new(key, value) @@ -43,7 +42,7 @@ class Thor end def delete(key) - if node = @hash[key] + if node = @hash[key] # rubocop:disable AssignmentInCondition prev_node = node.prev next_node = node.next @@ -61,25 +60,25 @@ class Thor end def keys - self.map { |k, v| k } + map { |k, v| k } end def values - self.map { |k, v| v } + map { |k, v| v } end def each return unless @first yield [@first.key, @first.value] node = @first - yield [node.key, node.value] while node = node.next + yield [node.key, node.value] while node = node.next # rubocop:disable AssignmentInCondition self end def merge(other) hash = self.class.new - self.each do |key, value| + each do |key, value| hash[key] = value end @@ -95,6 +94,5 @@ class Thor end end end - end end diff --git a/lib/bundler/vendor/thor/error.rb b/lib/bundler/vendor/thor/error.rb index 3174c57e..c53be49b 100644 --- a/lib/bundler/vendor/thor/error.rb +++ b/lib/bundler/vendor/thor/error.rb @@ -11,11 +11,11 @@ class Thor # Raised when a command was not found. class UndefinedCommandError < Error end - UndefinedTaskError = UndefinedCommandError + UndefinedTaskError = UndefinedCommandError # rubocop:disable ConstantName class AmbiguousCommandError < Error end - AmbiguousTaskError = AmbiguousCommandError + AmbiguousTaskError = AmbiguousCommandError # rubocop:disable ConstantName # Raised when a command was found, but not invoked properly. class InvocationError < Error diff --git a/lib/bundler/vendor/thor/group.rb b/lib/bundler/vendor/thor/group.rb index 2aaee737..780383c2 100644 --- a/lib/bundler/vendor/thor/group.rb +++ b/lib/bundler/vendor/thor/group.rb @@ -4,7 +4,7 @@ require 'thor/base' # is that it invokes all commands at once. It also include some methods that allows # invocations to be done at the class method, which are not available to Thor # commands. -class Thor::Group +class Thor::Group # rubocop:disable ClassLength class << self # The description for this Thor::Group. If none is provided, but a source root # exists, tries to find the USAGE one folder above it, otherwise searches @@ -13,13 +13,13 @@ class Thor::Group # ==== Parameters # description<String>:: The description for this Thor::Group. # - def desc(description=nil) + def desc(description = nil) @desc = case description - when nil - @desc || from_superclass(:desc, nil) - else - description - end + when nil + @desc || from_superclass(:desc, nil) + else + description + end end # Prints help information. @@ -28,11 +28,11 @@ class Thor::Group # short:: When true, shows only usage. # def help(shell) - shell.say "Usage:" + shell.say 'Usage:' shell.say " #{banner}\n" shell.say class_options_help(shell) - shell.say self.desc if self.desc + shell.say desc if desc end # Stores invocations for this class merging with superclass values. @@ -54,7 +54,7 @@ class Thor::Group # The namespace/class given will have its options showed on the help # usage. Check invoke_from_option for more information. # - def invoke(*names, &block) + def invoke(*names, &block) # rubocop:disable MethodLength options = names.last.is_a?(Hash) ? names.pop : {} verbose = options.fetch(:verbose, true) @@ -108,14 +108,14 @@ class Thor::Group # invoked. The block receives two parameters, an instance of the current # class and the klass to be invoked. # - def invoke_from_option(*names, &block) + def invoke_from_option(*names, &block) # rubocop:disable MethodLength options = names.last.is_a?(Hash) ? names.pop : {} verbose = options.fetch(:verbose, :white) names.each do |name| unless class_options.key?(name) - raise ArgumentError, "You have to define the option #{name.inspect} " << - "before setting invoke_from_option." + fail ArgumentError, "You have to define the option #{name.inspect} " << + 'before setting invoke_from_option.' end invocations[name] = true @@ -159,7 +159,7 @@ class Thor::Group # Overwrite class options help to allow invoked generators options to be # shown recursively when invoking a generator. # - def class_options_help(shell, groups={}) #:nodoc: + def class_options_help(shell, groups = {}) #:nodoc: get_options_from_invocations(groups, class_options) do |klass| klass.send(:get_options_from_invocations, groups, class_options) end @@ -170,14 +170,14 @@ class Thor::Group # options are added to group_options hash. Options that already exists # in base_options are not added twice. # - def get_options_from_invocations(group_options, base_options) #:nodoc: + def get_options_from_invocations(group_options, base_options) #:nodoc: # rubocop:disable MethodLength invocations.each do |name, from_option| value = if from_option - option = class_options[name] - option.type == :boolean ? name : option.default - else - name - end + option = class_options[name] + option.type == :boolean ? name : option.default + else + name + end next unless value klass, _ = prepare_for_invocation(name, value) @@ -200,70 +200,70 @@ class Thor::Group def printable_commands(*) item = [] item << banner - item << (desc ? "# #{desc.gsub(/\s+/m,' ')}" : "") + item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : '') [item] end - alias printable_tasks printable_commands + alias_method :printable_tasks, :printable_commands def handle_argument_error(command, error, args, arity) #:nodoc: msg = "#{basename} #{command.name} takes #{arity} argument" - msg << "s" if arity > 1 - msg << ", but it should not." - raise error, msg + msg << 's' if arity > 1 + msg << ', but it should not.' + fail error, msg end - protected + protected - # The method responsible for dispatching given the args. - def dispatch(command, given_args, given_opts, config) #:nodoc: - if Thor::HELP_MAPPINGS.include?(given_args.first) - help(config[:shell]) - return - end + # The method responsible for dispatching given the args. + def dispatch(command, given_args, given_opts, config) #:nodoc: + if Thor::HELP_MAPPINGS.include?(given_args.first) + help(config[:shell]) + return + end - args, opts = Thor::Options.split(given_args) - opts = given_opts || opts + args, opts = Thor::Options.split(given_args) + opts = given_opts || opts - instance = new(args, opts, config) - yield instance if block_given? + instance = new(args, opts, config) + yield instance if block_given? - if command - instance.invoke_command(all_commands[command]) - else - instance.invoke_all - end + if command + instance.invoke_command(all_commands[command]) + else + instance.invoke_all end + end - # The banner for this class. You can customize it if you are invoking the - # thor class by another ways which is not the Thor::Runner. - def banner - "#{basename} #{self_command.formatted_usage(self, false)}" - end + # The banner for this class. You can customize it if you are invoking the + # thor class by another ways which is not the Thor::Runner. + def banner + "#{basename} #{self_command.formatted_usage(self, false)}" + end - # Represents the whole class as a command. - def self_command #:nodoc: - Thor::DynamicCommand.new(self.namespace, class_options) - end - alias self_task self_command + # Represents the whole class as a command. + def self_command #:nodoc: + Thor::DynamicCommand.new(namespace, class_options) + end + alias_method :self_task, :self_command - def baseclass #:nodoc: - Thor::Group - end + def baseclass #:nodoc: + Thor::Group + end - def create_command(meth) #:nodoc: - commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil) - true - end - alias create_task create_command + def create_command(meth) #:nodoc: + commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil) + true + end + alias_method :create_task, :create_command end include Thor::Base - protected +protected # Shortcut to invoke with padding and block handling. Use internally by # invoke and invoke_from_option class methods. - def _invoke_for_class_method(klass, command=nil, *args, &block) #:nodoc: + def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc: with_padding do if block case block.arity diff --git a/lib/bundler/vendor/thor/invocation.rb b/lib/bundler/vendor/thor/invocation.rb index a9adeb56..afe4cab0 100644 --- a/lib/bundler/vendor/thor/invocation.rb +++ b/lib/bundler/vendor/thor/invocation.rb @@ -19,9 +19,9 @@ class Thor end # Make initializer aware of invocations and the initialization args. - def initialize(args=[], options={}, config={}, &block) #:nodoc: - @_invocations = config[:invocations] || Hash.new { |h,k| h[k] = [] } - @_initializer = [ args, options, config ] + def initialize(args = [], options = {}, config = {}, &block) #:nodoc: + @_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] } + @_initializer = [args, options, config] super end @@ -40,11 +40,11 @@ class Thor # class A < Thor # def foo # invoke :bar - # invoke "b:hello", ["José"] + # invoke "b:hello", ["Erik"] # end # # def bar - # invoke "b:hello", ["José"] + # invoke "b:hello", ["Erik"] # end # end # @@ -93,17 +93,18 @@ class Thor # # invoke Rspec::RR, [], :style => :foo # - def invoke(name=nil, *args) + def invoke(name = nil, *args) if name.nil? warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}" return invoke_all end - args.unshift(nil) if Array === args.first || NilClass === args.first + args.unshift(nil) if args.first.is_a?(Array) || args.first.nil? command, args, opts, config = args klass, command = _retrieve_class_and_command(name, command) - raise "Expected Thor class, got #{klass}" unless klass <= Thor::Base + fail "Missing Thor class for invoke #{name}" unless klass + fail "Expected Thor class, got #{klass}" unless klass <= Thor::Base args, opts, config = _parse_initialization_options(args, opts, config) klass.send(:dispatch, command, args, opts, config) do |instance| @@ -120,7 +121,7 @@ class Thor command.run(self, *args) end end - alias invoke_task invoke_command + alias_method :invoke_task, :invoke_command # Invoke all commands for the current instance. def invoke_all #:nodoc: @@ -132,41 +133,41 @@ class Thor with_padding { invoke(*args) } end - protected + protected - # Configuration values that are shared between invocations. - def _shared_configuration #:nodoc: - { :invocations => @_invocations } - end + # Configuration values that are shared between invocations. + def _shared_configuration #:nodoc: + {:invocations => @_invocations} + end - # This method simply retrieves the class and command to be invoked. - # If the name is nil or the given name is a command in the current class, - # use the given name and return self as class. Otherwise, call - # prepare_for_invocation in the current class. - def _retrieve_class_and_command(name, sent_command=nil) #:nodoc: - case - when name.nil? - [self.class, nil] - when self.class.all_commands[name.to_s] - [self.class, name.to_s] - else - klass, command = self.class.prepare_for_invocation(nil, name) - [klass, command || sent_command] - end + # This method simply retrieves the class and command to be invoked. + # If the name is nil or the given name is a command in the current class, + # use the given name and return self as class. Otherwise, call + # prepare_for_invocation in the current class. + def _retrieve_class_and_command(name, sent_command = nil) #:nodoc: + case + when name.nil? + [self.class, nil] + when self.class.all_commands[name.to_s] + [self.class, name.to_s] + else + klass, command = self.class.prepare_for_invocation(nil, name) + [klass, command || sent_command] end - alias _retrieve_class_and_task _retrieve_class_and_command + end + alias_method :_retrieve_class_and_task, :_retrieve_class_and_command - # Initialize klass using values stored in the @_initializer. - def _parse_initialization_options(args, opts, config) #:nodoc: - stored_args, stored_opts, stored_config = @_initializer + # Initialize klass using values stored in the @_initializer. + def _parse_initialization_options(args, opts, config) #:nodoc: + stored_args, stored_opts, stored_config = @_initializer - args ||= stored_args.dup - opts ||= stored_opts.dup + args ||= stored_args.dup + opts ||= stored_opts.dup - config ||= {} - config = stored_config.merge(_shared_configuration).merge!(config) + config ||= {} + config = stored_config.merge(_shared_configuration).merge!(config) - [ args, opts, config ] - end + [args, opts, config] + end end end diff --git a/lib/bundler/vendor/thor/line_editor.rb b/lib/bundler/vendor/thor/line_editor.rb new file mode 100644 index 00000000..021c926c --- /dev/null +++ b/lib/bundler/vendor/thor/line_editor.rb @@ -0,0 +1,17 @@ +require 'thor/line_editor/basic' +require 'thor/line_editor/readline' + +class Thor + module LineEditor + def self.readline(prompt, options={}) + best_available.new(prompt, options).readline + end + + def self.best_available + [ + Thor::LineEditor::Readline, + Thor::LineEditor::Basic + ].detect(&:available?) + end + end +end diff --git a/lib/bundler/vendor/thor/line_editor/basic.rb b/lib/bundler/vendor/thor/line_editor/basic.rb new file mode 100644 index 00000000..00840593 --- /dev/null +++ b/lib/bundler/vendor/thor/line_editor/basic.rb @@ -0,0 +1,35 @@ +class Thor + module LineEditor + class Basic + attr_reader :prompt, :options + + def self.available? + true + end + + def initialize(prompt, options) + @prompt = prompt + @options = options + end + + def readline + $stdout.print(prompt) + get_input + end + + private + + def get_input + if echo? + $stdin.gets + else + $stdin.noecho(&:gets) + end + end + + def echo? + options.fetch(:echo, true) + end + end + end +end diff --git a/lib/bundler/vendor/thor/line_editor/readline.rb b/lib/bundler/vendor/thor/line_editor/readline.rb new file mode 100644 index 00000000..3b14dc4c --- /dev/null +++ b/lib/bundler/vendor/thor/line_editor/readline.rb @@ -0,0 +1,87 @@ +begin + require 'readline' +rescue LoadError +end + +class Thor + module LineEditor + class Readline < Basic + def self.available? + Object.const_defined?(:Readline) + end + + def readline + if echo? + ::Readline.completion_append_character = nil + # Ruby 1.8.7 does not allow Readline.completion_proc= to receive nil. + if complete = completion_proc + ::Readline.completion_proc = complete + end + ::Readline.readline(prompt, add_to_history?) + else + super + end + end + + private + + def add_to_history? + options.fetch(:add_to_history, true) + end + + def completion_proc + if use_path_completion? + Proc.new { |text| PathCompletion.new(text).matches } + elsif completion_options.any? + Proc.new do |text| + completion_options.select { |option| option.start_with?(text) } + end + end + end + + def completion_options + options.fetch(:limited_to, []) + end + + def use_path_completion? + options.fetch(:path, false) + end + + class PathCompletion + def initialize(text) + @text = text + end + + def matches + relative_matches + end + + private + + attr_reader :text + + def relative_matches + absolute_matches.map { |path| path.sub(base_path, '') } + end + + def absolute_matches + Dir[glob_pattern].map do |path| + if File.directory?(path) + "#{path}/" + else + path + end + end + end + + def glob_pattern + "#{base_path}#{text}*" + end + + def base_path + "#{Dir.pwd}/" + end + end + end + end +end diff --git a/lib/bundler/vendor/thor/parser/argument.rb b/lib/bundler/vendor/thor/parser/argument.rb index 39ef9f29..baa75e49 100644 --- a/lib/bundler/vendor/thor/parser/argument.rb +++ b/lib/bundler/vendor/thor/parser/argument.rb @@ -1,17 +1,17 @@ class Thor class Argument #:nodoc: - VALID_TYPES = [ :numeric, :hash, :array, :string ] + VALID_TYPES = [:numeric, :hash, :array, :string] attr_reader :name, :description, :enum, :required, :type, :default, :banner - alias :human_name :name + alias_method :human_name, :name - def initialize(name, options={}) - class_name = self.class.name.split("::").last + def initialize(name, options = {}) + class_name = self.class.name.split('::').last type = options[:type] - raise ArgumentError, "#{class_name} name can't be nil." if name.nil? - raise ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) + fail ArgumentError, "#{class_name} name can't be nil." if name.nil? + fail ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) @name = name.to_s @description = options[:desc] @@ -41,34 +41,33 @@ class Thor end end - protected + protected - def validate! - if required? && !default.nil? - raise ArgumentError, "An argument cannot be required and have default value." - elsif @enum && !@enum.is_a?(Array) - raise ArgumentError, "An argument cannot have an enum other than an array." - end + def validate! + if required? && !default.nil? + fail ArgumentError, 'An argument cannot be required and have default value.' + elsif @enum && !@enum.is_a?(Array) + fail ArgumentError, 'An argument cannot have an enum other than an array.' end + end - def valid_type?(type) - self.class::VALID_TYPES.include?(type.to_sym) - end + def valid_type?(type) + self.class::VALID_TYPES.include?(type.to_sym) + end - def default_banner - case type - when :boolean - nil - when :string, :default - human_name.upcase - when :numeric - "N" - when :hash - "key:value" - when :array - "one two three" - end + def default_banner + case type + when :boolean + nil + when :string, :default + human_name.upcase + when :numeric + 'N' + when :hash + 'key:value' + when :array + 'one two three' end - + end end end diff --git a/lib/bundler/vendor/thor/parser/arguments.rb b/lib/bundler/vendor/thor/parser/arguments.rb index f86166d9..1cdddcc7 100644 --- a/lib/bundler/vendor/thor/parser/arguments.rb +++ b/lib/bundler/vendor/thor/parser/arguments.rb @@ -1,5 +1,5 @@ class Thor - class Arguments #:nodoc: + class Arguments #:nodoc: # rubocop:disable ClassLength NUMERIC = /(\d*\.\d+|\d+)/ # Receives an array of args and returns two arrays, one with arguments @@ -13,7 +13,7 @@ class Thor arguments << item end - return arguments, args[Range.new(arguments.size, -1)] + [arguments, args[Range.new(arguments.size, -1)]] end def self.parse(*args) @@ -23,12 +23,12 @@ class Thor # Takes an array of Thor::Argument objects. # - def initialize(arguments=[]) + def initialize(arguments = []) @assigns, @non_assigned_required = {}, [] @switches = arguments arguments.each do |argument| - if argument.default != nil + if !argument.default.nil? @assigns[argument.human_name] = argument.default elsif argument.required? @non_assigned_required << argument @@ -49,123 +49,127 @@ class Thor @assigns end - def remaining + def remaining # rubocop:disable TrivialAccessors @pile end - private + private - def no_or_skip?(arg) - arg =~ /^--(no|skip)-([-\w]+)$/ - $2 - end + def no_or_skip?(arg) + arg =~ /^--(no|skip)-([-\w]+)$/ + $2 + end - def last? - @pile.empty? - end + def last? + @pile.empty? + end - def peek - @pile.first - end + def peek + @pile.first + end - def shift - @pile.shift - end + def shift + @pile.shift + end - def unshift(arg) - unless arg.kind_of?(Array) - @pile.unshift(arg) - else - @pile = arg + @pile - end + def unshift(arg) + if arg.kind_of?(Array) + @pile = arg + @pile + else + @pile.unshift(arg) end + end - def current_is_value? - peek && peek.to_s !~ /^-/ - end + def current_is_value? + peek && peek.to_s !~ /^-/ + end - # Runs through the argument array getting strings that contains ":" and - # mark it as a hash: - # - # [ "name:string", "age:integer" ] - # - # Becomes: - # - # { "name" => "string", "age" => "integer" } - # - def parse_hash(name) - return shift if peek.is_a?(Hash) - hash = {} - - while current_is_value? && peek.include?(?:) - key, value = shift.split(':',2) - hash[key] = value - end - hash - end + # Runs through the argument array getting strings that contains ":" and + # mark it as a hash: + # + # [ "name:string", "age:integer" ] + # + # Becomes: + # + # { "name" => "string", "age" => "integer" } + # + def parse_hash(name) + return shift if peek.is_a?(Hash) + hash = {} - # Runs through the argument array getting all strings until no string is - # found or a switch is found. - # - # ["a", "b", "c"] - # - # And returns it as an array: - # - # ["a", "b", "c"] - # - def parse_array(name) - return shift if peek.is_a?(Array) - array = [] - - while current_is_value? - array << shift - end - array + while current_is_value? && peek.include?(':') + key, value = shift.split(':', 2) + hash[key] = value end + hash + end - # Check if the peek is numeric format and return a Float or Integer. - # Otherwise raises an error. - # - def parse_numeric(name) - return shift if peek.is_a?(Numeric) + # Runs through the argument array getting all strings until no string is + # found or a switch is found. + # + # ["a", "b", "c"] + # + # And returns it as an array: + # + # ["a", "b", "c"] + # + def parse_array(name) + return shift if peek.is_a?(Array) + array = [] + array << shift while current_is_value? + array + end - unless peek =~ NUMERIC && $& == peek - raise MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}" - end + # Check if the peek is numeric format and return a Float or Integer. + # Check if the peek is included in enum if enum is provided. + # Otherwise raises an error. + # + def parse_numeric(name) + return shift if peek.is_a?(Numeric) - $&.index('.') ? shift.to_f : shift.to_i + unless peek =~ NUMERIC && $& == peek + fail MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}" end - # Parse string: - # for --string-arg, just return the current value in the pile - # for --no-string-arg, nil - # - def parse_string(name) - if no_or_skip?(name) - nil - else - value = shift - if @switches.is_a?(Hash) && switch = @switches[name] - if switch.enum && !switch.enum.include?(value) - raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" - end + value = $&.index('.') ? shift.to_f : shift.to_i + if @switches.is_a?(Hash) && switch = @switches[name] + if switch.enum && !switch.enum.include?(value) + raise MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" end - value end - end - - # Raises an error if @non_assigned_required array is not empty. - # - def check_requirement! - unless @non_assigned_required.empty? - names = @non_assigned_required.map do |o| - o.respond_to?(:switch_name) ? o.switch_name : o.human_name - end.join("', '") + value + end - class_name = self.class.name.split('::').last.downcase - raise RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'" + # Parse string: + # for --string-arg, just return the current value in the pile + # for --no-string-arg, nil + # Check if the peek is included in enum if enum is provided. Otherwise raises an error. + # + def parse_string(name) + if no_or_skip?(name) + nil + else + value = shift + if @switches.is_a?(Hash) && switch = @switches[name] # rubocop:disable AssignmentInCondition + if switch.enum && !switch.enum.include?(value) + fail MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" + end end + value end + end + # Raises an error if @non_assigned_required array is not empty. + # + def check_requirement! + unless @non_assigned_required.empty? + names = @non_assigned_required.map do |o| + o.respond_to?(:switch_name) ? o.switch_name : o.human_name + end.join("', '") + + class_name = self.class.name.split('::').last.downcase + fail RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'" + end + end end end diff --git a/lib/bundler/vendor/thor/parser/option.rb b/lib/bundler/vendor/thor/parser/option.rb index 47810694..a076045d 100644 --- a/lib/bundler/vendor/thor/parser/option.rb +++ b/lib/bundler/vendor/thor/parser/option.rb @@ -4,7 +4,7 @@ class Thor VALID_TYPES = [:boolean, :numeric, :hash, :array, :string] - def initialize(name, options={}) + def initialize(name, options = {}) options[:required] = false unless options.key?(:required) super @lazy_default = options[:lazy_default] @@ -40,7 +40,7 @@ class Thor # # By default all options are optional, unless :required is given. # - def self.parse(key, value) + def self.parse(key, value) # rubocop:disable MethodLength if key.is_a?(Array) name, *aliases = key else @@ -51,21 +51,21 @@ class Thor default = value type = case value - when Symbol - default = nil - if VALID_TYPES.include?(value) - value - elsif required = (value == :required) - :string - end - when TrueClass, FalseClass - :boolean - when Numeric - :numeric - when Hash, Array, String - value.class.name.downcase.to_sym - end - self.new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases) + when Symbol + default = nil + if VALID_TYPES.include?(value) + value + elsif required = (value == :required) # rubocop:disable AssignmentInCondition + :string + end + when TrueClass, FalseClass + :boolean + when Numeric + :numeric + when Hash, Array, String + value.class.name.downcase.to_sym + end + new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases) end def switch_name @@ -76,17 +76,17 @@ class Thor @human_name ||= dasherized? ? undasherize(name) : name end - def usage(padding=0) + def usage(padding = 0) sample = if banner && !banner.to_s.empty? - "#{switch_name}=#{banner}" - else - switch_name - end + "#{switch_name}=#{banner}" + else + switch_name + end sample = "[#{sample}]" unless required? if aliases.empty? - (" " * padding) << sample + (' ' * padding) << sample else "#{aliases.join(', ')}, #{sample}" end @@ -103,7 +103,7 @@ class Thor protected def validate! - raise ArgumentError, "An option cannot be boolean and required." if boolean? && required? + fail ArgumentError, 'An option cannot be boolean and required.' if boolean? && required? end def dasherized? @@ -115,7 +115,7 @@ class Thor end def dasherize(str) - (str.length > 1 ? "--" : "-") + str.gsub('_', '-') + (str.length > 1 ? '--' : '-') + str.gsub('_', '-') end end end diff --git a/lib/bundler/vendor/thor/parser/options.rb b/lib/bundler/vendor/thor/parser/options.rb index 9542e816..fb3fd1e0 100644 --- a/lib/bundler/vendor/thor/parser/options.rb +++ b/lib/bundler/vendor/thor/parser/options.rb @@ -1,5 +1,5 @@ class Thor - class Options < Arguments #:nodoc: + class Options < Arguments #:nodoc: # rubocop:disable ClassLength LONG_RE = /^(--\w+(?:-\w+)*)$/ SHORT_RE = /^(-[a-z])$/i EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i @@ -14,22 +14,22 @@ class Thor when true "--#{key}" when Array - "--#{key} #{value.map{ |v| v.inspect }.join(' ')}" + "--#{key} #{value.map { |v| v.inspect }.join(' ')}" when Hash - "--#{key} #{value.map{ |k,v| "#{k}:#{v}" }.join(' ')}" + "--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}" when nil, false - "" + '' else "--#{key} #{value.inspect}" end - end.join(" ") + end.join(' ') end # Takes a hash of Thor::Option and a hash with defaults. # # If +stop_on_unknown+ is true, #parse will stop as soon as it encounters # an unknown option or a regular argument. - def initialize(hash_options={}, defaults={}, stop_on_unknown=false) + def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false) @stop_on_unknown = stop_on_unknown options = hash_options.values super(options) @@ -52,7 +52,7 @@ class Thor end end - def remaining + def remaining # rubocop:disable TrivialAccessors @extra end @@ -69,7 +69,7 @@ class Thor end end - def parse(args) + def parse(args) # rubocop:disable MethodLength @pile = args.dup @parsing_options = true @@ -119,100 +119,100 @@ class Thor def check_unknown! # an unknown option starts with - or -- and has no more --'s afterward. unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ } - raise UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty? + fail UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty? end - protected - - # Check if the current value in peek is a registered switch. - # - # Two booleans are returned. The first is true if the current value - # starts with a hyphen; the second is true if it is a registered switch. - def current_is_switch? - case peek - when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM - [true, switch?($1)] - when SHORT_SQ_RE - [true, $1.split('').any? { |f| switch?("-#{f}") }] - else - [false, false] - end - end + protected - def current_is_switch_formatted? - case peek - when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE - true - else - false - end + # Check if the current value in peek is a registered switch. + # + # Two booleans are returned. The first is true if the current value + # starts with a hyphen; the second is true if it is a registered switch. + def current_is_switch? + case peek + when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM + [true, switch?($1)] + when SHORT_SQ_RE + [true, $1.split('').any? { |f| switch?("-#{f}") }] + else + [false, false] end + end - def current_is_value? - peek && (!parsing_options? || super) + def current_is_switch_formatted? + case peek + when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE + true + else + false end + end - def switch?(arg) - switch_option(normalize_switch(arg)) - end + def current_is_value? + peek && (!parsing_options? || super) + end - def switch_option(arg) - if match = no_or_skip?(arg) - @switches[arg] || @switches["--#{match}"] - else - @switches[arg] - end - end + def switch?(arg) + switch_option(normalize_switch(arg)) + end - # Check if the given argument is actually a shortcut. - # - def normalize_switch(arg) - (@shorts[arg] || arg).tr('_', '-') + def switch_option(arg) + if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition + @switches[arg] || @switches["--#{match}"] + else + @switches[arg] end + end - def parsing_options? - peek - @parsing_options - end + # Check if the given argument is actually a shortcut. + # + def normalize_switch(arg) + (@shorts[arg] || arg).tr('_', '-') + end - # Parse boolean values which can be given as --foo=true, --foo or --no-foo. - # - def parse_boolean(switch) - if current_is_value? - if ["true", "TRUE", "t", "T", true].include?(peek) - shift - true - elsif ["false", "FALSE", "f", "F", false].include?(peek) - shift - false - else - true - end + def parsing_options? + peek + @parsing_options + end + + # Parse boolean values which can be given as --foo=true, --foo or --no-foo. + # + def parse_boolean(switch) + if current_is_value? + if ['true', 'TRUE', 't', 'T', true].include?(peek) + shift + true + elsif ['false', 'FALSE', 'f', 'F', false].include?(peek) + shift + false else - @switches.key?(switch) || !no_or_skip?(switch) + true end + else + @switches.key?(switch) || !no_or_skip?(switch) end + end - # Parse the value at the peek analyzing if it requires an input or not. - # - def parse_peek(switch, option) - if parsing_options? && (current_is_switch_formatted? || last?) - if option.boolean? - # No problem for boolean types - elsif no_or_skip?(switch) - return nil # User set value to nil - elsif option.string? && !option.required? - # Return the default if there is one, else the human name - return option.lazy_default || option.default || option.human_name - elsif option.lazy_default - return option.lazy_default - else - raise MalformattedArgumentError, "No value provided for option '#{switch}'" - end + # Parse the value at the peek analyzing if it requires an input or not. + # + def parse_peek(switch, option) + if parsing_options? && (current_is_switch_formatted? || last?) + if option.boolean? + # No problem for boolean types + elsif no_or_skip?(switch) + return nil # User set value to nil + elsif option.string? && !option.required? + # Return the default if there is one, else the human name + return option.lazy_default || option.default || option.human_name + elsif option.lazy_default + return option.lazy_default + else + fail MalformattedArgumentError, "No value provided for option '#{switch}'" end - - @non_assigned_required.delete(option) - send(:"parse_#{option.type}", switch) end + + @non_assigned_required.delete(option) + send(:"parse_#{option.type}", switch) + end end end diff --git a/lib/bundler/vendor/thor/rake_compat.rb b/lib/bundler/vendor/thor/rake_compat.rb index fcb3b24d..d347672d 100644 --- a/lib/bundler/vendor/thor/rake_compat.rb +++ b/lib/bundler/vendor/thor/rake_compat.rb @@ -12,7 +12,7 @@ class Thor # include Thor::RakeCompat # # RSpec::Core::RakeTask.new(:spec) do |t| - # t.spec_opts = ['--options', "./.rspec"] + # t.spec_opts = ['--options', './.rspec'] # t.spec_files = FileList['spec/**/*_spec.rb'] # end # end @@ -28,23 +28,23 @@ class Thor # Hack. Make rakefile point to invoker, so rdoc task is generated properly. rakefile = File.basename(caller[0].match(/(.*):\d+/)[1]) Rake.application.instance_variable_set(:@rakefile, rakefile) - self.rake_classes << base + rake_classes << base end end end # override task on (main), for compatibility with Rake 0.9 -self.instance_eval do +instance_eval do alias rake_namespace namespace def task(*) task = super - if klass = Thor::RakeCompat.rake_classes.last + if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition non_namespaced_name = task.name.split(':').last description = non_namespaced_name - description << task.arg_names.map{ |n| n.to_s.upcase }.join(' ') + description << task.arg_names.map { |n| n.to_s.upcase }.join(' ') description.strip! klass.desc description, Rake.application.last_description || non_namespaced_name @@ -58,7 +58,7 @@ self.instance_eval do end def namespace(name) - if klass = Thor::RakeCompat.rake_classes.last + if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition const_name = Thor::Util.camel_case(name.to_s).to_sym klass.const_set(const_name, Class.new(Thor)) new_klass = klass.const_get(const_name) @@ -69,4 +69,3 @@ self.instance_eval do Thor::RakeCompat.rake_classes.pop end end - diff --git a/lib/bundler/vendor/thor/runner.rb b/lib/bundler/vendor/thor/runner.rb index bef3d57b..761b7b31 100644 --- a/lib/bundler/vendor/thor/runner.rb +++ b/lib/bundler/vendor/thor/runner.rb @@ -8,8 +8,8 @@ require 'yaml' require 'digest/md5' require 'pathname' -class Thor::Runner < Thor #:nodoc: - map "-T" => :list, "-i" => :install, "-u" => :update, "-v" => :version +class Thor::Runner < Thor #:nodoc: # rubocop:disable ClassLength + map '-T' => :list, '-i' => :install, '-u' => :update, '-v' => :version # Override Thor#help so it can give information about any class and any method. # @@ -18,7 +18,7 @@ class Thor::Runner < Thor #:nodoc: initialize_thorfiles(meth) klass, command = Thor::Util.find_class_and_command_by_namespace(meth) self.class.handle_no_command_error(command, false) if klass.nil? - klass.start(["-h", command].compact, :shell => self.shell) + klass.start(['-h', command].compact, :shell => shell) else super end @@ -33,38 +33,38 @@ class Thor::Runner < Thor #:nodoc: klass, command = Thor::Util.find_class_and_command_by_namespace(meth) self.class.handle_no_command_error(command, false) if klass.nil? args.unshift(command) if command - klass.start(args, :shell => self.shell) + klass.start(args, :shell => shell) end - desc "install NAME", "Install an optionally named Thor file into your system commands" + desc 'install NAME', 'Install an optionally named Thor file into your system commands' method_options :as => :string, :relative => :boolean, :force => :boolean - def install(name) + def install(name) # rubocop:disable MethodLength initialize_thorfiles # If a directory name is provided as the argument, look for a 'main.thor' # command in said directory. begin if File.directory?(File.expand_path(name)) - base, package = File.join(name, "main.thor"), :directory - contents = open(base) {|input| input.read } + base, package = File.join(name, 'main.thor'), :directory + contents = open(base) { |input| input.read } else base, package = name, :file - contents = open(name) {|input| input.read } + contents = open(name) { |input| input.read } end rescue OpenURI::HTTPError raise Error, "Error opening URI '#{name}'" rescue Errno::ENOENT - raise Error, "Error opening file '#{name}'" + fail Error, "Error opening file '#{name}'" end - say "Your Thorfile contains:" + say 'Your Thorfile contains:' say contents - unless options["force"] - return false if no?("Do you wish to continue [y/N]?") + unless options['force'] + return false if no?('Do you wish to continue [y/N]?') end - as = options["as"] || begin + as = options['as'] || begin first_line = contents.split("\n")[0] (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil end @@ -75,11 +75,11 @@ class Thor::Runner < Thor #:nodoc: as = basename if as.empty? end - location = if options[:relative] || name =~ /^https?:\/\// - name - else - File.expand_path(name) - end + location = if options[:relative] || name =~ %r{^https?://} + name + else + File.expand_path(name) + end thor_yaml[as] = { :filename => Digest::MD5.hexdigest(name + as), @@ -88,11 +88,11 @@ class Thor::Runner < Thor #:nodoc: } save_yaml(thor_yaml) - say "Storing thor file in your system repository" + say 'Storing thor file in your system repository' destination = File.join(thor_root, thor_yaml[as][:filename]) if package == :file - File.open(destination, "w") { |f| f.puts contents } + File.open(destination, 'w') { |f| f.puts contents } else FileUtils.cp_r(name, destination) end @@ -100,32 +100,32 @@ class Thor::Runner < Thor #:nodoc: thor_yaml[as][:filename] # Indicate success end - desc "version", "Show Thor version" + desc 'version', 'Show Thor version' def version require 'thor/version' say "Thor #{Thor::VERSION}" end - desc "uninstall NAME", "Uninstall a named Thor module" + desc 'uninstall NAME', 'Uninstall a named Thor module' def uninstall(name) - raise Error, "Can't find module '#{name}'" unless thor_yaml[name] + fail Error, "Can't find module '#{name}'" unless thor_yaml[name] say "Uninstalling #{name}." FileUtils.rm_rf(File.join(thor_root, "#{thor_yaml[name][:filename]}")) thor_yaml.delete(name) save_yaml(thor_yaml) - puts "Done." + puts 'Done.' end - desc "update NAME", "Update a Thor file from its original location" + desc 'update NAME', 'Update a Thor file from its original location' def update(name) - raise Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] + fail Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] say "Updating '#{name}' from #{thor_yaml[name][:location]}" old_filename = thor_yaml[name][:filename] - self.options = self.options.merge("as" => name) + self.options = options.merge('as' => name) if File.directory? File.expand_path(name) FileUtils.rm_rf(File.join(thor_root, old_filename)) @@ -143,21 +143,21 @@ class Thor::Runner < Thor #:nodoc: end end - desc "installed", "List the installed Thor modules and commands" + desc 'installed', 'List the installed Thor modules and commands' method_options :internal => :boolean def installed initialize_thorfiles(nil, true) - display_klasses(true, options["internal"]) + display_klasses(true, options['internal']) end - desc "list [SEARCH]", "List the available thor commands (--substring means .*SEARCH)" + desc 'list [SEARCH]', 'List the available thor commands (--substring means .*SEARCH)' method_options :substring => :boolean, :group => :string, :all => :boolean, :debug => :boolean - def list(search="") + def list(search = '') initialize_thorfiles - search = ".*#{search}" if options["substring"] + search = ".*#{search}" if options['substring'] search = /^#{search}.*/i - group = options[:group] || "standard" + group = options[:group] || 'standard' klasses = Thor::Base.subclasses.select do |k| (options[:all] || k.group == group) && k.namespace =~ search @@ -166,157 +166,157 @@ class Thor::Runner < Thor #:nodoc: display_klasses(false, false, klasses) end - private +private - def self.banner(command, all = false, subcommand = false) - "thor " + command.formatted_usage(self, all, subcommand) - end + def self.banner(command, all = false, subcommand = false) + 'thor ' + command.formatted_usage(self, all, subcommand) + end + + def thor_root + Thor::Util.thor_root + end - def thor_root - Thor::Util.thor_root + def thor_yaml + @thor_yaml ||= begin + yaml_file = File.join(thor_root, 'thor.yml') + yaml = YAML.load_file(yaml_file) if File.exist?(yaml_file) + yaml || {} end + end - def thor_yaml - @thor_yaml ||= begin - yaml_file = File.join(thor_root, "thor.yml") - yaml = YAML.load_file(yaml_file) if File.exists?(yaml_file) - yaml || {} - end + # Save the yaml file. If none exists in thor root, creates one. + # + def save_yaml(yaml) + yaml_file = File.join(thor_root, 'thor.yml') + + unless File.exist?(yaml_file) + FileUtils.mkdir_p(thor_root) + yaml_file = File.join(thor_root, 'thor.yml') + FileUtils.touch(yaml_file) end - # Save the yaml file. If none exists in thor root, creates one. - # - def save_yaml(yaml) - yaml_file = File.join(thor_root, "thor.yml") + File.open(yaml_file, 'w') { |f| f.puts yaml.to_yaml } + end - unless File.exists?(yaml_file) - FileUtils.mkdir_p(thor_root) - yaml_file = File.join(thor_root, "thor.yml") - FileUtils.touch(yaml_file) - end + def self.exit_on_failure? + true + end - File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml } + # Load the Thorfiles. If relevant_to is supplied, looks for specific files + # in the thor_root instead of loading them all. + # + # By default, it also traverses the current path until find Thor files, as + # described in thorfiles. This look up can be skipped by supplying + # skip_lookup true. + # + def initialize_thorfiles(relevant_to = nil, skip_lookup = false) + thorfiles(relevant_to, skip_lookup).each do |f| + Thor::Util.load_thorfile(f, nil, options[:debug]) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) end + end - def self.exit_on_failure? - true - end + # Finds Thorfiles by traversing from your current directory down to the root + # directory of your system. If at any time we find a Thor file, we stop. + # + # We also ensure that system-wide Thorfiles are loaded first, so local + # Thorfiles can override them. + # + # ==== Example + # + # If we start at /Users/wycats/dev/thor ... + # + # 1. /Users/wycats/dev/thor + # 2. /Users/wycats/dev + # 3. /Users/wycats <-- we find a Thorfile here, so we stop + # + # Suppose we start at c:\Documents and Settings\james\dev\thor ... + # + # 1. c:\Documents and Settings\james\dev\thor + # 2. c:\Documents and Settings\james\dev + # 3. c:\Documents and Settings\james + # 4. c:\Documents and Settings + # 5. c:\ <-- no Thorfiles found! + # + def thorfiles(relevant_to = nil, skip_lookup = false) + thorfiles = [] - # Load the Thorfiles. If relevant_to is supplied, looks for specific files - # in the thor_root instead of loading them all. - # - # By default, it also traverses the current path until find Thor files, as - # described in thorfiles. This look up can be skipped by supplying - # skip_lookup true. - # - def initialize_thorfiles(relevant_to=nil, skip_lookup=false) - thorfiles(relevant_to, skip_lookup).each do |f| - Thor::Util.load_thorfile(f, nil, options[:debug]) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) + unless skip_lookup + Pathname.pwd.ascend do |path| + thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten + break unless thorfiles.empty? end end - # Finds Thorfiles by traversing from your current directory down to the root - # directory of your system. If at any time we find a Thor file, we stop. - # - # We also ensure that system-wide Thorfiles are loaded first, so local - # Thorfiles can override them. - # - # ==== Example - # - # If we start at /Users/wycats/dev/thor ... - # - # 1. /Users/wycats/dev/thor - # 2. /Users/wycats/dev - # 3. /Users/wycats <-- we find a Thorfile here, so we stop - # - # Suppose we start at c:\Documents and Settings\james\dev\thor ... - # - # 1. c:\Documents and Settings\james\dev\thor - # 2. c:\Documents and Settings\james\dev - # 3. c:\Documents and Settings\james - # 4. c:\Documents and Settings - # 5. c:\ <-- no Thorfiles found! - # - def thorfiles(relevant_to=nil, skip_lookup=false) - thorfiles = [] - - unless skip_lookup - Pathname.pwd.ascend do |path| - thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten - break unless thorfiles.empty? - end - end - - files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) - files += thorfiles - files -= ["#{thor_root}/thor.yml"] + files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) + files += thorfiles + files -= ["#{thor_root}/thor.yml"] - files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file - end + files.map! do |file| + File.directory?(file) ? File.join(file, 'main.thor') : file end + end - # Load Thorfiles relevant to the given method. If you provide "foo:bar" it - # will load all thor files in the thor.yaml that has "foo" e "foo:bar" - # namespaces registered. - # - def thorfiles_relevant_to(meth) - lookup = [ meth, meth.split(":")[0...-1].join(":") ] - - files = thor_yaml.select do |k, v| - v[:namespaces] && !(v[:namespaces] & lookup).empty? - end + # Load Thorfiles relevant to the given method. If you provide "foo:bar" it + # will load all thor files in the thor.yaml that has "foo" e "foo:bar" + # namespaces registered. + # + def thorfiles_relevant_to(meth) + lookup = [meth, meth.split(':')[0...-1].join(':')] - files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } + files = thor_yaml.select do |k, v| + v[:namespaces] && !(v[:namespaces] & lookup).empty? end - # Display information about the given klasses. If with_module is given, - # it shows a table with information extracted from the yaml file. - # - def display_klasses(with_modules=false, show_internal=false, klasses=Thor::Base.subclasses) - klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal + files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } + end - raise Error, "No Thor commands available" if klasses.empty? - show_modules if with_modules && !thor_yaml.empty? + # Display information about the given klasses. If with_module is given, + # it shows a table with information extracted from the yaml file. + # + def display_klasses(with_modules = false, show_internal = false, klasses = Thor::Base.subclasses) + klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal - list = Hash.new { |h,k| h[k] = [] } - groups = klasses.select { |k| k.ancestors.include?(Thor::Group) } + fail Error, 'No Thor commands available' if klasses.empty? + show_modules if with_modules && !thor_yaml.empty? - # Get classes which inherit from Thor - (klasses - groups).each { |k| list[k.namespace.split(":").first] += k.printable_commands(false) } + list = Hash.new { |h, k| h[k] = [] } + groups = klasses.select { |k| k.ancestors.include?(Thor::Group) } - # Get classes which inherit from Thor::Base - groups.map! { |k| k.printable_commands(false).first } - list["root"] = groups + # Get classes which inherit from Thor + (klasses - groups).each { |k| list[k.namespace.split(':').first] += k.printable_commands(false) } - # Order namespaces with default coming first - list = list.sort{ |a,b| a[0].sub(/^default/, '') <=> b[0].sub(/^default/, '') } - list.each { |n, commands| display_commands(n, commands) unless commands.empty? } - end + # Get classes which inherit from Thor::Base + groups.map! { |k| k.printable_commands(false).first } + list['root'] = groups - def display_commands(namespace, list) #:nodoc: - list.sort!{ |a,b| a[0] <=> b[0] } + # Order namespaces with default coming first + list = list.sort { |a, b| a[0].sub(/^default/, '') <=> b[0].sub(/^default/, '') } + list.each { |n, commands| display_commands(n, commands) unless commands.empty? } + end - say shell.set_color(namespace, :blue, true) - say "-" * namespace.size + def display_commands(namespace, list) #:nodoc: + list.sort! { |a, b| a[0] <=> b[0] } - print_table(list, :truncate => true) - say - end - alias display_tasks display_commands + say shell.set_color(namespace, :blue, true) + say '-' * namespace.size - def show_modules #:nodoc: - info = [] - labels = ["Modules", "Namespaces"] + print_table(list, :truncate => true) + say + end + alias_method :display_tasks, :display_commands - info << labels - info << [ "-" * labels[0].size, "-" * labels[1].size ] + def show_modules #:nodoc: + info = [] + labels = %w[Modules Namespaces] - thor_yaml.each do |name, hash| - info << [ name, hash[:namespaces].join(", ") ] - end + info << labels + info << ['-' * labels[0].size, '-' * labels[1].size] - print_table info - say "" + thor_yaml.each do |name, hash| + info << [name, hash[:namespaces].join(', ')] end + + print_table info + say '' + end end diff --git a/lib/bundler/vendor/thor/shell.rb b/lib/bundler/vendor/thor/shell.rb index a718c537..848dc9a1 100644 --- a/lib/bundler/vendor/thor/shell.rb +++ b/lib/bundler/vendor/thor/shell.rb @@ -2,28 +2,27 @@ require 'rbconfig' class Thor module Base - # Returns the shell used in all Thor classes. If you are in a Unix platform - # it will use a colored log, otherwise it will use a basic one without color. - # - def self.shell - @shell ||= if ENV['THOR_SHELL'] && ENV['THOR_SHELL'].size > 0 - Thor::Shell.const_get(ENV['THOR_SHELL']) - elsif ((RbConfig::CONFIG['host_os'] =~ /mswin|mingw/) && !(ENV['ANSICON'])) - Thor::Shell::Basic - else - Thor::Shell::Color - end - end + class << self + attr_writer :shell - # Sets the shell used in all Thor classes. - # - def self.shell=(klass) - @shell = klass + # Returns the shell used in all Thor classes. If you are in a Unix platform + # it will use a colored log, otherwise it will use a basic one without color. + # + def shell + @shell ||= if ENV['THOR_SHELL'] && ENV['THOR_SHELL'].size > 0 + Thor::Shell.const_get(ENV['THOR_SHELL']) + elsif RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ && !ENV['ANSICON'] + Thor::Shell::Basic + else + Thor::Shell::Color + end + end end end module Shell SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width] + attr_writer :shell autoload :Basic, 'thor/shell/basic' autoload :Color, 'thor/shell/color' @@ -42,10 +41,10 @@ class Thor # # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new # - def initialize(args=[], options={}, config={}) + def initialize(args = [], options = {}, config = {}) super self.shell = config[:shell] - self.shell.base ||= self if self.shell.respond_to?(:base) + shell.base ||= self if shell.respond_to?(:base) end # Holds the shell for the given Thor instance. If no shell is given, @@ -54,11 +53,6 @@ class Thor @shell ||= Thor::Base.shell.new end - # Sets the shell for this thor class. - def shell=(shell) - @shell = shell - end - # Common methods that are delegated to the shell. SHELL_DELEGATED_METHODS.each do |method| module_eval <<-METHOD, __FILE__, __LINE__ @@ -76,13 +70,12 @@ class Thor shell.padding -= 1 end - protected - - # Allow shell to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:shell => self.shell) - end + protected + # Allow shell to be shared between invocations. + # + def _shared_configuration #:nodoc: + super.merge!(:shell => shell) + end end end diff --git a/lib/bundler/vendor/thor/shell/basic.rb b/lib/bundler/vendor/thor/shell/basic.rb index d9119cae..9f404274 100644 --- a/lib/bundler/vendor/thor/shell/basic.rb +++ b/lib/bundler/vendor/thor/shell/basic.rb @@ -2,7 +2,7 @@ require 'tempfile' class Thor module Shell - class Basic + class Basic # rubocop:disable ClassLength attr_accessor :base attr_reader :padding @@ -23,7 +23,7 @@ class Thor # Check if base is muted # - def mute? + def mute? # rubocop:disable TrivialAccessors @mute end @@ -40,11 +40,23 @@ class Thor # they will be shown a message stating that one of those answers # must be given and re-asked the question. # + # If asking for sensitive information, the :echo option can be set + # to false to mask user input from $stdin. + # + # If the required input is a path, then set the path option to + # true. This will enable tab completion for file paths relative + # to the current working directory on systems that support + # Readline. + # # ==== Example # ask("What is your name?") # # ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"]) # + # ask("What is your password?", :echo => false) + # + # ask("Where should the file be saved?", :path => true) + # def ask(statement, *args) options = args.last.is_a?(Hash) ? args.pop : {} color = args.first @@ -63,18 +75,11 @@ class Thor # ==== Example # say("I know you knew that.") # - def say(message="", color=nil, force_new_line=(message.to_s !~ /( |\t)\Z/)) - message = message.to_s + def say(message = '', color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/)) + buffer = prepare_message(message, *color) + buffer << "\n" if force_new_line && !message.end_with?("\n") - message = set_color(message, *color) if color && can_display_colors? - - spaces = " " * padding - - if force_new_line - stdout.puts(spaces + message) - else - stdout.print(spaces + message) - end + stdout.print(buffer) stdout.flush end @@ -83,30 +88,33 @@ class Thor # in log_status, avoiding the message from being shown. If a Symbol is # given in log_status, it's used as the color. # - def say_status(status, message, log_status=true) + def say_status(status, message, log_status = true) return if quiet? || log_status == false - spaces = " " * (padding + 1) + spaces = ' ' * (padding + 1) color = log_status.is_a?(Symbol) ? log_status : :green status = status.to_s.rjust(12) status = set_color status, color, true if color - stdout.puts "#{status}#{spaces}#{message}" + buffer = "#{status}#{spaces}#{message}" + buffer << "\n" unless buffer.end_with?("\n") + + stdout.print(buffer) stdout.flush end # Make a question the to user and returns true if the user replies "y" or # "yes". # - def yes?(statement, color=nil) - !!(ask(statement, color) =~ is?(:yes)) + def yes?(statement, color = nil) + !!(ask(statement, color, :add_to_history => false) =~ is?(:yes)) end # Make a question the to user and returns true if the user replies "n" or # "no". # - def no?(statement, color=nil) - !yes?(statement, color) + def no?(statement, color = nil) + !!(ask(statement, color, :add_to_history => false) =~ is?(:no)) end # Prints values in columns @@ -116,7 +124,7 @@ class Thor # def print_in_columns(array) return if array.empty? - colwidth = (array.map{|el| el.to_s.size}.max || 0) + 2 + colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2 array.each_with_index do |value, index| # Don't output trailing spaces when printing the last column if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length @@ -136,7 +144,7 @@ class Thor # indent<Integer>:: Indent the first column by indent value. # colwidth<Integer>:: Force the first column to colwidth spaces wide. # - def print_table(array, options={}) + def print_table(array, options = {}) # rubocop:disable MethodLength return if array.empty? formats, indent, colwidth = [], options[:indent].to_i, options[:colwidth] @@ -145,26 +153,26 @@ class Thor formats << "%-#{colwidth + 2}s" if colwidth start = colwidth ? 1 : 0 - colcount = array.max{|a,b| a.size <=> b.size }.size + colcount = array.max { |a, b| a.size <=> b.size }.size maximas = [] start.upto(colcount - 1) do |index| - maxima = array.map {|row| row[index] ? row[index].to_s.size : 0 }.max + maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max maximas << maxima if index == colcount - 1 # Don't output 2 trailing spaces when printing the last column - formats << "%-s" + formats << '%-s' else formats << "%-#{maxima + 2}s" end end - formats[0] = formats[0].insert(0, " " * indent) - formats << "%s" + formats[0] = formats[0].insert(0, ' ' * indent) + formats << '%s' array.each do |row| - sentence = "" + sentence = '' row.each_with_index do |column, index| maxima = maximas[index] @@ -196,20 +204,18 @@ class Thor # ==== Options # indent<Integer>:: Indent each line of the printed paragraph by indent value. # - def print_wrapped(message, options={}) + def print_wrapped(message, options = {}) indent = options[:indent] || 0 width = terminal_width - indent paras = message.split("\n\n") paras.map! do |unwrapped| - unwrapped.strip.gsub(/\n/, " ").squeeze(" "). - gsub(/.{1,#{width}}(?:\s|\Z)/){($& + 5.chr). - gsub(/\n\005/,"\n").gsub(/\005/,"\n")} + unwrapped.strip.gsub(/\n/, ' ').squeeze(' ').gsub(/.{1,#{width}}(?:\s|\Z)/) { ($& + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n") } end paras.each do |para| para.split("\n").each do |line| - stdout.puts line.insert(0, " " * indent) + stdout.puts line.insert(0, ' ' * indent) end stdout.puts unless para == paras.last end @@ -223,15 +229,18 @@ class Thor # destination<String>:: the destination file to solve conflicts # block<Proc>:: an optional block that returns the value to be used in diff # - def file_collision(destination) + def file_collision(destination) # rubocop:disable MethodLength return true if @always_force - options = block_given? ? "[Ynaqdh]" : "[Ynaqh]" + options = block_given? ? '[Ynaqdh]' : '[Ynaqh]' - while true - answer = ask %[Overwrite #{destination}? (enter "h" for help) #{options}] + loop do + answer = ask( + %[Overwrite #{destination}? (enter "h" for help) #{options}], + :add_to_history => false + ) case answer - when is?(:yes), is?(:force), "" + when is?(:yes), is?(:force), '' return true when is?(:no), is?(:skip) return false @@ -239,7 +248,7 @@ class Thor return @always_force = true when is?(:quit) say 'Aborting...' - raise SystemExit + fail SystemExit when is?(:diff) show_diff(destination, yield) if block_given? say 'Retrying...' @@ -257,7 +266,7 @@ class Thor else result = unix? ? dynamic_width : 80 end - (result < 10) ? 80 : result + result < 10 ? 80 : result rescue 80 end @@ -280,6 +289,11 @@ class Thor protected + def prepare_message(message, *color) + spaces = " " * padding + spaces + set_color(message.to_s, *color) + end + def can_display_colors? false end @@ -293,10 +307,6 @@ class Thor $stdout end - def stdin - $stdin - end - def stderr $stderr end @@ -307,19 +317,19 @@ class Thor if value.size == 1 /\A#{value}\z/i else - /\A(#{value}|#{value[0,1]})\z/i + /\A(#{value}|#{value[0, 1]})\z/i end end def file_collision_help #:nodoc: -<<HELP -Y - yes, overwrite -n - no, do not overwrite -a - all, overwrite this and all others -q - quit, abort -d - diff, show the differences between the old and the new -h - help, show this help -HELP + <<-HELP + Y - yes, overwrite + n - no, do not overwrite + a - all, overwrite this and all others + q - quit, abort + d - diff, show the differences between the old and the new + h - help, show this help + HELP end def show_diff(destination, content) #:nodoc: @@ -359,18 +369,18 @@ HELP if chars.length <= width chars.join else - ( chars[0, width-3].join ) + "..." + ( chars[0, width - 3].join) + '...' end end end - if "".respond_to?(:encode) + if ''.respond_to?(:encode) def as_unicode yield end else def as_unicode - old, $KCODE = $KCODE, "U" + old, $KCODE = $KCODE, 'U' yield ensure $KCODE = old @@ -379,15 +389,15 @@ HELP def ask_simply(statement, color, options) default = options[:default] - message = [statement, ("(#{default})" if default), nil].uniq.join(" ") - say(message, color) - result = stdin.gets + message = [statement, ("(#{default})" if default), nil].uniq.join(' ') + message = prepare_message(message, color) + result = Thor::LineEditor.readline(message, options) return unless result result.strip! - if default && result == "" + if default && result == '' default else result @@ -398,14 +408,13 @@ HELP answer_set = options[:limited_to] correct_answer = nil until correct_answer - answers = answer_set.join(", ") + answers = answer_set.join(', ') answer = ask_simply("#{statement} [#{answers}]", color, options) correct_answer = answer_set.include?(answer) ? answer : nil say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer end correct_answer end - end end end diff --git a/lib/bundler/vendor/thor/shell/color.rb b/lib/bundler/vendor/thor/shell/color.rb index fcf9c25d..db3dcfc0 100644 --- a/lib/bundler/vendor/thor/shell/color.rb +++ b/lib/bundler/vendor/thor/shell/color.rb @@ -77,7 +77,9 @@ class Thor # :on_cyan # :on_white def set_color(string, *colors) - if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } + if colors.compact.empty? || !can_display_colors? + string + elsif colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } ansi_colors = colors.map { |color| lookup_color(color) } "#{ansi_colors.join}#{string}#{CLEAR}" else @@ -87,62 +89,61 @@ class Thor foreground, bold = colors foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol) - bold = bold ? BOLD : "" + bold = bold ? BOLD : '' "#{bold}#{foreground}#{string}#{CLEAR}" end end - protected + protected - def can_display_colors? - stdout.tty? - end + def can_display_colors? + stdout.tty? + end - # Overwrite show_diff to show diff with colors if Diff::LCS is - # available. - # - def show_diff(destination, content) #:nodoc: - if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? - actual = File.binread(destination).to_s.split("\n") - content = content.to_s.split("\n") + # Overwrite show_diff to show diff with colors if Diff::LCS is + # available. + # + def show_diff(destination, content) #:nodoc: + if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? + actual = File.binread(destination).to_s.split("\n") + content = content.to_s.split("\n") - Diff::LCS.sdiff(actual, content).each do |diff| - output_diff_line(diff) - end - else - super + Diff::LCS.sdiff(actual, content).each do |diff| + output_diff_line(diff) end + else + super end + end - def output_diff_line(diff) #:nodoc: - case diff.action - when '-' - say "- #{diff.old_element.chomp}", :red, true - when '+' - say "+ #{diff.new_element.chomp}", :green, true - when '!' - say "- #{diff.old_element.chomp}", :red, true - say "+ #{diff.new_element.chomp}", :green, true - else - say " #{diff.old_element.chomp}", nil, true - end + def output_diff_line(diff) #:nodoc: + case diff.action + when '-' + say "- #{diff.old_element.chomp}", :red, true + when '+' + say "+ #{diff.new_element.chomp}", :green, true + when '!' + say "- #{diff.old_element.chomp}", :red, true + say "+ #{diff.new_element.chomp}", :green, true + else + say " #{diff.old_element.chomp}", nil, true end + end - # Check if Diff::LCS is loaded. If it is, use it to create pretty output - # for diff. - # - def diff_lcs_loaded? #:nodoc: - return true if defined?(Diff::LCS) - return @diff_lcs_loaded unless @diff_lcs_loaded.nil? + # Check if Diff::LCS is loaded. If it is, use it to create pretty output + # for diff. + # + def diff_lcs_loaded? #:nodoc: + return true if defined?(Diff::LCS) + return @diff_lcs_loaded unless @diff_lcs_loaded.nil? - @diff_lcs_loaded = begin - require 'diff/lcs' - true - rescue LoadError - false - end + @diff_lcs_loaded = begin + require 'diff/lcs' + true + rescue LoadError + false end - + end end end end diff --git a/lib/bundler/vendor/thor/shell/html.rb b/lib/bundler/vendor/thor/shell/html.rb index 2a1bb384..296293b2 100644 --- a/lib/bundler/vendor/thor/shell/html.rb +++ b/lib/bundler/vendor/thor/shell/html.rb @@ -7,7 +7,7 @@ class Thor # class HTML < Basic # The start of an HTML bold sequence. - BOLD = "font-weight: bold" + BOLD = 'font-weight: bold' # Set the terminal's foreground HTML color to black. BLACK = 'color: black' @@ -67,61 +67,60 @@ class Thor # ask("What is your name?") # # TODO: Implement #ask for Thor::Shell::HTML - def ask(statement, color=nil) - raise NotImplementedError, "Implement #ask for Thor::Shell::HTML" + def ask(statement, color = nil) + fail NotImplementedError, 'Implement #ask for Thor::Shell::HTML' end - protected + protected - def can_display_colors? - true - end + def can_display_colors? + true + end - # Overwrite show_diff to show diff with colors if Diff::LCS is - # available. - # - def show_diff(destination, content) #:nodoc: - if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? - actual = File.binread(destination).to_s.split("\n") - content = content.to_s.split("\n") + # Overwrite show_diff to show diff with colors if Diff::LCS is + # available. + # + def show_diff(destination, content) #:nodoc: + if diff_lcs_loaded? && ENV['THOR_DIFF'].nil? && ENV['RAILS_DIFF'].nil? + actual = File.binread(destination).to_s.split("\n") + content = content.to_s.split("\n") - Diff::LCS.sdiff(actual, content).each do |diff| - output_diff_line(diff) - end - else - super + Diff::LCS.sdiff(actual, content).each do |diff| + output_diff_line(diff) end + else + super end + end - def output_diff_line(diff) #:nodoc: - case diff.action - when '-' - say "- #{diff.old_element.chomp}", :red, true - when '+' - say "+ #{diff.new_element.chomp}", :green, true - when '!' - say "- #{diff.old_element.chomp}", :red, true - say "+ #{diff.new_element.chomp}", :green, true - else - say " #{diff.old_element.chomp}", nil, true - end + def output_diff_line(diff) #:nodoc: + case diff.action + when '-' + say "- #{diff.old_element.chomp}", :red, true + when '+' + say "+ #{diff.new_element.chomp}", :green, true + when '!' + say "- #{diff.old_element.chomp}", :red, true + say "+ #{diff.new_element.chomp}", :green, true + else + say " #{diff.old_element.chomp}", nil, true end + end - # Check if Diff::LCS is loaded. If it is, use it to create pretty output - # for diff. - # - def diff_lcs_loaded? #:nodoc: - return true if defined?(Diff::LCS) - return @diff_lcs_loaded unless @diff_lcs_loaded.nil? + # Check if Diff::LCS is loaded. If it is, use it to create pretty output + # for diff. + # + def diff_lcs_loaded? #:nodoc: + return true if defined?(Diff::LCS) + return @diff_lcs_loaded unless @diff_lcs_loaded.nil? - @diff_lcs_loaded = begin - require 'diff/lcs' - true - rescue LoadError - false - end + @diff_lcs_loaded = begin + require 'diff/lcs' + true + rescue LoadError + false end - + end end end end diff --git a/lib/bundler/vendor/thor/util.rb b/lib/bundler/vendor/thor/util.rb index 2510630f..a551b7d9 100644 --- a/lib/bundler/vendor/thor/util.rb +++ b/lib/bundler/vendor/thor/util.rb @@ -15,9 +15,7 @@ class Thor # Thor::Util.load_thorfile("~/.thor/foo") # module Util - class << self - # Receives a namespace and search for it in the Thor::Base subclasses. # # ==== Parameters @@ -25,7 +23,7 @@ class Thor # def find_by_namespace(namespace) namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ - Thor::Base.subclasses.find { |klass| klass.namespace == namespace } + Thor::Base.subclasses.detect { |klass| klass.namespace == namespace } end # Receives a constant and converts it to a Thor namespace. Since Thor @@ -43,8 +41,8 @@ class Thor # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" # def namespace_from_thor_class(constant) - constant = constant.to_s.gsub(/^Thor::Sandbox::/, "") - constant = snake_case(constant).squeeze(":") + constant = constant.to_s.gsub(/^Thor::Sandbox::/, '') + constant = snake_case(constant).squeeze(':') constant end @@ -57,7 +55,7 @@ class Thor # ==== Returns # Array[Object] # - def namespaces_in_content(contents, file=__FILE__) + def namespaces_in_content(contents, file = __FILE__) old_constants = Thor::Base.subclasses.dup Thor::Base.subclasses.clear @@ -66,7 +64,7 @@ class Thor new_constants = Thor::Base.subclasses.dup Thor::Base.subclasses.replace(old_constants) - new_constants.map!{ |c| c.namespace } + new_constants.map! { |c| c.namespace } new_constants.compact! new_constants end @@ -92,7 +90,7 @@ class Thor def snake_case(str) return str.downcase if str =~ /^[A-Z_]+$/ str.gsub(/\B[A-Z]/, '_\&').squeeze('_') =~ /_*(.*)/ - return $+.downcase + $+.downcase end # Receives a string and convert it to camel case. camel_case returns CamelCase. @@ -131,10 +129,10 @@ class Thor # namespace<String> # def find_class_and_command_by_namespace(namespace, fallback = true) - if namespace.include?(?:) # look for a namespaced command - pieces = namespace.split(":") + if namespace.include?(':') # look for a namespaced command + pieces = namespace.split(':') command = pieces.pop - klass = Thor::Util.find_by_namespace(pieces.join(":")) + klass = Thor::Util.find_by_namespace(pieces.join(':')) end unless klass # look for a Thor::Group with the right name klass, command = Thor::Util.find_by_namespace(namespace), nil @@ -143,19 +141,19 @@ class Thor command = namespace klass = Thor::Util.find_by_namespace('') end - return klass, command + [klass, command] end - alias find_class_and_task_by_namespace find_class_and_command_by_namespace + alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace # Receives a path and load the thor file in the path. The file is evaluated # inside the sandbox to avoid namespacing conflicts. # - def load_thorfile(path, content=nil, debug=false) + def load_thorfile(path, content = nil, debug = false) content ||= File.binread(path) begin Thor::Sandbox.class_eval(content, path) - rescue Exception => e + rescue StandardError => e $stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}") if debug $stderr.puts(*e.backtrace) @@ -165,32 +163,32 @@ class Thor end end - def user_home - @@user_home ||= if ENV["HOME"] - ENV["HOME"] - elsif ENV["USERPROFILE"] - ENV["USERPROFILE"] - elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] - File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) - elsif ENV["APPDATA"] - ENV["APPDATA"] - else - begin - File.expand_path("~") - rescue - if File::ALT_SEPARATOR - "C:/" - else - "/" - end - end - end + def user_home # rubocop:disable MethodLength + @@user_home ||= if ENV['HOME'] + ENV['HOME'] + elsif ENV['USERPROFILE'] + ENV['USERPROFILE'] + elsif ENV['HOMEDRIVE'] && ENV['HOMEPATH'] + File.join(ENV['HOMEDRIVE'], ENV['HOMEPATH']) + elsif ENV['APPDATA'] + ENV['APPDATA'] + else + begin + File.expand_path('~') + rescue + if File::ALT_SEPARATOR + 'C:/' + else + '/' + end + end + end end # Returns the root where thor files are located, depending on the OS. # def thor_root - File.join(user_home, ".thor").gsub(/\\/, '/') + File.join(user_home, '.thor').gsub(/\\/, '/') end # Returns the files in the thor root. On Windows thor_root will be something @@ -204,7 +202,7 @@ class Thor files = Dir["#{escape_globs(thor_root)}/*"] files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file + File.directory?(file) ? File.join(file, 'main.thor') : file end end @@ -218,7 +216,7 @@ class Thor # Return the path to the ruby interpreter taking into account multiple # installations and windows extensions. # - def ruby_command + def ruby_command # rubocop:disable MethodLength @ruby_command ||= begin ruby_name = RbConfig::CONFIG['ruby_install_name'] ruby = File.join(RbConfig::CONFIG['bindir'], ruby_name) @@ -237,7 +235,7 @@ class Thor # symlink points to 'ruby_install_name' ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby end - rescue NotImplementedError + rescue NotImplementedError # rubocop:disable HandleExceptions # just ignore on windows end end @@ -264,7 +262,6 @@ class Thor def escape_globs(path) path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&') end - end end end diff --git a/lib/bundler/vendor/thor/version.rb b/lib/bundler/vendor/thor/version.rb index 646cd37d..41784aae 100644 --- a/lib/bundler/vendor/thor/version.rb +++ b/lib/bundler/vendor/thor/version.rb @@ -1,3 +1,3 @@ class Thor - VERSION = "0.18.1" + VERSION = '0.18.1' end |