forked from abcxyz/access-on-demand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cli_validate.go
97 lines (77 loc) · 2.44 KB
/
cli_validate.go
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
88
89
90
91
92
93
94
95
96
97
// Copyright 2023 The Authors (see AUTHORS file)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cli
import (
"context"
"fmt"
"github.com/abcxyz/pkg/cli"
"github.com/posener/complete/v2/predict"
"github.com/sqin2019/access-on-demand-fork/apis/v1alpha1"
"github.com/sqin2019/access-on-demand-fork/pkg/requestutil"
)
var _ cli.Command = (*CLIValidateCommand)(nil)
// CLIValidateCommand validates CLI requests.
type CLIValidateCommand struct {
cli.BaseCommand
flagPath string
}
func (c *CLIValidateCommand) Desc() string {
return `Validate the CLI request YAML file at the given path`
}
func (c *CLIValidateCommand) Help() string {
return `
Usage: {{ COMMAND }} [options]
Validate the IAM request YAML file at the given path:
{{ COMMAND }} -path "/path/to/file.yaml"
`
}
func (c *CLIValidateCommand) Flags() *cli.FlagSet {
set := cli.NewFlagSet()
// Command options
f := set.NewSection("COMMAND OPTIONS")
f.StringVar(&cli.StringVar{
Name: "path",
Target: &c.flagPath,
Example: "/path/to/file.yaml",
Predict: predict.Files("*"),
Usage: `The path of CLI request file, in YAML format.`,
})
return set
}
func (c *CLIValidateCommand) Run(ctx context.Context, args []string) error {
f := c.Flags()
if err := f.Parse(args); err != nil {
return fmt.Errorf("failed to parse flags: %w", err)
}
args = f.Args()
if len(args) > 0 {
return fmt.Errorf("unexpected arguments: %q", args)
}
if c.flagPath == "" {
return fmt.Errorf("path is required")
}
return c.validate(ctx)
}
func (c *CLIValidateCommand) validate(ctx context.Context) error {
// Read request from file path.
var req v1alpha1.CLIRequest
if err := requestutil.ReadRequestFromPath(c.flagPath, &req); err != nil {
return fmt.Errorf("failed to read %T: %w", &req, err)
}
if err := v1alpha1.ValidateCLIRequest(&req); err != nil {
return fmt.Errorf("failed to validate %T: %w", &req, err)
}
c.Outf("Successfully validated CLI request")
return nil
}