caddy icon indicating copy to clipboard operation
caddy copied to clipboard

caddycmd.Commands() function doesn't work

Open tozh opened this issue 11 months ago • 4 comments

In https://github.com/caddyserver/caddy/blob/9996d6a70ba76a94dfc90548f25fbac0ce9da497/cmd/commands.go#L80C1-L86C40. There is a function Commands() to get a list of commands initialised by RegisterCommand.

// Commands returns a list of commands initialised by
// RegisterCommand
func Commands() map[string]Command {
	return commands
}

var commands = make(map[string]Command)

But actually, the RegisterCommand function doesn't set the command into the commands map. It only reads from the commands map. So the funcion Commands() always return an empty map.

I wonder if the Commands() function still works.

By the way, I want to use the Commands() function get the caddy run command. Then I need to overwrite the original caddy run function to redirect its output to somewhere to remove its stdout/stderr from OS.Stdout/os.Stderr. Its output interferes with the go test output. Do you have any recommendations to achieve this?

tozh avatar Jan 30 '25 21:01 tozh

More git history found: function Commands() was introduced in #4316. And it didn't work since #4565.

tozh avatar Jan 30 '25 21:01 tozh

Hmm, @mohammed90 maybe we should look into this when we have a sec.

@tozh

Then I need to overwrite the original caddy run function to redirect its output to somewhere to remove its stdout/stderr from OS.Stdout/os.Stderr.

That seems like less of a program concern and more of a shell concern. I would just append this to your command (bash): >/dev/null 2>&1

mholt avatar Jan 30 '25 22:01 mholt

Hi @mholt ,

Thanks for your reply.

Unfortunately, I don't run caddy in bash. I am trying to compile and run caddy in go test, just like the way at https://github.com/caddyserver/caddy/blob/master/caddytest/caddytest.go#L268

os.Args = []string{"caddy", "run", "--config", f.Name(), "--adapter", "caddyfile"}

go func() {
	caddycmd.Main()
}()

tozh avatar Jan 31 '25 00:01 tozh

Regardless of which shell or execution environment, I feel like redirecting stdout/stderr is the concern of the shell or execution environment, rather than the program being executed. It's also going to be much simpler that way.

We'll look into the empty map thing though.

mholt avatar Jan 31 '25 00:01 mholt

Was working on some unrelated functionality involving (custom) commands and noticed this issue. I've opened a PR with a fix: https://github.com/caddyserver/caddy/pull/7059.

hslatman avatar Jun 11 '25 12:06 hslatman

Thanks so much @hslatman -- we hadn't gotten around to investigating yet, so we really appreciate your time and contribution here.

mholt avatar Jun 12 '25 23:06 mholt