All Projects → kareman → Moderator

kareman / Moderator

Licence: MIT license
A simple, modular command line argument parser in Swift.

Programming Languages

swift
15916 projects
ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Moderator

Deno Cliffy
Command line framework for deno 🦕 Including Commandline-Interfaces, Prompts, CLI-Table, Arguments Parser and more...
Stars: ✭ 149 (+684.21%)
Mutual labels:  argument-parser
sf
Simple Bash framework which provides argument parsing, usage output and text formatting variables
Stars: ✭ 16 (-15.79%)
Mutual labels:  argument-parser
vargs
Simple argument parsing library for V.
Stars: ✭ 36 (+89.47%)
Mutual labels:  argument-parser
Flags
⛳ Simple, extensible, header-only C++17 argument parser released into the public domain.
Stars: ✭ 187 (+884.21%)
Mutual labels:  argument-parser
argparse
Parser for command-line arguments
Stars: ✭ 24 (+26.32%)
Mutual labels:  argument-parser
argparser
Simple command-line parser for C/C++ programs
Stars: ✭ 50 (+163.16%)
Mutual labels:  argument-parser
Yaap
Yet Another (Swift) Argument Parser
Stars: ✭ 124 (+552.63%)
Mutual labels:  argument-parser
declarative-parser
Modern, declarative argument parser for Python 3.6+
Stars: ✭ 31 (+63.16%)
Mutual labels:  argument-parser
jsonargparse
Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
Stars: ✭ 168 (+784.21%)
Mutual labels:  argument-parser
CmdLine2
Command line argument parser (C++14)
Stars: ✭ 18 (-5.26%)
Mutual labels:  argument-parser
Lyra
A simple to use, composable, command line parser for C++ 11 and beyond
Stars: ✭ 238 (+1152.63%)
Mutual labels:  argument-parser
Argumentparser
Faster, easier, more declarative parsing of command line arguments in Objective-C/Foundation.
Stars: ✭ 251 (+1221.05%)
Mutual labels:  argument-parser
google-options
Command line argument parsing library from the folks at Google (java).
Stars: ✭ 61 (+221.05%)
Mutual labels:  argument-parser
Argagg
A simple C++11 command line argument parser
Stars: ✭ 180 (+847.37%)
Mutual labels:  argument-parser
docopt-ng
Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Stars: ✭ 94 (+394.74%)
Mutual labels:  argument-parser
Argparse.jl
Package for parsing command-line arguments to Julia programs.
Stars: ✭ 131 (+589.47%)
Mutual labels:  argument-parser
args
Simple and type-safe commandline argument parser for C++14
Stars: ✭ 63 (+231.58%)
Mutual labels:  argument-parser
dropt
dropt is yet another C library for parsing command-line options.
Stars: ✭ 39 (+105.26%)
Mutual labels:  argument-parser
ArgMacros.jl
Fast, flexible, macro-based, Julia package for parsing command line arguments.
Stars: ✭ 29 (+52.63%)
Mutual labels:  argument-parser
argparse-to-class
Transform argparse into class format for Jupyter Notebook execution
Stars: ✭ 20 (+5.26%)
Mutual labels:  argument-parser

 Run shell commands   |   Parse command line arguments | Handle files and directories


Build Status Platforms Version Carthage compatible

Moderator

Moderator is a simple Swift library for parsing commandline arguments.

Features

  • Modular, easy to extend.
  • Supports a cross platform syntax.
  • Generates help text automatically.
  • Handles arguments of the type '--option=value'.
  • Optional strict parsing, where an error is thrown if there are any unrecognised arguments.
  • Any arguments after an "--" argument are taken literally, they are not parsed as options and any '=' are left untouched.

See also why Moderator was created.

Example

from linuxmain-generator:

import Moderator
import FileSmith

let arguments = Moderator(description: "Automatically add code to Swift Package Manager projects to run unit tests on Linux.")
let overwrite = arguments.add(.option("o","overwrite", description: "Replace <test directory>/LinuxMain.swift if it already exists."))
let testdirarg = arguments.add(Argument<String?>
	.optionWithValue("testdir", name: "test directory", description: "The path to the directory with the unit tests.")
	.default("Tests"))
_ = arguments.add(Argument<String?>
	.singleArgument(name: "directory", description: "The project root directory.")
	.default("./")
	.map { (projectpath: String) in
		let projectdir = try Directory(open: projectpath)
		try projectdir.verifyContains("Package.swift")
		Directory.current = projectdir
	})

do {
	try arguments.parse()

	let testdir = try Directory(open: testdirarg.value)
	if !overwrite.value && testdir.contains("LinuxMain.swift") {
		throw ArgumentError(errormessage: "\(testdir.path)/LinuxMain.swift already exists. Use -o/--overwrite to replace it.")
	}
	...
} catch {
	WritableFile.stderror.print(error)
	exit(Int32(error._code))
}

Automatically generated help text:

Automatically add code to Swift Package Manager projects to run unit tests on Linux.

Usage: linuxmain-generator
  -o,--overwrite:
      Replace <test directory>/LinuxMain.swift if it already exists.
  --testdir <test directory>:
      The path to the directory with the unit tests. Default = 'Tests'.
  <directory>:
      The project root directory. Default = './'.

Introduction

Moderator works by having a single Moderator object which you add individual argument parsers to. When you start parsing it goes through each argument parser in the order they were added. Each parser takes the array of string arguments from the command line, finds the arguments it is responsible for, processes them and throws any errors if anything is wrong, removes the arguments from the array, returns its output (which for some parsers may be nil if the argument was not found) and passes the modified array to the next parser.

This keeps the code simple and each parser only has to take care of its own arguments. The built-in parsers can easily be customised, and you can create your own parsers from scratch.

Built-in parsers

Option

func option(_ names: String..., description: String? = nil) -> Argument<Bool>

Handles option arguments like -h and --help. Returns true if the argument is present and false otherwise.

Option with value

func optionWithValue(_ names: String..., name valuename: String? = nil, description: String? = nil)
-> Argument<String?>

Handles option arguments with a following value, like --help <topic>. It returns the value as a String, or nil if the option is not present.

Single argument

func singleArgument(name: String, description: String? = nil) -> Argument<String?>

Returns the next argument, or nil if there are no more arguments or the next argument is an option. Must be added after any option parsers.

Customise

default

Can be used on parsers returning optionals, to replace nil with a default value.

required

Can be used on parsers returning optionals, to throw an error on nil.

map

Takes the output of any argument parser and converts it to something else.

repeat

Looks for multiple occurrences of an argument, by repeating an optional parser until it returns nil.

let m = Moderator()
let options = m.add(Argument<String?>.optionWithValue("b").repeat())
let multiple = m.add(Argument<String?>.singleArgument(name: "multiple").repeat())

try m.parse(["-b", "b1", "-b", "b2", "-b", "b3", "one", "two", "three"])

options.value is now ["b1", "b2", "b3"] and multiple.value is ["one", "two", "three"]

count

Counts the number of times an option argument occurs.

let m = Moderator()
let option = m.add(Argument<Bool>.option("b").count())

try m.parse(["-b", "-b", "some", "other", "-b", "arguments"])

option.value returns 3  

Add new parsers

If the built in parsers and customisations are not enough, you can easily create your own parsers. As an example here is the implementation of the singleArgument parser:

extension Argument {
	public static func singleArgument (name: String, description: String? = nil) -> Argument<String?> {
		return Argument<String?>(usage: description.map { ("<"+name+">", $0) }) { args in
			let index = args.first == "--" ? args.index(after: args.startIndex) : args.startIndex
			guard index != args.endIndex, !isOption(index: index, args: args) else { return (nil, args) }
			var args = args
			return (args.remove(at: index), args)
		}
	}
}

In the Argument initialiser you return a tuple with the output of the parser and the arguments array without the processed argument(s).

Installation

Swift Package Manager

Add .Package(url: "https://github.com/kareman/Moderator", "0.5.0") to your Package.swift:

import PackageDescription

let package = Package(
	name: "somename",
	dependencies: [
		.Package(url: "https://github.com/kareman/Moderator", "0.5.0")
		 ]
	)

and run swift build.

Carthage

Add github "kareman/Moderator" to your Cartfile, then run carthage update and add the resulting framework to the "Embedded Binaries" section of the application. See Carthage's README for further instructions.

CocoaPods

Add Moderator to your Podfile.

pod "Moderator", git: "https://github.com/kareman/Moderator.git"

Then run pod install to install it.

License

Released under the MIT License (MIT), http://opensource.org/licenses/MIT

Kåre Morstøl, NotTooBad 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].