This repository has been archived by the owner on Jun 27, 2020. It is now read-only.
/
vagrant.go
80 lines (66 loc) · 2.14 KB
/
vagrant.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package vagrant
import (
"fmt"
"os"
"os/exec"
"sync"
"github.com/hashicorp/go-version"
"github.com/hashicorp/otto/context"
execHelper "github.com/hashicorp/otto/helper/exec"
"github.com/hashicorp/otto/helper/hashitools"
"github.com/hashicorp/otto/ui"
)
var (
vagrantMinVersion = version.Must(version.NewVersion("1.7.4"))
)
// Project returns the hashitools Project for this.
func Project(ctx *context.Shared) *hashitools.Project {
return &hashitools.Project{
Name: "vagrant",
MinVersion: vagrantMinVersion,
Installer: &hashitools.VagrantInstaller{
Ui: ctx.Ui,
},
}
}
// Vagrant wraps `vagrant` execution into an easy-to-use API.
type Vagrant struct {
// Dir is the working directory where all Vagrant commands will
// be executed from.
Dir string
// DataDir is the directory where Vagrant commands should store data.
DataDir string
// Ui, if given, will be used to stream output from the Vagrant
// commands. If this is nil, then the output will be logged but
// won't be visible to the user.
Ui ui.Ui
}
// A global mutex to prevent any Vagrant commands from running in parallel,
// which is not a supported mode of operation for Vagrant.
var vagrantMutex = &sync.Mutex{}
// The environment variable that Vagrant uses to configure its data dir.
const vagrantDataDirEnvVar = "VAGRANT_DOTFILE_PATH"
// Execute executes a raw Vagrant command.
func (v *Vagrant) Execute(command ...string) error {
vagrantMutex.Lock()
defer vagrantMutex.Unlock()
// Build the command to execute
cmd := exec.Command("vagrant", command...)
cmd.Dir = v.Dir
// Tell vagrant where to store data
origDataDir := os.Getenv(vagrantDataDirEnvVar)
defer os.Setenv(vagrantDataDirEnvVar, origDataDir)
if err := os.Setenv(vagrantDataDirEnvVar, v.DataDir); err != nil {
return err
}
// Run it with the execHelper
if err := execHelper.Run(v.Ui, cmd); err != nil {
return fmt.Errorf(
"Error executing Vagrant: %s\n\n"+
"The error messages from Vagrant are usually very informative.\n"+
"Please read it carefully and fix any issues it mentions. If\n"+
"the message isn't clear, please report this to the Otto project.",
err)
}
return nil
}