Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "fix: Duplicate project name issue and reintroduce logging changes " #3061

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
88 changes: 6 additions & 82 deletions cmd/infracost/breakdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,8 @@ func TestBreakdownTerraformDirectoryWithDefaultVarFiles(t *testing.T) {
"--path", dir,
"--terraform-plan-flags", "-var-file=input.tfvars -var=block2_ebs_volume_size=2000 -var block2_volume_type=io1",
"--terraform-force-cli",
}, &GoldenFileOptions{IgnoreNonGraph: true},
},
nil,
)
})

Expand All @@ -296,7 +297,7 @@ func TestBreakdownTerraformDirectoryWithDefaultVarFiles(t *testing.T) {
"--terraform-var", "block2_ebs_volume_size=2000",
"--terraform-var", "block2_volume_type=io1",
},
&GoldenFileOptions{IgnoreNonGraph: true},
nil,
)
})

Expand Down Expand Up @@ -463,9 +464,7 @@ func TestBreakdownTerragrunt(t *testing.T) {
func TestBreakdownTerragruntWithRemoteSource(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
wd, err := os.Getwd()
require.NoError(t, err)
cacheDir := filepath.Join(wd, ".infracost")
cacheDir := filepath.Join(dir, ".infracost")
require.NoError(t, os.RemoveAll(cacheDir))

GoldenFileCommandTest(
Expand All @@ -478,7 +477,7 @@ func TestBreakdownTerragruntWithRemoteSource(t *testing.T) {
nil)

dirs, err := getGitBranchesInDirs(filepath.Join(cacheDir, ".terragrunt-cache"))
require.NoError(t, err)
assert.NoError(t, err)

// check that there are 5 directories in the download directory as 3 of the 7 projects use the same ref,
// but one of these has a generate block.
Expand Down Expand Up @@ -1322,20 +1321,7 @@ func TestBreakdownTerragruntFileFuncs(t *testing.T) {
}

t.Setenv("INFRACOST_CI_PLATFORM", "github_app")
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
t,
testutil.CalcGoldenFileTestdataDirName(),
[]string{
"breakdown",
"--path", dir,
},
&GoldenFileOptions{IgnoreLogs: true, IgnoreNonGraph: true},
)
}

func TestBreakdownNoPricesWarnings(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
Expand All @@ -1345,7 +1331,7 @@ func TestBreakdownNoPricesWarnings(t *testing.T) {
"breakdown",
"--path", dir,
},
nil,
&GoldenFileOptions{IgnoreLogs: true, IgnoreNonGraph: true},
)
}

Expand All @@ -1368,65 +1354,3 @@ func TestBreakdownTerraformFileFuncs(t *testing.T) {
&GoldenFileOptions{IgnoreLogs: true, IgnoreNonGraph: true},
)
}

func TestBreakdownAutodetectionOutput(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
t,
testutil.CalcGoldenFileTestdataDirName(),
[]string{
"breakdown",
"--path", dir,
},
&GoldenFileOptions{LogLevel: strPtr("info")},
)
}

func TestBreakdownAutodetectionConfigFileOutput(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
t,
testutil.CalcGoldenFileTestdataDirName(),
[]string{
"breakdown",
"--config-file", filepath.Join(dir, "infracost.yml"),
"--log-level", "info",
},
&GoldenFileOptions{LogLevel: strPtr("info"), IgnoreNonGraph: true},
)
}

func TestBreakdownTerragruntAutodetectionOutput(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
t,
testutil.CalcGoldenFileTestdataDirName(),
[]string{
"breakdown",
"--path", dir,
},
&GoldenFileOptions{LogLevel: strPtr("info")},
)
}

func TestBreakdownTerragruntAutodetectionConfigFileOutput(t *testing.T) {
testName := testutil.CalcGoldenFileTestdataDirName()
dir := path.Join("./testdata", testName)
GoldenFileCommandTest(
t,
testutil.CalcGoldenFileTestdataDirName(),
[]string{
"breakdown",
"--config-file", filepath.Join(dir, "infracost.yml"),
"--log-level", "info",
},
&GoldenFileOptions{LogLevel: strPtr("info"), IgnoreNonGraph: true},
)
}

func strPtr(s string) *string {
return &s
}
12 changes: 4 additions & 8 deletions cmd/infracost/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ type GoldenFileOptions = struct {
RunTerraformCLI bool
IgnoreNonGraph bool
IgnoreLogs bool
LogLevel *string
}

func DefaultOptions() *GoldenFileOptions {
Expand Down Expand Up @@ -130,13 +129,10 @@ func GetCommandOutput(t *testing.T, args []string, testOptions *GoldenFileOption
c.OutWriter = outBuf
c.Exit = func(code int) {}

level := "warn"
if testOptions.LogLevel != nil {
level = *testOptions.LogLevel
}

if !testOptions.IgnoreLogs {
logBuf = testutil.ConfigureTestToCaptureLogs(t, c, level)
if testOptions.CaptureLogs {
logBuf = testutil.ConfigureTestToCaptureLogs(t, c)
} else if !testOptions.IgnoreLogs {
testutil.ConfigureTestToFailOnLogs(t, c)
}

for _, option := range ctxOptions {
Expand Down
6 changes: 3 additions & 3 deletions cmd/infracost/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@ import (
"github.com/spf13/cobra"

"github.com/infracost/infracost/internal/apiclient"
"github.com/infracost/infracost/internal/logging"

"github.com/infracost/infracost/internal/clierror"
"github.com/infracost/infracost/internal/config"
"github.com/infracost/infracost/internal/output"
"github.com/infracost/infracost/internal/ui"
)

type CommentOutput struct {
Expand Down Expand Up @@ -83,7 +83,7 @@ func buildCommentOutput(cmd *cobra.Command, ctx *config.RunContext, paths []stri

combined, err := output.Combine(inputs)
if errors.As(err, &clierror.WarningError{}) {
logging.Logger.Warn().Msgf(err.Error())
ui.PrintWarningf(cmd.ErrOrStderr(), err.Error())
} else if err != nil {
return nil, err
}
Expand All @@ -96,7 +96,7 @@ func buildCommentOutput(cmd *cobra.Command, ctx *config.RunContext, paths []stri
var result apiclient.AddRunResponse
if ctx.IsCloudUploadEnabled() && !dryRun {
if ctx.Config.IsSelfHosted() {
logging.Logger.Warn().Msg("Infracost Cloud is part of Infracost's hosted services. Contact [email protected] for help.")
ui.PrintWarning(cmd.ErrOrStderr(), "Infracost Cloud is part of Infracost's hosted services. Contact [email protected] for help.")
} else {
combined.Metadata.InfracostCommand = "comment"
commentFormat := apiclient.CommentFormatMarkdownHTML
Expand Down
11 changes: 5 additions & 6 deletions cmd/infracost/configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/spf13/cobra"

"github.com/infracost/infracost/internal/config"
"github.com/infracost/infracost/internal/logging"
"github.com/infracost/infracost/internal/ui"
)

Expand Down Expand Up @@ -207,7 +206,7 @@ func configureGetCmd(ctx *config.RunContext) *cobra.Command {
config.CredentialsFilePath(),
ui.PrimaryString("infracost configure set pricing_api_endpoint https://cloud-pricing-api"),
)
logging.Logger.Warn().Msg(msg)
ui.PrintWarning(cmd.ErrOrStderr(), msg)
}
case "api_key":
value = ctx.Config.Credentials.APIKey
Expand All @@ -217,7 +216,7 @@ func configureGetCmd(ctx *config.RunContext) *cobra.Command {
config.CredentialsFilePath(),
ui.PrimaryString("infracost configure set api_key MY_API_KEY"),
)
logging.Logger.Warn().Msg(msg)
ui.PrintWarning(cmd.ErrOrStderr(), msg)
}
case "currency":
value = ctx.Config.Configuration.Currency
Expand All @@ -227,7 +226,7 @@ func configureGetCmd(ctx *config.RunContext) *cobra.Command {
config.ConfigurationFilePath(),
ui.PrimaryString("infracost configure set currency CURRENCY"),
)
logging.Logger.Warn().Msg(msg)
ui.PrintWarning(cmd.ErrOrStderr(), msg)
}
case "tls_insecure_skip_verify":
if ctx.Config.Configuration.TLSInsecureSkipVerify == nil {
Expand All @@ -241,7 +240,7 @@ func configureGetCmd(ctx *config.RunContext) *cobra.Command {
config.ConfigurationFilePath(),
ui.PrimaryString("infracost configure set tls_insecure_skip_verify true"),
)
logging.Logger.Warn().Msg(msg)
ui.PrintWarning(cmd.ErrOrStderr(), msg)
}
case "tls_ca_cert_file":
value = ctx.Config.Configuration.TLSCACertFile
Expand All @@ -251,7 +250,7 @@ func configureGetCmd(ctx *config.RunContext) *cobra.Command {
config.ConfigurationFilePath(),
ui.PrimaryString("infracost configure set tls_ca_cert_file /path/to/ca.crt"),
)
logging.Logger.Warn().Msg(msg)
ui.PrintWarning(cmd.ErrOrStderr(), msg)
}
case "enable_dashboard":
if ctx.Config.Configuration.EnableDashboard == nil {
Expand Down
8 changes: 6 additions & 2 deletions cmd/infracost/diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,9 @@ projects:
configFilePath,
"--compare-to",
path.Join(dir, "prior.json"),
}, nil)
}, &GoldenFileOptions{
RunTerraformCLI: true,
})
}

func TestDiffWithConfigFileCompareToDeletedProject(t *testing.T) {
Expand All @@ -238,7 +240,9 @@ projects:
configFilePath,
"--compare-to",
path.Join(dir, "prior.json"),
}, nil)
}, &GoldenFileOptions{
RunTerraformCLI: true,
})
}

func TestDiffCompareToError(t *testing.T) {
Expand Down
32 changes: 17 additions & 15 deletions cmd/infracost/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
)

type generateConfigCommand struct {
wd string
repoPath string
templatePath string
template string
outFile string
Expand All @@ -44,7 +44,7 @@ func newGenerateConfigCommand() *cobra.Command {
RunE: gen.run,
}

cmd.Flags().StringVar(&gen.wd, "repo-path", ".", "Path to the Terraform repo or directory you want to run the template file on")
cmd.Flags().StringVar(&gen.repoPath, "repo-path", ".", "Path to the Terraform repo or directory you want to run the template file on")
cmd.Flags().StringVar(&gen.template, "template", "", "Infracost template string that will generate the config-file yaml output")
cmd.Flags().StringVar(&gen.templatePath, "template-path", "", "Path to the Infracost template file that will generate the config-file yaml output")
cmd.Flags().StringVar(&gen.outFile, "out-file", "", "Save output to a file")
Expand All @@ -59,9 +59,9 @@ func (g *generateConfigCommand) run(cmd *cobra.Command, args []string) error {
return nil
}

wd, _ := os.Getwd()
if g.wd != "." && g.wd != "" {
wd = g.wd
repoPath, _ := os.Getwd()
if g.repoPath != "." && g.repoPath != "" {
repoPath = g.repoPath
}

var buf bytes.Buffer
Expand Down Expand Up @@ -94,7 +94,7 @@ func (g *generateConfigCommand) run(cmd *cobra.Command, args []string) error {
}

var autoProjects []hcl.DetectedProject
detectionOutput, err := providers.Detect(ctx, &config.Project{Path: wd}, false)
autoProviders, err := providers.Detect(ctx, &config.Project{Path: repoPath}, false)
if err != nil {
if definedProjects {
logging.Logger.Debug().Err(err).Msg("could not detect providers")
Expand All @@ -103,32 +103,34 @@ func (g *generateConfigCommand) run(cmd *cobra.Command, args []string) error {
}
}

for _, provider := range detectionOutput.Providers {
for _, provider := range autoProviders {
if v, ok := provider.(hcl.DetectedProject); ok {
autoProjects = append(autoProjects, v)
}
}

if definedProjects {
m, err := vcs.MetadataFetcher.Get(wd, nil)
m, err := vcs.MetadataFetcher.Get(repoPath, nil)
if err != nil {
logging.Logger.Warn().Msgf("could not fetch git metadata err: %s, default template variables will be blank", err)
ui.PrintWarningf(cmd.ErrOrStderr(), "could not fetch git metadata err: %s, default template variables will be blank", err)
}

detectedProjects := make([]template.DetectedProject, len(autoProjects))
detectedPaths := map[string][]template.DetectedProject{}
for i, p := range autoProjects {
relPath := p.RelativePath()

detectedProjects[i] = template.DetectedProject{
Name: p.ProjectName(),
Path: p.RelativePath(),
Path: relPath,
Env: p.EnvName(),
TerraformVarFiles: p.VarFiles(),
TerraformVarFiles: p.TerraformVarFiles(),
}

if v, ok := detectedPaths[p.RelativePath()]; ok {
detectedPaths[p.RelativePath()] = append(v, detectedProjects[i])
if v, ok := detectedPaths[relPath]; ok {
detectedPaths[relPath] = append(v, detectedProjects[i])
} else {
detectedPaths[p.RelativePath()] = []template.DetectedProject{detectedProjects[i]}
detectedPaths[relPath] = []template.DetectedProject{detectedProjects[i]}
}
}

Expand All @@ -153,7 +155,7 @@ func (g *generateConfigCommand) run(cmd *cobra.Command, args []string) error {
variables.BaseBranch = m.PullRequest.BaseBranch
}

parser := template.NewParser(wd, variables)
parser := template.NewParser(repoPath, variables)
if g.template != "" {
err := parser.Compile(g.template, &buf)
if err != nil {
Expand Down
8 changes: 6 additions & 2 deletions cmd/infracost/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ func handleCLIError(ctx *config.RunContext, cliErr error) {
}

func handleUnexpectedErr(ctx *config.RunContext, err error) {
ui.PrintUnexpectedErrorStack(err)
ui.PrintUnexpectedErrorStack(ctx.ErrWriter, err)

err = apiclient.ReportCLIError(ctx, err, false)
if err != nil {
Expand Down Expand Up @@ -381,7 +381,11 @@ func saveOutFileWithMsg(ctx *config.RunContext, cmd *cobra.Command, outFile, suc
return errors.Wrap(err, "Unable to save output")
}

logging.Logger.Info().Msg(successMsg)
if ctx.Config.IsLogging() {
logging.Logger.Info().Msg(successMsg)
} else {
cmd.PrintErrf("%s\n", successMsg)
}

return nil
}