Example Boolean Count
Overview
This example demos the counting of boolean flags. Each matching flag is
removed as encountered and added to the final count. No errors are generated
by the Args.Count method.
It demonstrates the following szargs functions:
// New creates a new Args object based in the arguments passed. The first
// element of the arguments must be the program name.
func New(programDesc string, args []string) *Args
// Count returns the number of times the flag appears.
func (args *Args) Count(flag, desc string) int
// Done registers an error if there are any remaining arguments.
func (args *Args) Done()
// HasErr returns true if any errors have been encountered or registered.
func (args *Args) HasErr() bool
// Err returns any errors encountered or registered while parsing the
// arguments.
func (args *Args) Err() error
// Usage returns a usage message based on the parsed arguments.
func (args *Args) Usage() string
Contents
Source
The source used for this example. It simply defines a new szargs.Arg object,
then defines a "count" flag which counts and removes the flags from the
argument list. Finally the Done function is called to insure that no more
arguments exist in the list.
cat ./main.go
// Package main implements a simple example of using szargs.
//
//nolint:forbidigo // OK to print to os.Stdout.
package main
import (
"fmt"
"os"
"github.com/dancsecs/szargs"
)
func main() {
args := szargs.New(
"A simple utility to demo counting boolean flags.",
os.Args,
)
howMany := args.Count(
"[-c | --count ...]", // Short and long forms both repeatable.
"How many times?",
)
args.Done() // All arguments should have consumed.
if args.HasErr() {
fmt.Fprintf(os.Stderr, "Error: %v\n\n%s\n", args.Err(), args.Usage())
} else {
fmt.Printf("How many: %d\n", howMany)
}
}
Top of Page --
Szargs Contents
PASS: No Arguments
go run .
How many: 0
Top of Page --
Szargs Contents
go run . --count
How many: 1
Top of Page --
Szargs Contents
go run . -c
How many: 1
Top of Page --
Szargs Contents
go run . --count -c -c
How many: 3
Top of Page --
Szargs Contents
The error is generated by the args.Done() statement causing both the
error and a usage statement to be returned.
go run . --count extraUnknownArgument
Error: unexpected argument: [extraUnknownArgument]
booleanCount
A simple utility to demo counting boolean flags.
Usage: booleanCount [-c | --count ...]
[-c | --count ...]
How many times?
Top of Page --
Szargs Contents