From b8a0a6173c581bd488a57e53a150fa2f3303e78e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=8B=E5=AD=90=E6=A1=93=F0=9F=8C=88?= Date: Tue, 1 Apr 2025 17:52:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=8E=B7=E5=8F=96=E5=BD=93?= =?UTF-8?q?=E5=89=8D=E7=94=A8=E6=88=B7=E5=90=8D=E7=9A=84=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 使用user.Current()优先获取当前进程的真实用户,以解决通过sudo执行时显示原始用户的问题。如果user.Current()返回有效用户名,则直接返回;否则继续使用环境变量"USER"作为回退方案。 --- internal/osutil/osutil.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/internal/osutil/osutil.go b/internal/osutil/osutil.go index 28fa40f85..e075b184c 100644 --- a/internal/osutil/osutil.go +++ b/internal/osutil/osutil.go @@ -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 }