Class: Thor
- Inherits:
-
Object
- Object
- Thor
- Includes:
- Base
- Defined in:
- lib/thor.rb,
lib/thor/base.rb,
lib/thor/util.rb,
lib/thor/error.rb,
lib/thor/shell.rb,
lib/thor/actions.rb,
lib/thor/command.rb,
lib/thor/version.rb,
lib/thor/invocation.rb,
lib/thor/shell/html.rb,
lib/thor/line_editor.rb,
lib/thor/rake_compat.rb,
lib/thor/requirement.rb,
lib/thor/shell/basic.rb,
lib/thor/shell/color.rb,
lib/thor/parser/option.rb,
lib/thor/nested_context.rb,
lib/thor/parser/options.rb,
lib/thor/shell/terminal.rb,
lib/thor/parser/argument.rb,
lib/thor/parser/arguments.rb,
lib/thor/actions/directory.rb,
lib/thor/line_editor/basic.rb,
lib/thor/actions/create_file.rb,
lib/thor/actions/create_link.rb,
lib/thor/shell/table_printer.rb,
lib/thor/line_editor/readline.rb,
lib/thor/shell/column_printer.rb,
lib/thor/shell/wrapped_printer.rb,
lib/thor/actions/empty_directory.rb,
lib/thor/actions/inject_into_file.rb,
lib/thor/actions/file_manipulation.rb,
lib/thor/core_ext/hash_with_indifferent_access.rb
Direct Known Subclasses
Defined Under Namespace
Modules: Actions, Base, CoreExt, Invocation, LineEditor, RakeCompat, Sandbox, Shell, Util Classes: AmbiguousCommandError, Argument, Arguments, AtLeastOneRequiredArgumentError, Command, DynamicCommand, Error, ExclusiveArgumentError, Group, HiddenCommand, InvocationError, MalformattedArgumentError, NestedContext, Option, Options, RequiredArgumentMissingError, Requirement, RequirementError, Runner, UndefinedCommandError, UnknownArgumentError
Constant Summary collapse
- HELP_MAPPINGS =
Shortcuts for help and tree commands.
%w(-h -? --help -D)
- TREE_MAPPINGS =
%w(-t --tree)
- THOR_RESERVED_WORDS =
Thor methods that should not be overwritten by the user.
%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"- Correctable =
rubocop:disable Naming/ConstantName
if defined?(DidYouMean::SpellChecker) && defined?(DidYouMean::Correctable) # rubocop:disable Naming/ConstantName Module.new do def to_s super + DidYouMean.formatter.(corrections) end def corrections @corrections ||= self.class.const_get(:SpellChecker).new(self).corrections end end end
- UndefinedTaskError =
UndefinedCommandError- AmbiguousTaskError =
AmbiguousCommandError- Task =
Command- HiddenTask =
HiddenCommand- DynamicTask =
DynamicCommand- VERSION =
"1.5.0"
Class Method Summary collapse
-
.check_unknown_options!(options = {}) ⇒ Object
Extend check unknown options to accept a hash of conditions.
-
.check_unknown_options?(config) ⇒ Boolean
Overwrite check_unknown_options? to take subcommands and options into account.
-
.command_exists?(command_name) ⇒ Boolean
Checks if a specified command exists.
-
.command_help(shell, command_name) ⇒ Object
(also: task_help)
Prints help information for the given command.
-
.default_command(meth = nil) ⇒ Object
(also: default_task)
Sets the default command when thor is executed without an explicit command to be called.
-
.deprecation_warning(message) ⇒ Object
:nodoc:.
-
.desc(usage, description, options = {}) ⇒ Object
Defines the usage and the description of the next command.
-
.disable_required_check!(*command_names) ⇒ Object
Disable the check for required options for the given commands.
-
.disable_required_check?(command) ⇒ Boolean
:nodoc:.
-
.help(shell, subcommand = false) ⇒ Object
Prints help information for this class.
-
.long_desc(long_description, options = {}) ⇒ Object
Defines the long description of the next command.
-
.map(mappings = nil, **kw) ⇒ Object
Maps an input to a command.
-
.method_at_least_one(*args, &block) ⇒ Object
(also: at_least_one)
Adds and declares option group for required at least one of options in the block of arguments.
-
.method_exclusive(*args, &block) ⇒ Object
(also: exclusive)
Adds and declares option group for exclusive options in the block and arguments.
-
.method_option(name, options = {}) ⇒ Object
(also: option)
Adds an option to the set of method options.
-
.method_options(options = nil) ⇒ Object
(also: options)
Declares the options for the next command to be declared.
-
.package_name(name, _ = {}) ⇒ Object
Allows for custom "Command" package naming.
-
.printable_commands(all = true, subcommand = false) ⇒ Object
(also: printable_tasks)
Returns commands ready to be printed.
-
.register(klass, subcommand_name, usage, description, options = {}) ⇒ Object
Registers another Thor subclass as a command.
-
.requires(*names, args: nil, options: nil) ⇒ Object
Declares that the next command requires other commands to have run first.
-
.stop_on_unknown_option!(*command_names) ⇒ Object
Stop parsing of options as soon as an unknown option or a regular argument is encountered.
-
.stop_on_unknown_option?(command) ⇒ Boolean
:nodoc:.
- .subcommand(subcommand, subcommand_class) ⇒ Object (also: subtask)
- .subcommand_classes ⇒ Object
- .subcommands ⇒ Object (also: subtasks)
-
.validate_requirements! ⇒ Object
Resolves every requirement reachable from the commands of this class, through other classes too, and raises Thor::RequirementError listing the names that do not resolve to a command and the chains that form a cycle.
Instance Method Summary collapse
Class Method Details
.check_unknown_options!(options = {}) ⇒ Object
Extend check unknown options to accept a hash of conditions.
Parameters
options
421 422 423 424 425 426 427 428 429 430 431 |
# File 'lib/thor.rb', line 421 def ( = {}) @check_unknown_options ||= {} .each do |key, value| if value @check_unknown_options[key] = Array(value) else @check_unknown_options.delete(key) end end @check_unknown_options end |
.check_unknown_options?(config) ⇒ Boolean
Overwrite check_unknown_options? to take subcommands and options into account.
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
# File 'lib/thor.rb', line 434 def (config) #:nodoc: = return false unless command = config[:current_command] return true unless command name = command.name if subcommands.include?(name) false elsif [:except] ![:except].include?(name.to_sym) elsif [:only] [:only].include?(name.to_sym) else true end end |
.command_exists?(command_name) ⇒ Boolean
Checks if a specified command exists.
Parameters
- command_name
The name of the command to check for existence.
Returns
- Boolean
trueif the command exists,falseotherwise.
520 521 522 |
# File 'lib/thor.rb', line 520 def command_exists?(command_name) #:nodoc: commands.keys.include?(normalize_command_name(command_name)) end |
.command_help(shell, command_name) ⇒ Object Also known as: task_help
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/thor.rb', line 328 def command_help(shell, command_name) meth = normalize_command_name(command_name) command = all_commands[meth] handle_no_command_error(meth) unless command shell.say "Usage:" shell.say " #{(command).split("\n").join("\n ")}" shell.say (shell, nil => command..values) (shell, command) (shell, command) print_requirements(shell, command) if command.long_description shell.say "Description:" if command.wrap_long_description shell.print_wrapped(command.long_description, indent: 2) else shell.say command.long_description end else shell.say command.description end end |
.default_command(meth = nil) ⇒ Object Also known as: default_task
Sets the default command when thor is executed without an explicit command to be called.
Parameters
- meth
name of the default command
21 22 23 24 25 26 27 |
# File 'lib/thor.rb', line 21 def default_command(meth = nil) if meth @default_command = meth == :none ? "help" : meth.to_s else @default_command ||= from_superclass(:default_command, "help") end end |
.deprecation_warning(message) ⇒ Object
:nodoc:
28 29 30 31 32 33 |
# File 'lib/thor/base.rb', line 28 def deprecation_warning() #:nodoc: unless ENV["THOR_SILENCE_DEPRECATION"] warn "Deprecation warning: #{}\n" + "You can silence deprecations warning by setting the environment variable THOR_SILENCE_DEPRECATION." end end |
.desc(usage, description, options = {}) ⇒ Object
Defines the usage and the description of the next command.
Parameters
usage
54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/thor.rb', line 54 def desc(usage, description, = {}) if [:for] command = find_and_refresh_command([:for]) command.usage = usage if usage command.description = description if description else @usage = usage @desc = description @hide = [:hide] || false end end |
.disable_required_check!(*command_names) ⇒ Object
Disable the check for required options for the given commands. This is useful if you have a command that does not need the required options to work, like help.
Parameters
- Symbol ...
A list of commands that should be affected.
505 506 507 |
# File 'lib/thor.rb', line 505 def disable_required_check!(*command_names) @disable_required_check = disable_required_check | command_names end |
.disable_required_check?(command) ⇒ Boolean
:nodoc:
509 510 511 |
# File 'lib/thor.rb', line 509 def disable_required_check?(command) #:nodoc: command && disable_required_check.include?(command.name.to_sym) end |
.help(shell, subcommand = false) ⇒ Object
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
# File 'lib/thor.rb', line 359 def help(shell, subcommand = false) list = printable_commands(true, subcommand) Thor::Util.thor_classes_in(self).each do |klass| list += klass.printable_commands(false) end sort_commands!(list) if defined?(@package_name) && @package_name shell.say "#{@package_name} commands:" else shell.say "Commands:" end shell.print_table(list, indent: 2, truncate: true) shell.say (shell) (shell) (shell) end |
.long_desc(long_description, options = {}) ⇒ Object
Defines the long description of the next command.
Long description is by default indented, line-wrapped and repeated whitespace merged.
In order to print long description verbatim, with indentation and spacing exactly
as found in the code, use the wrap option
long_desc 'your very long description', wrap: false
Parameters
long description
78 79 80 81 82 83 84 85 86 |
# File 'lib/thor.rb', line 78 def long_desc(long_description, = {}) if [:for] command = find_and_refresh_command([:for]) command.long_description = long_description if long_description else @long_desc = long_description @long_desc_wrap = [:wrap] != false end end |
.map(mappings = nil, **kw) ⇒ Object
Maps an input to a command. If you define:
map "-T" => "list"
Running:
thor -T
Will invoke the list command.
Parameters
- Hash[String|Array => Symbol]
Maps the string or the strings in the array to the given command.
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
# File 'lib/thor.rb', line 101 def map(mappings = nil, **kw) @map ||= from_superclass(:map, {}) if mappings && !kw.empty? mappings = kw.merge!(mappings) else mappings ||= kw end if mappings mappings.each do |key, value| if key.respond_to?(:each) key.each { |subkey| @map[subkey] = value } else @map[key] = value end end end @map end |
.method_at_least_one(*args, &block) ⇒ Object Also known as: at_least_one
Adds and declares option group for required at least one of options in the block of arguments. You can declare options as the outside of the block.
If :for is given as option, it allows you to change the options from a previous defined command.
Parameters
- options
:for is applied for previous defined command.
Examples
at_least_one do
option :one
option :two
end
Or
option :one
option :two
at_least_one :one, :two
If you do not give "--one" and "--two" AtLeastOneRequiredArgumentError will be raised.
You can use at_least_one and exclusive at the same time.
exclusive do
at_least_one do
option :one
option :two
end
end
Then it is required either only one of "--one" or "--two".
246 247 248 249 |
# File 'lib/thor.rb', line 246 def method_at_least_one(*args, &block) (:method_options, :method_at_least_one_option_names, *args, &block) end |
.method_exclusive(*args, &block) ⇒ Object Also known as: exclusive
Adds and declares option group for exclusive options in the block and arguments. You can declare options as the outside of the block.
If :for is given as option, it allows you to change the options from a previous defined command.
Parameters
- options
:for is applied for previous defined command.
Examples
exclusive do
option :one
option :two
end
Or
option :one
option :two
exclusive :one, :two
If you give "--one" and "--two" at the same time ExclusiveArgumentsError will be raised.
203 204 205 206 |
# File 'lib/thor.rb', line 203 def method_exclusive(*args, &block) (:method_options, :method_exclusive_option_names, *args, &block) end |
.method_option(name, options = {}) ⇒ Object Also known as: option
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.
def previous_command
# magic
end
method_option :foo, :for => :previous_command
def next_command
# magic
end
Parameters
- name
The name of the argument.
- options
Described below.
Options
:desc - Description for the argument. :required - If the argument is required or not. :default - Default value for this argument. It cannot be required and have default values. :aliases - Aliases for this option. :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. :banner - String to show on usage notes. :hide - If you want to hide this option from the help.
163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/thor.rb', line 163 def method_option(name, = {}) unless [ Symbol, String ].any? { |klass| name.is_a?(klass) } raise ArgumentError, "Expected a Symbol or String, got #{name.inspect}" end scope = if [:for] find_and_refresh_command([:for]). else end build_option(name, , scope) end |
.method_options(options = nil) ⇒ Object Also known as: options
Declares the options for the next command to be declared.
Parameters
- Hash[Symbol => Object]
The hash key is the name of the option and the value
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.
129 130 131 132 133 |
# File 'lib/thor.rb', line 129 def ( = nil) @method_options ||= {} (, @method_options) if @method_options end |
.package_name(name, _ = {}) ⇒ Object
Allows for custom "Command" package naming.
Parameters
name
12 13 14 |
# File 'lib/thor.rb', line 12 def package_name(name, _ = {}) @package_name = name.nil? || name == "" ? nil : name end |
.printable_commands(all = true, subcommand = false) ⇒ Object Also known as: printable_tasks
Returns commands ready to be printed.
380 381 382 383 384 385 386 387 388 |
# File 'lib/thor.rb', line 380 def printable_commands(all = true, subcommand = false) (all ? all_commands : commands).map do |_, command| next if command.hidden? item = [] item << (command, false, subcommand) item << (command.description ? "# #{command.description.gsub(/\s+/m, ' ')}" : "") item end.compact end |
.register(klass, subcommand_name, usage, description, options = {}) ⇒ Object
Registers another Thor subclass as a command.
Parameters
- klass
Thor subclass to register
- command
Subcommand name to use
- usage
Short usage for the subcommand
- description
Description for the subcommand
37 38 39 40 41 42 43 44 45 |
# File 'lib/thor.rb', line 37 def register(klass, subcommand_name, usage, description, = {}) if klass <= Thor::Group desc usage, description, define_method(subcommand_name) { |*args| invoke(klass, args) } else desc usage, description, subcommand subcommand_name, klass end end |
.requires(*names, args: nil, options: nil) ⇒ Object
Declares that the next command requires other commands to have run
first. Required commands run through the standard invocation machinery
before the command body, depth-first and in declaration order, so a
command runs at most once per invocation (the same rule as invoke):
a command required twice, even with different arguments, runs the first
time only. A required command satisfies its own requirements first.
Takes one or more command names: a command of the same class, or a
"namespace:command" string naming a command of another Thor class.
Names must be exact (dashes normalize to underscores); the prefix and
map matching of the command line does not apply. The other class must
be loaded when the command runs: a Thorfile that requires its files is
enough, but Thor::Runner loads installed thorfiles (+thor install+) by
namespace, so a requirement into another installed thorfile does not
resolve. args and options map the current invocation into
a single required command; each can be a static Array/Hash or a callable
receiving the current invocation's (args, options). Options declared by
both commands (class options included) always auto-pass by name with
their current value, which is the current command's default when the
command line did not set them; an explicit options mapping merges
over them. Requirements run only when the command line is well formed:
a usage error is raised first and no requirement runs.
desc "publish", "Publish the built package"
method_option :target, type: :string, required: true
method_option :env, type: :string, default: "development"
requires :check_credentials, :package
requires :build, args: ->(args, ) { [[:target]] }
# no options mapping needed: :env auto-passes because both commands declare it
def publish
# runs after :check_credentials, :package, and :build have run
end
If both commands declare :env, an explicit mapping such as
options: { "env" => "production" } passes "production" to
build, even when the current value is different. String and symbol
option names match. Explicit options not declared by build are also
passed through.
A required command that does not exist, a cycle between requirements, or
a Thor::Error raised by a required command raises Thor::RequirementError
with the original error as cause. Other exceptions propagate unchanged.
Use validate_requirements! in a test to check every declared name
resolves. Requirements are listed in the command's help output.
297 298 299 300 301 302 303 304 305 306 |
# File 'lib/thor.rb', line 297 def requires(*names, args: nil, options: nil) raise ArgumentError, "Expected at least one command name for requires" if names.empty? if (args || ) && names.length > 1 raise ArgumentError, "Expected one command name when args: or options: is given; declare one requires per mapped command" end names.each do |name| (@requirements ||= []) << Thor::Requirement.new(name, args: args, options: ) end end |
.stop_on_unknown_option!(*command_names) ⇒ Object
Stop parsing of options as soon as an unknown option or a regular argument is encountered. All remaining arguments are passed to the command. This is useful if you have a command that can receive arbitrary additional options, and where those additional options should not be handled by Thor.
Example
To better understand how this is useful, let's consider a command that calls an external command. A user may want to pass arbitrary options and arguments to that command. The command itself also accepts some options, which should be handled by Thor.
class_option "verbose", :type => :boolean
stop_on_unknown_option! :exec
:except => :exec
desc "exec", "Run a shell command"
def exec(*args)
puts "diagnostic output" if [:verbose]
Kernel.exec(*args)
end
Here exec can be called with --verbose to get diagnostic output,
e.g.:
$ thor exec --verbose echo foo
diagnostic output
foo
But if --verbose is given after echo, it is passed to echo instead:
$ thor exec echo --verbose foo
--verbose foo
Parameters
- Symbol ...
A list of commands that should be affected.
491 492 493 |
# File 'lib/thor.rb', line 491 def stop_on_unknown_option!(*command_names) @stop_on_unknown_option = stop_on_unknown_option | command_names end |
.stop_on_unknown_option?(command) ⇒ Boolean
:nodoc:
495 496 497 |
# File 'lib/thor.rb', line 495 def stop_on_unknown_option?(command) #:nodoc: command && stop_on_unknown_option.include?(command.name.to_sym) end |
.subcommand(subcommand, subcommand_class) ⇒ Object Also known as: subtask
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 |
# File 'lib/thor.rb', line 400 def subcommand(subcommand, subcommand_class) subcommands << subcommand.to_s subcommand_class.subcommand_help subcommand subcommand_classes[subcommand.to_s] = subcommand_class define_method(subcommand) do |*args| args, opts = Thor::Arguments.split(args) invoke_args = [args, opts, {invoked_via_subcommand: true, class_options: }] invoke_args.unshift "help" if opts.delete("--help") || opts.delete("-h") invoke subcommand_class, *invoke_args end subcommand_class.commands.each do |_meth, command| command.ancestor_name = subcommand end end |
.subcommand_classes ⇒ Object
396 397 398 |
# File 'lib/thor.rb', line 396 def subcommand_classes @subcommand_classes ||= {} end |
.subcommands ⇒ Object Also known as: subtasks
391 392 393 |
# File 'lib/thor.rb', line 391 def subcommands @subcommands ||= from_superclass(:subcommands, []) end |
.validate_requirements! ⇒ Object
Resolves every requirement reachable from the commands of this class, through other classes too, and raises Thor::RequirementError listing the names that do not resolve to a command and the chains that form a cycle. Call it from a test so a requirement on a renamed or removed command fails before anyone runs it. Returns true when all is well.
Package.validate_requirements!
316 317 318 319 320 |
# File 'lib/thor.rb', line 316 def validate_requirements! problems = Thor::Requirement.problems(self) raise RequirementError, problems.join("\n") unless problems.empty? true end |
Instance Method Details
#help(command = nil, subcommand = false) ⇒ Object
751 752 753 754 755 756 757 758 759 760 761 |
# File 'lib/thor.rb', line 751 def help(command = nil, subcommand = false) if command if self.class.subcommands.include? command self.class.subcommand_classes[command].help(shell, true) else self.class.command_help(shell, command) end else self.class.help(shell, subcommand) end end |
#tree ⇒ Object
766 767 768 |
# File 'lib/thor.rb', line 766 def tree build_command_tree(self.class, "") end |