summaryrefslogtreecommitdiff
path: root/src/lib/os/env.go
blob: e7df309e03dbfe4390ccfb5c62ec2574efbf0155 (plain)
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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Environment variables.

package os

import (
	"once";
	"os";
)

// ENOENV is the Error indicating that an environment variable does not exist.
var ENOENV = NewError("no such environment variable");

var env map[string] string;


func copyenv() {
	env = make(map[string] string);
	for i, s := range sys.Envs {
		for j := 0; j < len(s); j++ {
			if s[j] == '=' {
				env[s[0:j]] = s[j+1:len(s)];
				break;
			}
		}
	}
}

// Getenv retrieves the value of the environment variable named by the key.
// It returns the value and an error, if any.
func Getenv(key string) (value string, err Error) {
	once.Do(copyenv);

	if len(key) == 0 {
		return "", EINVAL;
	}
	v, ok := env[key];
	if !ok {
		return "", ENOENV;
	}
	return v, nil;
}

// Setenv sets the value of the environment variable named by the key.
// It returns an Error, if any.
func Setenv(key, value string) Error {
	once.Do(copyenv);

	if len(key) == 0 {
		return EINVAL;
	}
	env[key] = value;
	return nil;
}

// Clearenv deletes all environment variables.
func Clearenv() {
	once.Do(copyenv);	// prevent copyenv in Getenv/Setenv
	env = make(map[string] string);
}

// Environ returns an array of strings representing the environment,
// in the form "key=value".
func Environ() []string {
	once.Do(copyenv);
	a := make([]string, len(env));
	i := 0;
	for k, v := range(env) {
		// check i < len(a) for safety,
		// in case env is changing underfoot.
		if i < len(a) {
			a[i] = k + "=" + v;
			i++;
		}
	}
	return a[0:i];
}