github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/user/user.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Copyright 2014 The Gogs Authors. All rights reserved.
     7  // Use of this source code is governed by a MIT-style
     8  // license that can be found in the LICENSE file.
     9  
    10  package user
    11  
    12  import (
    13  	"os"
    14  	"os/user"
    15  	"runtime"
    16  	"strings"
    17  )
    18  
    19  // CurrentUsername return current login OS user name
    20  func CurrentUsername() string {
    21  	userinfo, err := user.Current()
    22  	if err != nil {
    23  		return fallbackCurrentUsername()
    24  	}
    25  	username := userinfo.Username
    26  	if runtime.GOOS == "windows" {
    27  		parts := strings.Split(username, "\\")
    28  		username = parts[len(parts)-1]
    29  	}
    30  	return username
    31  }
    32  
    33  // Old method, used if new method doesn't work on your OS for some reason
    34  func fallbackCurrentUsername() string {
    35  	curUserName := os.Getenv("USER")
    36  	if len(curUserName) > 0 {
    37  		return curUserName
    38  	}
    39  
    40  	return os.Getenv("USERNAME")
    41  }