package shon

import "go.abhg.dev/shon"

Package shon provides a parser for the SHON format.

SHON is a notation for expressing complex objects on the command line.

Index

Functions

func Parse

func Parse(args []string, v any, opts ...ParseOption) error

Parse decodes args and stores the result into the value pointed to by v. If v is not a pointer, Parse returns an error.

The type and structure of v informs how Parse will decode values. The following provides a listing of the type of v and what Parse will accept for it.

Parsing structs

Structs are parsed by matching their field names to object keys. For example, given the struct:

type User struct {
	FirstName string
	LastName  string
}

We can pass the following arguments:

[ --first-name Jack --last-name Sparrow ]

Although these names are guessed implicitly, it is recommended to expliclty annotate fields with the shon:".." tag to specify names for those fields.

type User struct {
	FirstName string `shon:"first-name"`
	LastName  string `shon:"last-name"`
}

Parsing any value

As a special case, a field of type any (interface{}) will accept a complete value decoded into one of the following types:

bool
string
int64
float64
[]any
map[string]any

If the UseNumber option is used, int64 and float64 above will be replaced with Number.

func ParseObject

func ParseObject(args []string, v any, opts ...ParseOption) error

ParseObject is a variant of Parse that assumes an object at the top level.

It treats the following argument list:

--first-name Jack --last-name Sparrow

As if it was:

[ --first-name Jack --last-name Sparrow ]

This makes it a good starting point for CLIs that want to accept flags.

Types

type Number

type Number = json.Number

Number holds numeric values that could be integers or floats.

type ParseOption

type ParseOption interface {
	// contains filtered or unexported methods
}

ParseOption customizes the behavior of Parse.

func UseNumber

func UseNumber(b bool) ParseOption

UseNumber specifies whether the decoder should read numeric values as Number objects for fields of the type 'any'.

If false, the decoder will attempt to parse numeric values as an int64 or float64, and place that there instead.

Defaults to false.

Directories

cmd/shon shon is a program that accepts SHON input on the command line and prints an equivalent JSON object to stdout.