提交 03c982fa 编写于 作者: K Kasper Timm Hansen

Remove the old command files.

Wash out your old! These adhoc scripts are replaced by the new
commands.
上级 4e106ee0
require "rails/generators"
require "rails/generators/rails/app/app_generator"
module Rails
module Generators
class AppGenerator # :nodoc:
# We want to exit on failure to be kind to other libraries
# This is only when accessing via CLI
def self.exit_on_failure?
true
end
end
end
end
args = Rails::Generators::ARGVScrubber.new(ARGV).prepare!
Rails::Generators::AppGenerator.start args
require "rails/commands/rake_proxy"
require "rails/commands/common_commands_tasks"
require "active_support/core_ext/string/strip"
module Rails
# This is a class which takes in a rails command and initiates the appropriate
# initiation sequence.
#
# Warning: This class mutates ARGV because some commands require manipulating
# it before they are run.
class CommandsTasks # :nodoc:
include Rails::RakeProxy
include Rails::CommonCommandsTasks
attr_reader :argv
ADDITIONAL_COMMANDS = [
[ "destroy", 'Undo code generated with "generate" (short-cut alias: "d")' ],
[ "plugin new", "Generates skeleton for developing a Rails plugin" ],
[ "runner",
'Run a piece of code in the application environment (short-cut alias: "r")' ]
]
def initialize(argv)
@argv = argv
end
def plugin
require_command!("plugin")
end
def console
require_command!("console")
options = Rails::Console.parse_arguments(argv)
# RAILS_ENV needs to be set before config/application is required
ENV["RAILS_ENV"] = options[:environment] if options[:environment]
# shift ARGV so IRB doesn't freak
shift_argv!
require_application_and_environment!
Rails::Console.start(Rails.application, options)
end
def server
set_application_directory!
require_command!("server")
Rails::Server.new.tap do |server|
# We need to require application after the server sets environment,
# otherwise the --environment option given to the server won't propagate.
require APP_PATH
Dir.chdir(Rails.application.root)
server.start
end
end
def dbconsole
require_command!("dbconsole")
Rails::DBConsole.start
end
def runner
require_command!("runner")
end
def new
if %w(-h --help).include?(argv.first)
require_command!("application")
else
exit_with_initialization_warning!
end
end
private
def exit_with_initialization_warning!
puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
puts "Type 'rails' for help."
exit(1)
end
def shift_argv!
argv.shift if argv.first && argv.first[0] != "-"
end
# Change to the application's path if there is no config.ru file in current directory.
# This allows us to run `rails server` from other directories, but still get
# the main config.ru and properly set the tmp directory.
def set_application_directory!
Dir.chdir(File.expand_path("../../", APP_PATH)) unless File.exist?(File.expand_path("config.ru"))
end
def commands
ADDITIONAL_COMMANDS + formatted_rake_tasks
end
def command_whitelist
%w(plugin generate destroy console server dbconsole runner new version help test)
end
def help_message
<<-EOT.strip_heredoc
Usage: rails COMMAND [ARGS]
The most common rails commands are:
generate Generate new code (short-cut alias: "g")
console Start the Rails console (short-cut alias: "c")
server Start the Rails server (short-cut alias: "s")
test Run tests (short-cut alias: "t")
dbconsole Start a console for the database specified in config/database.yml
(short-cut alias: "db")
new Create a new Rails application. "rails new my_app" creates a
new application called MyApp in "./my_app"
All commands can be run with -h (or --help) for more information.
In addition to those commands, there are:
EOT
end
def require_application_and_environment!
require APP_PATH
Rails.application.require_environment!
end
def load_tasks
Rails.application.load_tasks
end
def load_generators
Rails.application.load_generators
end
end
end
module Rails
module CommonCommandsTasks # :nodoc:
def run_command!(command)
command = parse_command(command)
if command_whitelist.include?(command)
send(command)
else
run_rake_task(command)
end
end
def generate
generate_or_destroy(:generate)
end
def destroy
generate_or_destroy(:destroy)
end
def test
require_command!("test")
end
def version
argv.unshift "--version"
require_command!("application")
end
def help
write_help_message
write_commands(commands)
end
private
def generate_or_destroy(command)
require "rails/generators"
require_application_and_environment!
load_generators
require_command!(command)
end
def require_command!(command)
require "rails/commands/#{command}"
end
def write_help_message
puts help_message
end
def write_commands(commands)
width = commands.map { |name, _| name.size }.max || 10
commands.each { |command| printf(" %-#{width}s %s\n", *command) }
end
def parse_command(command)
case command
when "--version", "-v"
"version"
when "--help", "-h"
"help"
else
command
end
end
end
end
require "optparse"
require "irb"
require "irb/completion"
require "rails/commands/console_helper"
module Rails
class Console
include ConsoleHelper
module BacktraceCleaner
def filter_backtrace(bt)
if result = super
Rails.backtrace_cleaner.filter([result]).first
end
end
end
class << self
def parse_arguments(arguments)
options = {}
OptionParser.new do |opt|
opt.banner = "Usage: rails console [environment] [options]"
opt.on("-s", "--sandbox", "Rollback database modifications on exit.") { |v| options[:sandbox] = v }
opt.on("-e", "--environment=name", String,
"Specifies the environment to run this console under (test/development/production).",
"Default: development") { |v| options[:environment] = v.strip }
opt.parse!(arguments)
end
set_options_env(arguments, options)
end
end
attr_reader :options, :app, :console
def initialize(app, options={})
@app = app
@options = options
app.sandbox = sandbox?
app.load_console
@console = app.config.console || IRB
if @console == IRB
IRB::WorkSpace.prepend(BacktraceCleaner)
end
end
def sandbox?
options[:sandbox]
end
def environment
options[:environment] ||= super
end
alias_method :environment?, :environment
def set_environment!
Rails.env = environment
end
def start
set_environment! if environment?
if sandbox?
puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})"
puts "Any modifications you make will be rolled back on exit"
else
puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
end
if defined?(console::ExtendCommandBundle)
console::ExtendCommandBundle.include(Rails::ConsoleMethods)
end
console.start
end
end
end
require "active_support/concern"
module Rails
module ConsoleHelper # :nodoc:
extend ActiveSupport::Concern
module ClassMethods
def start(*args)
new(*args).start
end
private
def set_options_env(arguments, options)
if arguments.first && arguments.first[0] != "-"
env = arguments.first
if available_environments.include? env
options[:environment] = env
else
options[:environment] = %w(production development test).detect { |e| e =~ /^#{env}/ } || env
end
end
options
end
def available_environments
Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") }
end
end
def environment
ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
end
end
end
require "erb"
require "yaml"
require "optparse"
require "rails/commands/console_helper"
module Rails
class DBConsole
include ConsoleHelper
attr_reader :arguments
class << self
def parse_arguments(arguments)
options = {}
OptionParser.new do |opt|
opt.banner = "Usage: rails dbconsole [environment] [options]"
opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
options["include_password"] = true
end
opt.on("--mode [MODE]", ["html", "list", "line", "column"],
"Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
options["mode"] = mode
end
opt.on("--header") do |h|
options["header"] = h
end
opt.on("-h", "--help", "Show this help message.") do
puts opt
exit
end
opt.on("-e", "--environment=name", String,
"Specifies the environment to run this console under (test/development/production).",
"Default: development"
) { |v| options[:environment] = v.strip }
opt.parse!(arguments)
abort opt.to_s unless (0..1).include?(arguments.size)
end
set_options_env(arguments, options)
end
end
def initialize(arguments = ARGV)
@arguments = arguments
end
def start
options = self.class.parse_arguments(arguments)
ENV["RAILS_ENV"] = options[:environment] || environment
case config["adapter"]
when /^(jdbc)?mysql/
args = {
"host" => "--host",
"port" => "--port",
"socket" => "--socket",
"username" => "--user",
"encoding" => "--default-character-set",
"sslca" => "--ssl-ca",
"sslcert" => "--ssl-cert",
"sslcapath" => "--ssl-capath",
"sslcipher" => "--ssl-cipher",
"sslkey" => "--ssl-key"
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
if config["password"] && options["include_password"]
args << "--password=#{config['password']}"
elsif config["password"] && !config["password"].to_s.empty?
args << "-p"
end
args << config["database"]
find_cmd_and_exec(["mysql", "mysql5"], *args)
when /^postgres|^postgis/
ENV["PGUSER"] = config["username"] if config["username"]
ENV["PGHOST"] = config["host"] if config["host"]
ENV["PGPORT"] = config["port"].to_s if config["port"]
ENV["PGPASSWORD"] = config["password"].to_s if config["password"] && options["include_password"]
find_cmd_and_exec("psql", config["database"])
when "sqlite3"
args = []
args << "-#{options['mode']}" if options["mode"]
args << "-header" if options["header"]
args << File.expand_path(config["database"], Rails.respond_to?(:root) ? Rails.root : nil)
find_cmd_and_exec("sqlite3", *args)
when "oracle", "oracle_enhanced"
logon = ""
if config["username"]
logon = config["username"]
logon << "/#{config['password']}" if config["password"] && options["include_password"]
logon << "@#{config['database']}" if config["database"]
end
find_cmd_and_exec("sqlplus", logon)
when "sqlserver"
args = []
args += ["-D", "#{config['database']}"] if config["database"]
args += ["-U", "#{config['username']}"] if config["username"]
args += ["-P", "#{config['password']}"] if config["password"]
if config["host"]
host_arg = "#{config['host']}"
host_arg << ":#{config['port']}" if config["port"]
args += ["-S", host_arg]
end
find_cmd_and_exec("sqsh", *args)
else
abort "Unknown command-line client for #{config['database']}."
end
end
def config
@config ||= begin
if configurations[environment].blank?
raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}"
else
configurations[environment]
end
end
end
def environment
Rails.respond_to?(:env) ? Rails.env : super
end
protected
def configurations
require APP_PATH
ActiveRecord::Base.configurations = Rails.application.config.database_configuration
ActiveRecord::Base.configurations
end
def find_cmd_and_exec(commands, *args)
commands = Array(commands)
dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR)
unless (ext = RbConfig::CONFIG["EXEEXT"]).empty?
commands = commands.map { |cmd| "#{cmd}#{ext}" }
end
full_path_command = nil
found = commands.detect do |cmd|
dirs_on_path.detect do |path|
full_path_command = File.join(path, cmd)
File.file?(full_path_command) && File.executable?(full_path_command)
end
end
if found
exec full_path_command, *args
else
abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
end
end
end
end
require "rails/generators"
#if no argument/-h/--help is passed to rails destroy command, then
#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help "destroy"
exit
end
name = ARGV.shift
Rails::Generators.invoke name, ARGV, behavior: :revoke, destination_root: Rails.root
require "rails/generators"
#if no argument/-h/--help is passed to rails generate command, then
#it generates the help associated.
if [nil, "-h", "--help"].include?(ARGV.first)
Rails::Generators.help "generate"
exit
end
name = ARGV.shift
root = defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root
Rails::Generators.invoke name, ARGV, behavior: :invoke, destination_root: root
if ARGV.first != "new"
ARGV[0] = "--help"
else
ARGV.shift
unless ARGV.delete("--no-rc")
customrc = ARGV.index { |x| x.include?("--rc=") }
railsrc = if customrc
File.expand_path(ARGV.delete_at(customrc).gsub(/--rc=/, ""))
else
File.join(File.expand_path("~"), ".railsrc")
end
if File.exist?(railsrc)
extra_args_string = File.read(railsrc)
extra_args = extra_args_string.split(/\n+/).flat_map(&:split)
puts "Using #{extra_args.join(" ")} from #{railsrc}"
ARGV.insert(1, *extra_args)
end
end
end
require "rails/generators"
require "rails/generators/rails/plugin/plugin_generator"
Rails::Generators::PluginGenerator.start
require "active_support"
module Rails
module RakeProxy #:nodoc:
private
def run_rake_task(command)
require_rake
ARGV.unshift(command) # Prepend the command, so Rake knows how to run it.
Rake.application.standard_exception_handling do
Rake.application.init("rails")
Rake.application.load_rakefile
Rake.application.top_level
end
end
def rake_tasks
require_rake
return @rake_tasks if defined?(@rake_tasks)
ActiveSupport::Deprecation.silence do
require_application_and_environment!
end
Rake::TaskManager.record_task_metadata = true
Rake.application.instance_variable_set(:@name, "rails")
load_tasks
@rake_tasks = Rake.application.tasks.select(&:comment)
end
def formatted_rake_tasks
rake_tasks.map { |t| [ t.name_with_args, t.comment ] }
end
def require_rake
require "rake" # Defer booting Rake until we know it's needed.
end
end
end
require "optparse"
options = { environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup }
code_or_file = nil
command = "bin/rails runner"
if ARGV.first.nil?
ARGV.push "-h"
end
ARGV.clone.options do |opts|
opts.banner = "Usage: rails runner [options] [<'Some.ruby(code)'> | <filename.rb>]"
opts.separator ""
opts.on("-e", "--environment=name", String,
"Specifies the environment for the runner to operate under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
opts.separator ""
opts.on("-h", "--help",
"Show this help message.") { $stdout.puts opts; exit }
opts.separator ""
opts.separator "Examples: "
opts.separator " rails runner 'puts Rails.env'"
opts.separator " This runs the code `puts Rails.env` after loading the app"
opts.separator ""
opts.separator " rails runner path/to/filename.rb"
opts.separator " This runs the Ruby file located at `path/to/filename.rb` after loading the app"
if RbConfig::CONFIG["host_os"] !~ /mswin|mingw/
opts.separator ""
opts.separator "You can also use runner as a shebang line for your executables:"
opts.separator " -------------------------------------------------------------"
opts.separator " #!/usr/bin/env #{File.expand_path(command)}"
opts.separator ""
opts.separator " Product.all.each { |p| p.price *= 2 ; p.save! }"
opts.separator " -------------------------------------------------------------"
end
opts.order! { |o| code_or_file ||= o } rescue retry
end
ARGV.delete(code_or_file)
ENV["RAILS_ENV"] = options[:environment]
require APP_PATH
Rails.application.require_environment!
Rails.application.load_runner
if code_or_file.nil?
$stderr.puts "Run '#{command} -h' for help."
exit 1
elsif File.exist?(code_or_file)
$0 = code_or_file
Kernel.load code_or_file
else
begin
eval(code_or_file, binding, __FILE__, __LINE__)
rescue SyntaxError, NameError => e
$stderr.puts "Please specify a valid ruby command or the path of a script to run."
$stderr.puts "Run '#{command} -h' for help."
$stderr.puts
$stderr.puts e
exit 1
end
end
require "fileutils"
require "optparse"
require "action_dispatch"
require "rails"
require "rails/dev_caching"
module Rails
class Server < ::Rack::Server
class Options
DEFAULT_PID_PATH = File.expand_path("tmp/pids/server.pid").freeze
def parse!(args)
args, options = args.dup, {}
option_parser(options).parse! args
options[:log_stdout] = options[:daemonize].blank? && (options[:environment] || Rails.env) == "development"
options[:server] = args.shift
options
end
private
def option_parser(options)
OptionParser.new do |opts|
opts.banner = "Usage: rails server [puma, thin etc] [options]"
opts.on("-p", "--port=port", Integer,
"Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
opts.on("-b", "--binding=IP", String,
"Binds Rails to the specified IP.", "Default: localhost") { |v| options[:Host] = v }
opts.on("-c", "--config=file", String,
"Uses a custom rackup configuration.") { |v| options[:config] = v }
opts.on("-d", "--daemon", "Runs server as a Daemon.") { options[:daemonize] = true }
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
opts.on("-P", "--pid=pid", String,
"Specifies the PID file.",
"Default: tmp/pids/server.pid") { |v| options[:pid] = v }
opts.on("-C", "--[no-]dev-caching",
"Specifies whether to perform caching in development.",
"true or false") { |v| options[:caching] = v }
opts.separator ""
opts.on("-h", "--help", "Shows this help message.") { puts opts; exit }
end
end
end
def initialize(*)
super
set_environment
end
# TODO: this is no longer required but we keep it for the moment to support older config.ru files.
def app
@app ||= begin
app = super
app.respond_to?(:to_app) ? app.to_app : app
end
end
def opt_parser
Options.new
end
def set_environment
ENV["RAILS_ENV"] ||= options[:environment]
end
def start
print_boot_information
trap(:INT) { exit }
create_tmp_directories
setup_dev_caching
log_to_stdout if options[:log_stdout]
super
ensure
# The '-h' option calls exit before @options is set.
# If we call 'options' with it unset, we get double help banners.
puts "Exiting" unless @options && options[:daemonize]
end
def middleware
Hash.new([])
end
def default_options
super.merge(
Port: ENV.fetch("PORT", 3000).to_i,
Host: ENV.fetch("HOST", "localhost").dup,
DoNotReverseLookup: true,
environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup,
daemonize: false,
caching: nil,
pid: Options::DEFAULT_PID_PATH,
restart_cmd: restart_command)
end
private
def setup_dev_caching
if options[:environment] == "development"
Rails::DevCaching.enable_by_argument(options[:caching])
end
end
def print_boot_information
url = "#{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}"
puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
puts "=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"
puts "=> Run `rails server -h` for more startup options"
end
def create_tmp_directories
%w(cache pids sockets).each do |dir_to_make|
FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make))
end
end
def log_to_stdout
wrapped_app # touch the app so the logger is set up
console = ActiveSupport::Logger.new(STDOUT)
console.formatter = Rails.logger.formatter
console.level = Rails.logger.level
unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT)
Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
end
end
def restart_command
"bin/rails server #{ARGV.join(' ')}"
end
end
end
require "rails/test_unit/minitest_plugin"
if defined?(ENGINE_ROOT)
$LOAD_PATH << File.expand_path("test", ENGINE_ROOT)
else
$LOAD_PATH << File.expand_path("../../test", APP_PATH)
end
Minitest.run_via[:rails] = true
require "active_support/testing/autorun"
require "rails/commands/rake_proxy"
require "rails/commands/common_commands_tasks"
require "active_support/core_ext/string/strip"
module Rails
class Engine
class CommandsTasks # :nodoc:
include Rails::RakeProxy
include Rails::CommonCommandsTasks
attr_reader :argv
def initialize(argv)
@argv = argv
end
private
def commands
formatted_rake_tasks
end
def command_whitelist
%w(generate destroy version help test)
end
def help_message
<<-EOT.strip_heredoc
Usage: bin/rails COMMAND [ARGS]
The common Rails commands available for engines are:
generate Generate new code (short-cut alias: "g")
destroy Undo code generated with "generate" (short-cut alias: "d")
test Run tests (short-cut alias: "t")
All commands can be run with -h for more information.
If you want to run any commands that need to be run in context
of the application, like `rails server` or `rails console`,
you should do it from application's directory (typically test/dummy).
In addition to those commands, there are:
EOT
end
def require_application_and_environment!
require ENGINE_PATH
end
def load_tasks
Rake.application.init("rails")
Rake.application.load_rakefile
end
def load_generators
engine = ::Rails::Engine.find(ENGINE_ROOT)
Rails::Generators.namespace = engine.railtie_namespace
engine.load_generators
end
end
end
end
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册