diff --git a/apis/contexts.go b/apis/contexts.go index 4e8b60d6a..a8c7683a4 100644 --- a/apis/contexts.go +++ b/apis/contexts.go @@ -134,6 +134,12 @@ func WithinParent(ctx context.Context, om metav1.ObjectMeta) context.Context { return context.WithValue(ctx, parentMetaKey{}, om) } +// IsWithinParent returns true if we're within parent context. +func IsWithinParent(ctx context.Context) bool { + _, ok := ctx.Value(parentMetaKey{}).(metav1.ObjectMeta) + return ok +} + // ParentMeta accesses the ObjectMeta of the enclosing parent resource // from the context. See WithinParent for how to attach the parent's // ObjectMeta to the context. diff --git a/apis/contexts_test.go b/apis/contexts_test.go index 7d3e2856a..e55fddbbb 100644 --- a/apis/contexts_test.go +++ b/apis/contexts_test.go @@ -153,6 +153,16 @@ func TestContexts(t *testing.T) { ctx: WithDryRun(ctx), check: IsDryRun, want: true, + }, { + name: "within parent", + ctx: WithDryRun(ctx), + check: IsWithinParent, + want: false, + }, { + name: "in dry run", + ctx: WithinParent(ctx, metav1.ObjectMeta{Name: "jack"}), + check: IsWithinParent, + want: true, }} for _, tc := range tests {