Skip to content

Commit ac25dd3

Browse files
authored
feat: add reading crds from stdin (#172)
Signed-off-by: Gergely Brautigam <[email protected]>
1 parent 333bd9b commit ac25dd3

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

cmd/crd.go

+2
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,8 @@ func constructHandler(args *rootArgs) (Handler, error) {
128128
var crdHandler Handler
129129

130130
switch {
131+
case args.stdin:
132+
crdHandler = &StdInHandler{}
131133
case args.fileLocation != "":
132134
crdHandler = &FileHandler{location: args.fileLocation}
133135
case args.folderLocation != "":

cmd/generate.go

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ type rootArgs struct {
1717
privSSHKey string
1818
useSSHAgent bool
1919
gitURL string
20+
stdin bool
2021
}
2122

2223
var (
@@ -33,6 +34,7 @@ func init() {
3334
rootCmd.AddCommand(generateCmd)
3435
// using persistent flags so all flags will be available for all sub commands.
3536
f := generateCmd.PersistentFlags()
37+
f.BoolVarP(&args.stdin, "stdin", "i", false, "Take CRD content from stdin.")
3638
f.StringVarP(&args.fileLocation, "crd", "c", "", "The CRD file to generate a yaml from.")
3739
f.StringVarP(&args.folderLocation, "folder", "r", "", "A folder from which to parse a series of CRDs.")
3840
f.StringVarP(&args.url, "url", "u", "", "If provided, will use this URL to fetch CRD YAML content from.")

cmd/stdin_handler.go

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"os"
7+
8+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
9+
"k8s.io/apimachinery/pkg/util/yaml"
10+
11+
"github.com/Skarlso/crd-to-sample-yaml/pkg"
12+
"github.com/Skarlso/crd-to-sample-yaml/pkg/sanitize"
13+
)
14+
15+
type StdInHandler struct {
16+
group string
17+
}
18+
19+
func (s *StdInHandler) CRDs() ([]*pkg.SchemaType, error) {
20+
content, err := io.ReadAll(os.Stdin)
21+
if err != nil {
22+
return nil, fmt.Errorf("failed to read file: %w", err)
23+
}
24+
25+
content, err = sanitize.Sanitize(content)
26+
if err != nil {
27+
return nil, fmt.Errorf("failed to sanitize content: %w", err)
28+
}
29+
30+
crd := &unstructured.Unstructured{}
31+
if err := yaml.Unmarshal(content, crd); err != nil {
32+
return nil, fmt.Errorf("failed to unmarshal into custom resource definition: %w", err)
33+
}
34+
35+
schemaType, err := pkg.ExtractSchemaType(crd)
36+
if err != nil {
37+
return nil, fmt.Errorf("failed to extract schema type: %w", err)
38+
}
39+
40+
if schemaType == nil {
41+
return nil, nil
42+
}
43+
44+
if s.group != "" {
45+
schemaType.Rendering = pkg.Rendering{Group: s.group}
46+
}
47+
48+
return []*pkg.SchemaType{schemaType}, nil
49+
}

0 commit comments

Comments
 (0)