Skip to content

Commit

Permalink
enhance: Add --format=json flag option to comment commands (#2874)
Browse files Browse the repository at this point in the history
* enhance: Add --format=json flag option to comment commands

* fix: copy+paste error

* test: update golden files
  • Loading branch information
tim775 committed Feb 8, 2024
1 parent 268fe56 commit f372f1c
Show file tree
Hide file tree
Showing 10 changed files with 101 additions and 11 deletions.
23 changes: 16 additions & 7 deletions cmd/infracost/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,18 @@ import (
)

type CommentOutput struct {
Body string
HasDiff bool
ValidAt *time.Time
Body string
HasDiff bool
ValidAt *time.Time
AddRunResponse apiclient.AddRunResponse
}

var (
validCommentOutputFormats = []string{
"json",
}
)

func commentCmd(ctx *config.RunContext) *cobra.Command {
cmd := &cobra.Command{
Use: "comment",
Expand Down Expand Up @@ -84,6 +91,7 @@ func buildCommentOutput(cmd *cobra.Command, ctx *config.RunContext, paths []stri
var additionalCommentData string
var governanceFailures output.GovernanceFailures
dryRun, _ := cmd.Flags().GetBool("dry-run")
var result apiclient.AddRunResponse
if ctx.IsCloudUploadEnabled() && !dryRun {
if ctx.Config.IsSelfHosted() {
ui.PrintWarning(cmd.ErrOrStderr(), "Infracost Cloud is part of Infracost's hosted services. Contact [email protected] for help.")
Expand All @@ -93,7 +101,7 @@ func buildCommentOutput(cmd *cobra.Command, ctx *config.RunContext, paths []stri
if mdOpts.BasicSyntax {
commentFormat = apiclient.CommentFormatMarkdown
}
result := shareCombinedRun(ctx, combined, inputs, commentFormat)
result = shareCombinedRun(ctx, combined, inputs, commentFormat)
combined.RunID, combined.ShareURL, combined.CloudURL, governanceFailures = result.RunID, result.ShareURL, result.CloudURL, result.GovernanceFailures
additionalCommentData = result.GovernanceComment
}
Expand Down Expand Up @@ -139,9 +147,10 @@ func buildCommentOutput(cmd *cobra.Command, ctx *config.RunContext, paths []stri
ctx.ContextValues.SetValue("originalLength", md.OriginalMsgSize)

out := &CommentOutput{
Body: string(b),
HasDiff: combined.HasDiff(),
ValidAt: &combined.TimeGenerated,
Body: string(b),
HasDiff: combined.HasDiff(),
ValidAt: &combined.TimeGenerated,
AddRunResponse: result,
}

if policyChecks.HasFailed() {
Expand Down
17 changes: 16 additions & 1 deletion cmd/infracost/comment_azure_repos.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strconv"
"strings"

jsoniter "github.com/json-iterator/go"
"github.com/spf13/cobra"

"github.com/infracost/infracost/internal/apiclient"
Expand All @@ -31,6 +32,13 @@ func commentAzureReposCmd(ctx *config.RunContext) *cobra.Command {

var err error

format, _ := cmd.Flags().GetString("format")
format = strings.ToLower(format)
if format != "" && !contains(validCommentOutputFormats, format) {
ui.PrintUsage(cmd)
return fmt.Errorf("--format only supports %s", strings.Join(validCommentOutputFormats, ", "))
}

token, _ := cmd.Flags().GetString("azure-access-token")
tag, _ := cmd.Flags().GetString("tag")
extra := comment.AzureReposExtra{
Expand Down Expand Up @@ -90,7 +98,13 @@ func commentAzureReposCmd(ctx *config.RunContext) *cobra.Command {
logging.Logger.Err(err).Msg("could not report infracost-comment event")
}

if res.Posted {
if format == "json" {
b, err := jsoniter.MarshalIndent(commentOut.AddRunResponse, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal result: %w", err)
}
cmd.Printf(string(b))
} else if res.Posted {
cmd.Println("Comment posted to Azure Repos")
} else {
msg := "Comment not posted to Azure Repos"
Expand Down Expand Up @@ -127,6 +141,7 @@ func commentAzureReposCmd(ctx *config.RunContext) *cobra.Command {
_ = cmd.MarkFlagRequired("repo-url")
cmd.Flags().String("tag", "", "Customize hidden markdown tag used to detect comments posted by Infracost")
cmd.Flags().Bool("dry-run", false, "Generate comment without actually posting to Azure Repos")
cmd.Flags().String("format", "", "Output format: json")

return cmd
}
17 changes: 16 additions & 1 deletion cmd/infracost/comment_bitbucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strconv"
"strings"

jsoniter "github.com/json-iterator/go"
"github.com/spf13/cobra"

"github.com/infracost/infracost/internal/apiclient"
Expand Down Expand Up @@ -35,6 +36,13 @@ func commentBitbucketCmd(ctx *config.RunContext) *cobra.Command {

var err error

format, _ := cmd.Flags().GetString("format")
format = strings.ToLower(format)
if format != "" && !contains(validCommentOutputFormats, format) {
ui.PrintUsage(cmd)
return fmt.Errorf("--format only supports %s", strings.Join(validCommentOutputFormats, ", "))
}

serverURL, _ := cmd.Flags().GetString("bitbucket-server-url")
token, _ := cmd.Flags().GetString("bitbucket-token")
tag, _ := cmd.Flags().GetString("tag")
Expand Down Expand Up @@ -108,7 +116,13 @@ func commentBitbucketCmd(ctx *config.RunContext) *cobra.Command {
logging.Logger.Err(err).Msg("could not report infracost-comment event")
}

if res.Posted {
if format == "json" {
b, err := jsoniter.MarshalIndent(commentOut.AddRunResponse, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal result: %w", err)
}
cmd.Printf(string(b))
} else if res.Posted {
cmd.Println("Comment posted to Bitbucket")
} else {
msg := "Comment not posted to Bitbucket"
Expand Down Expand Up @@ -147,6 +161,7 @@ func commentBitbucketCmd(ctx *config.RunContext) *cobra.Command {
cmd.Flags().Bool("exclude-cli-output", false, "Exclude CLI output so comment has just the summary table")
cmd.Flags().String("tag", "", "Customize special text used to detect comments posted by Infracost (placed at the bottom of a comment)")
cmd.Flags().Bool("dry-run", false, "Generate comment without actually posting to Bitbucket")
cmd.Flags().String("format", "", "Output format: json")

return cmd
}
18 changes: 17 additions & 1 deletion cmd/infracost/comment_github.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strconv"
"strings"

jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/spf13/cobra"

Expand Down Expand Up @@ -38,6 +39,13 @@ func commentGitHubCmd(ctx *config.RunContext) *cobra.Command {

var commentErr error

format, _ := cmd.Flags().GetString("format")
format = strings.ToLower(format)
if format != "" && !contains(validCommentOutputFormats, format) {
ui.PrintUsage(cmd)
return fmt.Errorf("--format only supports %s", strings.Join(validCommentOutputFormats, ", "))
}

apiURL, _ := cmd.Flags().GetString("github-api-url")
token, _ := cmd.Flags().GetString("github-token")
tag, _ := cmd.Flags().GetString("tag")
Expand Down Expand Up @@ -132,7 +140,14 @@ func commentGitHubCmd(ctx *config.RunContext) *cobra.Command {
logging.Logger.Err(err).Msg("could not report infracost-comment event")
}

if res.Posted {
if format == "json" {
b, err := jsoniter.MarshalIndent(commentOut.AddRunResponse, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal result: %w", err)
}
cmd.Printf(string(b))
} else if res.Posted {

cmd.Println("Comment posted to GitHub")
} else {
msg := "Comment not posted to GitHub"
Expand Down Expand Up @@ -179,6 +194,7 @@ func commentGitHubCmd(ctx *config.RunContext) *cobra.Command {
_ = cmd.MarkFlagRequired("repo")
cmd.Flags().String("tag", "", "Customize hidden markdown tag used to detect comments posted by Infracost")
cmd.Flags().Bool("dry-run", false, "Generate comment without actually posting to GitHub")
cmd.Flags().String("format", "", "Output format: json")

return cmd
}
17 changes: 16 additions & 1 deletion cmd/infracost/comment_gitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"strconv"
"strings"

jsoniter "github.com/json-iterator/go"
"github.com/spf13/cobra"

"github.com/infracost/infracost/internal/apiclient"
Expand Down Expand Up @@ -35,6 +36,13 @@ func commentGitLabCmd(ctx *config.RunContext) *cobra.Command {

var err error

format, _ := cmd.Flags().GetString("format")
format = strings.ToLower(format)
if format != "" && !contains(validCommentOutputFormats, format) {
ui.PrintUsage(cmd)
return fmt.Errorf("--format only supports %s", strings.Join(validCommentOutputFormats, ", "))
}

serverURL, _ := cmd.Flags().GetString("gitlab-server-url")
token, _ := cmd.Flags().GetString("gitlab-token")
tag, _ := cmd.Flags().GetString("tag")
Expand Down Expand Up @@ -104,7 +112,13 @@ func commentGitLabCmd(ctx *config.RunContext) *cobra.Command {
logging.Logger.Err(err).Msg("could not report infracost-comment event")
}

if res.Posted {
if format == "json" {
b, err := jsoniter.MarshalIndent(commentOut.AddRunResponse, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal result: %w", err)
}
cmd.Printf(string(b))
} else if res.Posted {
cmd.Println("Comment posted to GitLab")
} else {
msg := "Comment not posted to GitLab"
Expand Down Expand Up @@ -142,6 +156,7 @@ func commentGitLabCmd(ctx *config.RunContext) *cobra.Command {
_ = cmd.MarkFlagRequired("repo")
cmd.Flags().String("tag", "", "Customize hidden markdown tag used to detect comments posted by Infracost")
cmd.Flags().Bool("dry-run", false, "Generate comment without actually posting to GitLab")
cmd.Flags().String("format", "", "Output format: json")

return cmd
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ FLAGS
new Create a new comment
delete-and-new Delete previous matching comments and create a new comment (default "update")
--dry-run Generate comment without actually posting to Azure Repos
--format string Output format: json
-h, --help help for azure-repos
-p, --path stringArray Path to Infracost JSON files, glob patterns need quotes
--policy-path stringArray Path to Infracost policy files, glob patterns need quotes (experimental)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ FLAGS
--commit string Commit SHA to post comment on, mutually exclusive with pull-request. Not available when bitbucket-server-url is set
--dry-run Generate comment without actually posting to Bitbucket
--exclude-cli-output Exclude CLI output so comment has just the summary table
--format string Output format: json
-h, --help help for bitbucket
-p, --path stringArray Path to Infracost JSON files, glob patterns need quotes
--policy-path stringArray Path to Infracost policy files, glob patterns need quotes (experimental)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ FLAGS
delete-and-new Delete previous matching comments and create a new comment (default "update")
--commit string Commit SHA to post comment on, mutually exclusive with pull-request
--dry-run Generate comment without actually posting to GitHub
--format string Output format: json
--github-api-url string GitHub API URL (default "https://api.github.com")
--github-tls-cert-file string Path to optional client certificate file when communicating with GitHub Enterprise API
--github-tls-insecure-skip-verify Skip TLS certificate checks for GitHub Enterprise API
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ FLAGS
delete-and-new Delete previous matching comments and create a new comment (default "update")
--commit string Commit SHA to post comment on, mutually exclusive with merge-request
--dry-run Generate comment without actually posting to GitLab
--format string Output format: json
--gitlab-server-url string GitLab Server URL (default "https://gitlab.com")
--gitlab-token string GitLab token
-h, --help help for gitlab
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,10 @@ _infracost_comment_azure-repos()
local_nonpersistent_flags+=("--behavior=")
flags+=("--dry-run")
local_nonpersistent_flags+=("--dry-run")
flags+=("--format=")
two_word_flags+=("--format")
local_nonpersistent_flags+=("--format")
local_nonpersistent_flags+=("--format=")
flags+=("--path=")
two_word_flags+=("--path")
flags_with_completion+=("--path")
Expand Down Expand Up @@ -611,6 +615,10 @@ _infracost_comment_bitbucket()
local_nonpersistent_flags+=("--dry-run")
flags+=("--exclude-cli-output")
local_nonpersistent_flags+=("--exclude-cli-output")
flags+=("--format=")
two_word_flags+=("--format")
local_nonpersistent_flags+=("--format")
local_nonpersistent_flags+=("--format=")
flags+=("--path=")
two_word_flags+=("--path")
flags_with_completion+=("--path")
Expand Down Expand Up @@ -683,6 +691,10 @@ _infracost_comment_github()
local_nonpersistent_flags+=("--commit=")
flags+=("--dry-run")
local_nonpersistent_flags+=("--dry-run")
flags+=("--format=")
two_word_flags+=("--format")
local_nonpersistent_flags+=("--format")
local_nonpersistent_flags+=("--format=")
flags+=("--github-api-url=")
two_word_flags+=("--github-api-url")
local_nonpersistent_flags+=("--github-api-url")
Expand Down Expand Up @@ -773,6 +785,10 @@ _infracost_comment_gitlab()
local_nonpersistent_flags+=("--commit=")
flags+=("--dry-run")
local_nonpersistent_flags+=("--dry-run")
flags+=("--format=")
two_word_flags+=("--format")
local_nonpersistent_flags+=("--format")
local_nonpersistent_flags+=("--format=")
flags+=("--gitlab-server-url=")
two_word_flags+=("--gitlab-server-url")
local_nonpersistent_flags+=("--gitlab-server-url")
Expand Down

0 comments on commit f372f1c

Please sign in to comment.