Application icon

Gem Version Build Status Code Climate Coverage Status Inline docs Gitter

TTY is a toolbox for developing beautiful command line clients in Ruby. It provides a fluid interface for gathering input from the user, querying system and terminal and displaying information back. It is not another command line options parser, rather a plumbing library that helps in common tasks.

Motivation

All too often libraries that interact with command line create their own interface logic that gathers input from users and displays information back. Many times utility files are created that contain methods for reading system or terminal properties. Shouldn't we focus our energy on building the actual client?

Even more so, any command line application needs a clear way of communicating its results back to terminal whether in tabular form, column form or colorfully indented text. Our time and energy should be spent in creating the tools not the foundation.

Features

Fully modular, choose out of many components to suite your needs and jump-start development of your command line app:

  • Terminal ASCII and Unicode tables. [status: ✔ ]
  • Terminal output colorization. [status: ✔ ]
  • Terminal output paging. [status: ✔ ]
  • System detection utilities. [status: ✔ ]
  • Command detection utilities. [status: ✔ ]
  • Text manipulation(wrapping/truncation) [status: ✔ ]
  • Terminal progress bars drawing. [status: ✔ ]
  • Terminal spinners. [status: ✔ ]
  • Prompt user interface. [status: In Progress]
  • File diffs. [status: TODO]
  • Configuration file management. [status: TODO]
  • Logging [status: In Progress]
  • Plugin ecosystem [status: TODO]
  • Fully tested with major ruby interpreters.

Installation

Add this line to your application's Gemfile:

gem 'tty'

And then execute:

$ bundle

Or install it yourself as:

$ gem install tty

Contents

Usage

TTY provides you with many tools to get the job done in terminal.

To print tabular output use TTY::Table:

table = TTY::Table[['a1', 'a2', 'a3'], ['b1', 'b2', 'b3']]
table.to_s
# => a1  a2  a3
     b1  b2  b3

To colorize your strings use Pastel:

pastel = Pastel.new
pastel.green.on_red.bold('Piotr')

To create a progress bar use TTY::ProgressBar:

bar = TTY::ProgressBar.new("downloading [:bar]", total: 30)
30.times { bar.advance }

To create a spinner use TTY::Spinner:

spinner = TTY::Spinner.new('Loading ... ', format: :spin_2)
30.times { spinner.spin }

To measure screen size use TTY::Screen:

screen = TTY::Screen.new
screen.size     # => [51, 280]
screen.width    # => 280
screen.height   # => 51

1. Table

TTY uses the tty-table component in order to convert data into table and render as string output in tabular form. For example, to render data with ASCII border:

table = TTY::Table.new ['header1','header2'], [['a1','a2'], ['b1','b2']]
table.render(:ascii)
# =>
  +-------+-------+
  |header1|header2|
  +-------+-------+
  |a1     |a2     |
  |b1     |b2     |
  +-------+-------+

Please refer to documentation for complete API.

2. Color

In order to colorize your output TTY uses the pastel component like so:

pastel = Pastel.new
pastel.red.on_green.bold 'text...'  # => red bold text on green background

Please refer to documentation for complete API.

3. ProgressBar

In order to draw progress bar TTY uses the tty-progressbar component. For example, to render basic download bar do:

bar = TTY::ProgressBar.new("downloading [:bar]", total: 30)
30.times { bar.advance }

Please refer to documentation for complete API.

4. Spinner

TTY uses the tty-spinner component to handle terminal spinning animation. For instance, to create a simple spinner do:

spinner = TTY::Spinner.new('Loading ... ', format: :spin_2)
30.times { spinner.spin }

Please refer to documentation for complete API.

5. Screen

TTY uses the tty-screen component to measure the screen properties. For example to get screen size do:

screen = TTY::Screen.new
screen.size     # => [51, 280]
screen.width    # => 280
screen.height   # => 51

Please refer to documentation for complete API.

6 Terminal

To read general terminal properties you can use on of the helpers

term = TTY::Terminal.new
term.echo(false) { }    # switch off echo for the block
term.page               # page terminal output, on non unix systems falls back to ruby implementation

6.1 Pager

To page your output do

term.page 'long text...'

7 Shell

Main responsibility is to interact with the prompt and provide convenience methods.

Available methods are

shell = TTY::Shell.new
shell.ask          # print question
shell.read         # read from stdin
shell.say          # print message to stdout
shell.confirm      # print message(s) in green
shell.warn         # print message(s) in yellow
shell.error        # print message(s) in red
shell.suggest      # print suggestion message based on possible matches
shell.print_table  # print table to stdout

In order to ask question and parse answers:

shell  = TTY::Shell.new
answer = shell.ask("What is your name?").read_string

The library provides small DSL to help with parsing and asking precise questions

argument   # :required or :optional
char       # turn character based input, otherwise line (default: false)
clean      # reset question
default    # default value used if none is provided
echo       # turn echo on and off (default: true)
mask       # mask characters i.e '****' (default: false)
modify     # apply answer modification :upcase, :downcase, :trim, :chomp etc..
in         # specify range '0-9', '0..9', '0...9' or negative '-1..-9'
validate   # regex against which stdin input is checked
valid      # a list of expected valid options

You can chain question methods or configure them inside a block

shell.ask("What is your name?").argument(:required).default('Piotr').validate(/\w+\s\w+/).read_string

shell.ask "What is your name?" do
  argument :required
  default  'Piotr'
  validate /\w+\s\w+/
  valid    ['Piotr', 'Piotrek']
  modify   :capitalize
end.read_string

Reading answers and converting them into required types can be done with custom readers

read_bool       # return true or false for strings such as "Yes", "No"
read_char       # return first character
read_date       # return date type
read_datetime   # return datetime type
read_email      # validate answer against email regex
read_file       # return a File object
read_float      # return decimal or error if cannot convert
read_int        # return integer or error if cannot convert
read_multiple   # return multiple line string
read_password   # return string with echo turned off
read_range      # return range type
read_regex      # return regex expression
read_string     # return string
read_symbol     # return symbol
read_text       # return multiline string
read_keypress   # return the key pressed

For example, if we wanted to ask a user for a single digit in given range

ask("Provide number in range: 0-9").in('0-9') do
  on_error :retry
end.read_int

on the other hand, if we are interested in range answer then

ask("Provide range of numbers?").read_range

To suggest possible matches for the user input use suggest method like so

shell.suggest('sta', ['stage', 'stash', 'commit', 'branch'])
# =>
  Did you mean one of these?
          stage
          stash

8 System

TTY::System.unix?        # check if unix platform
TTY::System.windows?     # check if windows platform
TTY::System.which(cmd)   # full path to executable if found, nil otherwise
TTY::System.exists?(cmd) # check if command is available
TTY::System.editor       # provides access to system editor

To set preferred editor you can either use shell environment variables such as EDITOR and VISUAL or set the command(s) manually like so

TTY::System.editor.command('vim')

To open a file in your editor of choice do

TTY::System.editor.open('file path...')

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Copyright (c) 2012-2015 Piotr Murach. See LICENSE for further details.