1 // Copyright 2010 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.
5 // Windows environment variables.
15 // ENOENV is the Error indicating that an environment variable does not exist.
16 var ENOENV = NewError("no such environment variable")
18 // Getenverror retrieves the value of the environment variable named by the key.
19 // It returns the value and an error, if any.
20 func Getenverror(key string) (value string, err Error) {
21 b := make([]uint16, 100)
22 n, e := syscall.GetEnvironmentVariable(syscall.StringToUTF16Ptr(key), &b[0], uint32(len(b)))
23 if n == 0 && e == syscall.ERROR_ENVVAR_NOT_FOUND {
26 if n > uint32(len(b)) {
28 n, e = syscall.GetEnvironmentVariable(syscall.StringToUTF16Ptr(key), &b[0], uint32(len(b)))
29 if n > uint32(len(b)) {
34 return "", NewSyscallError("GetEnvironmentVariable", e)
36 return string(utf16.Decode(b[0:n])), nil
39 // Getenv retrieves the value of the environment variable named by the key.
40 // It returns the value, which will be empty if the variable is not present.
41 func Getenv(key string) string {
42 v, _ := Getenverror(key)
46 // Setenv sets the value of the environment variable named by the key.
47 // It returns an Error, if any.
48 func Setenv(key, value string) Error {
51 v = syscall.StringToUTF16Ptr(value)
53 ok, e := syscall.SetEnvironmentVariable(syscall.StringToUTF16Ptr(key), v)
55 return NewSyscallError("SetEnvironmentVariable", e)
60 // Clearenv deletes all environment variables.
62 for _, s := range Environ() {
63 // Environment variables can begin with =
64 // so start looking for the separator = at j=1.
65 // http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
66 for j := 1; j < len(s); j++ {
75 // Environ returns an array of strings representing the environment,
76 // in the form "key=value".
77 func Environ() []string {
78 s, e := syscall.GetEnvironmentStrings()
82 defer syscall.FreeEnvironmentStrings(s)
83 r := make([]string, 0, 50) // Empty with room to grow.
84 for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
86 // empty string marks the end
90 r = append(r, string(utf16.Decode(p[from:i])))
97 // TempDir returns the default directory to use for temporary files.
98 func TempDir() string {
100 dirw := make([]uint16, syscall.MAX_PATH)
101 n, _ := syscall.GetTempPath(uint32(len(dirw)), &dirw[0])
102 if n > uint32(len(dirw)) {
103 dirw = make([]uint16, n)
104 n, _ = syscall.GetTempPath(uint32(len(dirw)), &dirw[0])
105 if n > uint32(len(dirw)) {
109 if n > 0 && dirw[n-1] == pathSep {
112 return string(utf16.Decode(dirw[0:n]))