Skip to content

Commit 795e712

Browse files
committed
os/user: make Current work without cgo
Fixes #14626 Change-Id: I91c40407dc35355e5c5046f24111a126f99260d9 Reviewed-on: https://go-review.googlesource.com/20192 Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Minux Ma <[email protected]>
1 parent 7893442 commit 795e712

File tree

2 files changed

+48
-4
lines changed

2 files changed

+48
-4
lines changed

src/os/user/lookup_stubs.go

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,44 @@
66

77
package user
88

9-
import "errors"
9+
import (
10+
"errors"
11+
"fmt"
12+
"os"
13+
"runtime"
14+
"strconv"
15+
)
1016

1117
func init() {
1218
userImplemented = false
1319
groupImplemented = false
1420
}
1521

1622
func current() (*User, error) {
17-
return nil, errors.New("user: Current requires cgo")
23+
u := &User{
24+
Uid: currentUID(),
25+
Gid: currentGID(),
26+
Username: os.Getenv("USER"),
27+
Name: "", // ignored
28+
HomeDir: os.Getenv("HOME"),
29+
}
30+
if runtime.GOOS == "nacl" {
31+
if u.Uid == "" {
32+
u.Uid = "1"
33+
}
34+
if u.Username == "" {
35+
u.Username = "nacl"
36+
}
37+
if u.HomeDir == "" {
38+
u.HomeDir = "/home/nacl"
39+
}
40+
}
41+
// cgo isn't available, but if we found the minimum information
42+
// without it, use it:
43+
if u.Uid != "" && u.Username != "" && u.HomeDir != "" {
44+
return u, nil
45+
}
46+
return nil, fmt.Errorf("user: Current not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
1847
}
1948

2049
func lookupUser(username string) (*User, error) {
@@ -36,3 +65,20 @@ func lookupGroupId(string) (*Group, error) {
3665
func listGroups(*User) ([]string, error) {
3766
return nil, errors.New("user: GroupIds requires cgo")
3867
}
68+
69+
func currentUID() string {
70+
if id := os.Getuid(); id >= 0 {
71+
return strconv.Itoa(id)
72+
}
73+
// Note: Windows returns -1, but this file isn't used on
74+
// Windows anyway, so this empty return path shouldn't be
75+
// used.
76+
return ""
77+
}
78+
79+
func currentGID() string {
80+
if id := os.Getgid(); id >= 0 {
81+
return strconv.Itoa(id)
82+
}
83+
return ""
84+
}

src/os/user/user_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ func checkUser(t *testing.T) {
1616
}
1717

1818
func TestCurrent(t *testing.T) {
19-
checkUser(t)
20-
2119
u, err := Current()
2220
if err != nil {
2321
t.Fatalf("Current: %v", err)

0 commit comments

Comments
 (0)