更新获取当前用户名的逻辑

使用user.Current()优先获取当前进程的真实用户,以解决通过sudo执行时显示原始用户的问题。如果user.Current()返回有效用户名,则直接返回;否则继续使用环境变量"USER"作为回退方案。
pull/7939/head
宋子桓🌈 2025-04-01 17:52:36 +08:00
parent ea7fab180d
commit b8a0a6173c
No known key found for this signature in database
GPG Key ID: BEF31CC2410A2E8A
1 changed files with 7 additions and 4 deletions

View File

@ -36,6 +36,13 @@ func IsExist(path string) bool {
// CurrentUsername returns the username of the current user.
func CurrentUsername() string {
// To get the real user of the current process, you should use user.Current(),
// and USER may not be the real user of the process (for example, executing it
// through sudo will display the original user)
if currentUser, err := user.Current(); err == nil && currentUser != nil && len(currentUser.Username) > 0 {
return currentUser.Username
}
username := os.Getenv("USER")
if len(username) > 0 {
return username
@ -45,9 +52,5 @@ func CurrentUsername() string {
if len(username) > 0 {
return username
}
if user, err := user.Current(); err == nil {
username = user.Username
}
return username
}