Module: Gorp::Commands

Included in:
TestCase
Defined in:
lib/gorp/rails.rb,
lib/gorp/commands.rb

Constant Summary collapse

@@section_number =
0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.stop_server(restart = false, signal = "INT") ⇒ Object

stop a server if it is currently running



182
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
210
# File 'lib/gorp/rails.rb', line 182

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

#cmd(args, opts = {}) ⇒ Object



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
# File 'lib/gorp/commands.rb', line 154

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'
	Dir.chdir 'db/migrate' do
	  date = '20110711000000'
      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



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
# File 'lib/gorp/commands.rb', line 112

def console script, env=nil
  if 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(statement, highlight = []) ⇒ Object



93
94
95
96
97
98
# File 'lib/gorp/commands.rb', line 93

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

#generate(*args) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
# File 'lib/gorp/commands.rb', line 138

def generate *args
  if args.length == 1
    ruby "script/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}
    ruby "script/generate #{args.join(' ')}"
  end
end

#head(number, title) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/gorp/commands.rb', line 63

def 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

#irb(file) ⇒ Object



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
# File 'lib/gorp/commands.rb', line 239

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



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/gorp/commands.rb', line 72

def issue text, options={}
  log :issue, text

  $issue+=1
  $x.p :class => 'issue', :id => "issue-#{$issue}" do
	$x.text! text
	if options[:ticket]
	  $x.text! ' ('
	  $x.a "ticket #{options[:ticket]}", :href=>
 'https://rails.lighthouseapp.com/projects/8994/tickets/' + 
 options[: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



58
59
60
# File 'lib/gorp/commands.rb', line 58

def log type, message
  Gorp.log type, message
end

#note(message) ⇒ Object Also known as: desc



53
54
55
# File 'lib/gorp/commands.rb', line 53

def note message
  $x.p message, :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



49
50
51
# File 'lib/gorp/commands.rb', line 49

def overview message
  $x.p message.gsub(/(^|\n)\s+/, ' ').strip, :class=>'overview'
end

#popen3(args, highlight = []) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
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
233
234
235
236
237
# File 'lib/gorp/commands.rb', line 192

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|
	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\[1m)?\x1b\[3\dm(.*?)\x1b\[0m/, '\2'
	  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
  end
end

#rails(name, app = nil) ⇒ Object

run rails as a command



97
98
99
100
101
102
103
104
105
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
# File 'lib/gorp/rails.rb', line 97

def rails name, app=nil
  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/ 
  opt = ''
  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 name == 'gorp'
        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}
      if $bundle
        cmd "bundle install"
      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

#rake(args) ⇒ Object



108
109
110
# File 'lib/gorp/commands.rb', line 108

def rake args
  cmd "rake #{args}"
end

#restart_serverObject

start/restart a rails server in a separate process



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
# File 'lib/gorp/rails.rb', line 213

def restart_server
  if $server
    log :server, 'restart'
	$x.h3 'Restart the server.'
    Gorp::Commands.stop_server(true)
  else
    log :CMD, 'ruby script/server'
	$x.h3 'Start the server.'
  end

  if 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).include? status
	  rescue Errno::ECONNREFUSED
	  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



100
101
102
103
104
105
106
# File 'lib/gorp/commands.rb', line 100

def ruby args
  if args == 'script/server'
    restart_server
  else
    cmd "ruby #{args}"
  end
end

#runner(*args) ⇒ Object



150
151
152
# File 'lib/gorp/commands.rb', line 150

def runner *args
  ruby "script/runner #{args.join(' ')}"
end

#secinclude(ranges, section) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/gorp/commands.rb', line 41

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



37
38
39
# File 'lib/gorp/commands.rb', line 37

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