Should return the provider by parsing the json in the box metadata file

This commit is contained in:
DanHam 2019-08-21 12:32:42 +01:00
parent 0bf0e7c078
commit a9e22a6bb2
No known key found for this signature in database
GPG Key ID: 58E79AEDD6AA987E
2 changed files with 34 additions and 6 deletions

View File

@ -8,10 +8,10 @@ import (
"archive/tar"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
@ -244,12 +244,18 @@ func providerFromVagrantBox(boxfile string) (providerName string, err error) {
}
tr := tar.NewReader(ar)
// The metadata.json file in the tar archive contains a 'provider' key
type metadata struct {
ProviderName string `json:"provider"`
}
md := metadata{}
// Loop through the files in the archive and read the provider
// information from the boxes metadata.json file
for {
hdr, err := tr.Next()
if err == io.EOF {
if providerName == "" {
if md.ProviderName == "" {
return "", fmt.Errorf("Error: Provider info was not found in box: %s", boxfile)
}
break
@ -263,11 +269,12 @@ func providerFromVagrantBox(boxfile string) (providerName string, err error) {
if err != nil {
return "", fmt.Errorf("Error reading contents of metadata.json file from box file: %s", err)
}
// TODO: Parse the json for the provider
log.Printf("Contents: %s", contents)
err = json.Unmarshal(contents, &md)
if err != nil {
return "", fmt.Errorf("Error parsing metadata.json file: %s", err)
}
break
}
}
return "", nil
return md.ProviderName, nil
}

View File

@ -14,6 +14,7 @@ import (
"testing"
"github.com/hashicorp/packer/packer"
"github.com/stretchr/testify/assert"
)
type tarFiles []struct {
@ -286,6 +287,26 @@ func TestProviderFromVagrantBox_no_metadata(t *testing.T) {
t.Logf("%s", err)
}
func TestProviderFromVagrantBox_metadata_ok(t *testing.T) {
// Good: The box contains the metadata.json file with the required
// 'provider' key/value
expectedProvider := "virtualbox"
files := tarFiles{
{"foo.txt", "This is a foo file"},
{"bar.txt", "This is a bar file"},
{"metadata.json", `{"provider":"` + expectedProvider + `"}`},
}
boxfile, err := createBox(files)
if err != nil {
t.Fatalf("Error creating test box: %s", err)
}
defer os.Remove(boxfile.Name())
provider, err := providerFromVagrantBox(boxfile.Name())
assert.Equal(t, expectedProvider, provider, "Error: Expected provider: '%s'. Got '%s'", expectedProvider, provider)
t.Logf("Expected provider '%s'. Got provider '%s'", expectedProvider, provider)
}
func newBoxFile() (boxfile *os.File, err error) {
boxfile, err = ioutil.TempFile(os.TempDir(), "test*.box")
if err != nil {