github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/os/user/lookup_stubs.go (about)

     1  // Copyright 2011 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  
     5  // +build !cgo,!windows,!plan9 android osusergo,!windows,!plan9
     6  
     7  package user
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"os"
    13  	"runtime"
    14  	"strconv"
    15  )
    16  
    17  func init() {
    18  	groupImplemented = false
    19  }
    20  
    21  func current() (*User, error) {
    22  	uid := currentUID()
    23  	// $USER and /etc/passwd may disagree; prefer the latter if we can get it.
    24  	// See issue 27524 for more information.
    25  	u, err := lookupUserId(uid)
    26  	if err == nil {
    27  		return u, nil
    28  	}
    29  
    30  	homeDir, _ := os.UserHomeDir()
    31  	u = &User{
    32  		Uid:      uid,
    33  		Gid:      currentGID(),
    34  		Username: os.Getenv("USER"),
    35  		Name:     "", // ignored
    36  		HomeDir:  homeDir,
    37  	}
    38  	// On Android, return a dummy user instead of failing.
    39  	switch runtime.GOOS {
    40  	case "android":
    41  		if u.Uid == "" {
    42  			u.Uid = "1"
    43  		}
    44  		if u.Username == "" {
    45  			u.Username = "android"
    46  		}
    47  	}
    48  	// cgo isn't available, but if we found the minimum information
    49  	// without it, use it:
    50  	if u.Uid != "" && u.Username != "" && u.HomeDir != "" {
    51  		return u, nil
    52  	}
    53  	var missing string
    54  	if u.Username == "" {
    55  		missing = "$USER"
    56  	}
    57  	if u.HomeDir == "" {
    58  		if missing != "" {
    59  			missing += ", "
    60  		}
    61  		missing += "$HOME"
    62  	}
    63  	return u, fmt.Errorf("user: Current requires cgo or %s set in environment", missing)
    64  }
    65  
    66  func listGroups(*User) ([]string, error) {
    67  	if runtime.GOOS == "android" || runtime.GOOS == "aix" {
    68  		return nil, fmt.Errorf("user: GroupIds not implemented on %s", runtime.GOOS)
    69  	}
    70  	return nil, errors.New("user: GroupIds requires cgo")
    71  }
    72  
    73  func currentUID() string {
    74  	if id := os.Getuid(); id >= 0 {
    75  		return strconv.Itoa(id)
    76  	}
    77  	// Note: Windows returns -1, but this file isn't used on
    78  	// Windows anyway, so this empty return path shouldn't be
    79  	// used.
    80  	return ""
    81  }
    82  
    83  func currentGID() string {
    84  	if id := os.Getgid(); id >= 0 {
    85  		return strconv.Itoa(id)
    86  	}
    87  	return ""
    88  }