hzDocs

Concise Version

Best practise for project layout

Small app with a better project layout

In last examples, we show you how to create a tiny CLI app from scratch, by cmdr.

It has a clear code ochestration step by step, including how to build a cli.App object, to add commands and to add flags into it, and so on.

And, in a truth, there is another way to clearify all of above, by Create().

The Builder interface returned by Create() supports these methods: WithAdders(...) can receive a set of subcommand definitions, and adds bunch of them into app.RootCommand.

Create() is our recommendation when using cmdr.v2.

./examples/tiny1/main.go
package main
 
import (
	"context"
	"os"
 
	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/examples/cmd"
	"github.com/hedzr/cmdr/v2/pkg/logz"
)
 
const (
	appName = "concise"
	desc    = `concise version of tiny app.`
	version = cmdr.Version
	author  = `The Example Authors`
)
 
func main() {
	app := cmdr.Create(appName, version, author, desc).
		WithAdders(cmd.Commands...).
		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)
	}
}

In the subpackage cmd/, you can split each subcommand definition within a standalone file.

All of these commands will be collected as var Commands, in cmd/all.go, then passed into Create(...).WithAdders(cmd.Commands...).

So we think it is a better style.

Although it does not make the codes less.

With Store, and loading external sources

This topic will be discussed at next two sections.

The forecast is, by using loaders.Create instead of cmdr.Create, you will get it done.

How is this guide?

Edit on GitHub

Last updated on

On this page