hzDocs

Blueprint

good practise for an app written with cmdr

Blueprint

blueprint app 展示了我们推荐的一种项目组织方法。源代码可以在 hedzr/cmdr-tests这里 找到。

all.go
soundex.go
main.go

cmdr-tests 中的 blueprint 具有完整的应用程序基础能力。 除了集成了 Store 提供的完整的配置数据管理功能之外,也包含了自动装载配置源的功能。

此外,blueprint 在所有的方面都具备基本的支持。

所以从这里开始,你可以立即投入功能性开发。

如何开始

在有了 blueprint 的基础架构之后,你可以添加子命令。

例如我们想要增加一个 hello 子命令,那么首先可以在 cmd/ 文件夹中增加一个 hello.go 源文件,内容如下:

cmd/hello.go
package cmd
 
import (
	"context"
	"fmt"
 
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/cmdr/v2/pkg/text"
)
 
type helloCmd struct{}
 
func (helloCmd) Add(app cli.App) {
	app.Cmd("hello", "hi").
		Description("hello test").
		Group("Test").
		OnAction(helloCmdRun).
		Build()
}
 
func helloCmdRun(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
	_, _ = cmd, args
	for ix, s := range args {
		fmt.Printf("%5d. %s => %s\n", ix, s, text.Soundex(s))
	}
	return
}

然后将 helloCmd{} 实例加入 cmd/all.goCommands 中:

cmd/all.go
package cmd
 
import (
	"github.com/hedzr/cmdr/v2/cli"
)
 
var Commands = append(
	[]cli.CmdAdder{
		sndx{},
    helloCmd{},
	},
	// cmd.Commands...,
)

现在 hello 子命令就添加就绪了,运行显示帮助屏将会得到下面的结果:

$ go run ./examples/blueprint/ -h
blueprint v2.1.1 ~ Copyright © 2025 by The Examples Authors ~ All Rights Reserved.
 
Usage:
 
  $ blueprint  [Options...][files...]
 
Description:
 
  a good blueprint for you.
 
Commands:
  [Test]
    snd, soundex, sndx, sound                 soundex test
    hello                                     hello test
 
Global Flags:
  [Misc]
    -h, --help,--info,--usage                 Show this help screen (-?) [Env: HELP] (Default: true)
 
Type '-h'/'-?' or '--help' to get command help screen.
More: '-D'/'--debug', '-V'/'--version', '-#'/'--build-info', '--no-color'...
 
$

devmode 一起工作

blueprint 集成了 devmode.go 来打包初始化用于开发模式的一系列状态环境:

  • debugMode, traceMode and levels of them
  • 状态同步的 logging 设置:是否允许 logz.Debug() 输出(以及 logz.Trace()
  • 自动检测 .devmode 文件是否存在并切入 DevMode

这是通过

With(func(app cli.App) {
  logz.Debug("in dev mode?", "mode", devmode.InDevelopmentMode())
}).

来达成的。

该调用在初始化时刻引用 devmode 包中的 init func 来完成环境检测和状态初始化。

配置文件

cmdr-loader 已经装配好了所有有关的基本工作,所以这样开始:

  1. 在工作目录下新建 blueprint.toml 填写如下内容
    [zoo.camel]
    grouped = false
  2. 运行 ./bin/blueprint ~~debug 查看和找到 app.zoo.canel.grouped 表项以证实配置文件正确装载。
  3. 证实 ./ci/etc/blueprint/ 的配置项已经被加载。

最后,在部署 app 时,将 ./ci/etc/blueprint/ 部署到 /etc/blueprint/,而将 ./blueprint.tomlbin/blueprint 可执行文件放在一起。

::: tip

windows

./ci/etc/blueprint/ 部署到 /etc/blueprint/ ?

macOS

./ci/etc/blueprint/ 部署到 /usr/local/etc/blueprint/ 或者 /opt/homebrew/etc/blueprint 或者 $HOME/.config/blueprint 都是可以的。

:::

:end:

How is this guide?

Edit on GitHub

Last updated on

On this page