parse

package module
v0.0.0-...-c6768a1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2021 License: MIT Imports: 10 Imported by: 0

README

Parse

Get rid of parsing boilerplate,
And make your program a shining UNIX citizen for free!

Want to Go and write some quick programs (solutions to CCC problems, perhaps) without dealing with boring parsing code or even figuring out where to get the arguments from in the first place? Parse has got you covered.

What are you waiting for?

$ go get github.com/mk12/parse

Features

  • abstracts away the source of program arguments
  • provides a flexible model for parsing said arguments
  • allows you to add custom parsers for your own data types
  • facilitates piping, input redirection, and interactive use
  • creates and displays a standard usage message
  • prints helpful, context-aware error messages

Usage

A program that uses Parse is easy to use. Here are some ways that you can use Meaner:

$ meaner --help
usage: meaner number ...
$ meaner 1 2 3
2
$ echo 1 1 2e50 | meaner
6.666666666666668e+49
$ echo -1 1 > data
$ meaner < data
0
$ meaner a b
meaner: a: invalid syntax
meaner: b: invalid syntax

Example

Meaner calculates the mean of a list of numbers. Read the documentation in parse.go for information on the functions it uses.

package main

import (
    "fmt"
    "github.com/mk12/parse"
)

func mean(numbers []float64) float64 {
    if len(numbers) == 0 {
        return 0
    }
    sum := 0.0
    for _, x := range numbers {
        sum += x
    }
    return sum / float64(len(numbers))
}

func main() {
    parse.SetUsage("number ...")
    parse.SetEveryParser(parse.Float64)
    parse.Main(func(args []interface{}) {
        fmt.Println(mean(parse.AssertFloat64s(args)))
    })
}

SimpleIO

Parse is based on SimpleIO, an extremely similar project that I wrote in C. I've included the SimpleIO in this repository in the files simpleio.h and simpleio.c.

License

© 2013 Mitchell Kember

Parse is available under the MIT License; see LICENSE for details.

Documentation

Overview

Package parse provides an abstraction for obtaining and parsing arguments in simple programs. It allows arguments to be passed either on the command line or via standard input, making it easy pipe data to the program in addition to specifying arguments manually. It also handles the usage message and the formatting of error messages.

Index

Constants

This section is empty.

Variables

View Source
var Float64 = Parser(func(s string) (interface{}, error) {
	n, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return nil, err.(*strconv.NumError).Err
	}
	return n, nil
})

Float64 is a Parser that parses a string as a float64.

View Source
var Int = Parser(func(s string) (interface{}, error) {
	n, err := strconv.ParseInt(s, 0, 0)
	if err != nil {
		return nil, err.(*strconv.NumError).Err
	}
	return int(n), nil
})

Int is a Parser that parses a string as an int.

Functions

func AssertFloat64s

func AssertFloat64s(args []interface{}) []float64

AssertFloat64s converts a list of interface{} to a list of float64s using a type assertion for each element. It is useful when combined with parse.SetEveryParser(parse.Float64).

func AssertInts

func AssertInts(args []interface{}) []int

AssertInts converts a list of interface{} to a list of ints using a type assertion for each element. It is useful when combined with parse.SetEveryParser(parse.Int).

func Main

func Main(fn func([]interface{}))

Main takes a function fn and applies it to a list of arguments, which comes from either the command line or from standard input depending on how the program is invoked.

The function fn can safely use type assertions on the arguments passed to it as long as they match the types that are returned by the parser(s) passed to SetEveryParser or SetParsers. If neither of those functions were called, the arguments will all be strings. If an argument can be valid for the parser but invalid for the program, a custom Parser should be written or an existing one should be modified using Restrict (don't print error messages from fn).

When the program is invoked with "-h" or "--help", the usage message will be printed to standard output. When invoked directly with the wrong number of arguments, the usage message will be printed to standard error. When the only argument is "-", or when there are none and input is piped or redirected, the arguments will be read and parsed from a line of standard input in a loop until an EOF is encountered (each line is like a separate invocation of fn). When invoked with the correct number of arguments, they will be parsed and passed to fn.

func SetEveryParser

func SetEveryParser(p Parser)

SetEveryParser assigns p to be used to parse the program's arguments. The function passed to Main must be prepared to receive any nonzero number of arguments (but they are guaranteed to be of the type that p returns).

func SetParsers

func SetParsers(ps ...Parser)

SetParsers assigns ps to be used to parse the program's arguments. The function passed to Main is guaranteed to receive len(ps) arguments. Each Parser in ps corresponds to a single argument, so, for example, if the third parses an int, then the third argument received by the program is guaranteed to be an int.

func SetUsage

func SetUsage(args string)

SetUsage creates the usage message using args, which should contain the portion of the usage message that lists the arguments. This is typically a list of the argument names separated by spaces.

For example, the sleep command found on Unix systems takes one argument, the number of seconds to sleep for. A sleep program using parse should call SetUsage("seconds"). This will produce "usage: sleep seconds".

Types

type Parser

type Parser func(string) (interface{}, error)

A Parser is a function that parses a string that is supposed to represent a particular data type. It returns an error when the string cannot be parsed. A nil parser is equivalent to a function that simply returns the passed string.

func (Parser) Restrict

func (p Parser) Restrict(pred func(interface{}) error) Parser

Restrict creates a new Parser by restricting p with the predicate function pred. If the string is parsed without error by p, the value will be passed on to pred, which return an error for invalid parsed values not covered by p. For example, Restrict can be used to return an error if a well-formed string parsed as an integer is negative (when negative inputs do not make sense).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL