All Projects → ioquatix → Samovar

ioquatix / Samovar

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Samovar

literator
📝 Generate literate-style markdown docs from your sources
Stars: ✭ 55 (+139.13%)
Mutual labels:  parsing, documentation-generator
Fuzi
A fast & lightweight XML & HTML parser in Swift with XPath & CSS support
Stars: ✭ 894 (+3786.96%)
Mutual labels:  parsing
Swiftcli
A powerful framework for developing CLIs in Swift
Stars: ✭ 673 (+2826.09%)
Mutual labels:  option-parser
Esprima
ECMAScript parsing infrastructure for multipurpose analysis
Stars: ✭ 6,391 (+27686.96%)
Mutual labels:  parsing
Pydantic
Data parsing and validation using Python type hints
Stars: ✭ 8,362 (+36256.52%)
Mutual labels:  parsing
Apidoc
RESTful API 文档生成工具,支持 Go、Java、Swift、JavaScript、Rust、PHP、Python、Typescript、Kotlin 和 Ruby 等大部分语言。
Stars: ✭ 785 (+3313.04%)
Mutual labels:  documentation-generator
Wowchemy Hugo Modules
🔥 Hugo website builder, Hugo themes & Hugo CMS. No code, build with widgets! 创建在线课程,学术简历或初创网站。
Stars: ✭ 6,093 (+26391.3%)
Mutual labels:  documentation-generator
Jkt
Simple helper to parse JSON based on independent schema
Stars: ✭ 22 (-4.35%)
Mutual labels:  parsing
Rust Peg
Parsing Expression Grammar (PEG) parser generator for Rust
Stars: ✭ 836 (+3534.78%)
Mutual labels:  parsing
Phonelib
Ruby gem for phone validation and formatting using google libphonenumber library data
Stars: ✭ 731 (+3078.26%)
Mutual labels:  parsing
Optparse Applicative
Applicative option parser
Stars: ✭ 707 (+2973.91%)
Mutual labels:  option-parser
Clipp
easy to use, powerful & expressive command line argument parsing for modern C++ / single header / usage & doc generation
Stars: ✭ 687 (+2886.96%)
Mutual labels:  option-parser
M3u8
Parser and generator of M3U8-playlists for Apple HLS. Library for Go language. 🎦
Stars: ✭ 800 (+3378.26%)
Mutual labels:  parsing
Neon
🍸 Encodes and decodes NEON file format.
Stars: ✭ 674 (+2830.43%)
Mutual labels:  parsing
Feedkit
An RSS, Atom and JSON Feed parser written in Swift
Stars: ✭ 895 (+3791.3%)
Mutual labels:  parsing
Owl
A parser generator for visibly pushdown languages.
Stars: ✭ 645 (+2704.35%)
Mutual labels:  parsing
Gatsby Gitbook Starter
Generate GitBook style modern docs/tutorial websites using Gatsby + MDX
Stars: ✭ 700 (+2943.48%)
Mutual labels:  documentation-generator
Ason
[DEPRECATED]: Prefer Moshi, Jackson, Gson, or LoganSquare
Stars: ✭ 777 (+3278.26%)
Mutual labels:  parsing
Forma
Typespec based parsing of JSON-like data for Elixir
Stars: ✭ 23 (+0%)
Mutual labels:  parsing
Moment.php
Parse, validate, manipulate, and display dates in PHP w/ i18n support. Inspired by moment.js
Stars: ✭ 900 (+3813.04%)
Mutual labels:  parsing

Samovar

Teapot

Samovar is a modern framework for building command-line tools and applications. It provides a declarative class-based DSL for building command-line parsers that include automatic documentation generation. It helps you keep your functionality clean and isolated where possible.

Build Status Code Climate Coverage Status

Motivation

I've been using Trollop and while it's not bad, it's hard to use for sub-commands in a way that generates nice documentation. It also has pretty limited support for complex command lines (e.g. nested commands, splits, matching tokens, etc). Samovar is a high level bridge between the command line and your code: it generates decent documentation, maps nicely between the command line syntax and your functions, and supports sub-commands using classes which are easy to compose.

One of the other issues I had with existing frameworks is testability. Most frameworks expect to have some pretty heavy logic directly in the binary executable, or at least don't structure your code in a way which makes testing easy. Samovar structures your command processing logic into classes which can be easily tested in isolation, which means that you can mock up and spec your command-line executables easily.

Examples

  • Teapot is a build system and uses multiple top-level commands.
  • Utopia is a web application platform and uses nested commands.
  • Synco is a backup tool and sends commands across the network and has lots of options with default values.

Installation

Add this line to your application's Gemfile:

gem 'samovar'

And then execute:

$ bundle

Or install it yourself as:

$ gem install samovar

Usage

Generally speaking, you should create Command classes that represent specific functions in your program. The top level command might look something like this:

require 'samovar'

class List < Samovar::Command
	self.description = "List the current directory"
	
	def call
		system("ls -lah")
	end
end

class Application < Samovar::Command
	options do
		option '--help', "Do you need help?"
	end
	
	nested :command, {
		'list' => List
	}, default: 'list'
	
	def call
		if @options[:help]
			self.print_usage
		else
			@command.call
		end
	end
end

Application.call # Defaults to ARGV.

Basic Options

require 'samovar'

class Application < Samovar::Command
	options do
		option '-f/--frobulate <text>', "Frobulate the text"
		option '-x | -y', "Specify either x or y axis.", key: :axis
		option '-F/--yeah/--flag', "A boolean flag with several forms."
		option '--things <a,b,c>', "A list of things" do |value|
			value.split(/\s*,\s*/)
		end
	end
end

application = Application.new(['-f', 'Algebraic!'])
application.options[:frobulate] # 'Algebraic!'

application = Application.new(['-x', '-y'])
application.options[:axis] # :y

application = Application.new(['-F'])
application.options[:flag] # true

application = Application.new(['--things', 'x,y,z'])
application.options[:things] # ['x', 'y', 'z']

Nested Commands

require 'samovar'

class Create < Samovar::Command
	def invoke(parent)
		puts "Creating"
	end
end

class Application < Samovar::Command
	nested '<command>',
		'create' => Create
	
	def invoke(program_name: File.basename($0))
		if @command
			@command.invoke
		else
			print_usage(program_name)
		end
	end
end

Application.new(['create']).invoke

ARGV Splits

require 'samovar'

class Application < Samovar::Command
	many :packages
	split :argv
end

application = Application.new(['foo', 'bar', 'baz', '--', 'apples', 'oranges', 'feijoas'])
application.packages # ['foo', 'bar', 'baz']
application.argv # ['apples', 'oranges', 'feijoas']

Parsing Tokens

require 'samovar'

class Application < Samovar::Command
	self.description = "Mix together your favorite things."
	
	one :fruit, "Name one fruit"
	many :cakes, "Any cakes you like"
end

application = Application.new(['apple', 'chocolate cake', 'fruit cake'])
application.fruit # 'apple'
application.cakes # ['chocolate cake', 'fruit cake']

Explicit Commands

Given a custom Samovar::Command subclass, you can instantiate it with options:

application = Application['--root', path]

You can also duplicate an existing command instance with additions/changes:

concurrent_application = application['--threads', 12]

These forms can be useful when invoking one command from another, or in unit tests.

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

Future Work

Multi-value Options

Right now, options can take a single argument, e.g. --count <int>. Ideally, we support a specific sub-parser defined by the option, e.g. --count <int...> or --tag <section> <tags...>. These would map to specific parsers using Samovar::One and Samovar::Many internally.

Global Options

Options can only be parsed at the place they are explicitly mentioned, e.g. a command with sub-commands won't parse an option added to the end of the command:

command list --help

One might reasonably expect this to parse but it isn't so easy to generalize this:

command list -- --help

In this case, do we show help? Some effort is required to disambiguate this. Initially, it makes sense to keep things as simple as possible. But, it might make sense for some options to be declared in a global scope, which are extracted before parsing begins. I'm not sure if this is really a good idea. It might just be better to give good error output in this case (you specified an option but it was in the wrong place).

Shell Auto-completion

Because of the structure of the Samovar command parser, it should be possible to generate a list of all possible tokens at each point. Therefore, semantically correct tab completion should be possible.

As a secondary to this, it would be nice if Samovar::One and Samovar::Many could take a list of potential tokens so that auto-completion could give meaningful suggestions, and possibly improved validation.

Short/Long Help

It might be interesting to explore whether it's possible to have -h and --help do different things. This could include command specific help output, more detailed help output (similar to a man page), and other useful help related tasks.

License

Released under the MIT license.

Copyright, 2016, by Samuel G. D. Williams.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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].