You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
792 B

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