Source

Strelka / bin / strelka

The default branch has multiple heads

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 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
180
181
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
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
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
319
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
367
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#!/usr/bin/env ruby
# vim: set nosta noet ts=4 sw=4:

require 'strelka'
require 'trollop'
require 'highline'
require 'loggability'

# Have to do it this way to avoid the vendored 'sysexits' under OSX.
gem 'sysexits'
require 'sysexits'


# A tool for setting up and running Strelka apps
class Strelka::CLICommand
	extend ::Sysexits,
	       Loggability
	include Sysexits,
	        Strelka::Constants


	# Write logs to Strelka's logger
	log_to :strelka


	# Make a HighLine color scheme
	COLOR_SCHEME = HighLine::ColorScheme.new do |scheme|
		scheme[:header]    = [ :bold, :yellow ]
		scheme[:subheader] = [ :bold, :white ]
		scheme[:key]       = [ :white ]
		scheme[:value]     = [ :bold, :white ]
		scheme[:error]     = [ :red ]
		scheme[:warning]   = [ :yellow ]
		scheme[:message]   = [ :reset ]
	end


	# Class instance variables
	@command_help = Hash.new {|h,k| h[k] = { :desc => nil, :usage => ''} }
	@prompt = @option_parser = nil


	### Run the utility with the given +args+.
	def self::run( args )
		HighLine.color_scheme = COLOR_SCHEME

		oparser = self.make_option_parser
		opts = Trollop.with_standard_exception_handling( oparser ) do
			oparser.parse( args )
		end

		command = oparser.leftovers.shift
		self.new( opts ).run( command, *oparser.leftovers )
		exit :ok

	rescue => err
		self.log.fatal "Oops: %s: %s" % [ err.class.name, err.message ]
		self.log.debug { '  ' + err.backtrace.join("\n  ") }

		exit :software_error
	end


	### Return a String that describes the available commands, e.g., for the 'help'
	### command.
	def self::make_command_table
		commands = self.available_commands

		# Build the command table
		col1len = commands.map( &:length ).max
		return commands.collect do |cmd|
			helptext = self.help( cmd.to_sym ) or next # no help == invisible command
			"%s  %s" % [
				self.prompt.color(cmd.rjust(col1len), :key),
				self.prompt.color(helptext, :value)
			]
		end.compact
	end


	### Return an Array of the available commands.
	def self::available_commands
		return self.public_instance_methods( false ).
			map( &:to_s ).
			grep( /_command$/ ).
			map {|methodname| methodname.sub(/_command$/, '') }.
			sort
	end


	### Create and configure a command-line option parser for the command.
	### Returns a Trollop::Parser.
	def self::make_option_parser
		unless @option_parser
			progname = File.basename( $0 )

			# Make a list of the log level names and the available commands
			loglevels = Loggability::LOG_LEVELS.
				sort_by {|name,lvl| lvl }.
				collect {|name,lvl| name.to_s }.
				join( ', ' )
			command_table = self.make_command_table

			@option_parser = Trollop::Parser.new do
				banner "Manage Strelka apps"
				version( Strelka.version_string(true) )

				text ''
				command_table.each {|line| text(line) }
				text ''

				text 'Global Options'
				opt :config, "Specify the config file to load.", :type => :string
				opt :datadir, "Override the Strelka data directory.", :type => :string,
					:short => :D
				text ''

				text 'Other Options:'
				opt :debug, "Turn debugging on. Also sets the --loglevel to 'debug'."
				opt :loglevel, "Set the logging level. Must be one of: #{loglevels}",
					:default => Strelka.logger.level.to_s
			end
		end

		return @option_parser
	end


	### Add a help string for the given +command+.
	def self::help( command, helpstring=nil )
		if helpstring
			@command_help[ command.to_sym ][:desc] = helpstring
		end

		return @command_help[ command.to_sym ][:desc]
	end


	### Add/fetch the +usagestring+ for +command+.
	def self::usage( command, usagestring=nil )
		if usagestring
			prefix = usagestring[ /\A(\s+)/, 1 ]
			usagestring.gsub!( /^#{prefix}/m, '' ) if prefix

			@command_help[ command.to_sym ][:usage] = usagestring
		end

		return @command_help[ command.to_sym ][:usage]
	end


	### Return the global Highline prompt object, creating it if necessary.
	def self::prompt
		unless @prompt
			@prompt = HighLine.new

			columns = @prompt.output_cols.nonzero? || 80
			rows    = @prompt.output_rows.nonzero? || 1000

			@prompt.page_at = rows - 5
			@prompt.wrap_at = columns - 2
		end

		return @prompt
	end


	#################################################################
	###	I N S T A N C E   M E T H O D S
	#################################################################

	### Create a new instance of the command and set it up with the given
	### +options+.
	def initialize( options )
		Loggability.format_with( :color ) if $stderr.tty?
		@options = options

		if @options.debug
			$DEBUG = true
			$VERBOSE = true
			Loggability.level = :debug
		elsif @options.loglevel
			Loggability.level = @options.loglevel
		end

	end


	######
	public
	######

	# The Trollop options hash the command will read its configuration from
	attr_reader :options


	# Delegate the instance #prompt method to the class method instead
	define_method( :prompt, &self.method(:prompt) )


	### Run the command with the specified +command+ and +args+.
	def run( command, *args )
		command ||= 'help'
		cmd_method = nil

		# Set the datadir override if it's given
		if self.options.datadir
			self.log.debug "Using data dir option: %s" % [ self.options.datadir ]
			Strelka::App.local_data_dirs = Pathname( self.options.datadir )
		end

		# Include a 'lib' directory if there is one
		$LOAD_PATH.unshift( 'lib' ) if File.directory?( 'lib' )

		# Run the command
		begin
			cmd_method = self.method( "#{command}_command" )
		rescue NameError => err
			error "No such command %p" % [ command ]
			exit :usage
		end

		cmd_method.call( *args )
	end


	#
	# Commands
	#

	### The 'help' command
	def help_command( *args )

		# Subcommand help
		if !args.empty?
			command = args.shift

			if self.class.available_commands.include?( command )
				header( self.class.help(command) )
				desc = "\n" + 'Usage: ' + command + ' ' + self.class.usage(command) + "\n"
				message( desc )
			else
				error "No such command %p" % [ command ]
			end

		# Help by itself show the table of available commands
		else
			command_table = self.class.make_command_table
			header "Available Commands"
			message( *command_table )
		end

	end
	help :help, "Show help for a single COMMAND if given, or list available commands if not"
	usage :help, "[COMMAND]"


	### The 'discover' command
	def discover_command( *args )
		header "Searching for Strelka applications..."

		paths = Strelka::App.discover_paths
		if paths.empty?
			message "None found."
		else
			paths.each do |gemname, paths|
				message "\n"

				if gemname == ''
					subheader "Local: "
				else
					subheader "Gem: #{gemname}"
				end

				filenames = paths.map {|path| path.basename.to_s }
				list( filenames )
			end
		end
	end
	help :discover, "Show available Strelka applications installed as gems."


	### The 'setup' command
	def setup_command( *args )
	end
	help :setup, "Set up a new Strelka environment and start the admin server."


	### The 'start' command
	def start_command( *args )
		path, appname, gemname = self.find_specified_app( *args )

		header "Starting the %s app%s" % [
			appname,
			gemname == '' ? '' : " from the #{gemname} gem"
		]

		apps = Strelka::App.load( path )
		Strelka.load_config( self.options.config ) if self.options.config
		self.log.debug "  loaded: %p" % [ apps ]
		apps.first.run
	end
	help :start, "Start a Strelka app"


	### The 'version' command
	def version_command( *args )
		message( "<%= color 'Version:', :header %> " + Mongrel2.version_string(true) )
	end
	help :version, "Prints the Ruby-Mongrel2 version."


	### The 'config' command
	def config_command( *args )
		gemname = args.shift
		discovery_name = gemname || ''

		header "Dumping config for %s" % [ gemname || 'local apps' ]
		discovered_apps = Strelka::App.discover_paths

		raise ArgumentError, "No apps discovered" unless discovered_apps.key?( discovery_name )

		discovered_apps[ discovery_name ].each do |apppath|
			message "  loading %s (%s)" % [ apppath, apppath.basename('.rb') ]
			Strelka::App.load( apppath )
		end

		message "  dumping config:"
		$stdout.puts Configurability.default_config.dump
	end
	help :config, "Dump the configuration for GEMNAME (or the local directory if no gem is specified)"
	usage :config, "[GEMNAME]"


	### The 'version' command
	def version_command( *args )
		message( "<%= color 'Version:', :header %> " + Mongrel2.version_string(true) )
	end
	help :version, "Prints the Ruby-Mongrel2 version."


	#
	# Helper methods
	#

	### Find the app specified in the specified +args+ and return the Pathname to it and the
	### name of the gem it belongs to. Raises a RuntimeError if the +args+ didn't contain a
	### valid application specification.
	def find_specified_app( *args )
		appname = args.pop
		gemname = args.pop
		discovered_apps = Strelka::App.discover_paths

		path = nil
		if gemname
			discovered_apps[ gemname ].each do |apppath|
				self.log.debug "    %s (%s)" % [ apppath, apppath.basename('.rb') ]
				if apppath.basename('.rb').to_s == appname
					path = apppath
					break
				end
			end
		else
			self.log.debug "No gem name; searching them all:"
			discovered_apps.each do |disc_gemname, paths|
				self.log.debug "  %s: %d paths" % [ disc_gemname, paths.length ]
				path = paths.find do |apppath|
					self.log.debug "    %s (%s)" % [ apppath, apppath.basename('.rb') ]
					self.log.debug "    %p vs. %p" % [ apppath.basename('.rb').to_s, appname ]
					apppath.basename('.rb').to_s == appname
				end or next
				gemname = disc_gemname
				break
			end
		end

		unless path
			msg = "Couldn't find an app named '#{appname}'"
			msg << " in the #{gemname} gem" if gemname
			raise( msg )
		end
		self.log.debug "  found: %s" % [ path ]

		return path, appname, gemname
	end


	#
	# Utility methods
	#

	### Output normal output
	def message( *parts )
		self.prompt.say( parts.map(&:to_s).join($/) )
	end


	### Output the given +text+ highlighted as a header.
	def header( text )
		message( self.prompt.color(text, :header) )
	end


	### Output the given +text+ highlighted as a subheader.
	def subheader( text )
		message( self.prompt.color(text, :subheader) )
	end


	### Output the given +text+ highlighted as an error.
	def error( text )
		message( self.prompt.color(text, :error) )
	end


	### Output the given +items+ as a columnar list.
	def list( *items )
		message( self.prompt.list(items.flatten.compact.map(&:to_s), :columns_down) )
	end

end # class Strelka::CLICommand


Strelka::CLICommand.run( ARGV.dup )