1 // Copyright 2017 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
21 bashConfig = ".bash_profile"
25 // appendToPATH adds the given path to the PATH environment variable and
26 // persists it for future sessions.
27 func appendToPATH(value string) error {
31 return persistEnvVar("PATH", pathVar+envSeparator+value)
34 func isInPATH(dir string) bool {
35 p := os.Getenv("PATH")
37 paths := strings.Split(p, envSeparator)
38 for _, d := range paths {
47 func getHomeDir() (string, error) {
48 home := os.Getenv(homeKey)
53 u, err := user.Current()
60 func checkStringExistsFile(filename, value string) (bool, error) {
61 file, err := os.OpenFile(filename, os.O_RDONLY, 0600)
63 if os.IsNotExist(err) {
70 scanner := bufio.NewScanner(file)
72 line := scanner.Text()
78 return false, scanner.Err()
81 func appendToFile(filename, value string) error {
82 verbosef("Adding %q to %s", value, filename)
84 ok, err := checkStringExistsFile(filename, value)
93 f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
99 _, err = f.WriteString(lineEnding + value + lineEnding)
103 func isShell(name string) bool {
104 return strings.Contains(currentShell(), name)
107 // persistEnvVarWindows sets an environment variable in the Windows
109 func persistEnvVarWindows(name, value string) error {
110 _, err := runCommand(context.Background(), "powershell", "-command",
111 fmt.Sprintf(`[Environment]::SetEnvironmentVariable("%s", "%s", "User")`, name, value))
115 func persistEnvVar(name, value string) error {
116 if runtime.GOOS == "windows" {
117 if err := persistEnvVarWindows(name, value); err != nil {
121 if isShell("cmd.exe") || isShell("powershell.exe") {
122 return os.Setenv(strings.ToUpper(name), value)
124 // User is in bash, zsh, etc.
125 // Also set the environment variable in their shell config.
128 rc, err := shellConfigFile()
133 line := fmt.Sprintf("export %s=%s", strings.ToUpper(name), value)
134 if err := appendToFile(rc, line); err != nil {
138 return os.Setenv(strings.ToUpper(name), value)
141 func shellConfigFile() (string, error) {
142 home, err := getHomeDir()
148 case isShell("bash"):
149 return filepath.Join(home, bashConfig), nil
151 return filepath.Join(home, zshConfig), nil
153 return "", fmt.Errorf("%q is not a supported shell", currentShell())