1
0

osutil.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package osutil
  2. import (
  3. "os"
  4. "os/user"
  5. )
  6. // IsFile returns true if given path exists as a file (i.e. not a directory)
  7. // following any symlinks.
  8. func IsFile(path string) bool {
  9. f, e := os.Stat(path)
  10. if e != nil {
  11. return false
  12. }
  13. return !f.IsDir()
  14. }
  15. // IsDir returns true if given path is a directory following any symlinks, and
  16. // returns false when it's a file or does not exist.
  17. func IsDir(dir string) bool {
  18. f, e := os.Stat(dir)
  19. if e != nil {
  20. return false
  21. }
  22. return f.IsDir()
  23. }
  24. // Exist returns true if a file or directory exists following any symlinks.
  25. func Exist(path string) bool {
  26. _, err := os.Stat(path)
  27. return err == nil || os.IsExist(err)
  28. }
  29. // IsSymlink returns true if given path is a symbolic link.
  30. func IsSymlink(path string) bool {
  31. fileInfo, err := os.Lstat(path)
  32. if err != nil {
  33. return false
  34. }
  35. return fileInfo.Mode()&os.ModeSymlink != 0
  36. }
  37. // CurrentUsername returns the username of the current user.
  38. func CurrentUsername() string {
  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. if user, err := user.Current(); err == nil {
  48. username = user.Username
  49. }
  50. return username
  51. }