Skip to content

Commit

Permalink
Add check flag to fmt command (open-policy-agent#655)
Browse files Browse the repository at this point in the history
* Add fail flag to fmt command

Signed-off-by: John Reese <[email protected]>

* Update command to be check

Signed-off-by: John Reese <[email protected]>
  • Loading branch information
jpreese authored Jan 4, 2022
1 parent 06793a4 commit ab9c9f1
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions internal/commands/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package commands
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"os"

"github.com/open-policy-agent/opa/format"
"github.com/open-policy-agent/opa/loader"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

// NewFormatCommand creates a format command.
Expand All @@ -18,6 +20,13 @@ func NewFormatCommand(ctx context.Context) *cobra.Command {
cmd := cobra.Command{
Use: "fmt <path> [path [...]]",
Short: "Format Rego files",
PreRunE: func(cmd *cobra.Command, args []string) error {
if err := viper.BindPFlag("check", cmd.Flags().Lookup("check")); err != nil {
return fmt.Errorf("bind flag: %w", err)
}

return nil
},
RunE: func(cmd *cobra.Command, files []string) error {
policies, err := loader.AllRegos(files)
if err != nil {
Expand All @@ -42,10 +51,18 @@ func NewFormatCommand(ctx context.Context) *cobra.Command {
return fmt.Errorf("format: %w", err)
}

// If the original file contents match the formatted contents, formatting does not
// need to be done and we can try the next module.
if bytes.Equal(contents, formattedContents) {
continue
}

// When we are running the format command in check mode and the file contents are different
// we want to return an error code to the user and not update any of the files.
if viper.GetBool("check") {
return errors.New("files not formatted")
}

outfile, err := os.OpenFile(policy.Package.Location.File, os.O_WRONLY|os.O_TRUNC, info.Mode().Perm())
if err != nil {
return fmt.Errorf("open file for write: %w", err)
Expand All @@ -62,5 +79,7 @@ func NewFormatCommand(ctx context.Context) *cobra.Command {
},
}

cmd.Flags().Bool("check", false, "Returns a non-zero exit code if the policies are not formatted")

return &cmd
}

0 comments on commit ab9c9f1

Please sign in to comment.