hzDocs

Flag: External Editor

Using external editor

Get text by launch an external editor

git tool has a command commit, which flag -m msg supports lauching shell editor to get text input with -m msg. If user gived a command line git commit -m without msg, git will find shell program identified by EDITOR envvar (constantly it's vim or nano) and launch it, and waiting the user's input, and return the input text as message of -m after editor closed.

cmdr allows you define a flag with the same behavior.

A flag with using ExternalEditor(envVarName) will get the interactive actions like git -m.

The envVarName is the envvar name.

While you have a definition EDITOR=nano in the OS environment, ExternalEditor("EDITOR") will launch nano and wait for the user's input, and return the input text as the flag's value finally.

Sometimes, you may try launch a different editor/viewer via envVarName like LESS, or MAN, or else.

Totally the flag' default value must by a string.

Define

.ExternalEditor(envVarName) can enable External Editor feature 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 = "external-editor"
	desc    = `a sample to show u how to use external editor flag.`
	version = cmdr.Version
	author  = `The Example Authors`
)
 
func main() {
	app := cmdr.Create(appName, version, author, desc).
		With(func(app cli.App) {
			app.OnAction(func(ctx context.Context, cmd cli.Cmd, args []string) (err error) {
				msg := cmd.Store().MustString("message")
				println(`Hello, World.`, msg)
				return
			})
		}).
		WithBuilders(common.AddExternalEditorFlag).
		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 above app can have the following result:

$ go run ./examples/external-editor -m 123
Hello, World. 123
$ go run ./examples/external-editor -m
(open nano and waiting for user's input...)
Hello, World. dsada
 
$

额外的话题

How is this guide?

Edit on GitHub

Last updated on

On this page