Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newbie question: how to _really_ change CommandHelpTemplate and where did AppHelpTemplate go? (v3) #2062

Open
GwynethLlewelyn opened this issue Feb 22, 2025 · 5 comments
Labels
area/v3 relates to / is being considered for v3 kind/discussion is for discussion kind/question someone asking a question status/triage maintainers still need to look into this status/waiting-for-response Waiting for response from original requester

Comments

@GwynethLlewelyn
Copy link

GwynethLlewelyn commented Feb 22, 2025

Hi there 👋 I'm currently using v3 to do some quick & dirty CLI applications. I've been often overwhelmed by the sheer size and complexity of this package, considering that the 'official' documentation just covers the bare essentials, and there are levels and levels of goodies hidden below the surface, if only you can understand how they all fit together.

A few of my odd experiments are targeted to a non-English-speaking audience. While I'm well aware that the whole issue of internationalisation/localisation of cli is postponed sine die, I have some questions regarding the proper use of the template system, with which a lot can already been done (and, most importantly, tweaked for specific purposes.

I seem to have no issues whatsoever with RootCommandHelpTemplate — I can change it at will, and even those non-public templates it pulls in can be simply copied & pasted to the template (and then freely edited), and the 'root' or 'main' help does, indeed, use this template.

Changing CommandHelpTemplate is another story: when I call my 'override' at the very beginning — i.e., before any command has been defined, it simply gets completely ignored, and the package continues to use its internally defined one. I haven't delved deep into the code to try to understand why.

If called just before cli.Run() is called, then it does work — almost always. It just fails when calling help for a second alias, something that probably nobody in their right mind will have anyway. In my case, I discovered that by sheer luck — since, besides the usual help command, with the h alias, I had defined another one, ajuda, which stands for, well, 'help', in Portuguese 🇵‍🇹 .

More specifically, as far as I can test:

Command & parameters Template being used
my-cmd help oneCmd My overridden template
my-command help help My overridden template
my-command help h My overridden template
my-command help ajuda Original template
my-command ajuda help My overridden template

Curious, isn't it? (as said, I didn't look up the code for displaying help for the help aliases).

Last question... what exactly is the AppHelpTemplate, and under which circumstances can it be used? It figures extensively in the documentation (and elsewhere), but I can't find it anywhere in the v3 code itself. Is it something specific to pre-v3 versions, and just not consistently updated elsewhere? Was this template discontinued — or replaced by a different one? If so, what's the name of the replacement, please? I can't find anything similarly named — certainly it's not on templates.go for sure.

Alas, now I just need all other templates to be able to be overridden as well, and then I'll be a happy girl 👯‍♀️👧🤗
Maybe for v4...

@GwynethLlewelyn GwynethLlewelyn added area/v2 relates to / is being considered for v2 kind/question someone asking a question status/triage maintainers still need to look into this labels Feb 22, 2025
@dearchap dearchap added kind/discussion is for discussion area/v3 relates to / is being considered for v3 and removed area/v2 relates to / is being considered for v2 labels Feb 23, 2025
@dearchap
Copy link
Contributor

@GwynethLlewelyn thank you for the thorough post. I'm AFK so I can't reply to each and every point right now but I'll try to get to them in the next day or so. Some quick thoughts, AppHelpTemplate is for v2 versions only. It's been removed in v3 and the SubcommandTemplate/CommandTemplate will be used depending on whether the root command has sub commands or not . i8n is a different beast. I've tried to work on it many times but ran into issues so I'm unable to pursue it

@dearchap
Copy link
Contributor

@GwynethLlewelyn The AppHelpTemplate was renamed to RootCommandHelpTemplate. In addition there are CommandHelpTemplate and SubcommandHelpTemplate. Can you give me a sample of your code ?

@dearchap dearchap added the status/waiting-for-response Waiting for response from original requester label Feb 24, 2025
@GwynethLlewelyn
Copy link
Author

GwynethLlewelyn commented Feb 26, 2025

Ah! Regarding the name change, I suspected as much — maybe some nice volunteer might update the v3 documentation then? 😅🙏

As for the code, I might not be allowed to show it all (complex NDA issues, sorry, even though this particular example is absolutely 'harmless') — which is a pity, really — but I can give you a taste. It's meant to be a very basic CLI to allow communication with a Redis server, with only the essential commands and nothing else. The language used on the original comments in the code is Portuguese, while my 'comments on comments' are in English. Those parts that can be safely shared are shown below...

Note how cli.RootCommandHelpTemplate is set at the very top, and this works; by contrast, doing the same with the cli.CommandHelpTemplate ignores it. The way to get it working on some cases (i.e., the ones mentioned at the top) is to register it at the very end — so there is merely a constant string defined at the top, which gets assigned at the end, just before cli.Run() is called.

Unless, of course, this template needs to be instantiated on all commands individually... I thought of that as well, but I couldn't find a field in the cli structure that allowed that (unless it's a private field, accessible via a getter of some sort, which is not mentioned in the documentation, either — but I did not check in the code, so it might be there...).

You'll also notice that the templates are essentially the same as the original ones — just with a few words translated to Portuguese, and that's pretty much it. I don't quite remember if I have deleted something from the templates which isn't currently being used, though...

Code snippet here ↩️

// lots of initialisation code, which results in having a Redis server operational on the `rdb` handle.

func main() {
	// Verificar se o servidor Redis está operacional:
	if status := rdb.Ping(ctx); status != nil {
		val, err := status.Result()
		if err != nil {
			log.Fatalf("Ao tentar entrar em contato com o servidor Redis, ocorreu um erro: %v\n", err)
		}
		log.Printf("Servidor Redis operacional: %q", val)
	}

	// Tradução dos modelos de ajuda para o português:
	cli.RootCommandHelpTemplate = `NOME:
{{template "helpNameTemplate" .}}

UTILIZAÇÃO:
   {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[opções globais]{{end}}{{if .VisibleCommands}} [comando [opções do comando]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}}

VERSÃO:
   {{.Version}}{{end}}{{end}}{{if .Description}}

DESCRIÇÃO:
{{template "descriptionTemplate" .}}{{end}}
{{- if len .Authors}}

AUTORIA:{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}}

COMANDOS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}}

OPÇÕES GLOBAIS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}

OPÇÕES GLOBAIS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}}

COPYRIGHT:
   {{template "copyrightTemplate" .}}{{end}}
`
	const commandHelpTemplate = `NOME:
{{template "helpNameTemplate" .}}

UTILIZAÇÃO:
   {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleFlags}} [comando [opções do comando]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} {{template "argsTemplate" .}}{{end}}{{end}}{{end}}{{if .Category}}

CATEGORIA:
   {{.Category}}{{end}}{{if .Description}}

DESCRIÇÃO:
   {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}}

OPÇÕES:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}}

OPÇÕES:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}}

OPÇÕES GLOBAIS:{{template "visiblePersistentFlagTemplate" .}}{{end}}
`
	// cmd é a estrutura fundamental do `urfave/cli`: toda a funcionalidade
	// do aplicativo é definida aí.
	cmd := &cli.Command{
		Name: "clitest",
		Version: "v0.0.1",
		Usage: "acede aos pares chave/valor em um servidor Redis local",
		HideHelpCommand: true,
		Commands: []*cli.Command{
			{
				Name:  "set",
				Usage: "Define o valor de uma chave, com duração temporal opcional.",
				ArgsUsage: "chave valor [duração temporal]",
				HideHelp: true,
				Action: func(ctx context.Context, cmd *cli.Command) error {
					var estampaTemporal time.Duration	// Conversão da duração num time.Duration.
					var erro error	// Lidando com questões de escopo.
					nArgs := cmd.NArg()

	// bla bla bla bla... skipping the remaining definition of the basic commands...
	// At the very end, the help flag gets overridden as well; this only works after-the-fact, i.e., after
	// the `cmd` has been fully instantiated. 
	// 
	}

	cli.HelpFlag = &cli.BoolFlag{
		Name:    "help",
		Aliases: []string{"h", "ajuda"},
		Usage:   "mostra a ajuda",
	}

	cli.CommandHelpTemplate = commandHelpTemplate

	if erro := cmd.Run(ctx, os.Args); erro != nil {
		log.Fatal(erro)
	}
}
// EOF!

In any case, thanks so much for your willingness to have a look at this issue! I suspect that it's merely an issue of understanding how to properly set things up — since some of the differences between v2 and v3 weren't updated on the docs yet...

@GwynethLlewelyn
Copy link
Author

Whoops, and I'm very sorry for my delay in replying...

@dearchap
Copy link
Contributor

@GwynethLlewelyn Thanks for the example. RootCommandHelpTemplate and CommandHelpTemplate are global variables so it would be prudent to set them before calling cmd.Run . You can set the CustomHelpTemplate in Command to have a separate template for each Command. The example you provided does not have any issues.

$ go run .
NOME:
clitest - acede aos pares chave/valor em um servidor Redis local

UTILIZAÇÃO:
   clitest [opções globais] [comando [opções do comando]]

VERSÃO:
   v0.0.1

COMANDOS:
   set  Define o valor de uma chave, com duração temporal opcional.

OPÇÕES GLOBAIS:
   --help, -h, --ajuda  mostra a ajuda (default: false)
   --version, -v        print the version

and

$ go run . set -h
NOME:
clitest set - Define o valor de uma chave, com duração temporal opcional.

UTILIZAÇÃO:
   clitest set chave valor [duração temporal]

OPÇÕES GLOBAIS:
   --help, -h, --ajuda  mostra a ajuda (default: false)

and

$ go run . -h set 
NOME:
clitest set - Define o valor de uma chave, com duração temporal opcional.

UTILIZAÇÃO:
   clitest set chave valor [duração temporal]

OPÇÕES GLOBAIS:
   --help, -h, --ajuda  mostra a ajuda (default: false)

So I'm still unclear what the actual problem is. Is it possible you have further subcommands under "set" ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/v3 relates to / is being considered for v3 kind/discussion is for discussion kind/question someone asking a question status/triage maintainers still need to look into this status/waiting-for-response Waiting for response from original requester
Projects
None yet
Development

No branches or pull requests

2 participants