Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Overview

Build Status

Description

pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

pflag is compatible with the GNU extensions to the POSIX recommendations for command-line options. For a more precise description, see the "Command-line flag syntax" section below.

pflag is available under the same style of BSD license as the Go language, which can be found in the LICENSE file.

Installation

pflag is available using the standard go get command.

Install by running:

go get github.com/ogier/pflag

Run tests by running:

go test github.com/ogier/pflag

Usage

pflag is a drop-in replacement of Go's native flag package. If you import pflag under the name "flag" then all code should continue to function with no changes.

import flag "github.com/ogier/pflag"

There is one exception to this: if you directly instantiate the Flag struct there is one more field "Shorthand" that you will need to set. Most code never instantiates this struct directly, and instead uses functions such as String(), BoolVar(), and Var(), and is therefore unaffected.

Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type *int.

var ip *int = flag.Int("flagname", 1234, "help message for flagname")

If you like, you can bind the flag to a variable using the Var() functions.

var flagvar int
func init() {
    flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}

Or you can create custom flags that satisfy the Value interface (with pointer receivers) and couple them to flag parsing by

flag.Var(&flagVal, "name", "help message for flagname")

For such flags, the default value is just the initial value of the variable.

After all flags are defined, call

flag.Parse()

to parse the command line into the defined flags.

Flags may then be used directly. If you're using the flags themselves, they are all pointers; if you bind to variables, they're values.

fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)

After parsing, the arguments after the flag are available as the slice flag.Args() or individually as flag.Arg(i). The arguments are indexed from 0 through flag.NArg()-1.

The pflag package also defines some new functions that are not in flag, that give one-letter shorthands for flags. You can use these by appending 'P' to the name of any function that defines a flag.

var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
    flag.BoolVarP("boolname", "b", true, "help message")
}
flag.VarP(&flagVar, "varname", "v", 1234, "help message")

Shorthand letters can be used with single dashes on the command line. Boolean shorthand flags can be combined with other shorthand flags.

The default set of command-line flags is controlled by top-level functions. The FlagSet type allows one to define independent sets of flags, such as to implement subcommands in a command-line interface. The methods of FlagSet are analogous to the top-level functions for the command-line flag set.

Command line flag syntax

--flag    // boolean flags only
--flag=x

Unlike the flag package, a single dash before an option means something different than a double dash. Single dashes signify a series of shorthand letters for flags. All but the last shorthand letter must be boolean flags.

// boolean flags
-f
-abc

// non-boolean flags
-n 1234
-Ifile

// mixed
-abcs "hello"
-abcn1234

Flag parsing stops after the terminator "--". Unlike the flag package, flags can be interspersed with arguments anywhere on the command line before this terminator.

Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags (in their long form) accept 1, 0, t, f, true, false, TRUE, FALSE, True, False. Duration flags accept any input valid for time.ParseDuration.

More info

You can see the full reference documentation of the pflag package at godoc.org, or through go's standard documentation system by running godoc -http=:6060 and browsing to http://localhost:6060/pkg/github.com/ogier/pflag after installation.

Issues
  • Disallow interspersed options/non-options

    Disallow interspersed options/non-options

    This is very useful in conjunction with FlagSets for supporting "commands" with differing sets of options.

    eg.

    cmd --loglevel=debug ls -la
    cmd run --command=/bin/ls
    

    Where the arguments to the ls and run commands are in different FlagSets. Without this capability, FlagSets are quite a bit less useful.

    I personally prefer this as the default, but it may not be what you want. If that is the case I can modify the patch to optionally allow interspersed options via an alternate Parse() entry point.

    opened by alecthomas 5
  • Support space as the delimiter for long arguments

    Support space as the delimiter for long arguments

    Most cli tools I use have a space character to delimit the flag and it's option, and it would be cool to be able to do so for pflag. I realize this would be yet another departure from the flag stdlib, but it would definitely be cool to have.

    I tried just changing https://github.com/ogier/pflag/blob/master/flag.go#L429 to a space character, but it seems I'll also need to change something in FlagSet, just not sure where. Would be happy to make a PR adding another method that configures this and make the requisite changes given some direction :)

    opened by josegonzalez 4
  • Missing flag prints name of the first flag, not the missing flag.

    Missing flag prints name of the first flag, not the missing flag.

    consider a command foo --bar --baz

    where --bar is defined, but --baz isn't.

    pflag prints unknown flag: --bar even though the actual offending flag is --baz

    opened by brendandburns 4
  •  Add poweron architecture ppc64le to travis build

    Add poweron architecture ppc64le to travis build

    This is part of the Ubuntu distribution for ppc64le. This helps us simplify testing later when distributions are re-building and re-releasing, For more info please tag @gerrith3.

    opened by asellappen 3
  • Consistent documented parsing for stringtostring

    Consistent documented parsing for stringtostring

    I'm having some trouble passing an element of a map to stringtostring, where the value may or may not contain equal signs, quotes, and/or commas. It seems there is no normative passing, quoting, escaping mechanism.

    The documentation says the items won't be split on commas, but if they contain an equal sign, they are. Then to have the commas and quotes preserved, they must be quoted: but this won't be correct if they don't contain an equal sign, no?

    opened by xloem 2
  • Parsing ranges apart from single values

    Parsing ranges apart from single values

    Is there any functionality to parse ranges as flags. For example the namp tool takes a range of ports to scan nmap HOST -p 10-100

    This would scan ports in the range 10 to 100. Similar functionalities being implemented would be helpful!

    opened by Gituser143 2
  • "Help" flag to list flags

    Hi, is there a way to don't lose the -h flag that in the standard library produce a list of all flags registered?

    Hi have register a flag:

    var userID *int = pflag.IntP("user", "u", 0, "User ID")
    
    flag.Parse()
    
    fmt.Printf("User ID %v\n", *userID)
    

    if I run go run main.go -h I get this message:

    Usage of /tmp/go-build252835213/command-line-arguments/_obj/exe/main:
    exit status 2
    

    Thanks

    opened by matiux 2
  • More data types. Each in a separate file.

    More data types. Each in a separate file.

    Now we cover complete integer and float types, including (u)int(8,16,32,64) and float(32,64).

    Two data types from net package are also included: net.IP and net.IPMask.

    opened by riobard 2
  • Is it possible to change source of flags ?

    Is it possible to change source of flags ?

    Hello,

    I'm wondering if it's possible to change source of flags. For the moment you seems to use os.Args to parse flags. Is it possible to change this source like giving an array ?

    Thanks :)

    opened by raskyer 1
  • Shorthand only flags

    Shorthand only flags

    I wanted flags that can only be specified as -f and not --f. Mainly because it allows for the help to look better. I think this type of flag is mostly useful for bool flags, but I added convenience methods/functions for all flag types by adding S to the name: BoolS. For BoolS("f", false, "blah") the help is: -f=false: blah.

    opened by ThinkChaos 1
  • Add ability to disable interspersed option support.

    Add ability to disable interspersed option support.

    This is very useful in conjunction with FlagSets for supporting "commands" with differing sets of options.

    eg.

    cmd --loglevel=debug ls -la
    cmd run --command=/bin/ls
    

    Where the arguments to the ls and run commands are in different FlagSets. Without this capability, FlagSets are quite a bit less useful.

    opened by alecthomas 1
  • How to check which flag has been given as input in the cli?

    How to check which flag has been given as input in the cli?

    If I've got multiple flags, say, like this:

    --user="something"
    --language="blah"
    --starCount=2
    ....
    ...
    ...
    

    then how to check which flag has been given input in the cli? Because different flag has different functionality.

    opened by SamsadSajid 0
  • Add support for IsSpecified

    Add support for IsSpecified

    Removes Init method to standardize on NewFlagSet.

    This method can be used to check if a flag was specified by the user.

    (I noticed a similar attempt was done in #8 but didn't know at the time I wrote this, which is arguably a smaller changeset)

    opened by gdm85 0
  • Is it still maintained or the maintained version is spf13 fork?

    Is it still maintained or the maintained version is spf13 fork?

    Hello,

    I would like to confirm if this package is still maintained or basically the maintained fork is https://github.com/spf13/pflag.

    In case that the mentioned fork is the maintained version, could you please add a note at the beginning of the README; I think that it will be very useful for the people who lands in the repo browsing in Google.

    Many thanks.

    opened by ifraixedes 4
  • Parse positional argument and arcs with prefix always fail.

    Parse positional argument and arcs with prefix always fail.

    Hi, things is I want parse 2 bool args, but there is a positional arg, like this:

    gofind ./ -d -f

    ./ is a positional arg, but once I add this , -d -f cannot parse which is default by false , so it should be true if set. But always false. How to parse them? and what if I want using

    -d -f as -df just like tar -xvf? Many thanks if can get a reply or advise!

    opened by jinfagang 0
  • FlagSet should be an interface

    FlagSet should be an interface

    I spent a bit scratching my head trying to figure out why my flags weren't being set/parsed correctly. The issue was that I was using f := pflag.FlagSet{} instead of f := pflag.NewFlagSet(...)

    Making an interface would be a simple way to make the behavior more obvious. Thanks!

    opened by buchanae 0
Releases(v0.0.1)
Owner
Alex Ogier
Alex Ogier
A Go library for implementing command-line interfaces.

Go CLI Library cli is a library for implementing powerful command-line interfaces in Go. cli is the library that powers the CLI for Packer, Serf, Cons

Mitchell Hashimoto 1.5k Jun 23, 2022
Drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.

Description pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. pflag is compatible with the GNU extensions to

Alex Ogier 516 Jun 24, 2022
Package varflag implements command-line flag parsing into vars.Variables for easy type handling with additional flag types.

varflag Package flag implements command-line flag parsing into vars.Variables for easy type handling with additional flag types. varflag Flags String

Marko Kungla 2 Feb 11, 2022
Golang library with POSIX-compliant command-line UI (CLI) and Hierarchical-configuration. Better substitute for stdlib flag.

cmdr cmdr is a POSIX-compliant, command-line UI (CLI) library in Golang. It is a getopt-like parser of command-line options, be compatible with the ge

hz 109 Jun 28, 2022
Gos: Armed Golang 💪 ( solutions for go module, goproxy, cross compilation, etc.)

The current gos is still an alpha version, welcome more heroes to comment and improve it ?? , you can add more commands to it, or modify something to make it perform better.

storyicon 373 Jun 16, 2022
Drop-in replacement for the standard library errors package and github.com/pkg/errors

Emperror: Errors Drop-in replacement for the standard library errors package and github.com/pkg/errors. This is a single, lightweight library merging

Emperror 149 Jun 29, 2022
Golang (Go) bindings for GNU's gettext (http://www.gnu.org/software/gettext/)

gosexy/gettext Go bindings for GNU gettext, an internationalization and localization library for writing multilingual systems. Requeriments GNU gettex

Go toolbelt 61 Jun 6, 2022
Highly concurrent drop-in replacement for bufio.Writer

concurrent-writer Highly concurrent drop-in replacement for bufio.Writer. concurrent.Writer implements highly concurrent buffering for an io.Writer ob

Alin Sinpalean 44 Jun 21, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Kamaleshwar 42 May 18, 2022
Zero downtime restarts for go servers (Drop in replacement for http.ListenAndServe)

endless Zero downtime restarts for golang HTTP and HTTPS servers. (for golang 1.3+) Inspiration & Credits Well... it's what you want right - no need t

Florian von Bock 3.5k Jun 21, 2022
A high-performance 100% compatible drop-in replacement of "encoding/json"

A high-performance 100% compatible drop-in replacement of "encoding/json" You can also use thrift like JSON using thrift-iterator Benchmark Source cod

Jsoniter 11k Jun 30, 2022
a simple & tiny scrapy clustering solution, considered a drop-in replacement for scrapyd

scrapyr a very simple scrapy orchestrator engine that could be distributed among multiple machines to build a scrapy cluster, under-the-hood it uses r

Mohammed Al Ashaal 50 Nov 24, 2021
🔥 ~6x faster, stricter, configurable, extensible, and beautiful drop-in replacement for golint

revive Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. Revive provides a framework for developme

Minko Gechev 3.6k Jun 25, 2022
A high-performance 100% compatible drop-in replacement of "encoding/json"

A high-performance 100% compatible drop-in replacement of "encoding/json" You can also use thrift like JSON using thrift-iterator Benchmark Source cod

Jsoniter 11k Jun 23, 2022
drpc is a lightweight, drop-in replacement for gRPC

drpc is a lightweight, drop-in replacement for gRPC

Storj Labs 1.1k Jun 25, 2022
Drop-in replacement for Go net/http when running in AWS Lambda & API Gateway

Package gateway provides a drop-in replacement for net/http's ListenAndServe for use in AWS Lambda & API Gateway, simply swap it out for gateway.Liste

Apex 626 Jun 28, 2022
Drop-in replacement for Go's stringer tool with support for bitflag sets.

stringer This program is a drop-in replacement for Go's commonly used stringer tool. In addition to generating String() string implementations for ind

null 0 Nov 26, 2021
twtr (pronounced "tweeter") is a drop-in replacement of the original twtxt client

twtr twtr (pronounced "tweeter") is a drop-in replacement of the original twtxt client, with some extensions and bonus features, so you can make the s

~duriny 1 Jun 24, 2022
A drop-in replacement to any Writer type, which also calculates a hash using the provided hash type.

writehasher A drop-in replacement to any Writer type, which also calculates a hash using the provided hash type. Example package main import ( "fmt"

Max 0 Jan 10, 2022
Goslmailer (GoSlurmMailer) is a drop-in replacement MailProg for slurm

GoSlurmMailer - drop in replacement for default slurm MailProg. Delivers slurm job messages to various destinations.

PetarJ 2 May 16, 2022
Dependency-free replacement for GNU parallel, perfect fit for usage in an initramfs.

coshell v0.2.5 A no-frills dependency-free replacement for GNU parallel, perfect for initramfs usage. Licensed under GNU/GPL v2. How it works An sh -c

gdm85 41 May 11, 2022
GNU-stow replacement to manage my dotfiles

Basically a replacement to GNU Stow for my use cases: TODO package for Homebrew add --dotfiles true|false flag add --script filename.sh flag that prin

Benjamin Kane 13 Jun 2, 2022
LeetCode in Go with the code style strictly follows the Google Golang Style Guide

LeetCode in Go LeetCode Online Judge is a website containing many algorithm questions. Most of them are real interview questions of Google, Facebook,

null 0 Nov 13, 2021
The standard library flag package with its missing features

cmd Package cmd is a minimalistic library that enables easy sub commands with the standard flag library. This library extends the standard library fla

Eyal Posener 33 Sep 23, 2021
A collection of CLI argument types for the Go `flag` package.

flagvar A collection of CLI argument types for the flag package. import "github.com/sgreben/flagvar" Or just copy & paste what you need. It's public d

Sergey Grebenshchikov 39 Jun 6, 2022
Go (Golang) GNU gettext utilities package

Gotext GNU gettext utilities for Go. Features Implements GNU gettext support in native Go. Complete support for PO files including: Support for multil

Leonel Quinteros 342 Jun 29, 2022
Interactive package manager and resource monitor designed for the GNU/Linux.

pkgtop is an interactive package manager & resource monitor tool designed for the GNU/Linux. Package management (install/upgrade/remove etc.) can be a

Orhun Parmaksız 244 Jul 1, 2022
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Eric Greer 801 Jun 22, 2022
getopt-like flags package for golang,

goopt A getopt-like processor of command-line flags. It works much like the "flag" package, only it processes arguments in a way that is compatible wi

David Roundy 81 Jun 2, 2022