1
0

osutil.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2020 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 and LICENSE.gogs file.
  4. package osutil
  5. import (
  6. "os"
  7. "os/user"
  8. )
  9. // IsFile returns true if given path exists as a file (i.e. not a directory).
  10. func IsFile(path string) bool {
  11. f, e := os.Stat(path)
  12. if e != nil {
  13. return false
  14. }
  15. return !f.IsDir()
  16. }
  17. // IsDir returns true if given path is a directory, and returns false when it's
  18. // a file or does not exist.
  19. func IsDir(dir string) bool {
  20. f, e := os.Stat(dir)
  21. if e != nil {
  22. return false
  23. }
  24. return f.IsDir()
  25. }
  26. // IsExist returns true if a file or directory exists.
  27. func IsExist(path string) bool {
  28. _, err := os.Stat(path)
  29. return err == nil || os.IsExist(err)
  30. }
  31. // CurrentUsername returns the username of the current user.
  32. func CurrentUsername() string {
  33. // To get the real user of the current process, you should use user.Current(),
  34. // and USER may not be the real user of the process (for example, executing it
  35. //through sudo will display the original user)
  36. if currentUser, err := user.Current(); err == nil && currentUser != nil && len(currentUser.Username) > 0 {
  37. return currentUser.Username
  38. }
  39. username := os.Getenv("USER")
  40. if len(username) > 0 {
  41. return username
  42. }
  43. username = os.Getenv("USERNAME")
  44. if len(username) > 0 {
  45. return username
  46. }
  47. return username
  48. }