Giter Club home page Giter Club logo

pflag's Introduction

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.

pflag's People

Contributors

alecthomas avatar asellappen avatar filbranden avatar glkz avatar ogier avatar riobard avatar schickling avatar ssgelm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pflag's Issues

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!

how to support glob?

var files = flag.StringSlice("files", "", "")

for _, file := range *files {
     fmt.Println(file)
}
./p --files a b c -b xxx

which prints:
a
b
c
#now if I got three files
$ ls *.txt
a.txt b.txt c.txt

./p --files *.txt -b xxx
#shall print:
a.txt
b.txt
c.txt

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!

Flags aren't being registered/looked up correctly

I register two flags, then look them up. The short-hand and descriptions are not correct. They are swapped around with each other. Unless there's user error involved.

INFO[0000] "tenant-id" "azure subscription id" *pflag.Flag
INFO[0000] "subscription-id" "azure tenant id" *pflag.Flag

https://gist.github.com/anonymous/94dccf42b133a425f41e:

package main

import (
    log "github.com/Sirupsen/logrus"
    "github.com/spf13/cobra"
)

func main() {
    if err := NewRootCmd().Execute(); err != nil {
        log.Fatalln(err)
    }
}

type Args struct {
    TenantID       string
    SubscriptionID string
}

var args Args

func NewRootCmd() *cobra.Command {
    var rootCmd = &cobra.Command{
        Use: "root",
    }

    rootCmd.Flags().StringVar(&args.TenantID, "tenant-id", "", "azure subscription id")
    rootCmd.Flags().StringVar(&args.SubscriptionID, "subscription-id", "", "azure tenant id")

    x := rootCmd.Flags().Lookup("tenant-id")
    log.Infof("%q %q %T", x.Name, x.Usage, x)
    // prints: INFO[0000] "tenant-id" "azure subscription id" *pflag.Flag

    x = rootCmd.Flags().Lookup("subscription-id")
    log.Infof("%q %q %T", x.Name, x.Usage, x)
    // prints: INFO[0000] "subscription-id" "azure tenant id" *pflag.Flag

    return rootCmd
}

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!

"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

Possible to have short flag without a long flag?

I'm probably missing something obvious, but how do I use pflag so that the only valid option is the short variant? That is, if I want just "-h" rather than something like "-h" and "--help"?

If I use:

flag.BoolVar(&help, "h", false, "Give help")

then Parse() requires --h

If I use:

flag.BoolVarP(&help, "", "h", false, "Give help")

then Parse() requires "-h" and the odd "--" whereas I was hoping an empty long-opt would have deactivated that variant.

I'm pretty sure that Posix/GNU do not insist on both variants of an option, but I've been wrong before.

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 :)

Are multiple flags supported?

Does this library support passing multiple flags of the same key?

e.g. --something=... --something=... --something=...
parsed to [...,...,...]

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 :)

Tagged releases?

I've just started using gpm to manage dependency versions. Could I persuade you to tag a release?

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?

Use default value for non-bool flag when there's no value supplied

Currently only flag.Bool can be used as --flag without supplying a value. There's some situation when non-bool flag should be able to use default value when no value was supplied.

E.g. the ls command in coreutils have a --color string flag. When there's no value supplied, it assume to be always. Right now there's no way to do the same using pflag

Support importing existing flag package flags

This is important for packages (like https://github.com/golang/glog) where the flags are embedded deeply into the code.

I already have this supported in kubernetes here that we can borrow/steal:
https://github.com/GoogleCloudPlatform/kubernetes/blob/master/pkg/util/plog_import.go

(I typo'd the name of that file and I'll fix it up soon).

This would be a lot easier if the pflag.Value.Type didn't exist or was an extended optional interface. It is unclear why that is there and where it is used.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.