Repository navigation
Expand file tree
/
Copy pathdriverhyperv-interfacescript.go
More file actions
109 lines (87 loc) · 2.14 KB
/
Copy pathdriverhyperv-interfacescript.go
File metadata and controls
109 lines (87 loc) · 2.14 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package driverhyperv
import (
_ "embed"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/kuttiproject/workspace"
)
type driverresult struct {
Success bool
ErrorMessage string
Payload map[string]interface{}
}
const scriptVersion = "0.4"
var scriptname = "hypervmanage-" + scriptVersion + ".ps1"
// findPowerShell finds the PowerShell to run the interface script with. It is
// a variable so that tests can replace it.
var findPowerShell = lookupPowerShell
func lookupPowerShell() (string, error) {
// First, try looking up Windows PowerShell on the path
toolpath, err := exec.LookPath("powershell.exe")
if err == nil {
return toolpath, nil
}
// If not, look for cross-platform PowerShell
toolpath, err = exec.LookPath("pwsh.exe")
if err == nil {
return toolpath, nil
}
return "", errors.New("PowerShell not found")
}
func machineDir() (string, error) {
return workspace.CacheSubDir("driver-hyperv-machines")
}
func diskDir() (string, error) {
return workspace.CacheSubDir("driver-hyperv-disks")
}
func findScript() (string, error) {
scriptdir, err := hypervCacheDir()
if err != nil {
return "", fmt.Errorf("could not find script: %v", err.Error())
}
scriptpath := filepath.Join(scriptdir, scriptname)
if _, err := os.Stat(scriptpath); err != nil {
err = writeScript(scriptpath)
if err != nil {
return "", err
}
}
return scriptpath, nil
}
//go:embed assets/hypervmanage.ps1
var script string
func writeScript(scriptpath string) error {
scriptFile, err := os.Create(scriptpath)
if err != nil {
return err
}
defer scriptFile.Close()
_, err = scriptFile.WriteString(script)
if err != nil {
return err
}
return nil
}
func (vd *Driver) runwithresults(args ...string) (*driverresult, error) {
powershellargs := []string{
"-NoProfile",
"-NonInteractive",
"-File",
vd.scriptpath,
}
powershellargs = append(powershellargs, args...)
resultstring, err := workspace.RunWithResults(vd.powershellpath, powershellargs...)
if err != nil {
return nil, err
}
dr := &driverresult{}
err = json.Unmarshal([]byte(resultstring), dr)
if err != nil {
return nil, err
}
return dr, nil
}