env_windows.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.
  4. // Windows environment variables.
  5. package windows
  6. import (
  7. "unicode/utf16"
  8. "unsafe"
  9. )
  10. func Getenv(key string) (value string, found bool) {
  11. keyp, err := UTF16PtrFromString(key)
  12. if err != nil {
  13. return "", false
  14. }
  15. b := make([]uint16, 100)
  16. n, e := GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
  17. if n == 0 && e == ERROR_ENVVAR_NOT_FOUND {
  18. return "", false
  19. }
  20. if n > uint32(len(b)) {
  21. b = make([]uint16, n)
  22. n, e = GetEnvironmentVariable(keyp, &b[0], uint32(len(b)))
  23. if n > uint32(len(b)) {
  24. n = 0
  25. }
  26. }
  27. return string(utf16.Decode(b[0:n])), true
  28. }
  29. func Setenv(key, value string) error {
  30. v, err := UTF16PtrFromString(value)
  31. if err != nil {
  32. return err
  33. }
  34. keyp, err := UTF16PtrFromString(key)
  35. if err != nil {
  36. return err
  37. }
  38. e := SetEnvironmentVariable(keyp, v)
  39. if e != nil {
  40. return e
  41. }
  42. return nil
  43. }
  44. func Clearenv() {
  45. for _, s := range Environ() {
  46. // Environment variables can begin with =
  47. // so start looking for the separator = at j=1.
  48. // http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
  49. for j := 1; j < len(s); j++ {
  50. if s[j] == '=' {
  51. Setenv(s[0:j], "")
  52. break
  53. }
  54. }
  55. }
  56. }
  57. func Environ() []string {
  58. s, e := GetEnvironmentStrings()
  59. if e != nil {
  60. return nil
  61. }
  62. defer FreeEnvironmentStrings(s)
  63. r := make([]string, 0, 50) // Empty with room to grow.
  64. for from, i, p := 0, 0, (*[1 << 24]uint16)(unsafe.Pointer(s)); true; i++ {
  65. if p[i] == 0 {
  66. // empty string marks the end
  67. if i <= from {
  68. break
  69. }
  70. r = append(r, string(utf16.Decode(p[from:i])))
  71. from = i + 1
  72. }
  73. }
  74. return r
  75. }