Ruby / Console libraries

From WhyNotWiki
Jump to: navigation, search

Contents

Main

star_full.gif star_full.gif star_full.gif facets/console_command (Console::Command)

http://facets.rubyforge.org/api/more/classes/Console/Command.html

Console::Command is to command-line applications as ActiveRecord is to database tables (Object relational mapping): A "Command-line to object mapping" as its author calls it. It maps each subcommand (like svn diff) to a method and maps each option (--revision or -r) to a method. Using introspection on the method it determines the "arity" of the option itself (whether it takes a value or not). A pretty clever idea! Unfortunately, the current implementation has some shortcomings, IMHO. I've patched some of them.

http://facets.rubyforge.org/api/more/classes/Console/Command.html

  require "rubygems"
  #require_gem "facets", '=1.8.20'  # Optional
  #require 'facet/console_command'   # Did *not* work for me.
  require "facets/more/command"

  MyCmd << Console::Command

    # options
    def _v
      $VERBOSE = true
    end

    # subcommand
    def jump
      if $VERBOSE
        puts "JUMP! JUMP! JUMP!"
      else
        puts "Jump"
      end
    end

  end

  MyCmd.execute

Then on the command line:

  > mycmd jump
  Jump

  > mycmd -v jump
  JUMP! JUMP! JUMP!

RCommand

Project/Development: http://rubyforge.org/projects/rcommand/


Description: RCommand is a generic way for ruby scripts to present a full-featured command interface to users, complete with command history and tab completion.




Readiness: 3 - Alpha


[Ruby DSLs (category)] [abstractions in Ruby (category)] ShellScriptBuilder -- write shell (bash) scripts using Ruby

http://brainspl.at/articles/2007/01/22/shellscriptbuilder-for-capistrano ShellScriptBuilder for Capistrano

[Ruby DSLs (category)] [abstractions in Ruby (category)]: Reminds me of the XML Builder DSL that Rails has to let you generate XML output with Ruby commands, and of course JavaScript Generator (.rjs templates)...

Currently it appears to be target towards use in Capistrano, but I don't see why it couldn't be used anywhere you want to execute shell commands/scripts from Ruby...

script = shell do |sh|
  sh.sudo.ln_nsf "foo/bar", "bar/bar" 

  sh.echo "some string" => "/path/to/log.txt" 

  sh.if :directory? => "some/dir" do |sub|
    sub.rm_rf 'some/dir'
    sub.ln_nsf "shared/foo", "some/dir" 
    sub.if_not :file? => 'foo' do |ssub|
      ssub.mkdir_p "some/foo" 
    end  
  end

  sh.unless :file? => 'foo/bario' do |sub|
    sub.touch 'foo/bario'
  end

  sh.if :writable? => "some/file.txt" do |sub|
    sub.echo "#{Time.now}" => 'some/file.txt'
  end  
  sh.mkdir_p 'foo/bar'
  sh.rm_rf 'foo/bar'
end

puts script

Simple Console - console microframework

Homepage: http://simpleconsole.rubyforge.org/
Documentation: RDoc


Project/Development: http://rubyforge.org/projects/simpleconsole/


Description: [[description := SimpleConsole is a microframework to get console apps quickly. Some features: Separation of logic and view (useful for 'puts'), Option parsing (--age => params[:age]), Filters for method calls (before_filter, after_filter)|SimpleConsole is a microframework to get console apps quickly. Some features: Separation of logic and view (useful for 'puts'), Option parsing (--age => params[:age]), Filters for method calls (before_filter, after_filter)]]




Readiness: 1 - Planning


Obviously inspired by Rails...

http://simpleconsole.rubyforge.org/

class Controller < SimpleConsole::Controller
  params :string => {:n => :name, :w => :word}

  def print
    @name = params[:name]
    @word = params[:word]
  end
end

class View < SimpleConsole::View
  def print
    puts "Your name is " + @name + "." 
    puts "You wanted me to say the word " + @word + "." 
  end
end

SimpleConsole::Application.run(ARGV, Controller, View

Command parsing

http://simpleconsole.rubyforge.org/tutorial.html

Here’s an example of parameter parsing -

class Controller < SimpleConsole::Controller
  params :string => {:n => :name},
         :text => {:d => :description},
         :bool => {:o => :old},
         :int => {:a = :age}

  # ...
end

Now from the command line, we can do this:

[t0fuu] ruby myapp --name Sensei -d "old and wise" --old -a 98

Inside our Controller, we’ll have access to all of these arguments through the params hash.

params[:name]           # => "Sensei" 
params[:description]    # => "old and wise" 
params[:old]            # => true
params[:age]            # => 98

rshell

Project/Development: http://rubyforge.org/projects/rshell/


Description: This gem provides a shell for managing commands, managing aliases and loading libraries of commands. This shell can handle most frontends including a console such as irb or a web app via Rails.




Readiness: 3 - Alpha



[escaping (category)]

See Comparison of Escape class and String.shell escape

Escape class -- Escape special characters so that sh doesn't treat them specially

http://www.a-k-r.org/escape/ escape - HTML/URI/shell escaping utilities

irb -> require 'escape'  # http://www.a-k-r.org/escape/
Escape.shell_command(["echo", "*"]) #=> "echo '*'"

Can also be used to escape in other contexts:

Escape.uri_path("a?b/c?d/e?f") #=> "a%3Fb/c%3Fd/e%3Ff"
Escape.html_form([["a","b"], ["c","d"]]) #=> "a=b&c=d"
Escape.html_form({"a"=>"b", "c"=>"d"}) #=> "a=b&c=d"
Escape.html_text("a & b < c > d") #=> "a & b < c > d"
Escape.html_attr("ab&<>\"c") #=> "\"ab&<>"c\""

String#shell_escape -- Escape special characters so that sh doesn't treat them specially

irb -> require 'rubygems'
irb -> require 'facets/core/string/shell_escape'

irb -> system("echo " + %q{!'"$0 ()`<>}.shell_escape)
!'"sh ()`<>

irb -> system("echo $0")
sh

irb -> system("echo '" + %q{$0} + "'")
$0


Option / argument parsing

[core Ruby (category)] Shellwords (parse command-line arguments) from a string

http://www.ruby-doc.org/core/classes/Shellwords.html

Split text into an array of tokens in the same way the UNIX Bourne shell does.

star_full.gif star_full.gif star_empty.gif cmdparse

Homepage: http://cmdparse.rubyforge.org/


Project/Development: http://rubyforge.org/projects/cmdparse/


Description: cmdparse is an advanced command line parser which supports 'commands'. Programs that use command line interfaces with commands are, for example, subversion's 'svn' or Rubygem's 'gem' program.





Code example

[1]

cmd = CmdParse::CommandParser.new( true, true )
cmd.program_name = "net"
cmd.program_version = [0, 1, 1]

cmd.options = CmdParse::OptionParserWrapper.new do |opt|
  opt.separator "Global options:"
  opt.on("--verbose", "Be verbose when outputting info") {|t| $verbose = true }
end

cmd.add_command( CmdParse::HelpCommand.new )
cmd.add_command( CmdParse::VersionCommand.new )

# ipaddr
ipaddr = CmdParse::Command.new( 'ipaddr', true, true )
ipaddr.short_desc = "Manage IP addresses"
cmd.add_command( ipaddr )

# ipaddr add
add = CmdParse::Command.new( 'add', false )
add.short_desc = "Add an IP address"
add.set_execution_block do |args|
  puts "Adding ip addresses: #{args.join(', ')}" if $verbose
  $ipaddrs += args
end
ipaddr.add_command( add )

...

Features

  • partial command matching -- Can use net.rb ip instead of net.rb ipaddr. ("If partial command matching is used, then the shortest unambiguous part of a command name can be used instead of always specifying the full command name.") [2]

From Change-log [3]

  • Commands can now have subcommands which can have subcommands which can have subcommands…
  • No need to implement a whole new class for simple commands anymore
  • Default option parser library is optparse, however, any option parser library can be used after writing a small wrapper
  • Improved HelpCommand: the global options -h and—help take an optional command name now
  • Possibility to define a default command which is used when no command was specified
  • A NoCommandGivenError is thrown when no command on the CLI and no default command was specified
  • added possibility to parse global options, command and local options separately

optparse

http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/index.html

http://beaver.net/slides/ruby/10-easy-pieces.html

  1. Add argument parsing to your application
  2. Supports both short and long arguments (-h vs --help)

Getopt::Declare

Project/Development: http://rubyforge.org/projects/getoptdeclare/


Description: Declare is yet another command-line argument parser, one which is specifically designed to be powerful but exceptionally easy to use. It supports many options not supported by optparser or getoptlong as well as it has a simpler syntax.



Environment: Console (Text Based)
Readiness: 5 - Production/Stable



User interaction / reading from standard input (stdin)

readline

http://www.ruby-doc.org/stdlib/libdoc/readline/rdoc/index.html

http://beaver.net/slides/ruby/10-easy-pieces.html

  • Wrapper around GNU readline library
  • Input prompt that supports history and inline editing
  • Nicer way to grab input than just reading from stdin


HighLine

http://rubyforge.org/projects/highline/

A high-level IO library that provides validation, type conversion, and more for command-line interfaces. HighLine also includes a complete menu system that can crank out anything from simple list selection to complete shells with just minutes of work.

http://highline.rubyforge.org/doc/

http://highline.rubyforge.org/

Command line interfaces are meant to be easy. So why shouldn’t building them be easy, too? HighLine provides a solid toolset to help you get the job done cleanly so you can focus on the real task at hand, your task.

zip = ask("Zip?  ") { |q| q.validate = /\A\d{5}(?:-?\d{4})?\Z/ }

EasyPrompt

Homepage: http://easyprompt.rubyforge.org/


Project/Development: http://rubyforge.org/projects/easyprompt







> correct = prompt.ask( "Is your name #{ fname } #{ lname }?", true, :boolean )
  Is your name John Doe? [y]

termios

http://raa.ruby-lang.org/project/ruby-termios/

http://arika.org/ruby/termios

http://rubyforge.org/projects/termios/

http://blog.rezra.com/articles/2005/12/05/single-character-input

require 'termios'

# Set up termios so that it returns immediately when you press a key.
# (http://blog.rezra.com/articles/2005/12/05/single-character-input)
t = Termios.tcgetattr(STDIN)
t.lflag &= ~Termios::ICANON
Termios.tcsetattr(STDIN,0,t)
c = ''
while c != 'q' do
  c = STDIN.getc.chr
  puts "You entered: " + c.inspect
end

# Example:
uYou entered: "u"
aYou entered: "a"
uYou entered: "u"
eYou entered: "e"

Ruby Quiz - HighLine

Ruby Quiz - HighLine (#29) -- Has 5 solutions.


Windows-specific

Win32::Console

Categories/Tags: (includes: [ANSI (category)])



Project/Development: http://rubyforge.org/projects/win32console/


Description: ANSI. It allows working with Windows' Consoles much more easily (changing colors, positioning cursor, querying info, and emulates ANSI control characters).





Article metadata

Aliases: Ruby / Console libraries, Ruby / Console commands, Ruby / Console command development, Ruby / Console application development, Ruby / Command-line application development

Ads
Personal tools