argparse

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

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

Go to latest
Published: May 4, 2025 License: MIT Imports: 6 Imported by: 0

README

ArgParse Go

A powerful command-line argument parser for Go applications.

Go Version License Version

ArgParse Go is a flexible and feature-rich command-line argument parsing library for Go applications. It provides intuitive APIs for defining and handling various argument types, subcommands, and validation rules.

Features

  • 📦 Easy to use, lightweight, with zero dependencies
  • 💪 Support for multiple argument types (string, int, float, bool, list, etc.)
  • 🔍 Automatic help text generation
  • 🧩 Support for subcommands
  • ✅ Required arguments and validation
  • 🔄 Default values and choices
  • 🕰️ Date/time parsing

Important Note

This library is hosted at github.com/bunnyhawper/argparse-go but uses the package name argparse for better usability. When importing the library, use:

import "github.com/bunnyhawper/argparse-go"

Then in your code, you'll refer to it simply as argparse:

parser := argparse.NewParser("myapp", "My application")

Installation

go get github.com/bunnyhawper/argparse-go

Quick Start

package main

import (
    "fmt"
    "github.com/bunnyhawper/argparse-go"
)

func main() {
    // Create a new parser
    parser := argparse.NewParser("example", "Example command-line application")
    
    // Add help and version flags
    parser.AddHelp()
    parser.AddVersion()
    
    // Add a required string argument
    parser.String("n", "name", &argparse.Argument{
        Description: "Your name",
        IsRequired:  true,
    })
    
    // Add a boolean flag
    parser.Bool("v", "verbose", &argparse.Argument{
        Description: "Enable verbose output",
        DefaultVal:  false,
    })
    
    // Add a positional argument
    parser.Positional("file", &argparse.Argument{
        Description: "File to process",
        IsRequired:  true,
    })
    
    // Parse arguments
    parser.ParseOrExit()
    
    // Use the arguments
    fmt.Printf("Hello, %s!\n", parser.GetString("name"))
    
    if parser.GetBool("verbose") {
        fmt.Println("Verbose mode enabled")
    }
    
    fmt.Printf("Processing file: %s\n", parser.GetString("file"))
}

Run with:

go run main.go -n "John Doe" -v example.txt

API Reference

Creating a Parser
parser := argparse.NewParser(name, description)
Parameters:
  • name (string): The name of your application
  • description (string): A short description of your application
Parser Methods
Setting Parser Information
parser.SetEpilog(epilog)    // Sets text to display after help message
parser.SetVersion(version)  // Sets version string
parser.AddHelp()            // Adds -h/--help option
parser.AddVersion()         // Adds -V/--version option
Adding Arguments
// Add a flag argument (general method)
parser.Flag(shortName, longName, options)

// Type-specific methods
parser.String(shortName, longName, options)    // String argument
parser.Int(shortName, longName, options)       // Integer argument
parser.Float(shortName, longName, options)     // Float argument
parser.Bool(shortName, longName, options)      // Boolean flag
parser.List(shortName, longName, options)      // List of values
parser.Counter(shortName, longName, options)   // Counter (increments with each occurrence)
parser.DateTime(shortName, longName, options)  // Date/time value

// Positional arguments
parser.Positional(name, options)
Parameters:
  • shortName (string): Short name for the argument (e.g., "v" for -v)
  • longName (string): Long name for the argument (e.g., "verbose" for --verbose)
  • name (string): Name for positional arguments
  • options (*Argument): Argument options (see below)
Argument Options

When creating arguments, you can provide an Argument struct with the following options:

&argparse.Argument{
    Description: "Description of the argument",
    IsRequired:  true,                    // Whether the argument is required
    ArgType:     argparse.String,         // Argument type (automatically set by type-specific methods)
    DefaultVal:  "default value",         // Default value if argument is not provided
    ValidChoices: []string{"opt1", "opt2"}, // Valid choices for the argument
}
Argument Modifiers

After creating an argument, you can add modifiers:

arg := parser.String("n", "name", &argparse.Argument{...})

arg.Required()              // Make the argument required
arg.Default("John Doe")     // Set a default value
arg.Help("Help text")       // Set help text
arg.Choices([]string{...})  // Set valid choices
Subcommands
// Create a subcommand
cmd := parser.NewCommand(name, description)

// Add arguments to the subcommand
cmd.Parser.String(...)
cmd.Parser.Int(...)
// etc.
Parsing Arguments
// Parse arguments and exit on error
parser.ParseOrExit()

// Parse arguments and handle errors manually
args, err := parser.Parse(os.Args[1:])
if err != nil {
    // Handle error
}
Getting Argument Values
// Get values using type-specific methods
s := parser.GetString("name")     // Get string value
i := parser.GetInt("count")       // Get integer value
f := parser.GetFloat("amount")    // Get float value
b := parser.GetBool("verbose")    // Get boolean value
l := parser.GetList("tags")       // Get list value
dt := parser.GetDateTime("date")  // Get datetime value

// Generic method (returns interface{})
val := parser.Get("name")

Argument Types

Type Description Example
String Text value -s "hello" or --string "hello"
Int Integer value -i 42 or --int 42
Float Floating-point value -f 3.14 or --float 3.14
Bool Boolean flag -b or --bool
List List of values -l "one,two,three" or --list "one,two,three"
Counter Increments with each occurrence -c -c -c (value would be 3)
DateTime Date and time value --date "2023-01-01" or --date "2023-01-01 15:30:00"

Examples

Basic Example

See the basic example for a simple application.

Subcommands Example

See the advanced example for an application with subcommands.

All Argument Types

See the complete example for an application using all argument types.

Command-line Usage

When you run your application with -h or --help, it will display automatically generated help text:

usage: example [-h] [-V] -n NAME [-b] file

Example command-line application

positional arguments:
  file                  File to process

optional arguments:
  -h, --help            Show this help message and exit
  -V, --version         Show program's version and exit
  -n, --name NAME       Your name
  -b, --verbose         Enable verbose output

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.


Created by Dhruv Rawat with ❤️

Documentation

Overview

Package argparse provides a powerful command-line argument parser for Go applications.

Version: 1.0.0 Author: Dhruv Rawat GitHub: bunnyhawper

Index

Constants

View Source
const (
	Version = "1.0.0"
	Author  = "Dhruv Rawat"
	GitHub  = "bunnyhawper"
)

Version information

Variables

This section is empty.

Functions

This section is empty.

Types

type Argument

type Argument struct {
	Name         string
	ShortName    string
	Description  string
	IsRequired   bool
	ArgType      ArgumentType
	DefaultVal   interface{}
	ValidChoices []string
	// contains filtered or unexported fields
}

Argument represents a command-line argument

func (*Argument) Choices

func (a *Argument) Choices(choices []string) *Argument

Choices sets the valid choices for the argument

func (*Argument) Default

func (a *Argument) Default(value interface{}) *Argument

Default sets the default value for the argument

func (*Argument) Help

func (a *Argument) Help(helpText string) *Argument

Help sets the help text for the argument

func (*Argument) Required

func (a *Argument) Required() *Argument

Required sets the argument as required

type ArgumentType

type ArgumentType int

ArgumentType defines the type of an argument

const (
	// String argument type
	String ArgumentType = iota
	// Int argument type
	Int
	// Float argument type
	Float
	// Bool argument type
	Bool
	// List argument type (multiple values)
	List
	// Counter argument type (counts occurrences)
	Counter
	// DateTime argument type
	DateTime
)

type Command

type Command struct {
	Parser *Parser
}

Command represents a subcommand in the parser

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser represents the argument parser

func NewParser

func NewParser(name string, description string) *Parser

NewParser creates a new argument parser

func (*Parser) AddHelp

func (p *Parser) AddHelp() *Argument

AddHelp adds a help argument to the parser

func (*Parser) AddVersion

func (p *Parser) AddVersion() *Argument

AddVersion adds a version argument to the parser

func (*Parser) Bool

func (p *Parser) Bool(shortName, longName string, options *Argument) *Argument

Bool adds a boolean argument

func (*Parser) Counter

func (p *Parser) Counter(shortName, longName string, options *Argument) *Argument

Counter adds a counter argument

func (*Parser) DateTime

func (p *Parser) DateTime(shortName, longName string, options *Argument) *Argument

DateTime adds a datetime argument

func (*Parser) Flag

func (p *Parser) Flag(shortName, longName string, options *Argument) *Argument

Flag adds a new flag argument

func (*Parser) Float

func (p *Parser) Float(shortName, longName string, options *Argument) *Argument

Float adds a float argument

func (*Parser) Get

func (p *Parser) Get(name string) interface{}

Get retrieves the value of an argument by name

func (*Parser) GetBool

func (p *Parser) GetBool(name string) bool

GetBool retrieves the bool value of an argument

func (*Parser) GetDateTime

func (p *Parser) GetDateTime(name string) time.Time

GetDateTime retrieves the datetime value of an argument

func (*Parser) GetFloat

func (p *Parser) GetFloat(name string) float64

GetFloat retrieves the float value of an argument

func (*Parser) GetInt

func (p *Parser) GetInt(name string) int

GetInt retrieves the int value of an argument

func (*Parser) GetList

func (p *Parser) GetList(name string) []string

GetList retrieves the list value of an argument

func (*Parser) GetString

func (p *Parser) GetString(name string) string

GetString retrieves the string value of an argument

func (*Parser) Int

func (p *Parser) Int(shortName, longName string, options *Argument) *Argument

Int adds an integer argument

func (*Parser) List

func (p *Parser) List(shortName, longName string, options *Argument) *Argument

List adds a list argument

func (*Parser) NewCommand

func (p *Parser) NewCommand(name string, description string) *Command

NewCommand creates a new subcommand

func (*Parser) Parse

func (p *Parser) Parse(args []string) (map[string]interface{}, error)

Parse parses the command line arguments

func (*Parser) ParseOrExit

func (p *Parser) ParseOrExit() map[string]interface{}

ParseOrExit parses command line arguments or exits on error

func (*Parser) Positional

func (p *Parser) Positional(name string, options *Argument) *Argument

Positional adds a positional argument

func (*Parser) PrintHelp

func (p *Parser) PrintHelp()

PrintHelp prints the help message

func (*Parser) SetEpilog

func (p *Parser) SetEpilog(epilog string) *Parser

SetEpilog sets the epilog text for the parser

func (*Parser) SetVersion

func (p *Parser) SetVersion(version string) *Parser

SetVersion sets the version for the parser

func (*Parser) String

func (p *Parser) String(shortName, longName string, options *Argument) *Argument

String adds a string argument

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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