56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
//go:build linux
|
|
|
|
/*
|
|
Copyright 2024 API Testing Authors.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package home
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"os"
|
|
"os/exec"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func Dir() string {
|
|
// First prefer the HOME environmental variable
|
|
if home := getCommonHomeDir(); home != "" {
|
|
return home
|
|
}
|
|
|
|
var stdout bytes.Buffer
|
|
cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid()))
|
|
cmd.Stdout = &stdout
|
|
if err := cmd.Run(); err != nil {
|
|
// If the error is ErrNotFound, we ignore it. Otherwise, return it.
|
|
if !errors.Is(err, exec.ErrNotFound) {
|
|
return ""
|
|
}
|
|
} else {
|
|
if passwd := strings.TrimSpace(stdout.String()); passwd != "" {
|
|
// username:password:uid:gid:gecos:home:shell
|
|
passwdParts := strings.SplitN(passwd, ":", 7)
|
|
if len(passwdParts) > 5 {
|
|
return passwdParts[5]
|
|
}
|
|
}
|
|
}
|
|
|
|
return getHomeDirViaShell()
|
|
}
|