/
validate.go
115 lines (93 loc) · 2.04 KB
/
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"github.com/spf13/cobra"
"go.flipt.io/flipt/core/validation"
"go.flipt.io/flipt/internal/containers"
"go.flipt.io/flipt/internal/storage/fs"
)
type validateCommand struct {
issueExitCode int
format string
extraPath string
workDirectory string
}
const (
jsonFormat = "json"
textFormat = "text"
)
func newValidateCommand() *cobra.Command {
v := &validateCommand{}
cmd := &cobra.Command{
Use: "validate",
Short: "Validate Flipt flag state (.yaml, .yml) files",
RunE: v.run,
}
cmd.Flags().IntVar(&v.issueExitCode, "issue-exit-code", 1, "exit code to use when issues are found")
cmd.Flags().StringVarP(
&v.format,
"format", "F",
"text",
"output format: json, text",
)
cmd.Flags().StringVarP(
&v.extraPath,
"extra-schema", "e",
"",
"path to extra schema constraints",
)
cmd.Flags().StringVarP(
&v.workDirectory,
"work-dir", "d",
".",
"set the working directory",
)
return cmd
}
func (v *validateCommand) run(cmd *cobra.Command, args []string) error {
logger, _, err := buildConfig()
if err != nil {
return err
}
var opts []containers.Option[fs.SnapshotOption]
if v.extraPath != "" {
schema, err := os.ReadFile(v.extraPath)
if err != nil {
return err
}
opts = append(opts, fs.WithValidatorOption(
validation.WithSchemaExtension(schema),
))
}
if v.workDirectory == "" {
return errors.New("non-empty working directory expected")
}
if len(args) == 0 {
_, err = fs.SnapshotFromFS(logger, os.DirFS(v.workDirectory), opts...)
} else {
_, err = fs.SnapshotFromPaths(logger, os.DirFS(v.workDirectory), args, opts...)
}
errs, ok := validation.Unwrap(err)
if !ok {
return err
}
if len(errs) > 0 {
if v.format == jsonFormat {
if err := json.NewEncoder(os.Stdout).Encode(errs); err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(v.issueExitCode)
return nil
}
fmt.Println("Validation failed!")
for _, err := range errs {
fmt.Printf("%v\n", err)
}
os.Exit(v.issueExitCode)
}
return nil
}