mkideal / cli

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

Abnormal with root options #25

Closed suntong closed 8 years ago

suntong commented 8 years ago

Hi again 仕晋,

I found two issues with root options (i.e., options not for sub-commands). I've built a small example to show that, https://github.com/suntong/lang/tree/master/lang/Go/src/sys/CLI/015-fileI

$ go run main.go 
ERR! required argument --name missing
ERR! required argument --tag missing

It should show usage instead of complaining.

$ cat fi.json 
{ "ID": "1234" }

$ go run main.go -n NN -t TT
{"Help":false,"Name":"NN","Tag":"TT","ID":"","Fi":{}}{"Help":false,"Name":"NN","Tag":"TT","ID":"","Fi":{}}

The "ID" should be "1234" instead of empty, right?

mkideal commented 8 years ago
mkideal commented 8 years ago
package main

import (
    "fmt"
    "github.com/mkideal/cli"
    clix "github.com/mkideal/cli/ext"
    "os"
)

type rootT struct {
    cli.Helper
    Self *rootT       `cli:"c,config"usage:"config file" json:"-" parser:"jsonfile" dft:"fi.json"`
    Name string       `cli:"*n,name"usage:"Name (mandatory)"`
    Tag  string       `cli:"*t,tag"usage:"Tag used for record saving (mandatory)"`
    ID   string       `cli:"id"usage:"ID to use"`
    Fi   *clix.Reader `cli:"i,input"usage:"The source (or stdin if unspecified)"`
}

var root = &cli.Command{
    NumOption: cli.AtLeast(1),
    Name:      "fi",
    Desc:      "File input demo",
    Text:      "File input demo with mandatory options",
    Argv:      func() interface{} { argv := new(rootT); argv.Self = argv; return argv },
    Fn:        fi,
}

func main() {
    cli.SetUsageStyle(cli.ManualStyle) // up-down, for left-right, use NormalStyle
    //NOTE: You can set any writer implements io.Writer
    // default writer is os.Stdout
    if err := cli.Root(root).Run(os.Args[1:]); err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    fmt.Println("")
}

func fi(ctx *cli.Context) error {
    ctx.JSON(ctx.RootArgv())
    ctx.JSON(ctx.Argv())
    fmt.Println()

    return nil
}
suntong commented 8 years ago

Oh, I'm so sorry to trouble you with my own silly mistake. You saved my day. Thanks A LOT!