hzDocs

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

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
$

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page