crossplane
77 строк · 1.9 Кб
1/*
2Copyright 2023 The Crossplane Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17// Package examples contains utilities for parsing examples.
18package examples
19
20import (
21"bufio"
22"context"
23"io"
24
25"github.com/crossplane/crossplane-runtime/pkg/parser"
26"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
27"k8s.io/apimachinery/pkg/util/yaml"
28k8syaml "sigs.k8s.io/yaml"
29)
30
31// Examples is the set of metadata and objects in a package.
32type Examples struct {
33objects []unstructured.Unstructured
34}
35
36// Parser is a Parser implementation for parsing examples.
37type Parser struct {
38objScheme parser.ObjectCreaterTyper
39}
40
41// NewExamples creates a new Examples object.
42func NewExamples() *Examples {
43return &Examples{}
44}
45
46// New creates a new Package.
47func New() *Parser {
48return &Parser{}
49}
50
51// Parse is the underlying logic for parsing examples.
52func (p *Parser) Parse(ctx context.Context, reader io.ReadCloser) (*Examples, error) {
53ex := NewExamples()
54if reader == nil {
55return ex, nil
56}
57defer func() { _ = reader.Close() }()
58yr := yaml.NewYAMLReader(bufio.NewReader(reader))
59for {
60bytes, err := yr.Read()
61if err != nil && err != io.EOF {
62return ex, err
63}
64if err == io.EOF {
65break
66}
67if len(bytes) == 0 {
68continue
69}
70var obj unstructured.Unstructured
71if err := k8syaml.Unmarshal(bytes, &obj); err != nil {
72return ex, err
73}
74ex.objects = append(ex.objects, obj)
75}
76return ex, nil
77}
78