cmd/parse: Move accidental pkg var to local var. (#7813)

This commit moves an accidental package-level definition of the `opa
parse` CLI subcommand to a local variable inside the `initParse`
function, similar to how we do command initialization for all other OPA
CLI subcommands.

Before this change, it was possible to see panics from the package
variable `cobra.Command` in `parse.go` having some of its flags redefined.
This fix makes it possible for `make generate-cli-docs` to run without
error again.

Signed-off-by: Philip Conrad <philip@chariot-chaser.net>
(cherry picked from commit 47e2b74dda)
This commit is contained in:
Philip Conrad
2025-07-31 15:27:16 -04:00
parent 21a527db6e
commit 9874953f5e
+22 -22
View File
@@ -46,28 +46,6 @@ var configuredParseParams = parseParams{
jsonInclude: "",
}
var parseCommand = &cobra.Command{
Use: "parse <path>",
Short: "Parse Rego source file",
Long: `Parse Rego source file and print AST.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("no source file specified")
}
return env.CmdFlags.CheckEnvironmentVariables(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
exit := parse(args, &configuredParseParams, os.Stdout, os.Stderr)
if exit != 0 {
return newExitError(exit)
}
return nil
},
}
func parse(args []string, params *parseParams, stdout io.Writer, stderr io.Writer) int {
if len(args) == 0 {
return 0
@@ -140,6 +118,28 @@ func parse(args []string, params *parseParams, stdout io.Writer, stderr io.Write
}
func initParse(root *cobra.Command, _ string) {
parseCommand := &cobra.Command{
Use: "parse <path>",
Short: "Parse Rego source file",
Long: `Parse Rego source file and print AST.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.New("no source file specified")
}
return env.CmdFlags.CheckEnvironmentVariables(cmd)
},
RunE: func(cmd *cobra.Command, args []string) error {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
exit := parse(args, &configuredParseParams, os.Stdout, os.Stderr)
if exit != 0 {
return newExitError(exit)
}
return nil
},
}
addOutputFormat(parseCommand.Flags(), configuredParseParams.format)
parseCommand.Flags().StringVarP(&configuredParseParams.jsonInclude, "json-include", "", "", "include or exclude optional elements. By default comments are included. Current options: locations, comments. E.g. --json-include locations,-comments will include locations and exclude comments.")
addV1CompatibleFlag(parseCommand.Flags(), &configuredParseParams.v1Compatible, false)