mkideal / cli

CLI - A package for building command line app with go
MIT License
730 stars 43 forks source link

IsSet always returns false #62

Closed chrjen closed 3 years ago

chrjen commented 3 years ago

v0.2.7, although using previous versions didn't seem to help.

I'm trying to figure out if a flag is present or not as I only want to use the value if it was specified. I tried using IsSet though it doesn't seem to work. Example program,

package main

import (
    "fmt"
    "os"

    "github.com/mkideal/cli"
    clix "github.com/mkideal/cli/ext"
)

type argT struct {
    Name string    `cli:"name" usage:"read name"`
    Time clix.Time `cli:"time" usage:"read text"`
}

func main() {
    os.Exit(cli.Run(new(argT), func(ctx *cli.Context) error {
        argv := ctx.Argv().(*argT)

        fmt.Println(ctx.IsSet("name"), ctx.IsSet("time"))
        fmt.Println(argv.Name, argv.Time)

        return nil
    }))
}

Output:

% ./cli
false false
 0001-01-01 00:00:00 +0000 UTC
% ./cli maing.go --name Frank --time 2021-08-10
false false
Frank 2021-08-10 00:00:00 +0000 UTC

Shouldn't IsSet return true here? The problem seems to be because ctx.flagSet.flagMap is always empty.

suntong commented 3 years ago

From https://pkg.go.dev/github.com/mkideal/cli?utm_source=godoc#Context.IsSet:

IsSet determins whether flag is set

I.e., it is meant to work for the "flag" option, not the normal options as shown in OP.

For example of the "flag" option, see:
https://github.com/suntong/lang/tree/master/lang/Go/src/sys/cli#002-flaggo

See also #31, which is yet to be implemented.

mkideal commented 3 years ago

Preappend double ‘-‘ to long flag name, one ‘-‘ to short flag name, e.g.

ctx.IsSet(“—name”) ctx.IsSet(“-v”)

Sent from my iPhone

On Aug 10, 2021, at 16:21, Christer Jensen @.***> wrote:

ctx.IsSet("time"))

chrjen commented 3 years ago

Thank you! Yes, that seems to work.