osutil.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 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. // following any symlinks.
  11. func IsFile(path string) bool {
  12. f, e := os.Stat(path)
  13. if e != nil {
  14. return false
  15. }
  16. return !f.IsDir()
  17. }
  18. // IsDir returns true if given path is a directory following any symlinks, and
  19. // returns false when it's a file or does not exist.
  20. func IsDir(dir string) bool {
  21. f, e := os.Stat(dir)
  22. if e != nil {
  23. return false
  24. }
  25. return f.IsDir()
  26. }
  27. // IsExist returns true if a file or directory exists following any symlinks.
  28. func IsExist(path string) bool {
  29. _, err := os.Stat(path)
  30. return err == nil || os.IsExist(err)
  31. }
  32. // IsSymlink returns true if given path is a symbolic link.
  33. func IsSymlink(path string) bool {
  34. fileInfo, err := os.Lstat(path)
  35. if err != nil {
  36. return false
  37. }
  38. return fileInfo.Mode()&os.ModeSymlink != 0
  39. }
  40. // CurrentUsername returns the username of the current user.
  41. func CurrentUsername() string {
  42. username := os.Getenv("USER")
  43. if len(username) > 0 {
  44. return username
  45. }
  46. username = os.Getenv("USERNAME")
  47. if len(username) > 0 {
  48. return username
  49. }
  50. if user, err := user.Current(); err == nil {
  51. username = user.Username
  52. }
  53. return username
  54. }