summaryrefslogtreecommitdiff
path: root/libgo/go/syscall/env_plan9.go
blob: 518573318efa59908192d70fae4b9f85972c3be0 (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
// Copyright 2011 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.

// Plan 9 environment variables.

package syscall

import "errors"

func Getenv(key string) (value string, found bool) {
	if len(key) == 0 {
		return "", false
	}
	f, e := Open("/env/"+key, O_RDONLY)
	if e != nil {
		return "", false
	}
	defer Close(f)

	l, _ := Seek(f, 0, 2)
	Seek(f, 0, 0)
	buf := make([]byte, l)
	n, e := Read(f, buf)
	if e != nil {
		return "", false
	}

	if n > 0 && buf[n-1] == 0 {
		buf = buf[:n-1]
	}
	return string(buf), true
}

func Setenv(key, value string) error {
	if len(key) == 0 {
		return errors.New("bad arg in system call")
	}

	f, e := Create("/env/"+key, O_RDWR, 0666)
	if e != nil {
		return e
	}
	defer Close(f)

	_, e = Write(f, []byte(value))
	return nil
}

func Clearenv() {
	RawSyscall(SYS_RFORK, RFCENVG, 0, 0)
}

func Environ() []string {
	env := make([]string, 0, 100)

	f, e := Open("/env", O_RDONLY)
	if e != nil {
		panic(e)
	}
	defer Close(f)

	names, e := readdirnames(f)
	if e != nil {
		panic(e)
	}

	for _, k := range names {
		if v, ok := Getenv(k); ok {
			env = append(env, k+"="+v)
		}
	}
	return env[0:len(env)]
}