-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevshell.go
More file actions
113 lines (102 loc) · 2.43 KB
/
Copy pathdevshell.go
File metadata and controls
113 lines (102 loc) · 2.43 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
110
111
112
113
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
const envSentinel = "==VSENV_BEGIN=="
func captureDevShellEnv(
ctx context.Context,
install *Install,
arch, hostArch, devArgs string,
) (map[string]string, error) {
vsdevcmd := filepath.Join(install.InstallationPath, "Common7", "Tools", "VsDevCmd.bat")
if _, err := os.Stat(vsdevcmd); err != nil {
return nil, fmt.Errorf("VsDevCmd.bat not found at %s", vsdevcmd)
}
args := []string{"-no_logo", "-arch=" + arch}
if hostArch != "" {
args = append(args, "-host_arch="+hostArch)
}
if devArgs != "" {
args = append(args, strings.Fields(devArgs)...)
}
bat, err := writeTempBat(vsdevcmd, args)
if err != nil {
return nil, err
}
defer func() { _ = os.Remove(bat) }()
c := exec.CommandContext(ctx, "cmd.exe", "/d", "/c", bat)
var out bytes.Buffer
c.Stdout = &out
c.Stderr = &out
if runErr := c.Run(); runErr != nil {
return nil, fmt.Errorf("VsDevCmd.bat failed: %w\noutput:\n%s", runErr, out.String())
}
return parseSetOutput(out.String())
}
func writeTempBat(vsdevcmd string, args []string) (string, error) {
f, err := os.CreateTemp("", "vsenv-*.bat")
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
writes := []string{
"@echo off\r\n",
fmt.Sprintf("call \"%s\" %s\r\n", vsdevcmd, strings.Join(args, " ")),
"if errorlevel 1 exit /b %errorlevel%\r\n",
"echo " + envSentinel + "\r\n",
"set\r\n",
}
for _, line := range writes {
if _, writeErr := io.WriteString(f, line); writeErr != nil {
return "", writeErr
}
}
return f.Name(), nil
}
func parseSetOutput(out string) (map[string]string, error) {
_, tail, ok := strings.Cut(out, envSentinel)
if !ok {
return nil, errors.New("env sentinel not found in VsDevCmd output")
}
env := map[string]string{}
for line := range strings.SplitSeq(tail, "\n") {
line = strings.TrimRight(line, "\r")
if line == "" {
continue
}
k, v, hasEq := strings.Cut(line, "=")
if !hasEq || k == "" {
continue
}
env[k] = v
}
return env, nil
}
func diffEnv(parent, full map[string]string) map[string]string {
diff := map[string]string{}
for k, v := range full {
if pv, ok := parent[k]; !ok || pv != v {
diff[k] = v
}
}
return diff
}
func parentEnvMap() map[string]string {
m := map[string]string{}
for _, e := range os.Environ() {
k, v, hasEq := strings.Cut(e, "=")
if !hasEq || k == "" {
continue
}
m[k] = v
}
return m
}