Prevents providers mirror from crashing with bad lock file (#1985)

Signed-off-by: Andrew Hayes <andrew.hayes@harness.io>
This commit is contained in:
Andy Hayes 2024-09-25 14:01:17 +01:00 committed by GitHub
parent 485be411c0
commit 20187d859f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 67 additions and 0 deletions

View File

@ -84,3 +84,47 @@ func testOpenTofuProvidersMirror(t *testing.T, fixture string) {
t.Errorf("unexpected files in result\n%s", diff)
}
}
// this test is based on testOpenTofuProvidersMirror above.
func TestOpenTofuProvidersMirrorBadLockfile(t *testing.T) {
// This test reaches out to registry.opentofu.org to download the
// template and null providers, so it can only run if network access is
// allowed.
skipIfCannotAccessNetwork(t)
outputDir := t.TempDir()
t.Logf("creating mirror directory in %s", outputDir)
fixturePath := filepath.Join("testdata", "tofu-providers-mirror-with-bad-lock-file")
tf := e2e.NewBinary(t, tofuBin, fixturePath)
stdout, stderr, err := tf.Run("providers", "mirror", outputDir)
if err == nil {
t.Fatalf("expected error: %s\nstdout:\n%s\nstderr:\n%s", err, stdout, stderr)
}
var want []string
var got []string
walkErr := filepath.Walk(outputDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil // we only care about leaf files for this test
}
relPath, err := filepath.Rel(outputDir, path)
if err != nil {
return err
}
got = append(got, filepath.ToSlash(relPath))
return nil
})
if walkErr != nil {
t.Fatal(walkErr)
}
sort.Strings(got)
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("unexpected files in result\n%s", diff)
}
}

View File

@ -0,0 +1,8 @@
# This file is maintained automatically by "tofu init".
# Manual edits may be lost in future updates.
provider "registry.opentofu.org/hashicorp/tfcoremocka" {
version = "0.2.0"
hashes = ["zh:"
]
}

View File

@ -0,0 +1,7 @@
terraform {
required_providers {
tfcoremock = {
source = "tfcoremock"
}
}
}

View File

@ -164,6 +164,14 @@ func (c *ProvidersMirrorCommand) Run(args []string) int {
}
selected := candidates.Newest()
if !lockedDeps.Empty() {
if lockedDeps.Provider(provider) == nil {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Provider not found in lockfile",
fmt.Sprintf("Failed to find %s in the lock file", provider.String()),
))
continue
}
selected = lockedDeps.Provider(provider).Version()
c.Ui.Output(fmt.Sprintf(" - Selected v%s to match dependency lock file", selected.String()))
} else if len(constraintsStr) > 0 {