From 3912d67d76791790e7d5ae07d717c92bc8e6cc21 Mon Sep 17 00:00:00 2001
From: Fraser Waters <fraser@pulumi.com>
Date: Thu, 20 Feb 2025 15:03:24 +0000
Subject: [PATCH] Flow context to command in SetHelpFunc

Fixes https://github.com/spf13/cobra/issues/2240
---
 command.go      |  5 +++++
 command_test.go | 27 +++++++++++++++++++++++++++
 2 files changed, 32 insertions(+)

diff --git a/command.go b/command.go
index dbb2c298..140fbfdf 100644
--- a/command.go
+++ b/command.go
@@ -1296,6 +1296,11 @@ Simply type ` + c.DisplayName() + ` help [path to command] for full details.`,
 					c.Printf("Unknown help topic %#q\n", args)
 					CheckErr(c.Root().Usage())
 				} else {
+					// FLow the context down to be used in help text
+					if cmd.ctx == nil {
+						cmd.ctx = c.ctx
+					}
+
 					cmd.InitDefaultHelpFlag()    // make possible 'help' flag to be shown
 					cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown
 					CheckErr(cmd.Help())
diff --git a/command_test.go b/command_test.go
index 7e7c3418..0c7aae74 100644
--- a/command_test.go
+++ b/command_test.go
@@ -2921,3 +2921,30 @@ func TestUnknownFlagShouldReturnSameErrorRegardlessOfArgPosition(t *testing.T) {
 		})
 	}
 }
+
+func TestHelpFuncExecuted(t *testing.T) {
+	helpText := "Long description"
+
+	child := &Command{Use: "child", Run: emptyRun}
+	child.SetHelpFunc(func(cmd *Command, args []string) {
+		_, err := cmd.OutOrStdout().Write([]byte(helpText))
+		if err != nil {
+			t.Error(err)
+		}
+
+		// Test for https://github.com/spf13/cobra/issues/2240
+		if cmd.Context() == nil {
+			t.Error("Context is nil")
+		}
+	})
+
+	rootCmd := &Command{Use: "root", Run: emptyRun}
+	rootCmd.AddCommand(child)
+
+	output, err := executeCommand(rootCmd, "help", "child")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+
+	checkStringContains(t, output, helpText)
+}