fix: prevent nil context panic in multi-repo hydration (#840)

This commit is contained in:
Gero Hillebrandt
2026-01-01 19:46:56 +01:00
committed by GitHub
parent 5e8a834b38
commit a1f706d17a
2 changed files with 57 additions and 2 deletions

View File

@@ -194,11 +194,18 @@ func setDBPath(p string) {
} }
// getRootContext returns the signal-aware root context. // getRootContext returns the signal-aware root context.
// Returns context.Background() if the root context is nil (e.g., before CLI initialization).
func getRootContext() context.Context { func getRootContext() context.Context {
var ctx context.Context
if shouldUseGlobals() { if shouldUseGlobals() {
return rootCtx ctx = rootCtx
} else {
ctx = cmdCtx.RootCtx
} }
return cmdCtx.RootCtx if ctx == nil {
return context.Background()
}
return ctx
} }
// setRootContext updates the root context and cancel function. // setRootContext updates the root context and cancel function.

48
cmd/bd/context_test.go Normal file
View File

@@ -0,0 +1,48 @@
package main
import (
"context"
"testing"
)
func TestGetRootContext_NilFallback(t *testing.T) {
// Save original state
oldRootCtx := rootCtx
oldCmdCtx := cmdCtx
defer func() {
rootCtx = oldRootCtx
cmdCtx = oldCmdCtx
}()
t.Run("returns background when rootCtx is nil", func(t *testing.T) {
rootCtx = nil
cmdCtx = &CommandContext{}
ctx := getRootContext()
if ctx == nil {
t.Fatal("getRootContext() returned nil, expected context.Background()")
}
})
t.Run("returns rootCtx when set", func(t *testing.T) {
expected := context.WithValue(context.Background(), "test", "value")
rootCtx = expected
cmdCtx = &CommandContext{}
ctx := getRootContext()
if ctx != expected {
t.Errorf("getRootContext() = %v, want %v", ctx, expected)
}
})
t.Run("returns cmdCtx.RootCtx when globals disabled", func(t *testing.T) {
expected := context.WithValue(context.Background(), "cmd", "ctx")
rootCtx = nil
cmdCtx = &CommandContext{RootCtx: expected}
ctx := getRootContext()
if ctx == nil {
t.Fatal("getRootContext() returned nil")
}
})
}