Skip to content

Commit ddd3124

Browse files
committed
Add ability to deserialize yaml/json to client.Object
Signed-off-by: Angel Misevski <[email protected]>
1 parent d94ea4d commit ddd3124

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Copyright (c) 2019-2022 Red Hat, Inc.
2+
// Licensed under the Apache License, Version 2.0 (the "License");
3+
// you may not use this file except in compliance with the License.
4+
// You may obtain a copy of the License at
5+
//
6+
// http://www.apache.org/licenses/LICENSE-2.0
7+
//
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
14+
package kubernetes
15+
16+
import (
17+
"fmt"
18+
gosync "sync"
19+
20+
"github.com/devfile/devworkspace-operator/pkg/provision/sync"
21+
"k8s.io/apimachinery/pkg/runtime"
22+
"k8s.io/apimachinery/pkg/runtime/serializer"
23+
"sigs.k8s.io/controller-runtime/pkg/client"
24+
)
25+
26+
var (
27+
decoder runtime.Decoder
28+
decoderMutex gosync.Mutex
29+
)
30+
31+
func InitializeDeserializer(scheme *runtime.Scheme) error {
32+
decoderMutex.Lock()
33+
defer decoderMutex.Unlock()
34+
if decoder != nil {
35+
return fmt.Errorf("attempting to re-initialize kubernetes object decoder")
36+
}
37+
decoder = serializer.NewCodecFactory(scheme).UniversalDeserializer()
38+
return nil
39+
}
40+
41+
func deserializeToObject(jsonObj []byte, api sync.ClusterAPI) (client.Object, error) {
42+
if decoder == nil {
43+
return nil, fmt.Errorf("kubernetes object deserializer is not initialized")
44+
}
45+
obj, _, err := decoder.Decode(jsonObj, nil, nil)
46+
if err != nil {
47+
return nil, err
48+
}
49+
if obj.GetObjectKind().GroupVersionKind().Kind == "List" {
50+
return nil, fmt.Errorf("objects of kind 'List' are unsupported")
51+
}
52+
clientObj, ok := obj.(client.Object)
53+
if !ok {
54+
// Should never occur but to avoid a panic
55+
return nil, fmt.Errorf("object does not have standard metadata and cannot be processed")
56+
}
57+
return clientObj, nil
58+
}

0 commit comments

Comments
 (0)