• Stars
    star
    521
  • Rank 84,952 (Top 2 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created almost 14 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Start your command line scripts off right in Ruby

optparse-plus - Wrapper around OptionParse to Make CLIs a bit Easier

Author

Dave Copeland (davetron5000 at g mail dot com)

Copyright

Copyright © 2011 by Dave Copeland

License

Distributes under the Apache License, see LICENSE.txt in the source distro

A smattering of tools to make your command-line apps easily awesome; Ideally makes it almost as easy as bash to get a command line app up and running.

The goal of this project is to make it as easy as possible to write awesome and powerful command-line applications.

Toward that end, this gem provides:

  • A command-line app to bootstrap a new command-line app.

  • A lightweight DSL to create your command-line interface, that loses none of OptionParser‘s power.

  • A simplified means of running external commands that has better error handling and diagnostics.

  • Simplified zero-config logging that is a better-than-puts puts.

  • Support for integration-testing your CLI using Test::Unit

Read about the name change if you care

Platforms

This library only supports the latest versions of Ruby. JRuby support has been too difficult to keep up with, though the library should work for JRuby.

Bootstrapping a new CLI App

The optparse_plus command-line app will bootstrap a new command-line app, setting up a proper gem structure, unit tests, and integration tests.

It assumes you are using a standard Ruby development environment, which includes:

  • Some sort of Ruby version manager to allow you to manage Ruby as yourself and not as root/system

  • Bundler

  • Git

_(Note that apps powered by this gem have no particular runtime dependencies as classes this gem provides depend only on the standard library)_

$ optparse_plus --help
Usage: optparse_plus [options] app_name

Kick the bash habit by bootstrapping your Ruby command-line apps

v2.0.0

Options:
    -h, --help                       Show command line help
        --force                      Overwrite files if they exist
        --[no-]readme                [Do not ]produce a README file
        --rspec                      Generate RSpec unit tests instead of Test::Unit
    -l, --license LICENSE            Specify the license for your project
                                     (mit|apache|gplv2|gplv3|custom|NONE)
        --log-level LEVEL            Set the logging level
                                     (debug|info|warn|error|fatal)
                                     (Default: info)
        --version                    Show help/version info

Arguments:

    app_name
        Name of your app, which is used for the gem name and executable name

Usage: optparse_plus [options] app_name
        --force                      Overwrite files if they exist
$ optparse_plus myapp -l mit
$ cd myapp
$ bundle install
...
$ bundle exec rake
Started
.
Finished in 0.000499 seconds.
-----------------------------------------------------------------------------------------
1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
-----------------------------------------------------------------------------------------
2004.01 tests/s, 2004.01 assertions/s
Started
.
Finished in 0.298281 seconds.
-----------------------------------------------------------------------------------------
1 tests, 8 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed
-----------------------------------------------------------------------------------------
3.35 tests/s, 26.82 assertions/s

$ cat test/integration/test_cli.rb
require "optparse_plus/test/base_integration_test"

class TestSomething < OptparsePlus::BaseIntegrationTest
  def test_truth
    stdout,stderr,results = run_app("myapp","--help")
    assert_banner(stdout, "myapp", takes_options: true, takes_arguments: false)
    assert_option(stdout,"-h", "--help")
    assert_option(stdout,"--version")
    assert_oneline_summary(stdout)
  end
end

Basically, this sets you up with all the boilerplate that you should be using to write a command-line app. Specifically, you get:

  • Gemified project (based on bundle gem)

  • An executable using OptparsePlus::Main to outline your new app

  • Test::Unit test task set up and an empty unit test.

  • Test::Unit integration tests with some of optparse-plus’s assertions to let you drive your CLI’s development

  • The outline of a README

  • An optional license included

DSL for your bin file

A canonical OptionParser-driven app has a few problems with it structurally that optparse-plus can solve:

  • Backwards organization - main logic is at the bottom of the file, not the top

  • Verbose to use opts.on just to set a value in a Hash

  • No exception handling - you have to explicitly call exit and/or let exceptions’ stack traces leak through.

optparse-plus provides OptparsePlus::Main to help make a clean and easy-to-maintain bin file. See the rdoc for an example, and see my blog on the derivation of this module.

Wrapper for running external commands with good logging

While backtick and %x[] are nice for compact, bash-like scripting, they have some failings:

  • You have to check the return value via $?

  • You have no access to the standard error

  • You really want to log: the command, the output, and the error so that for cron-like tasks, you can sort out what happened

Enter OptparsePlus::SH

sh "cp foo.txt /tmp"
# => logs command at DEBUG level
#    if the command exited zero:
#        logs the standard output at DEBUG
#        logs the standard error at WARN
#    if the command exited nonzero:
#        logs the standard output at INFO
#        logs the standard error at WARN
#        returns the exit code for your examination
#
#        there's a LOT MORE

See the rdoc for more detailed examples and usage.

This isn’t a replacement for Open3 or ChildProcess, but a way to easily “do the right thing” for most cases.

Zero-Config Logging

Chances are, your code is littered with STDERR.puts on a good day, and nothing on a bad day. You probably also have a bunch of debug puts calls that you have commented out. Logging is extremely helpful in understanding how your app is behaving (or how it behaved in the past). Logging can be a pain to set up, and can also make it hard to give the user at the command-prompt a good experience.

OptparsePlus::CLILogger is designed to handle this. It’s a proper subclass of Ruby’s built-in Logger with a few enhancements:

  • Messages don’t get formatting if they are destined for a TTY (e.g. the user sitting at her terminal)

  • Errors and warnings go to the standard error.

  • Debug and info messages go to the standard output.

  • When these are redirected to a file, the log messages are properly date/time stamped as you’d expect

  • You can mix-in OptparsePlus::CLILogging to get access to a global logger instances without resorting to an explicit global variable

See CLILogger’s rdoc and then CLILogging’s for more.

Currently, there are classes that assist in directing output logger-style to the right place; basically ensuring that errors go to STDERR and everything else goes to STDOUT. All of this is, of course, configurable

Integration Tests

optparse-plus provides some basic features for executing your CLI and asserting things about it. OptparsePlus::Test::IntegrationTestAssertions documents these.

Contributing

  • Feel free to file an issue, even if you don’t have time to submit a patch

  • Please try to include a test for any patch you submit. If you don’t include a test, I’ll have to write one, and it’ll take longer to get your code in.

  • This is not intended to support “command-suite” style CLIs. See GLI if that’s what you want.

More Repositories

1

gli

Make awesome command-line applications the easy way
Ruby
1,255
star
2

brutalist-web-design

Source for Brutalist Web Design
CSS
84
star
3

receta

Example deployable Rails app using AngularJS
Ruby
75
star
4

ruby-style

My personal Ruby Style Guide along with tools you can use to make your own! See usage.md
Ruby
46
star
5

angular-rails-book

Micro eBook on Getting Started with Angular on Rails
CSS
35
star
6

rails-app-template-sustainable

A Rails App Template that creates a new Rails app according to the sustainable rails book
Ruby
27
star
7

awesome-cli-ruby

Awesome Command Line Applications in Ruby Presentation
CSS
27
star
8

shorty

RESTful URL Shortener for utf-8 vanity urls, written in Scala
Scala
22
star
9

moocow

Ruby Client for Remember The Milk
Ruby
18
star
10

scala-boss

NovaJUG Presentation: "Convince your Boss to let you use Scala"
JavaScript
18
star
11

trickster

Developer-Friendly, In-Browser Presentation Software with auto-resize and syntax highlighting
CSS
17
star
12

clean_test

Write clean, understandable tests in Test::Unit
Ruby
14
star
13

ghola

Color Picker for Developers
JavaScript
14
star
14

docker-dev-template

I'm sooooo tired of googling Docker and finding shit Medium blog posts and Docker's mediocre documentation
Shell
13
star
15

hl

Highlight terms in output or files to assist with visual scanning
Ruby
11
star
16

wtf-is-a-webpack

SCSS
10
star
17

dotfiles

My various dot files
Vim Script
8
star
18

bookingit

Create code-based content based on git repos, diffs, and tags
Ruby
7
star
19

daves-resume

Move along, I'm not interested
Ruby
7
star
20

sneaking-scala

Presentation slides from my talk at ScalaDays 2010 - "Sneaking Scala Into The Enterprise"
Scala
7
star
21

event_lawyer

Prototype code to explore consumer/producer-driven contracts for messaging systems
Ruby
6
star
22

adventureclone

A clone of Atari 2600's Adventure
C++
6
star
23

oc

Make org charts with Graph Viz
Ruby
5
star
24

vimdoclet

Javadoc doclet that generates VIM helpfiles
Java
5
star
25

naildrivin5.com-OLD

My website and blog
HTML
5
star
26

weird-ruby

Presentation and code for my RubyConf talk
CSS
4
star
27

gliffy

Ruby client to Gliffy's API
Ruby
4
star
28

awesome-cli

Gem for Build Awesome Command-Line Applications in Ruby
Ruby
3
star
29

rspec_test_data

Create complex test data using factories, re-usable across multiple tests and your seed data
Ruby
3
star
30

sclassy

Scala DSL for yuml.me Class Diagrams
Scala
3
star
31

tdd_cli_talk

Slides for "Test-drive the development of your command-line applications"
Ruby
3
star
32

jruby-and-threads-talk

Presentation from my RubyNation Talk on JRuby and Threads
3
star
33

scala_tour_content

Content for Another Tour of Scala
3
star
34

importscour

Fork of ImportScrubber which normalizes import statements in Java code
Java
2
star
35

gtd

Command line app for a lightweight GTD workflow
Ruby
2
star
36

java-javadoc-vim

JDK javadoc in vimdoc format for java.* packages
2
star
37

naildrivin5.com

My Website (deployed)
HTML
2
star
38

halen

A bare-bones wiki with a Git backend, Gliffy & Disqus integration
Ruby
2
star
39

static-site-in-react

Take 2 of making a static site generator with react as templating engine
JavaScript
2
star
40

sidekiq-book

Starting App used for the Sidekiq book
Ruby
2
star
41

devbox

Shell
2
star
42

melange-css

CSS utility framework for full stack developers
CSS
2
star
43

claret

dependency-based CLI todo list app
Ruby
2
star
44

service-layer-railsconf-2022

Slides for my talk at RailsConf
JavaScript
1
star
45

restunit

A unit testing framework for REST services
Java
1
star
46

whatdavesaid.com

Source for whatdavesaid.com
HTML
1
star
47

fwf

Experiment in creating a fun web framework for Java (BTW, it failed)
Java
1
star
48

sustainable-rails.com

Website for sustainable-rails.com
HTML
1
star
49

rkarel

Ruby implementation of Karel The Robot
Ruby
1
star
50

timeline-lang.com

Website for the Timeline programming language
Handlebars
1
star
51

supercade

My old band's data-driven website in PHP (for posterity)
PHP
1
star
52

webpack2-rails

THIS IS DEAD -- DO NOT USE
Ruby
1
star
53

bookdown

Make an online book that has code that executes as you build your book
Ruby
1
star
54

javax-javadoc-vim

Javadoc in vimdoc format for javax.* packages (save javax.xml)
1
star
55

shindig

Currently theoretical event logger written in elixir
Elixir
1
star
56

you_might_are_gonna_need_it

Slides from my talk at RubyNation 2013
JavaScript
1
star
57

fullstop

Manage dotfiles
Ruby
1
star
58

fauxml

Indented file-to-xml transcoder for hand-authoring annoying Java XML files
Java
1
star