summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/zed/internal/commands/schema.go
blob: b56f152eb3994f03c6c23d8ff909e65c90c34fb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package commands

import (
	"context"

	"github.com/jzelinskie/cobrautil/v2"
	"github.com/jzelinskie/stringz"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"

	"github.com/authzed/zed/internal/client"
	"github.com/authzed/zed/internal/console"
)

func RegisterSchemaCmd(rootCmd *cobra.Command) *cobra.Command {
	rootCmd.AddCommand(schemaCmd)

	schemaCmd.AddCommand(schemaReadCmd)
	schemaReadCmd.Flags().Bool("json", false, "output as JSON")

	return schemaCmd
}

var (
	schemaCmd = &cobra.Command{
		Use:   "schema <subcommand>",
		Short: "Manage schema for a permissions system",
	}

	schemaReadCmd = &cobra.Command{
		Use:               "read",
		Short:             "Read the schema of a permissions system",
		Args:              ValidationWrapper(cobra.ExactArgs(0)),
		ValidArgsFunction: cobra.NoFileCompletions,
		RunE:              schemaReadCmdFunc,
	}
)

func schemaReadCmdFunc(cmd *cobra.Command, _ []string) error {
	client, err := client.NewClient(cmd)
	if err != nil {
		return err
	}
	request := &v1.ReadSchemaRequest{}
	log.Trace().Interface("request", request).Msg("requesting schema read")

	resp, err := client.ReadSchema(cmd.Context(), request)
	if err != nil {
		return err
	}

	if cobrautil.MustGetBool(cmd, "json") {
		prettyProto, err := PrettyProto(resp)
		if err != nil {
			return err
		}

		console.Println(string(prettyProto))
		return nil
	}

	console.Println(stringz.Join("\n\n", resp.SchemaText))
	return nil
}

// ReadSchema calls read schema for the client and returns the schema found.
func ReadSchema(ctx context.Context, client client.Client) (string, error) {
	request := &v1.ReadSchemaRequest{}
	log.Trace().Interface("request", request).Msg("requesting schema read")

	resp, err := client.ReadSchema(ctx, request)
	if err != nil {
		errStatus, ok := status.FromError(err)
		if !ok || errStatus.Code() != codes.NotFound {
			return "", err
		}

		log.Debug().Msg("no schema defined")
		return "", nil
	}

	return resp.SchemaText, nil
}