Skip to content

Commit

Permalink
#11 implement the vagrant.GetImageURL
Browse files Browse the repository at this point in the history
  • Loading branch information
mhewedy committed Aug 21, 2020
1 parent dadebc2 commit 4a3776e
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 7 deletions.
105 changes: 105 additions & 0 deletions vagrant/image_url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package vagrant

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
)

type vagrantResp struct {
Versions []version `json:"versions"`
}
type provider struct {
Name string `json:"name"`
URL string `json:"url"`
}
type version struct {
Version string `json:"version"`
Status string `json:"status"`
Providers []provider `json:"providers"`
}

func GetImageURL(image string) (string, error) {

user, imageName, imageVersion := getImageParts(image)

req, err := http.NewRequest("GET", fmt.Sprintf("https://app.vagrantup.com/%s/boxes/%s", user, imageName), nil)
if err != nil {
return "", err
}

req.Header.Set("Accept", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()

b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}

var obj vagrantResp
if err := json.Unmarshal(b, &obj); err != nil {
return "", err
}

p, err := filterByVersion(obj, user, imageName, imageVersion)
if err != nil {
return "", err
}

return p.URL, nil
}

func filterByVersion(resp vagrantResp, user, imageName, imageVersion string) (provider, error) {

if len(resp.Versions) == 0 {
return provider{}, errors.New("vagrant response contains no versions")
}

if imageVersion == "" {
// get latest version
return getVirtualBoxProvider(resp.Versions[0].Providers)
} else {
for _, v := range resp.Versions {
if v.Version == imageVersion {
return getVirtualBoxProvider(v.Providers)
}
}
return provider{}, fmt.Errorf("vagrant image version not found, "+
"check correct version number here: https://app.vagrantup.com/%s/boxes/%s", user, imageName)
}
}

func getVirtualBoxProvider(providers []provider) (provider, error) {
for _, p := range providers {
if p.Name == "virtualbox" {
return p, nil
}
}
return provider{}, errors.New("VirtualBox image not found for specified version")
}

// getImageParts syntax vagrant/USER/BOX:VERSION e.g.: vagrant/ubuntu/trusty64:20190429.0.1
// returns USER, BOX, VERSION (ubuntu, trusty64, 20190429.0.1)
func getImageParts(image string) (user string, imageName string, imageVersion string) {

parts := strings.Split(image, "/")
user = parts[1]
box := parts[2]

boxParts := strings.Split(box, ":")
imageName = boxParts[0]

if len(boxParts) > 1 {
imageVersion = boxParts[1]
}
return user, imageName, imageVersion
}
File renamed without changes.
7 changes: 0 additions & 7 deletions vagrant/vagrant.go

This file was deleted.

0 comments on commit 4a3776e

Please sign in to comment.