Commit 9cfd8af3 authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

fix help

parent 3a578315
Loading
Loading
Loading
Loading
+50 −0
Original line number Diff line number Diff line
package main

import (
	"bytes"
	"io"
	"os"
	"reflect"
	"sort"
@@ -134,6 +136,26 @@ func TestHelpRunsForAllCLICommands(t *testing.T) {
	})
}

func TestCommandHelpShowsPositionalArgsInUsage(t *testing.T) {
	previous := currentLocale
	setLocale(localeFR)
	t.Cleanup(func() {
		setLocale(previous)
	})

	out := captureStdout(t, func() {
		root := newRootCmd()
		root.SetArgs([]string{"new", "--help"})
		if err := root.Execute(); err != nil {
			t.Fatalf("help execution failed for new --help: %v", err)
		}
	})

	if !strings.Contains(out, "climax new [OPTIONS] [directory]") {
		t.Fatalf("expected usage to include [directory], got:\n%s", out)
	}
}

func findSubCommand(t *testing.T, root *cobra.Command, name string) *cobra.Command {
	t.Helper()
	cmd, _, err := root.Find([]string{name})
@@ -185,3 +207,31 @@ func withDiscardedStdIO(t *testing.T, fn func()) {

	fn()
}

func captureStdout(t *testing.T, fn func()) string {
	t.Helper()

	reader, writer, err := os.Pipe()
	if err != nil {
		t.Fatalf("failed to create stdout pipe: %v", err)
	}
	defer reader.Close()

	oldOut := os.Stdout
	os.Stdout = writer
	defer func() {
		os.Stdout = oldOut
	}()

	done := make(chan string, 1)
	go func() {
		var buf bytes.Buffer
		_, _ = io.Copy(&buf, reader)
		done <- buf.String()
	}()

	fn()

	_ = writer.Close()
	return <-done
}
+13 −0
Original line number Diff line number Diff line
@@ -2484,6 +2484,8 @@ func renderHelp(cmd *cobra.Command, _ []string) {
	usage := fmt.Sprintf("%s: %s [OPTIONS]", T("help.usage_prefix"), cmd.CommandPath())
	if cmd.HasAvailableSubCommands() {
		usage += fmt.Sprintf(" %s [%s]...", T("help.command_token"), T("help.args_token"))
	} else if argsSpec := commandArgsSpec(cmd); argsSpec != "" {
		usage += " " + argsSpec
	}
	fmt.Println(usage)
	fmt.Println()
@@ -2538,6 +2540,17 @@ func renderHelp(cmd *cobra.Command, _ []string) {
	}
}

func commandArgsSpec(cmd *cobra.Command) string {
	if cmd == nil {
		return ""
	}
	parts := strings.Fields(strings.TrimSpace(cmd.Use))
	if len(parts) <= 1 {
		return ""
	}
	return strings.Join(parts[1:], " ")
}

func flagLabel(f *pflag.Flag) string {
	if f.Shorthand != "" && f.ShorthandDeprecated == "" {
		return fmt.Sprintf("-%s, --%s", f.Shorthand, f.Name)