Module: Gorp::Commands
- Included in:
- TestCase
- Defined in:
- lib/gorp/rails.rb,
lib/gorp/commands.rb
Defined Under Namespace
Classes: XmlMarkup
Constant Summary collapse
- @@section_number =
0
Class Method Summary collapse
-
.stop_server(restart = false, signal = "INT") ⇒ Object
stop a server if it is currently running.
Instance Method Summary collapse
- #bundle(*args) ⇒ Object
- #cmd(args, opts = {}) ⇒ Object
- #console(script, env = nil) ⇒ Object
- #db(action) ⇒ Object
- #flag(message) ⇒ Object (also: #warn)
- #generate(*args) ⇒ Object
- #irb(file) ⇒ Object
- #issue(text, options = {}) ⇒ Object
- #log(type, message) ⇒ Object
- #note(message) ⇒ Object (also: #desc)
- #omit(*sections) ⇒ Object
- #overview(message) ⇒ Object
- #popen3(args, highlight = []) ⇒ Object
-
#rails(name, app = nil, opt = '') ⇒ Object
run rails as a command.
-
#rails_epoc ⇒ Object
Determine which version of the rails cli to use.
- #rake(args, opts = {}) ⇒ Object
-
#restart_server ⇒ Object
start/restart a rails server in a separate process.
- #ruby(args) ⇒ Object
- #runner(*args) ⇒ Object
- #secinclude(ranges, section) ⇒ Object
- #secsplit(section) ⇒ Object
- #section(number, title, &steps) ⇒ Object
- #section_head(number, title) ⇒ Object
- #test(*args) ⇒ Object
- #unbundle ⇒ Object
Class Method Details
.stop_server(restart = false, signal = "INT") ⇒ Object
stop a server if it is currently running
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/gorp/rails.rb', line 204 def self.stop_server(restart=false, signal="INT") if !restart and $cleanup $cleanup.call $cleanup = nil end if $server if $server.respond_to?(:process_id) # Windows signal = 1 if signal == "INT" Process.kill signal, $server.process_id Process.waitpid($server.process_id) rescue nil else # UNIX require 'timeout' Process.kill signal, $server begin Timeout::timeout(15) do Process.wait $server end rescue Timeout::Error Process.kill 9, $server Process.wait $server end end end ensure $server = nil end |
Instance Method Details
#bundle(*args) ⇒ Object
238 239 240 241 242 243 |
# File 'lib/gorp/commands.rb', line 238 def bundle *args unbundle do args << '--local' if args == ['install'] cmd "bundle #{args.join(' ')}" end end |
#cmd(args, opts = {}) ⇒ Object
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/gorp/commands.rb', line 281 def cmd args, opts={} if args =~ /^ruby script\/(\w+)/ and File.exist?('script/rails') unless File.exist? "script/#{$1}" args.sub! 'ruby script/performance/', 'ruby script/' args.sub! 'ruby script/', 'ruby script/rails ' end end if RUBY_PLATFORM =~ /w32/ args.gsub! '/', '\\' unless args =~ /http:/ args.sub! /^cmd \\c/, 'cmd /c' args.sub! /^cp -v/, 'xcopy /i /f /y' args.sub! /^ls -p/, 'dir/w' args.sub! /^ls/, 'dir' args.sub! /^cat/, 'type' end as = opts[:as] || args as = as.sub('ruby script/rails ', 'rails ') log :cmd, as $x.pre as, :class=>'stdin' if args == 'rake db:migrate' and File.exist? 'db/migrate' Dir.chdir 'db/migrate' do time = ((defined? DATETIME) ? Time.parse(DATETIME) : Time.now) date = time.strftime('%Y%m%d000000') mask = Regexp.new("^#{date[0..-4]}") Dir['[0-9]*'].sort_by {|fn| fn=~mask ? fn : 'x'+fn}.each do |file| file =~ /^([0-9]*)_(.*)$/ FileUtils.mv file, "#{date}_#{$2}" unless $1 == date.next! $x.pre "mv #{file} #{date}_#{$2}" unless $1 == date end end end args += ' -C' if args == 'ls -p' popen3 args, opts[:highlight] || [] end |
#console(script, env = nil) ⇒ Object
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
# File 'lib/gorp/commands.rb', line 183 def console script, env=nil if File.exist? 'bin/rails' console_cmd = 'bin/rails console' elsif File.exist? 'script/rails' console_cmd = 'script/rails console' else console_cmd = 'script/console' end console_cmd = "#{console_cmd} #{env}" if env open('tmp/irbrc','w') {|fh| fh.write('IRB.conf[:PROMPT_MODE]=:SIMPLE')} if RUBY_PLATFORM =~ /cygwin/i open('tmp/irbin','w') {|fh| fh.write(script.gsub('\n',"\n")+"\n")} cmd "IRBRC=tmp/irbrc ruby #{console_cmd} < tmp/irbin" FileUtils.rm_rf 'tmp/irbin' elsif RUBY_PLATFORM =~ /w32/ open('tmp/irbin','w') {|fh| fh.write(script.gsub('\n',"\r\n")+"\r\n")} save, ENV['IRBRC']=ENV['IRBRC'], 'tmp/irbin' cmd "cmd /c ruby #{console_cmd} < tmp/irbin" ENV['IRBRC']=save FileUtils.rm_rf 'tmp/irbin' else cmd "echo #{script.inspect} | IRBRC=tmp/irbrc ruby #{console_cmd}" end FileUtils.rm_rf 'tmp/irbrc' end |
#db(action) ⇒ Object
142 143 144 145 146 147 |
# File 'lib/gorp/commands.rb', line 142 def db statement, highlight=[] log :db, statement $x.pre "sqlite3> #{statement}", :class=>'stdin' cmd = "sqlite3 --line db/development.sqlite3 #{statement.inspect}" popen3 cmd, highlight end |
#flag(message) ⇒ Object Also known as: warn
101 102 103 |
# File 'lib/gorp/commands.rb', line 101 def flag $x.p , :class=>'traceback' end |
#generate(*args) ⇒ Object
211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/gorp/commands.rb', line 211 def generate *args if args.length == 1 cmd "rails generate #{args.first}" else if args.last.respond_to? :keys args.push args.pop.map {|key,value| "#{key}:#{value}"}.join(' ') end args.map! {|arg| arg.inspect.include?('\\') ? arg.inspect : arg} cmd "rails generate #{args.join(' ')}" end end |
#irb(file) ⇒ Object
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
# File 'lib/gorp/commands.rb', line 368 def irb file $x.pre "irb #{file}", :class=>'stdin' log :irb, file cmd = "irb -f -rubygems -r ./config/boot --prompt-mode simple " + "#{$CODE}/#{file}" Open3.popen3(cmd) do |pin, pout, perr| terr = Thread.new do until perr.eof? line = perr.readline.chomp line.gsub! /\x1b\[4(;\d+)*m(.*?)\x1b\[0m/, '\2' line.gsub! /\x1b\[0(;\d+)*m(.*?)\x1b\[0m/, '\2' line.gsub! /\x1b\[0(;\d+)*m/, '' $x.pre! line, :class=>'stderr' end end pin.close prompt = nil until pout.eof? line = pout.readline if line =~ /^([?>]>)\s*#\s*(START|END):/ prompt = $1 elsif line =~ /^([?>]>)\s+$/ $x.pre! ' ', :class=>'irb' prompt ||= $1 elsif line =~ /^([?>]>)(.*)\n/ prompt ||= $1 $x.pre prompt + $2, :class=>'irb' prompt = nil elsif line =~ /^\w+(::\w+)*: / $x.pre! line.chomp, :class=>'stderr' elsif line =~ /^\s+from [\/.:].*:\d+:in `\w.*'\s*$/ $x.pre! line.chomp, :class=>'stderr' else $x.pre! line.chomp, :class=>'stdout' end end terr.join end end |
#issue(text, options = {}) ⇒ Object
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/gorp/commands.rb', line 120 def issue text, ={} log :issue, text $issue+=1 $x.p :class => 'issue', :id => "issue-#{$issue}" do $x.text! text if [:pull] $x.text! ' (' repository = [:repository] || 'rails' $x.a "pull #{[:pull]}", :href=> "https://github.com/rails/#{repository}/pull/#{[:pull]}" [:ticket].to_s $x.text! ')' end end $todos.li do section = $section.split(' ').first $todos.a "Section #{section}:", :href => "#section-#{section}" $todos.a "#{text}", :href => "#issue-#{$issue}" end end |
#log(type, message) ⇒ Object
106 107 108 |
# File 'lib/gorp/commands.rb', line 106 def log type, Gorp.log type, end |
#note(message) ⇒ Object Also known as: desc
96 97 98 |
# File 'lib/gorp/commands.rb', line 96 def note $x.p , :class=>'note' end |
#omit(*sections) ⇒ Object
10 11 12 13 14 15 |
# File 'lib/gorp/commands.rb', line 10 def omit *sections sections.each do |section| section = [section] unless section.respond_to? :include? $omit << Range.new(secsplit(section.first), secsplit(section.last)) end end |
#overview(message) ⇒ Object
92 93 94 |
# File 'lib/gorp/commands.rb', line 92 def overview $x.p .gsub(/(^|\n)\s+/, ' ').strip, :class=>'overview' end |
#popen3(args, highlight = []) ⇒ Object
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/gorp/commands.rb', line 320 def popen3 args, highlight=[] echo = '' if args =~ /echo\s+((["')])(.*?)\2)\s+\|\s+(.*)$/ args = "bash -c #{$4.inspect}" echo = eval($1).gsub("\\n","\n") end Open3.popen3(args) do |pin, pout, perr, wait| terr = Thread.new do begin $x.pre! perr.readline.chomp, :class=>'stderr' until perr.eof? rescue EOFError end end tin = Thread.new do echo.split("\n").each do |line| pin.puts line end pin.close end until pout.eof? begin line = pout.readline rescue EOFError break end if highlight.any? {|pattern| line.include? pattern} outclass='hilight' elsif line =~ /\x1b\[\d/ outclass = 'logger' outclass = 'stderr' if line =~ /\x1b\[31m/ line.gsub! /\x1b\[\d+m/, '' else outclass='stdout' end if line.strip.size == 0 $x.pre! ' ', :class=>outclass else $x.pre! line.chomp, :class=>outclass end end terr.join tin.join wait && wait.value end end |
#rails(name, app = nil, opt = '') ⇒ Object
run rails as a command
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 |
# File 'lib/gorp/rails.rb', line 106 def rails name, app=nil, opt='' Dir.chdir($WORK) FileUtils.rm_rf name log :rails, name $rails_app = name # determine how to invoke rails rails = Gorp.which_rails($rails) rails += ' new' if `#{rails} -v` !~ /Rails 2/ gemfile = ENV['BUNDLE_GEMFILE'] || 'Gemfile' if File.exist? gemfile rails = "bundle exec " + rails opt += ' --skip-bundle' opt += ' --dev' if File.read(gemfile) =~ /gem ['"]rails['"], :path/ elsif `ruby -v` =~ /1\.8/ rails.sub! /^/, 'ruby ' unless rails =~ /^ruby / rails.sub! 'ruby ', 'ruby -rubygems ' end $x.pre "#{rails.gsub('/',FILE_SEPARATOR)} #{name}#{opt}", :class=>'stdin' popen3 "#{rails} #{name}#{opt.sub(' --dev','')}" # canonicalize the reference to Ruby Dir["#{name}/script/**/*"].each do |script| next if File.directory? script code = open(script) {|file| file.read} code.sub! /^#!.*/, '#!/usr/bin/env ruby' open(script,'w') {|file| file.write code} end cmd "mkdir #{name}" unless File.exist?(name) Dir.chdir(name) FileUtils.rm_rf 'public/.htaccess' cmd 'rake rails:freeze:edge' if ARGV.include? '--edge' if $rails != 'rails' and File.directory?($rails) if File.exist? 'Gemfile' gemfile=open('Gemfile') {|file| file.read} gemfile[/^gem 'rails',()/,1] = " :path => #{$rails.inspect} #" ENV['RUBYLIB'].split(File::PATH_SEPARATOR).each do |path| path.sub! /\/lib$/, '' name = path.split(File::SEPARATOR).last next if %w(gorp rails).include? name if File.exist?(File.join(path, "/#{name}.gemspec")) if gemfile =~ /^\s*gem ['"]#{name}['"],\s*:git/ gemfile[/^\s*gem ['"]#{name}['"],\s*(:git\s*=>\s*).*/,1] = ":path => #{path.inspect} # " elsif gemfile =~ /^\s*gem ['"]#{name}['"],/ gemfile[/^\s*gem ['"]#{name}['"],\s*()/,1] = ":path => #{path.inspect} # " else gemfile.sub!(/(^\s*gem ['"]#{name}['"])/) {|line| '# ' + line} gemfile[/gem 'rails',.*\n()/,1] = "gem #{name.inspect}, :path => #{path.inspect}\n" end end end gemfile[/^()source/, 1] = '# ' open('Gemfile','w') {|file| file.write gemfile} gemfile = File.('Gemfile') at_exit do source = File.read(gemfile) source[/^(# )source/, 1] = '' open(gemfile,'w') {|file| file.write source} end if $bundle begin rubyopt, ENV['RUBYOPT'] = ENV['RUBYOPT'], nil bundle "install" ensure ENV['RUBYOPT'] = rubyopt end else cmd "ln -s #{$rails} vendor/rails" system "mkdir -p .bundle" system "cp #{__FILE__.sub(/\.rb$/,'.env')} .bundle/environment.rb" end else system 'mkdir -p vendor' system "ln -s #{$rails} vendor/rails" end end if ARGV.include?('--rails-debug') edit 'config/initializers/rails_debug.rb' do |data| data.all = <<-EOF.unindent(12) ENV['BACKTRACE'] = '1' Thread.abort_on_exception = true EOF end end end |
#rails_epoc ⇒ Object
Determine which version of the rails cli to use. Over time, things change. The basic strategy is to code the scripts to the latest version of rails, and have the DSL automatically substitute prior equivalents when run against older baselines.
This method returns a list of symbols that can be used to control which version of a given command is to be used.
54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/gorp/commands.rb', line 54 def rails_epoc return @rails_epoc if @rails_epoc version = File.read('Gemfile.lock')[/^\s+rails \((\d+\.\d+)/, 1]. split('.').map(&:to_i) @rails_epoc = [] @rails_epoc << :rake_test if (version <=> [5, 0]) == -1 @rails_epoc << :rake_db if (version <=> [5, 0]) == -1 @rails_epoc end |
#rake(args, opts = {}) ⇒ Object
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/gorp/commands.rb', line 165 def rake args, opts = {} if args == 'test:controllers' and File.exist? 'test/functional' args = 'test:functionals' elsif args == 'test:models' and File.exist? 'test/unit' args = 'test:units' end status = cmd "rake #{args}" if status and (opts[:pass] or opts[:fail]) if status.success? == true and opts[:pass] issue opts[:pass], opts end if status.success? == false and opts[:fail] issue opts[:fail], opts end end end |
#restart_server ⇒ Object
start/restart a rails server in a separate process
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
# File 'lib/gorp/rails.rb', line 235 def restart_server if $server log :server, 'restart' $x.h3 'Restart the server.' Gorp::Commands.stop_server(true) else log :CMD, 'rails server' $x.h3 'Start the server.' end if File.exist? 'bin/rails' rails_server = "#{$ruby} bin/rails server --port #{$PORT}" elsif File.exist? 'script/rails' rails_server = "#{$ruby} script/rails server --port #{$PORT}" else rails_server = "#{$ruby} script/server --port #{$PORT}" end if RUBY_PLATFORM !~ /mingw32/ $server = fork else require 'win32/process' begin save = STDOUT.dup STDOUT.reopen(File.open('NUL','w+')) $server = Process.create(:app_name => rails_server, :inherit => true) # :startup_info => {:stdout => File.open('server.log','w+')}) ensure STDOUT.reopen save end end if $server # wait for server to start 60.times do sleep 0.5 begin status = Net::HTTP.get_response('localhost','/',$PORT).code break if %(200 404 500).include? status rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT end end else # start a new bundler context ENV.keys.dup.each { |key| ENV.delete key if key =~ /^BUNDLE_/ } ENV.delete('RUBYOPT') # For unknown reason, when run as CGI, the below produces: # undefined method `chomp' for nil:NilClass (NoMethodError) # from rails/actionpack/lib/action_dispatch/middleware/static.rb:13 # path = env['PATH_INFO'].chomp('/') # unless ENV['GATEWAY_INTERFACE'].to_s =~ /CGI/ STDOUT.reopen '/dev/null', 'a' exec rails_server end # alternatives to the above, with backtrace begin if File.exist?('config.ru') require 'rack' server = Rack::Builder.new {eval(open('config.ru') {|fh| fh.read})} Rack::Handler::WEBrick.run(server, :Port => $PORT) else ARGV.clear.unshift('--port', $PORT.to_s) # start server, redirecting stdout to a string $stdout = StringIO.open('','w') require './config/boot' if Rails::VERSION::MAJOR == 2 require 'commands/server' else require 'rails/commands/server' Rails::Server.start end end rescue STDERR.puts $! $!.backtrace.each {|method| STDERR.puts "\tfrom " + method} ensure Process.exit! end end end |
#ruby(args) ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'lib/gorp/commands.rb', line 149 def ruby args if args == 'script/server' restart_server else args = args.split(' ') args.map! do |arg| if arg.include? '*' files = Dir[arg] arg = files.first if files.length == 1 end arg end cmd "ruby #{args.join(' ')}" end end |
#runner(*args) ⇒ Object
223 224 225 |
# File 'lib/gorp/commands.rb', line 223 def runner *args cmd "rails runner #{args.join(' ')}" end |
#secinclude(ranges, section) ⇒ Object
84 85 86 87 88 89 90 |
# File 'lib/gorp/commands.rb', line 84 def secinclude ranges, section # was (in Ruby 1.8): range.include?(secsplit(section)) ranges.any? do |range| ss = secsplit(section) (range.first <=> ss) <= 0 and (range.last <=> ss) >= 0 end end |
#secsplit(section) ⇒ Object
80 81 82 |
# File 'lib/gorp/commands.rb', line 80 def secsplit section section.to_s.split('.').map {|n| n.to_i} end |
#section(number, title, &steps) ⇒ Object
19 20 21 22 |
# File 'lib/gorp/commands.rb', line 19 def section number, title, &steps number = (sprintf "%f", number).sub(/0+$/,'') if number.kind_of? Float $sections << [number, title, steps] end |
#section_head(number, title) ⇒ Object
111 112 113 114 115 116 117 118 |
# File 'lib/gorp/commands.rb', line 111 def section_head number, title $section = "#{number} #{title}".strip number ||= (@@section_number+=1) log '====>', $section $x.a(:class => 'toc', :id => "section-#{number}") {$x.h2 $section} $toc.li {$toc.a $section, :href => "#section-#{number}"} end |
#test(*args) ⇒ Object
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/gorp/commands.rb', line 253 def test *args if args.length == 0 if rails_epoc.include? :rake_test rake 'test' else cmd 'rails test' end elsif args.join.include? '.' if File.exist? 'bin/rails' # target = Dir[args.first].first.sub(/^test\//,'').sub(/\.rb$/,'') target = Dir[args.first].first if rails_epoc.include? :rake_test cmd "rake test #{target}" else cmd "rails test #{target}" end else ruby "-I test #{args.join(' ')}" end else if rails_epoc.include? :rake_test rake "test:#{args.first}" else cmd "rails test:#{args.first}" end end end |
#unbundle ⇒ Object
227 228 229 230 231 232 233 234 235 236 |
# File 'lib/gorp/commands.rb', line 227 def unbundle save = {} ENV.keys.dup.each {|key| save[key]=ENV.delete(key) if key =~ /^BUNDLE_/} save['RUBYOPT'] = ENV.delete('RUBYOPT') if ENV['RUBYOPT'] yield ensure save.delete('BUNDLE_GEMFILE') save.each {|key, value| ENV[key] = value} end |