Flag: `Head -1` style
Head like flag
Head -1 Style
GNU head utility has a special way to input a line number: head -n.
Here the n can be a positive number.
For example, head -3 means the the top 3 lines from standard input or a file.
cmdr allows you define a flag has the same behavior.
Generally the default value of a head-like flag must be a positive number. Then the end user typing -number can be converted to --flag number semantic meaning.
In a single app, only one head-like flag can be declared.
Define
.HeadLike(true) can enable head-like style for a flag.
package main
import (
"context"
"os"
"github.com/hedzr/cmdr/v2"
"github.com/hedzr/cmdr/v2/cli"
"github.com/hedzr/cmdr/v2/examples/common"
logz "github.com/hedzr/logg/slog"
)
const (
appName = "head-like"
desc = `a sample to show u how to build a facade like "head -123".`
version = cmdr.Version
author = ``
)
func main() {
app := cmdr.Create(appName, version, author, desc).
With(func(app cli.App) {}).
WithBuilders(common.AddHeadLikeFlag).
WithAdders().
Build()
ctx := context.Background()
if err := app.Run(ctx); err != nil {
logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build
os.Exit(app.SuggestRetCode())
} else if rc := app.SuggestRetCode(); rc != 0 {
os.Exit(rc)
}
}package examples
import (
"context"
"github.com/hedzr/cmdr/v2/cli"
)
func AddHeadLikeFlag(parent cli.CommandBuilder) { AddHeadLikeFlagImpl(parent) }
func AddHeadLikeFlagWithoutCmd(parent cli.CommandBuilder) { AddHeadLikeFlagImpl(parent, true) }
func AddHeadLikeFlagImpl(parent cli.CommandBuilder, dontHandlingParentCmd ...bool) { //nolint:revive
parent.Flg("lines", "l").
Description("`head -1` like", "").
Group("Head Like").
HeadLike(true).
Default(1).
Required(true).
Build()
var noHpc bool
for _, p := range dontHandlingParentCmd {
if p {
noHpc = true
}
}
if !noHpc {
// give root command an action to handle it
parent.OnAction(func(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
lines := cmd.Store().MustInt("lines")
println("using lines: ", lines)
return
})
}
parent.Examples(`Try to use head-like app,
$ $APP -567
this command request 567 lines just like "$APP --lines 567"
`)
}Run
The result of running the above example app is:
$ go run ./examples/head-like -8
using lines: 8
$ go run ./examples/head-like -123
using lines: 123
$额外的话题
What is Next?
How is this guide?
Last updated on