Skip to content

Commit

Permalink
adds WithNamespace ability to contexts
Browse files Browse the repository at this point in the history
  • Loading branch information
gab-satchi committed Jan 12, 2022
1 parent 96f1852 commit c0eba4e
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
16 changes: 16 additions & 0 deletions apis/contexts.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,22 @@ func IsWithinParent(ctx context.Context) bool {
return ok
}

type namespaceKey struct{}
// WithNamespace attaches the request's namespace. Intended to be used
// where defaulting depends on the namespace (eventing channels, brokers)
// and the client may not provide it in the resource ObjectMeta
func WithNamespace(ctx context.Context, ns string) context.Context {
return context.WithValue(ctx, namespaceKey{}, ns)
}

func GetNamespace(ctx context.Context) string {
if ns, ok := ctx.Value(namespaceKey{}).(string); ok {
return ns
}

return ""
}

// 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.
Expand Down
15 changes: 15 additions & 0 deletions apis/contexts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,18 @@ func TestGetHTTPRequest(t *testing.T) {
t.Errorf("GetHTTPRequest() = %v, wanted %v", got, want)
}
}

func TestGetNamespace(t *testing.T) {
ctx := context.Background()

if got := GetNamespace(ctx); got != "" {
t.Errorf("GetNamespace() = \"%v\", wanted \"\"", got)
}

ns := "some-namespace"
ctx = WithNamespace(ctx, ns)

if want, got := ns, GetNamespace(ctx); got != want {
t.Errorf("GetNamespace() = \"%v\", wanted \"%v\"", got, want)
}
}
2 changes: 1 addition & 1 deletion webhook/resourcesemantics/defaulting/defaulting.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ func (ac *reconciler) mutate(ctx context.Context, req *admissionv1.AdmissionRequ
ctx = apis.WithinCreate(ctx)
}
ctx = apis.WithUserInfo(ctx, &req.UserInfo)

ctx = apis.WithNamespace(ctx, req.Namespace)
// Default the new object.
if patches, err = setDefaults(ctx, patches, newObj); err != nil {
logger.Errorw("Failed the resource specific defaulter", zap.Error(err))
Expand Down

0 comments on commit c0eba4e

Please sign in to comment.