Browse Source

更新CurrentUsername函数逻辑

修改了获取当前用户名的逻辑,优先使用`user.Current()`方法来获取用户名,并简化了后续环境变量和系统属性的检查流程。
SongZihuan 1 tháng trước cách đây
mục cha
commit
da83b8c1d2
1 tập tin đã thay đổi với 7 bổ sung4 xóa
  1. 7 4
      internal/osutil/osutil.go

+ 7 - 4
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
 }