All Projects → leejarvis → Slop

leejarvis / Slop

Licence: mit
Simple Lightweight Option Parsing - ✨ new contributors welcome ✨

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Slop

dhtml2pdf
Simple, free and very easy to use PHP API that allows you to see, download or get the binary of the PDF generated from the HTML of an URL.
Stars: ✭ 27 (-97.47%)
Mutual labels:  simple, easy-to-use
Lang-app
Add a multi lang configuration to your WEB APP 'from scratch' [ANY FRAMEWORK, ANY PLUGIN, ANY API]
Stars: ✭ 15 (-98.59%)
Mutual labels:  simple, easy-to-use
Hacktoberfest-Banned-The-Repo-Guys-Sorry-For-Your-Time-and-effort
A beginner-friendly open source repository to create your first pull request.
Stars: ✭ 27 (-97.47%)
Mutual labels:  simple, beginner-friendly
Clikt
Multiplatform command line interface parsing for Kotlin
Stars: ✭ 1,658 (+55.39%)
Mutual labels:  command-line, option-parser
Hacktoberfest 2020
Welcome to Open-source! Simply add your details to contributors | Repo for Hacktoberfest 2020 ✅
Stars: ✭ 621 (-41.8%)
Mutual labels:  beginner-friendly, easy-to-use
Simple
The Simple Intelligent and Modular Programming Language and Environment
Stars: ✭ 120 (-88.75%)
Mutual labels:  command-line, simple
AppImageUpdater
AppImage Updater for Humans built with QML/C++ with Qt5 ❤️.
Stars: ✭ 31 (-97.09%)
Mutual labels:  simple, easy-to-use
QArchive
Async C++ Cross-Platform library that modernizes libarchive using Qt5 🚀. Simply extracts 7z 🍔, Tarballs 🎱 and other supported formats by libarchive. ❤️
Stars: ✭ 66 (-93.81%)
Mutual labels:  simple, easy-to-use
HACKTOBERFEST2021 INSPIRATION
😎A Hacktoberfest-2021 Contribution Repository For Beginners😎...Simplest Repo for Beginners👨‍💻👨‍💻👨‍💻...Add your Profile Details, Photo and Inspirational Quote 🙌🙌🙌& There you go to do your first PR❤❤❤
Stars: ✭ 30 (-97.19%)
Mutual labels:  simple, beginner-friendly
Chocolater
Chocolater is simply a PowerShell code generator and it was conceived in order to facilitate the selection and installation of your favorite applications in one go.
Stars: ✭ 26 (-97.56%)
Mutual labels:  simple, easy-to-use
Algobook
A beginner-friendly project to help you in open-source contributions. Data Structures & Algorithms in various programming languages Please leave a star ⭐ to support this project! ✨
Stars: ✭ 132 (-87.63%)
Mutual labels:  beginner-friendly, easy-to-use
Clipp
easy to use, powerful & expressive command line argument parsing for modern C++ / single header / usage & doc generation
Stars: ✭ 687 (-35.61%)
Mutual labels:  command-line, option-parser
Valine
A fast, simple & powerful comment system.
Stars: ✭ 1,899 (+77.98%)
Mutual labels:  simple, easy-to-use
ytmous
Anonymous Youtube Proxy
Stars: ✭ 60 (-94.38%)
Mutual labels:  simple, easy-to-use
Perfectwindows
PerfectWindows 软件家族 - Windows 从未如此完美!
Stars: ✭ 1,326 (+24.27%)
Mutual labels:  simple, easy-to-use
DM-BOT
📧 DM-BOT is discord bot that can record direct messages. One of us! You can also reply to those messages! DM-BOT is easy to use & understand! I decided to use Discord.js, it's literally the best.
Stars: ✭ 31 (-97.09%)
Mutual labels:  simple, easy-to-use
Swiftcli
A powerful framework for developing CLIs in Swift
Stars: ✭ 673 (-36.93%)
Mutual labels:  command-line, option-parser
Mcdowell Cv
A Nice-looking CV template made into LaTeX
Stars: ✭ 855 (-19.87%)
Mutual labels:  simple, easy-to-use
Art
🎨 ASCII art library for Python
Stars: ✭ 1,026 (-3.84%)
Mutual labels:  easy-to-use
A Tiny Js World
A tiny task for those who isn't familiar with OOP and JS OOP in particular yet
Stars: ✭ 50 (-95.31%)
Mutual labels:  beginner-friendly

Slop

Slop is a simple option parser with an easy to remember syntax and friendly API.

Build Status

Installation

gem install slop

Usage

opts = Slop.parse do |o|
  o.string '-h', '--host', 'a hostname'
  o.integer '--port', 'custom port', default: 80
  o.string '-l', '--login', required: true
  o.bool '-v', '--verbose', 'enable verbose mode'
  o.bool '-q', '--quiet', 'suppress output (quiet mode)'
  o.bool '-c', '--check-ssl-certificate', 'check SSL certificate for host'
  o.on '--version', 'print the version' do
    puts Slop::VERSION
    exit
  end
end

ARGV #=> -v --login alice --host 192.168.0.1 --check-ssl-certificate

opts[:host]                 #=> 192.168.0.1
opts[:login]                #=> alice
opts.verbose?               #=> true
opts.quiet?                 #=> false
opts.check_ssl_certificate? #=> true

opts.to_hash  #=> { host: "192.168.0.1", login: "alice", port: 80, verbose: true, quiet: false, check_ssl_certificate: true }

Note that the block we've added to the --version flag will be executed during parse time. Therefore these blocks should be reserved for immediately reacting to the presence of a flag. If you want to access other options or mutate values, check out the "Custom option types" section below and implement the #finish method.

Option types

Built in Option types are as follows:

o.string  #=> Slop::StringOption, expects an argument
o.bool    #=> Slop::BoolOption, no argument, aliased to BooleanOption
o.integer #=> Slop::IntegerOption, expects an argument, aliased to IntOption
o.float   #=> Slop::FloatOption, expects an argument
o.array   #=> Slop::ArrayOption, expects an argument
o.regexp  #=> Slop::RegexpOption, expects an argument
o.null    #=> Slop::NullOption, no argument and ignored from `to_hash`
o.on      #=> alias for o.null

You can see all built in types in slop/types.rb. Suggestions or pull requests for more types are welcome.

Advanced Usage

This example is really just to describe how the underlying API works. It's not necessarily the best way to do it.

opts = Slop::Options.new
opts.banner = "usage: connect [options] ..."
opts.separator ""
opts.separator "Connection options:"
opts.string "-H", "--hostname", "a hostname"
opts.int "-p", "--port", "a port", default: 80
opts.separator ""
opts.separator "Extra options:"
opts.array "--files", "a list of files to import"
opts.bool "-v", "--verbose", "enable verbose mode", default: true

parser = Slop::Parser.new(opts)
result = parser.parse(["--hostname", "192.168.0.1", "--no-verbose"])

result.to_hash #=> { hostname: "192.168.0.1", port: 80,
                 #     files: [], verbose: false }

puts opts # prints out help

Arguments

It's common to want to retrieve an array of arguments that were not processed by the parser (i.e options or consumed arguments). You can do that with the Result#arguments method:

args = %w(connect --host google.com GET)
opts = Slop.parse args do |o|
  o.string '--host'
end

p opts.arguments #=> ["connect", "GET"] # also aliased to `args`

This is particularly useful when writing scripts with ARGF:

opts = Slop.parse do |blah|
  # ...
end

# make sure sloptions aren't consumed by ARGF
ARGV.replace opts.arguments

ARGF.each { |line|
  # ...
}

Arrays

Slop has a built in ArrayOption for handling array values:

opts = Slop.parse do |o|
  # the delimiter defaults to ','
  o.array '--files', 'a list of files', delimiter: ','
end

# both of these will return o[:files] as ["foo.txt", "bar.rb"]:
# --files foo.txt,bar.rb
# --files foo.txt --files bar.rb

If you want to disable the built-in string-splitting, set the delimiter to nil.

Custom option types

Slop uses option type classes for every new option added. They default to the NullOption. When you type o.array Slop looks for an option called Slop::ArrayOption. This class must contain at least 1 method, call. This method is executed at parse time, and the return value of this method is used for the option value. We can use this to build custom option types:

module Slop
  class PathOption < Option
    def call(value)
      Pathname.new(value)
    end
  end
end

opts = Slop.parse %w(--path ~/) do |o|
  o.path '--path', 'a custom path name'
end

p opts[:path] #=> #<Pathname:~/>

Custom options can also implement a finish method. This method by default does nothing, but it's executed once all options have been parsed. This allows us to go back and mutate state without having to rely on options being parsed in a particular order. Here's an example:

module Slop
  class FilesOption < ArrayOption
    def finish(opts)
      if opts.expand?
        self.value = value.map { |f| File.expand_path(f) }
      end
    end
  end
end

opts = Slop.parse %w(--files foo.txt,bar.rb -e) do |o|
  o.files '--files', 'an array of files'
  o.bool '-e', '--expand', 'if used, list of files will be expanded'
end

p opts[:files] #=> ["/full/path/foo.txt", "/full/path/bar.rb"]

Errors

Slop will raise errors for the following:

  • An option used without an argument when it expects one: Slop::MissingArgument
  • An option used that Slop doesn't know about: Slop::UnknownOption
  • An option marked as required when not provided: Slop::MissingRequiredOption

These errors inherit from Slop::Error, so you can rescue them all. Alternatively you can suppress these errors with the suppress_errors config option:

opts = Slop.parse suppress_errors: true do
  o.string '-name'
end

# or per option:

opts = Slop.parse do
  o.string '-host', suppress_errors: true
  o.int '-port'
end

Printing help

The return value of Slop.parse is a Slop::Result which provides a nice help string to display your options. Just puts opts or call opts.to_s:

opts = Slop.parse do |o|
  o.string '-h', '--host', 'hostname'
  o.int '-p', '--port', 'port (default: 80)', default: 80
  o.string '--username'
  o.separator ''
  o.separator 'other options:'
  o.bool '--quiet', 'suppress output'
  o.on '-v', '--version' do
    puts "1.1.1"
  end
end

puts opts

Output:

% ruby run.rb
usage: run.rb [options]
    -h, --host     hostname
    -p, --port     port (default: 80)
    --username

other options:
    --quiet        suppress output
    -v, --version

This method takes an optional prefix value, which defaults to " " * 4:

puts opts.to_s(prefix: "  ")

It'll deal with aligning your descriptions according to the longest option flag.

Here's an example of adding your own help option:

o.on '--help' do
  puts o
  exit
end

Commands

Slop not longer has built in support for git-style subcommands.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].